-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'abstract_controller'
-
1
require 'action_mailer/version'
-
-
# Common Active Support usage in Action Mailer
-
1
require 'active_support/rails'
-
1
require 'active_support/core_ext/class'
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/lazy_load_hooks'
-
-
1
module ActionMailer
-
1
extend ::ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Collector
-
end
-
-
1
autoload :Base
-
1
autoload :DeliveryMethods
-
1
autoload :InlinePreviewInterceptor
-
1
autoload :MailHelper
-
1
autoload :Preview
-
1
autoload :Previews, 'action_mailer/preview'
-
1
autoload :TestCase
-
1
autoload :TestHelper
-
1
autoload :MessageDelivery
-
1
autoload :DeliveryJob
-
end
-
-
1
autoload :Mime, 'action_dispatch/http/mime_type'
-
-
1
ActiveSupport.on_load(:action_view) do
-
1
ActionView::Base.default_formats ||= Mime::SET.symbols
-
1
ActionView::Template::Types.delegate_to Mime
-
end
-
1
require 'mail'
-
1
require 'action_mailer/collector'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/module/anonymous'
-
-
1
require 'action_mailer/log_subscriber'
-
-
1
module ActionMailer
-
# Action Mailer allows you to send email from your application using a mailer model and views.
-
#
-
# = Mailer Models
-
#
-
# To use Action Mailer, you need to create a mailer model.
-
#
-
# $ rails generate mailer Notifier
-
#
-
# The generated model inherits from <tt>ApplicationMailer</tt> which in turn
-
# inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods
-
# used to generate an email message. In these methods, you can setup variables to be used in
-
# the mailer views, options on the mail itself such as the <tt>:from</tt> address, and attachments.
-
#
-
# class ApplicationMailer < ActionMailer::Base
-
# default from: 'from@exmaple.com'
-
# layout 'mailer'
-
# end
-
#
-
# class Notifier < ApplicationMailer
-
# default from: 'no-reply@example.com',
-
# return_path: 'system@example.com'
-
#
-
# def welcome(recipient)
-
# @account = recipient
-
# mail(to: recipient.email_address_with_name,
-
# bcc: ["bcc@example.com", "Order Watcher <watcher@example.com>"])
-
# end
-
# end
-
#
-
# Within the mailer method, you have access to the following methods:
-
#
-
# * <tt>attachments[]=</tt> - Allows you to add attachments to your email in an intuitive
-
# manner; <tt>attachments['filename.png'] = File.read('path/to/filename.png')</tt>
-
#
-
# * <tt>attachments.inline[]=</tt> - Allows you to add an inline attachment to your email
-
# in the same manner as <tt>attachments[]=</tt>
-
#
-
# * <tt>headers[]=</tt> - Allows you to specify any header field in your email such
-
# as <tt>headers['X-No-Spam'] = 'True'</tt>. Note that declaring a header multiple times
-
# will add many fields of the same name. Read #headers doc for more information.
-
#
-
# * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such
-
# as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt>
-
#
-
# * <tt>mail</tt> - Allows you to specify email to be sent.
-
#
-
# The hash passed to the mail method allows you to specify any header that a <tt>Mail::Message</tt>
-
# will accept (any valid email header including optional fields).
-
#
-
# The mail method, if not passed a block, will inspect your views and send all the views with
-
# the same name as the method, so the above action would send the +welcome.text.erb+ view
-
# file as well as the +welcome.html.erb+ view file in a +multipart/alternative+ email.
-
#
-
# If you want to explicitly render only certain templates, pass a block:
-
#
-
# mail(to: user.email) do |format|
-
# format.text
-
# format.html
-
# end
-
#
-
# The block syntax is also useful in providing information specific to a part:
-
#
-
# mail(to: user.email) do |format|
-
# format.text(content_transfer_encoding: "base64")
-
# format.html
-
# end
-
#
-
# Or even to render a special view:
-
#
-
# mail(to: user.email) do |format|
-
# format.text
-
# format.html { render "some_other_template" }
-
# end
-
#
-
# = Mailer views
-
#
-
# Like Action Controller, each mailer class has a corresponding view directory in which each
-
# method of the class looks for a template with its name.
-
#
-
# To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same
-
# name as the method in your mailer model. For example, in the mailer defined above, the template at
-
# <tt>app/views/notifier/welcome.text.erb</tt> would be used to generate the email.
-
#
-
# Variables defined in the methods of your mailer model are accessible as instance variables in their
-
# corresponding view.
-
#
-
# Emails by default are sent in plain text, so a sample view for our model example might look like this:
-
#
-
# Hi <%= @account.name %>,
-
# Thanks for joining our service! Please check back often.
-
#
-
# You can even use Action View helpers in these views. For example:
-
#
-
# You got a new note!
-
# <%= truncate(@note.body, length: 25) %>
-
#
-
# If you need to access the subject, from or the recipients in the view, you can do that through message object:
-
#
-
# You got a new note from <%= message.from %>!
-
# <%= truncate(@note.body, length: 25) %>
-
#
-
#
-
# = Generating URLs
-
#
-
# URLs can be generated in mailer views using <tt>url_for</tt> or named routes. Unlike controllers from
-
# Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need
-
# to provide all of the details needed to generate a URL.
-
#
-
# When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
-
#
-
# <%= url_for(host: "example.com", controller: "welcome", action: "greeting") %>
-
#
-
# When using named routes you only need to supply the <tt>:host</tt>:
-
#
-
# <%= users_url(host: "example.com") %>
-
#
-
# You should use the <tt>named_route_url</tt> style (which generates absolute URLs) and avoid using the
-
# <tt>named_route_path</tt> style (which generates relative URLs), since clients reading the mail will
-
# have no concept of a current URL from which to determine a relative path.
-
#
-
# It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt>
-
# option as a configuration option in <tt>config/application.rb</tt>:
-
#
-
# config.action_mailer.default_url_options = { host: "example.com" }
-
#
-
# When you decide to set a default <tt>:host</tt> for your mailers, then you need to make sure to use the
-
# <tt>only_path: false</tt> option when using <tt>url_for</tt>. Since the <tt>url_for</tt> view helper
-
# will generate relative URLs by default when a <tt>:host</tt> option isn't explicitly provided, passing
-
# <tt>only_path: false</tt> will ensure that absolute URLs are generated.
-
#
-
# = Sending mail
-
#
-
# Once a mailer action and template are defined, you can deliver your message or create it and save it
-
# for delivery later:
-
#
-
# Notifier.welcome(User.first).deliver_now # sends the email
-
# mail = Notifier.welcome(User.first) # => an ActionMailer::MessageDelivery object
-
# mail.deliver_now # sends the email
-
#
-
# The <tt>ActionMailer::MessageDelivery</tt> class is a wrapper around a <tt>Mail::Message</tt> object. If
-
# you want direct access to the <tt>Mail::Message</tt> object you can call the <tt>message</tt> method on
-
# the <tt>ActionMailer::MessageDelivery</tt> object.
-
#
-
# Notifier.welcome(User.first).message # => a Mail::Message object
-
#
-
# Action Mailer is nicely integrated with Active Job so you can send emails in the background (example: outside
-
# of the request-response cycle, so the user doesn't have to wait on it):
-
#
-
# Notifier.welcome(User.first).deliver_later # enqueue the email sending to Active Job
-
#
-
# You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
-
#
-
# = Multipart Emails
-
#
-
# Multipart messages can also be used implicitly because Action Mailer will automatically detect and use
-
# multipart templates, where each template is named after the name of the action, followed by the content
-
# type. Each such detected template will be added as a separate part to the message.
-
#
-
# For example, if the following templates exist:
-
# * signup_notification.text.erb
-
# * signup_notification.html.erb
-
# * signup_notification.xml.builder
-
# * signup_notification.yml.erb
-
#
-
# Each would be rendered and added as a separate part to the message, with the corresponding content
-
# type. The content type for the entire message is automatically set to <tt>multipart/alternative</tt>,
-
# which indicates that the email contains multiple different representations of the same email
-
# body. The same instance variables defined in the action are passed to all email templates.
-
#
-
# Implicit template rendering is not performed if any attachments or parts have been added to the email.
-
# This means that you'll have to manually add each part to the email and set the content type of the email
-
# to <tt>multipart/alternative</tt>.
-
#
-
# = Attachments
-
#
-
# Sending attachment in emails is easy:
-
#
-
# class Notifier < ApplicationMailer
-
# def welcome(recipient)
-
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
-
# mail(to: recipient, subject: "New account information")
-
# end
-
# end
-
#
-
# Which will (if it had both a <tt>welcome.text.erb</tt> and <tt>welcome.html.erb</tt>
-
# template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts,
-
# the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside,
-
# and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book
-
# with the filename +free_book.pdf+.
-
#
-
# If you need to send attachments with no content, you need to create an empty view for it,
-
# or add an empty body parameter like this:
-
#
-
# class Notifier < ApplicationMailer
-
# def welcome(recipient)
-
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
-
# mail(to: recipient, subject: "New account information", body: "")
-
# end
-
# end
-
#
-
# = Inline Attachments
-
#
-
# You can also specify that a file should be displayed inline with other HTML. This is useful
-
# if you want to display a corporate logo or a photo.
-
#
-
# class Notifier < ApplicationMailer
-
# def welcome(recipient)
-
# attachments.inline['photo.png'] = File.read('path/to/photo.png')
-
# mail(to: recipient, subject: "Here is what we look like")
-
# end
-
# end
-
#
-
# And then to reference the image in the view, you create a <tt>welcome.html.erb</tt> file and
-
# make a call to +image_tag+ passing in the attachment you want to display and then call
-
# +url+ on the attachment to get the relative content id path for the image source:
-
#
-
# <h1>Please Don't Cringe</h1>
-
#
-
# <%= image_tag attachments['photo.png'].url -%>
-
#
-
# As we are using Action View's +image_tag+ method, you can pass in any other options you want:
-
#
-
# <h1>Please Don't Cringe</h1>
-
#
-
# <%= image_tag attachments['photo.png'].url, alt: 'Our Photo', class: 'photo' -%>
-
#
-
# = Observing and Intercepting Mails
-
#
-
# Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
-
# register classes that are called during the mail delivery life cycle.
-
#
-
# An observer class must implement the <tt>:delivered_email(message)</tt> method which will be
-
# called once for every email sent after the email has been sent.
-
#
-
# An interceptor class must implement the <tt>:delivering_email(message)</tt> method which will be
-
# called before the email is sent, allowing you to make modifications to the email before it hits
-
# the delivery agents. Your class should make any needed modifications directly to the passed
-
# in <tt>Mail::Message</tt> instance.
-
#
-
# = Default Hash
-
#
-
# Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
-
# default method inside the class definition:
-
#
-
# class Notifier < ApplicationMailer
-
# default sender: 'system@example.com'
-
# end
-
#
-
# You can pass in any header value that a <tt>Mail::Message</tt> accepts. Out of the box,
-
# <tt>ActionMailer::Base</tt> sets the following:
-
#
-
# * <tt>mime_version: "1.0"</tt>
-
# * <tt>charset: "UTF-8",</tt>
-
# * <tt>content_type: "text/plain",</tt>
-
# * <tt>parts_order: [ "text/plain", "text/enriched", "text/html" ]</tt>
-
#
-
# <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields,
-
# but Action Mailer translates them appropriately and sets the correct values.
-
#
-
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
-
# an underscored symbol, so the following will work:
-
#
-
# class Notifier < ApplicationMailer
-
# default 'Content-Transfer-Encoding' => '7bit',
-
# content_description: 'This is a description'
-
# end
-
#
-
# Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you
-
# can define methods that evaluate as the message is being generated:
-
#
-
# class Notifier < ApplicationMailer
-
# default 'X-Special-Header' => Proc.new { my_method }
-
#
-
# private
-
#
-
# def my_method
-
# 'some complex call'
-
# end
-
# end
-
#
-
# Note that the proc is evaluated right at the start of the mail message generation, so if you
-
# set something in the defaults using a proc, and then set the same thing inside of your
-
# mailer method, it will get over written by the mailer method.
-
#
-
# It is also possible to set these default options that will be used in all mailers through
-
# the <tt>default_options=</tt> configuration in <tt>config/application.rb</tt>:
-
#
-
# config.action_mailer.default_options = { from: "no-reply@example.org" }
-
#
-
# = Callbacks
-
#
-
# You can specify callbacks using before_action and after_action for configuring your messages.
-
# This may be useful, for example, when you want to add default inline attachments for all
-
# messages sent out by a certain mailer class:
-
#
-
# class Notifier < ApplicationMailer
-
# before_action :add_inline_attachment!
-
#
-
# def welcome
-
# mail
-
# end
-
#
-
# private
-
#
-
# def add_inline_attachment!
-
# attachments.inline["footer.jpg"] = File.read('/path/to/filename.jpg')
-
# end
-
# end
-
#
-
# Callbacks in Action Mailer are implemented using
-
# <tt>AbstractController::Callbacks</tt>, so you can define and configure
-
# callbacks in the same manner that you would use callbacks in classes that
-
# inherit from <tt>ActionController::Base</tt>.
-
#
-
# Note that unless you have a specific reason to do so, you should prefer using before_action
-
# rather than after_action in your Action Mailer classes so that headers are parsed properly.
-
#
-
# = Previewing emails
-
#
-
# You can preview your email templates visually by adding a mailer preview file to the
-
# <tt>ActionMailer::Base.preview_path</tt>. Since most emails do something interesting
-
# with database data, you'll need to write some scenarios to load messages with fake data:
-
#
-
# class NotifierPreview < ActionMailer::Preview
-
# def welcome
-
# Notifier.welcome(User.first)
-
# end
-
# end
-
#
-
# Methods must return a <tt>Mail::Message</tt> object which can be generated by calling the mailer
-
# method without the additional <tt>deliver_now</tt> / <tt>deliver_later</tt>. The location of the
-
# mailer previews directory can be configured using the <tt>preview_path</tt> option which has a default
-
# of <tt>test/mailers/previews</tt>:
-
#
-
# config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews"
-
#
-
# An overview of all previews is accessible at <tt>http://localhost:3000/rails/mailers</tt>
-
# on a running development server instance.
-
#
-
# Previews can also be intercepted in a similar manner as deliveries can be by registering
-
# a preview interceptor that has a <tt>previewing_email</tt> method:
-
#
-
# class CssInlineStyler
-
# def self.previewing_email(message)
-
# # inline CSS styles
-
# end
-
# end
-
#
-
# config.action_mailer.preview_interceptors :css_inline_styler
-
#
-
# Note that interceptors need to be registered both with <tt>register_interceptor</tt>
-
# and <tt>register_preview_interceptor</tt> if they should operate on both sending and
-
# previewing emails.
-
#
-
# = Configuration options
-
#
-
# These options are specified on the class level, like
-
# <tt>ActionMailer::Base.raise_delivery_errors = true</tt>
-
#
-
# * <tt>default_options</tt> - You can pass this in at a class level as well as within the class itself as
-
# per the above section.
-
#
-
# * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
-
# Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and Log4r loggers.
-
#
-
# * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
-
# * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default
-
# "localhost" setting.
-
# * <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
-
# * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
-
# * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
-
# * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
-
# * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the
-
# authentication type here.
-
# This is a symbol and one of <tt>:plain</tt> (will send the password Base64 encoded), <tt>:login</tt> (will
-
# send the password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange
-
# information and a cryptographic Message Digest 5 algorithm to hash important information)
-
# * <tt>:enable_starttls_auto</tt> - Detects if STARTTLS is enabled in your SMTP server and starts
-
# to use it. Defaults to <tt>true</tt>.
-
# * <tt>:openssl_verify_mode</tt> - When using TLS, you can set how OpenSSL checks the certificate. This is
-
# really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name
-
# of an OpenSSL verify constant (<tt>'none'</tt>, <tt>'peer'</tt>, <tt>'client_once'</tt>,
-
# <tt>'fail_if_no_peer_cert'</tt>) or directly the constant (<tt>OpenSSL::SSL::VERIFY_NONE</tt>,
-
# <tt>OpenSSL::SSL::VERIFY_PEER</tt>, ...).
-
#
-
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
-
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
-
# * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@address</tt>
-
# added automatically before the message is sent.
-
#
-
# * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
-
# * <tt>:location</tt> - The directory into which emails will be written. Defaults to the application
-
# <tt>tmp/mails</tt>.
-
#
-
# * <tt>raise_delivery_errors</tt> - Whether or not errors should be raised if the email fails to be delivered.
-
#
-
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default),
-
# <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method
-
# object e.g. +MyOwnDeliveryMethodClass+. See the Mail gem documentation on the interface you need to
-
# implement for a custom delivery agent.
-
#
-
# * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you
-
# call <tt>.deliver</tt> on an email message or on an Action Mailer method. This is on by default but can
-
# be turned off to aid in functional testing.
-
#
-
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with
-
# <tt>delivery_method :test</tt>. Most useful for unit and functional testing.
-
1
class Base < AbstractController::Base
-
1
include DeliveryMethods
-
1
include Previews
-
-
1
abstract!
-
-
1
include AbstractController::Rendering
-
-
1
include AbstractController::Logger
-
1
include AbstractController::Helpers
-
1
include AbstractController::Translation
-
1
include AbstractController::AssetPaths
-
1
include AbstractController::Callbacks
-
-
1
include ActionView::Layouts
-
-
1
PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [:@_action_has_layout]
-
-
1
def _protected_ivars # :nodoc:
-
PROTECTED_IVARS
-
end
-
-
1
helper ActionMailer::MailHelper
-
-
1
private_class_method :new #:nodoc:
-
-
1
class_attribute :default_params
-
1
self.default_params = {
-
mime_version: "1.0",
-
charset: "UTF-8",
-
content_type: "text/plain",
-
parts_order: [ "text/plain", "text/enriched", "text/html" ]
-
}.freeze
-
-
1
class << self
-
# Register one or more Observers which will be notified when mail is delivered.
-
1
def register_observers(*observers)
-
1
observers.flatten.compact.each { |observer| register_observer(observer) }
-
end
-
-
# Register one or more Interceptors which will be called before mail is sent.
-
1
def register_interceptors(*interceptors)
-
1
interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }
-
end
-
-
# Register an Observer which will be notified when mail is delivered.
-
# Either a class, string or symbol can be passed in as the Observer.
-
# If a string or symbol is passed in it will be camelized and constantized.
-
1
def register_observer(observer)
-
delivery_observer = case observer
-
when String, Symbol
-
observer.to_s.camelize.constantize
-
else
-
observer
-
end
-
-
Mail.register_observer(delivery_observer)
-
end
-
-
# Register an Interceptor which will be called before mail is sent.
-
# Either a class, string or symbol can be passed in as the Interceptor.
-
# If a string or symbol is passed in it will be camelized and constantized.
-
1
def register_interceptor(interceptor)
-
delivery_interceptor = case interceptor
-
when String, Symbol
-
interceptor.to_s.camelize.constantize
-
else
-
interceptor
-
end
-
-
Mail.register_interceptor(delivery_interceptor)
-
end
-
-
# Returns the name of current mailer. This method is also being used as a path for a view lookup.
-
# If this is an anonymous mailer, this method will return +anonymous+ instead.
-
1
def mailer_name
-
@mailer_name ||= anonymous? ? "anonymous" : name.underscore
-
end
-
# Allows to set the name of current mailer.
-
1
attr_writer :mailer_name
-
1
alias :controller_path :mailer_name
-
-
# Sets the defaults through app configuration:
-
#
-
# config.action_mailer.default(from: "no-reply@example.org")
-
#
-
# Aliased by ::default_options=
-
1
def default(value = nil)
-
self.default_params = default_params.merge(value).freeze if value
-
default_params
-
end
-
# Allows to set defaults through app configuration:
-
#
-
# config.action_mailer.default_options = { from: "no-reply@example.org" }
-
1
alias :default_options= :default
-
-
# Receives a raw email, parses it into an email object, decodes it,
-
# instantiates a new mailer, and passes the email object to the mailer
-
# object's +receive+ method.
-
#
-
# If you want your mailer to be able to process incoming messages, you'll
-
# need to implement a +receive+ method that accepts the raw email string
-
# as a parameter:
-
#
-
# class MyMailer < ActionMailer::Base
-
# def receive(mail)
-
# # ...
-
# end
-
# end
-
1
def receive(raw_mail)
-
ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
-
mail = Mail.new(raw_mail)
-
set_payload_for_mail(payload, mail)
-
new.receive(mail)
-
end
-
end
-
-
# Wraps an email delivery inside of <tt>ActiveSupport::Notifications</tt> instrumentation.
-
#
-
# This method is actually called by the <tt>Mail::Message</tt> object itself
-
# through a callback when you call <tt>:deliver</tt> on the <tt>Mail::Message</tt>,
-
# calling +deliver_mail+ directly and passing a <tt>Mail::Message</tt> will do
-
# nothing except tell the logger you sent the email.
-
1
def deliver_mail(mail) #:nodoc:
-
ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload|
-
set_payload_for_mail(payload, mail)
-
yield # Let Mail do the delivery actions
-
end
-
end
-
-
1
def respond_to?(method, include_private = false) #:nodoc:
-
3
super || action_methods.include?(method.to_s)
-
end
-
-
1
protected
-
-
1
def set_payload_for_mail(payload, mail) #:nodoc:
-
payload[:mailer] = name
-
payload[:message_id] = mail.message_id
-
payload[:subject] = mail.subject
-
payload[:to] = mail.to
-
payload[:from] = mail.from
-
payload[:bcc] = mail.bcc if mail.bcc.present?
-
payload[:cc] = mail.cc if mail.cc.present?
-
payload[:date] = mail.date
-
payload[:mail] = mail.encoded
-
end
-
-
1
def method_missing(method_name, *args) # :nodoc:
-
if action_methods.include?(method_name.to_s)
-
MessageDelivery.new(self, method_name, *args)
-
else
-
super
-
end
-
end
-
end
-
-
1
attr_internal :message
-
-
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
-
# will be initialized according to the named method. If not, the mailer will
-
# remain uninitialized (useful when you only need to invoke the "receive"
-
# method, for instance).
-
1
def initialize(method_name=nil, *args)
-
super()
-
@_mail_was_called = false
-
@_message = Mail.new
-
process(method_name, *args) if method_name
-
end
-
-
1
def process(method_name, *args) #:nodoc:
-
payload = {
-
mailer: self.class.name,
-
action: method_name
-
}
-
-
ActiveSupport::Notifications.instrument("process.action_mailer", payload) do
-
lookup_context.skip_default_locale!
-
-
super
-
@_message = NullMail.new unless @_mail_was_called
-
end
-
end
-
-
1
class NullMail #:nodoc:
-
1
def body; '' end
-
1
def header; {} end
-
-
1
def respond_to?(string, include_all=false)
-
true
-
end
-
-
1
def method_missing(*args)
-
nil
-
end
-
end
-
-
# Returns the name of the mailer object.
-
1
def mailer_name
-
self.class.mailer_name
-
end
-
-
# Allows you to pass random and unusual headers to the new <tt>Mail::Message</tt>
-
# object which will add them to itself.
-
#
-
# headers['X-Special-Domain-Specific-Header'] = "SecretValue"
-
#
-
# You can also pass a hash into headers of header field names and values,
-
# which will then be set on the <tt>Mail::Message</tt> object:
-
#
-
# headers 'X-Special-Domain-Specific-Header' => "SecretValue",
-
# 'In-Reply-To' => incoming.message_id
-
#
-
# The resulting <tt>Mail::Message</tt> will have the following in its header:
-
#
-
# X-Special-Domain-Specific-Header: SecretValue
-
#
-
# Note about replacing already defined headers:
-
#
-
# * +subject+
-
# * +sender+
-
# * +from+
-
# * +to+
-
# * +cc+
-
# * +bcc+
-
# * +reply-to+
-
# * +orig-date+
-
# * +message-id+
-
# * +references+
-
#
-
# Fields can only appear once in email headers while other fields such as
-
# <tt>X-Anything</tt> can appear multiple times.
-
#
-
# If you want to replace any header which already exists, first set it to
-
# +nil+ in order to reset the value otherwise another field will be added
-
# for the same header.
-
1
def headers(args = nil)
-
if args
-
@_message.headers(args)
-
else
-
@_message
-
end
-
end
-
-
# Allows you to add attachments to an email, like so:
-
#
-
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
-
#
-
# If you do this, then Mail will take the file name and work out the mime type
-
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
-
# base64 encode the contents of the attachment all for you.
-
#
-
# You can also specify overrides if you want by passing a hash instead of a string:
-
#
-
# mail.attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
-
# content: File.read('/path/to/filename.jpg')}
-
#
-
# If you want to use a different encoding than Base64, you can pass an encoding in,
-
# but then it is up to you to pass in the content pre-encoded, and don't expect
-
# Mail to know how to decode this data:
-
#
-
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
-
# mail.attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
-
# encoding: 'SpecialEncoding',
-
# content: file_content }
-
#
-
# You can also search for specific attachments:
-
#
-
# # By Filename
-
# mail.attachments['filename.jpg'] # => Mail::Part object or nil
-
#
-
# # or by index
-
# mail.attachments[0] # => Mail::Part (first attachment)
-
#
-
1
def attachments
-
if @_mail_was_called
-
LateAttachmentsProxy.new(@_message.attachments)
-
else
-
@_message.attachments
-
end
-
end
-
-
1
class LateAttachmentsProxy < SimpleDelegator
-
1
def inline; _raise_error end
-
1
def []=(_name, _content); _raise_error end
-
-
1
private
-
1
def _raise_error
-
raise RuntimeError, "Can't add attachments after `mail` was called.\n" \
-
"Make sure to use `attachments[]=` before calling `mail`."
-
end
-
end
-
-
# The main method that creates the message and renders the email templates. There are
-
# two ways to call this method, with a block, or without a block.
-
#
-
# It accepts a headers hash. This hash allows you to specify
-
# the most used headers in an email message, these are:
-
#
-
# * +:subject+ - The subject of the message, if this is omitted, Action Mailer will
-
# ask the Rails I18n class for a translated +:subject+ in the scope of
-
# <tt>[mailer_scope, action_name]</tt> or if this is missing, will translate the
-
# humanized version of the +action_name+
-
# * +:to+ - Who the message is destined for, can be a string of addresses, or an array
-
# of addresses.
-
# * +:from+ - Who the message is from
-
# * +:cc+ - Who you would like to Carbon-Copy on this email, can be a string of addresses,
-
# or an array of addresses.
-
# * +:bcc+ - Who you would like to Blind-Carbon-Copy on this email, can be a string of
-
# addresses, or an array of addresses.
-
# * +:reply_to+ - Who to set the Reply-To header of the email to.
-
# * +:date+ - The date to say the email was sent on.
-
#
-
# You can set default values for any of the above headers (except +:date+)
-
# by using the ::default class method:
-
#
-
# class Notifier < ActionMailer::Base
-
# default from: 'no-reply@test.lindsaar.net',
-
# bcc: 'email_logger@test.lindsaar.net',
-
# reply_to: 'bounces@test.lindsaar.net'
-
# end
-
#
-
# If you need other headers not listed above, you can either pass them in
-
# as part of the headers hash or use the <tt>headers['name'] = value</tt>
-
# method.
-
#
-
# When a +:return_path+ is specified as header, that value will be used as
-
# the 'envelope from' address for the Mail message. Setting this is useful
-
# when you want delivery notifications sent to a different address than the
-
# one in +:from+. Mail will actually use the +:return_path+ in preference
-
# to the +:sender+ in preference to the +:from+ field for the 'envelope
-
# from' value.
-
#
-
# If you do not pass a block to the +mail+ method, it will find all
-
# templates in the view paths using by default the mailer name and the
-
# method name that it is being called from, it will then create parts for
-
# each of these templates intelligently, making educated guesses on correct
-
# content type and sequence, and return a fully prepared <tt>Mail::Message</tt>
-
# ready to call <tt>:deliver</tt> on to send.
-
#
-
# For example:
-
#
-
# class Notifier < ActionMailer::Base
-
# default from: 'no-reply@test.lindsaar.net'
-
#
-
# def welcome
-
# mail(to: 'mikel@test.lindsaar.net')
-
# end
-
# end
-
#
-
# Will look for all templates at "app/views/notifier" with name "welcome".
-
# If no welcome template exists, it will raise an ActionView::MissingTemplate error.
-
#
-
# However, those can be customized:
-
#
-
# mail(template_path: 'notifications', template_name: 'another')
-
#
-
# And now it will look for all templates at "app/views/notifications" with name "another".
-
#
-
# If you do pass a block, you can render specific templates of your choice:
-
#
-
# mail(to: 'mikel@test.lindsaar.net') do |format|
-
# format.text
-
# format.html
-
# end
-
#
-
# You can even render plain text directly without using a template:
-
#
-
# mail(to: 'mikel@test.lindsaar.net') do |format|
-
# format.text { render plain: "Hello Mikel!" }
-
# format.html { render html: "<h1>Hello Mikel!</h1>".html_safe }
-
# end
-
#
-
# Which will render a +multipart/alternative+ email with +text/plain+ and
-
# +text/html+ parts.
-
#
-
# The block syntax also allows you to customize the part headers if desired:
-
#
-
# mail(to: 'mikel@test.lindsaar.net') do |format|
-
# format.text(content_transfer_encoding: "base64")
-
# format.html
-
# end
-
#
-
1
def mail(headers = {}, &block)
-
return @_message if @_mail_was_called && headers.blank? && !block
-
-
m = @_message
-
-
# At the beginning, do not consider class default for content_type
-
content_type = headers[:content_type]
-
-
# Call all the procs (if any)
-
default_values = {}
-
self.class.default.each do |k,v|
-
default_values[k] = v.is_a?(Proc) ? instance_eval(&v) : v
-
end
-
-
# Handle defaults
-
headers = headers.reverse_merge(default_values)
-
headers[:subject] ||= default_i18n_subject
-
-
# Apply charset at the beginning so all fields are properly quoted
-
m.charset = charset = headers[:charset]
-
-
# Set configure delivery behavior
-
wrap_delivery_behavior!(headers.delete(:delivery_method), headers.delete(:delivery_method_options))
-
-
# Assign all headers except parts_order, content_type and body
-
assignable = headers.except(:parts_order, :content_type, :body, :template_name, :template_path)
-
assignable.each { |k, v| m[k] = v }
-
-
# Render the templates and blocks
-
responses = collect_responses(headers, &block)
-
@_mail_was_called = true
-
-
create_parts_from_responses(m, responses)
-
-
# Setup content type, reapply charset and handle parts order
-
m.content_type = set_content_type(m, content_type, headers[:content_type])
-
m.charset = charset
-
-
if m.multipart?
-
m.body.set_sort_order(headers[:parts_order])
-
m.body.sort_parts!
-
end
-
-
m
-
end
-
-
1
protected
-
-
# Used by #mail to set the content type of the message.
-
#
-
# It will use the given +user_content_type+, or multipart if the mail
-
# message has any attachments. If the attachments are inline, the content
-
# type will be "multipart/related", otherwise "multipart/mixed".
-
#
-
# If there is no content type passed in via headers, and there are no
-
# attachments, or the message is multipart, then the default content type is
-
# used.
-
1
def set_content_type(m, user_content_type, class_default)
-
params = m.content_type_parameters || {}
-
case
-
when user_content_type.present?
-
user_content_type
-
when m.has_attachments?
-
if m.attachments.detect { |a| a.inline? }
-
["multipart", "related", params]
-
else
-
["multipart", "mixed", params]
-
end
-
when m.multipart?
-
["multipart", "alternative", params]
-
else
-
m.content_type || class_default
-
end
-
end
-
-
# Translates the +subject+ using Rails I18n class under <tt>[mailer_scope, action_name]</tt> scope.
-
# If it does not find a translation for the +subject+ under the specified scope it will default to a
-
# humanized version of the <tt>action_name</tt>.
-
# If the subject has interpolations, you can pass them through the +interpolations+ parameter.
-
1
def default_i18n_subject(interpolations = {})
-
mailer_scope = self.class.mailer_name.tr('/', '.')
-
I18n.t(:subject, interpolations.merge(scope: [mailer_scope, action_name], default: action_name.humanize))
-
end
-
-
1
def collect_responses(headers) #:nodoc:
-
responses = []
-
-
if block_given?
-
collector = ActionMailer::Collector.new(lookup_context) { render(action_name) }
-
yield(collector)
-
responses = collector.responses
-
elsif headers[:body]
-
responses << {
-
body: headers.delete(:body),
-
content_type: self.class.default[:content_type] || "text/plain"
-
}
-
else
-
templates_path = headers.delete(:template_path) || self.class.mailer_name
-
templates_name = headers.delete(:template_name) || action_name
-
-
each_template(Array(templates_path), templates_name) do |template|
-
self.formats = template.formats
-
-
responses << {
-
body: render(template: template),
-
content_type: template.type.to_s
-
}
-
end
-
end
-
-
responses
-
end
-
-
1
def each_template(paths, name, &block) #:nodoc:
-
templates = lookup_context.find_all(name, paths)
-
if templates.empty?
-
raise ActionView::MissingTemplate.new(paths, name, paths, false, 'mailer')
-
else
-
templates.uniq { |t| t.formats }.each(&block)
-
end
-
end
-
-
1
def create_parts_from_responses(m, responses) #:nodoc:
-
if responses.size == 1 && !m.has_attachments?
-
responses[0].each { |k,v| m[k] = v }
-
elsif responses.size > 1 && m.has_attachments?
-
container = Mail::Part.new
-
container.content_type = "multipart/alternative"
-
responses.each { |r| insert_part(container, r, m.charset) }
-
m.add_part(container)
-
else
-
responses.each { |r| insert_part(m, r, m.charset) }
-
end
-
end
-
-
1
def insert_part(container, response, charset) #:nodoc:
-
response[:charset] ||= charset
-
part = Mail::Part.new(response)
-
container.add_part(part)
-
end
-
-
# Emails do not support relative path links.
-
1
def self.supports_path?
-
false
-
end
-
-
1
ActiveSupport.run_load_hooks(:action_mailer, self)
-
end
-
end
-
1
require 'abstract_controller/collector'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActionMailer
-
1
class Collector
-
1
include AbstractController::Collector
-
1
attr_reader :responses
-
-
1
def initialize(context, &block)
-
@context = context
-
@responses = []
-
@default_render = block
-
end
-
-
1
def any(*args, &block)
-
options = args.extract_options!
-
raise ArgumentError, "You have to supply at least one format" if args.empty?
-
args.each { |type| send(type, options.dup, &block) }
-
end
-
1
alias :all :any
-
-
1
def custom(mime, options = {})
-
options.reverse_merge!(content_type: mime.to_s)
-
@context.formats = [mime.to_sym]
-
options[:body] = block_given? ? yield : @default_render.call
-
@responses << options
-
end
-
end
-
end
-
1
require 'tmpdir'
-
-
1
module ActionMailer
-
# This module handles everything related to mail delivery, from registering
-
# new delivery methods to configuring the mail object to be sent.
-
1
module DeliveryMethods
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :delivery_methods, :delivery_method
-
-
# Do not make this inheritable, because we always want it to propagate
-
1
cattr_accessor :raise_delivery_errors
-
1
self.raise_delivery_errors = true
-
-
1
cattr_accessor :perform_deliveries
-
1
self.perform_deliveries = true
-
-
1
self.delivery_methods = {}.freeze
-
1
self.delivery_method = :smtp
-
-
1
add_delivery_method :smtp, Mail::SMTP,
-
address: "localhost",
-
port: 25,
-
domain: 'localhost.localdomain',
-
user_name: nil,
-
password: nil,
-
authentication: nil,
-
enable_starttls_auto: true
-
-
1
add_delivery_method :file, Mail::FileDelivery,
-
location: defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
-
-
1
add_delivery_method :sendmail, Mail::Sendmail,
-
location: '/usr/sbin/sendmail',
-
arguments: '-i -t'
-
-
1
add_delivery_method :test, Mail::TestMailer
-
end
-
-
# Helpers for creating and wrapping delivery behavior, used by DeliveryMethods.
-
1
module ClassMethods
-
# Provides a list of emails that have been delivered by Mail::TestMailer
-
1
delegate :deliveries, :deliveries=, to: Mail::TestMailer
-
-
# Adds a new delivery method through the given class using the given
-
# symbol as alias and the default options supplied.
-
#
-
# add_delivery_method :sendmail, Mail::Sendmail,
-
# location: '/usr/sbin/sendmail',
-
# arguments: '-i -t'
-
1
def add_delivery_method(symbol, klass, default_options={})
-
4
class_attribute(:"#{symbol}_settings") unless respond_to?(:"#{symbol}_settings")
-
4
send(:"#{symbol}_settings=", default_options)
-
4
self.delivery_methods = delivery_methods.merge(symbol.to_sym => klass).freeze
-
end
-
-
1
def wrap_delivery_behavior(mail, method=nil, options=nil) # :nodoc:
-
method ||= self.delivery_method
-
mail.delivery_handler = self
-
-
case method
-
when NilClass
-
raise "Delivery method cannot be nil"
-
when Symbol
-
if klass = delivery_methods[method]
-
mail.delivery_method(klass, (send(:"#{method}_settings") || {}).merge(options || {}))
-
else
-
raise "Invalid delivery method #{method.inspect}"
-
end
-
else
-
mail.delivery_method(method)
-
end
-
-
mail.perform_deliveries = perform_deliveries
-
mail.raise_delivery_errors = raise_delivery_errors
-
end
-
end
-
-
1
def wrap_delivery_behavior!(*args) # :nodoc:
-
self.class.wrap_delivery_behavior(message, *args)
-
end
-
end
-
end
-
1
module ActionMailer
-
# Returns the version of the currently loaded Action Mailer as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 2
-
1
TINY = 5
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'active_support/log_subscriber'
-
-
1
module ActionMailer
-
# Implements the ActiveSupport::LogSubscriber for logging notifications when
-
# email is delivered and received.
-
1
class LogSubscriber < ActiveSupport::LogSubscriber
-
# An email was delivered.
-
1
def deliver(event)
-
info do
-
recipients = Array(event.payload[:to]).join(', ')
-
"\nSent mail to #{recipients} (#{event.duration.round(1)}ms)"
-
end
-
-
debug { event.payload[:mail] }
-
end
-
-
# An email was received.
-
1
def receive(event)
-
info { "\nReceived mail (#{event.duration.round(1)}ms)" }
-
debug { event.payload[:mail] }
-
end
-
-
# An email was generated.
-
1
def process(event)
-
debug do
-
mailer = event.payload[:mailer]
-
action = event.payload[:action]
-
"\n#{mailer}##{action}: processed outbound mail in #{event.duration.round(1)}ms"
-
end
-
end
-
-
# Use the logger configured for ActionMailer::Base
-
1
def logger
-
ActionMailer::Base.logger
-
end
-
end
-
end
-
-
1
ActionMailer::LogSubscriber.attach_to :action_mailer
-
1
module ActionMailer
-
# Provides helper methods for ActionMailer::Base that can be used for easily
-
# formatting messages, accessing mailer or message instances, and the
-
# attachments list.
-
1
module MailHelper
-
# Take the text and format it, indented two spaces for each line, and
-
# wrapped at 72 columns.
-
1
def block_format(text)
-
formatted = text.split(/\n\r?\n/).collect { |paragraph|
-
format_paragraph(paragraph)
-
}.join("\n\n")
-
-
# Make list points stand on their own line
-
formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { " #{$1} #{$2.strip}\n" }
-
formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { " #{$1} #{$2.strip}\n" }
-
-
formatted
-
end
-
-
# Access the mailer instance.
-
1
def mailer
-
@_controller
-
end
-
-
# Access the message instance.
-
1
def message
-
@_message
-
end
-
-
# Access the message attachments list.
-
1
def attachments
-
mailer.attachments
-
end
-
-
# Returns +text+ wrapped at +len+ columns and indented +indent+ spaces.
-
#
-
# my_text = 'Here is a sample text with more than 40 characters'
-
#
-
# format_paragraph(my_text, 25, 4)
-
# # => " Here is a sample text with\n more than 40 characters"
-
1
def format_paragraph(text, len = 72, indent = 2)
-
sentences = [[]]
-
-
text.split.each do |word|
-
if sentences.first.present? && (sentences.last + [word]).join(' ').length > len
-
sentences << [word]
-
else
-
sentences.last << word
-
end
-
end
-
-
indentation = " " * indent
-
sentences.map! { |sentence|
-
"#{indentation}#{sentence.join(' ')}"
-
}.join "\n"
-
end
-
end
-
end
-
1
require 'active_job/railtie'
-
1
require "action_mailer"
-
1
require "rails"
-
1
require "abstract_controller/railties/routes_helpers"
-
-
1
module ActionMailer
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.action_mailer = ActiveSupport::OrderedOptions.new
-
1
config.eager_load_namespaces << ActionMailer
-
-
1
initializer "action_mailer.logger" do
-
2
ActiveSupport.on_load(:action_mailer) { self.logger ||= Rails.logger }
-
end
-
-
1
initializer "action_mailer.set_configs" do |app|
-
1
paths = app.config.paths
-
1
options = app.config.action_mailer
-
-
1
options.assets_dir ||= paths["public"].first
-
1
options.javascripts_dir ||= paths["public/javascripts"].first
-
1
options.stylesheets_dir ||= paths["public/stylesheets"].first
-
1
options.show_previews = Rails.env.development? if options.show_previews.nil?
-
-
1
if options.show_previews
-
options.preview_path ||= defined?(Rails.root) ? "#{Rails.root}/test/mailers/previews" : nil
-
end
-
-
# make sure readers methods get compiled
-
1
options.asset_host ||= app.config.asset_host
-
1
options.relative_url_root ||= app.config.relative_url_root
-
-
1
ActiveSupport.on_load(:action_mailer) do
-
1
include AbstractController::UrlFor
-
1
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes, false)
-
1
include app.routes.mounted_helpers
-
-
1
register_interceptors(options.delete(:interceptors))
-
1
register_preview_interceptors(options.delete(:preview_interceptors))
-
1
register_observers(options.delete(:observers))
-
-
8
options.each { |k,v| send("#{k}=", v) }
-
-
1
if options.show_previews
-
app.routes.append do
-
get '/rails/mailers' => "rails/mailers#index"
-
get '/rails/mailers/*path' => "rails/mailers#preview"
-
end
-
end
-
end
-
end
-
-
1
initializer "action_mailer.compile_config_methods" do
-
1
ActiveSupport.on_load(:action_mailer) do
-
1
config.compile_methods! if config.respond_to?(:compile_methods!)
-
end
-
end
-
-
1
config.after_initialize do
-
1
if ActionMailer::Base.preview_path
-
ActiveSupport::Dependencies.autoload_paths << ActionMailer::Base.preview_path
-
end
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActionMailer
-
# Returns the version of the currently loaded Action Mailer as a
-
# <tt>Gem::Version</tt>.
-
1
def self.version
-
gem_version
-
end
-
end
-
1
require 'action_pack'
-
1
require 'active_support/rails'
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/i18n'
-
-
1
module AbstractController
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Base
-
1
autoload :Callbacks
-
1
autoload :Collector
-
1
autoload :DoubleRenderError, "abstract_controller/rendering"
-
1
autoload :Helpers
-
1
autoload :Logger
-
1
autoload :Rendering
-
1
autoload :Translation
-
1
autoload :AssetPaths
-
1
autoload :UrlFor
-
end
-
1
module AbstractController
-
1
module AssetPaths #:nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
2
config_accessor :asset_host, :assets_dir, :javascripts_dir,
-
:stylesheets_dir, :default_asset_host_protocol, :relative_url_root
-
end
-
end
-
end
-
1
require 'erubis'
-
1
require 'set'
-
1
require 'active_support/configurable'
-
1
require 'active_support/descendants_tracker'
-
1
require 'active_support/core_ext/module/anonymous'
-
-
1
module AbstractController
-
1
class Error < StandardError #:nodoc:
-
end
-
-
# Raised when a non-existing controller action is triggered.
-
1
class ActionNotFound < StandardError
-
end
-
-
# <tt>AbstractController::Base</tt> is a low-level API. Nobody should be
-
# using it directly, and subclasses (like ActionController::Base) are
-
# expected to provide their own +render+ method, since rendering means
-
# different things depending on the context.
-
1
class Base
-
1
attr_internal :response_body
-
1
attr_internal :action_name
-
1
attr_internal :formats
-
-
1
include ActiveSupport::Configurable
-
1
extend ActiveSupport::DescendantsTracker
-
-
1
undef_method :not_implemented
-
1
class << self
-
1
attr_reader :abstract
-
1
alias_method :abstract?, :abstract
-
-
# Define a controller as abstract. See internal_methods for more
-
# details.
-
1
def abstract!
-
4
@abstract = true
-
end
-
-
1
def inherited(klass) # :nodoc:
-
# Define the abstract ivar on subclasses so that we don't get
-
# uninitialized ivar warnings
-
9
unless klass.instance_variable_defined?(:@abstract)
-
9
klass.instance_variable_set(:@abstract, false)
-
end
-
9
super
-
end
-
-
# A list of all internal methods for a controller. This finds the first
-
# abstract superclass of a controller, and gets a list of all public
-
# instance methods on that abstract class. Public instance methods of
-
# a controller would normally be considered action methods, so methods
-
# declared on abstract classes are being removed.
-
# (ActionController::Metal and ActionController::Base are defined as abstract)
-
1
def internal_methods
-
6
controller = self
-
-
6
controller = controller.superclass until controller.abstract?
-
6
controller.public_instance_methods(true)
-
end
-
-
# The list of hidden actions. Defaults to an empty array.
-
# This can be modified by other modules or subclasses
-
# to specify particular actions as hidden.
-
#
-
# ==== Returns
-
# * <tt>Array</tt> - An array of method names that should not be considered actions.
-
1
def hidden_actions
-
1
[]
-
end
-
-
# A list of method names that should be considered actions. This
-
# includes all public instance methods on a controller, less
-
# any internal methods (see #internal_methods), adding back in
-
# any methods that are internal, but still exist on the class
-
# itself. Finally, #hidden_actions are removed.
-
#
-
# ==== Returns
-
# * <tt>Set</tt> - A set of all methods that should be considered actions.
-
1
def action_methods
-
@action_methods ||= begin
-
# All public instance methods of this class, including ancestors
-
6
methods = (public_instance_methods(true) -
-
# Except for public instance methods of Base and its ancestors
-
internal_methods +
-
# Be sure to include shadowed public instance methods of this class
-
281
public_instance_methods(false)).uniq.map { |x| x.to_s } -
-
# And always exclude explicitly hidden actions
-
hidden_actions.to_a
-
-
# Clear out AS callback method pollution
-
281
Set.new(methods.reject { |method| method =~ /_one_time_conditions/ })
-
6
end
-
end
-
-
# action_methods are cached and there is sometimes need to refresh
-
# them. clear_action_methods! allows you to do that, so next time
-
# you run action_methods, they will be recalculated
-
1
def clear_action_methods!
-
244
@action_methods = nil
-
end
-
-
# Returns the full controller name, underscored, without the ending Controller.
-
# For instance, MyApp::MyPostsController would return "my_app/my_posts" for
-
# controller_path.
-
#
-
# ==== Returns
-
# * <tt>String</tt>
-
1
def controller_path
-
26
@controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous?
-
end
-
-
# Refresh the cached action_methods when a new action_method is added.
-
1
def method_added(name)
-
244
super
-
244
clear_action_methods!
-
end
-
end
-
-
1
abstract!
-
-
# Calls the action going through the entire action dispatch stack.
-
#
-
# The actual method that is called is determined by calling
-
# #method_for_action. If no method can handle the action, then an
-
# AbstractController::ActionNotFound error is raised.
-
#
-
# ==== Returns
-
# * <tt>self</tt>
-
1
def process(action, *args)
-
66
@_action_name = action.to_s
-
-
66
unless action_name = _find_action_name(@_action_name)
-
raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
-
end
-
-
66
@_response_body = nil
-
-
66
process_action(action_name, *args)
-
end
-
-
# Delegates to the class' #controller_path
-
1
def controller_path
-
self.class.controller_path
-
end
-
-
# Delegates to the class' #action_methods
-
1
def action_methods
-
self.class.action_methods
-
end
-
-
# Returns true if a method for the action is available and
-
# can be dispatched, false otherwise.
-
#
-
# Notice that <tt>action_methods.include?("foo")</tt> may return
-
# false and <tt>available_action?("foo")</tt> returns true because
-
# this method considers actions that are also available
-
# through other means, for example, implicit render ones.
-
#
-
# ==== Parameters
-
# * <tt>action_name</tt> - The name of an action to be tested
-
#
-
# ==== Returns
-
# * <tt>TrueClass</tt>, <tt>FalseClass</tt>
-
1
def available_action?(action_name)
-
_find_action_name(action_name).present?
-
end
-
-
# Returns true if the given controller is capable of rendering
-
# a path. A subclass of +AbstractController::Base+
-
# may return false. An Email controller for example does not
-
# support paths, only full URLs.
-
1
def self.supports_path?
-
5
true
-
end
-
-
1
private
-
-
# Returns true if the name can be considered an action because
-
# it has a method defined in the controller.
-
#
-
# ==== Parameters
-
# * <tt>name</tt> - The name of an action to be tested
-
#
-
# ==== Returns
-
# * <tt>TrueClass</tt>, <tt>FalseClass</tt>
-
#
-
# :api: private
-
1
def action_method?(name)
-
66
self.class.action_methods.include?(name)
-
end
-
-
# Call the action. Override this in a subclass to modify the
-
# behavior around processing an action. This, and not #process,
-
# is the intended way to override action dispatching.
-
#
-
# Notice that the first argument is the method to be dispatched
-
# which is *not* necessarily the same as the action name.
-
1
def process_action(method_name, *args)
-
66
send_action(method_name, *args)
-
end
-
-
# Actually call the method associated with the action. Override
-
# this method if you wish to change how action methods are called,
-
# not to add additional behavior around it. For example, you would
-
# override #send_action if you want to inject arguments into the
-
# method.
-
1
alias send_action send
-
-
# If the action name was not found, but a method called "action_missing"
-
# was found, #method_for_action will return "_handle_action_missing".
-
# This method calls #action_missing with the current action name.
-
1
def _handle_action_missing(*args)
-
action_missing(@_action_name, *args)
-
end
-
-
# Takes an action name and returns the name of the method that will
-
# handle the action.
-
#
-
# It checks if the action name is valid and returns false otherwise.
-
#
-
# See method_for_action for more information.
-
#
-
# ==== Parameters
-
# * <tt>action_name</tt> - An action name to find a method name for
-
#
-
# ==== Returns
-
# * <tt>string</tt> - The name of the method that handles the action
-
# * false - No valid method name could be found.
-
# Raise AbstractController::ActionNotFound.
-
1
def _find_action_name(action_name)
-
66
_valid_action_name?(action_name) && method_for_action(action_name)
-
end
-
-
# Takes an action name and returns the name of the method that will
-
# handle the action. In normal cases, this method returns the same
-
# name as it receives. By default, if #method_for_action receives
-
# a name that is not an action, it will look for an #action_missing
-
# method and return "_handle_action_missing" if one is found.
-
#
-
# Subclasses may override this method to add additional conditions
-
# that should be considered an action. For instance, an HTTP controller
-
# with a template matching the action name is considered to exist.
-
#
-
# If you override this method to handle additional cases, you may
-
# also provide a method (like _handle_method_missing) to handle
-
# the case.
-
#
-
# If none of these conditions are true, and method_for_action
-
# returns nil, an AbstractController::ActionNotFound exception will be raised.
-
#
-
# ==== Parameters
-
# * <tt>action_name</tt> - An action name to find a method name for
-
#
-
# ==== Returns
-
# * <tt>string</tt> - The name of the method that handles the action
-
# * <tt>nil</tt> - No method name could be found.
-
1
def method_for_action(action_name)
-
66
if action_method?(action_name)
-
66
action_name
-
elsif respond_to?(:action_missing, true)
-
"_handle_action_missing"
-
end
-
end
-
-
# Checks if the action name is valid and returns false otherwise.
-
1
def _valid_action_name?(action_name)
-
66
!action_name.to_s.include? File::SEPARATOR
-
end
-
end
-
end
-
1
module AbstractController
-
1
module Callbacks
-
1
extend ActiveSupport::Concern
-
-
# Uses ActiveSupport::Callbacks as the base functionality. For
-
# more details on the whole callback system, read the documentation
-
# for ActiveSupport::Callbacks.
-
1
include ActiveSupport::Callbacks
-
-
1
included do
-
2
define_callbacks :process_action,
-
138
terminator: ->(controller,_) { controller.response_body },
-
skip_after_callbacks_if_terminated: true
-
end
-
-
# Override AbstractController::Base's process_action to run the
-
# process_action callbacks around the normal behavior.
-
1
def process_action(*args)
-
66
run_callbacks(:process_action) do
-
66
super
-
end
-
end
-
-
1
module ClassMethods
-
# If :only or :except are used, convert the options into the
-
# :unless and :if options of ActiveSupport::Callbacks.
-
# The basic idea is that :only => :index gets converted to
-
# :if => proc {|c| c.action_name == "index" }.
-
#
-
# ==== Options
-
# * <tt>only</tt> - The callback should be run only for this action
-
# * <tt>except</tt> - The callback should be run for all actions except this action
-
1
def _normalize_callback_options(options)
-
4
_normalize_callback_option(options, :only, :if)
-
4
_normalize_callback_option(options, :except, :unless)
-
end
-
-
1
def _normalize_callback_option(options, from, to) # :nodoc:
-
8
if from = options[from]
-
5
from = Array(from).map {|o| "action_name == '#{o}'"}.join(" || ")
-
1
options[to] = Array(options[to]).unshift(from)
-
end
-
end
-
-
# Skip before, after, and around action callbacks matching any of the names.
-
#
-
# ==== Parameters
-
# * <tt>names</tt> - A list of valid names that could be used for
-
# callbacks. Note that skipping uses Ruby equality, so it's
-
# impossible to skip a callback defined using an anonymous proc
-
# using #skip_action_callback
-
1
def skip_action_callback(*names)
-
skip_before_action(*names)
-
skip_after_action(*names)
-
skip_around_action(*names)
-
end
-
1
alias_method :skip_filter, :skip_action_callback
-
-
# Take callback names and an optional callback proc, normalize them,
-
# then call the block with each callback. This allows us to abstract
-
# the normalization across several methods that use it.
-
#
-
# ==== Parameters
-
# * <tt>callbacks</tt> - An array of callbacks, with an optional
-
# options hash as the last parameter.
-
# * <tt>block</tt> - A proc that should be added to the callbacks.
-
#
-
# ==== Block Parameters
-
# * <tt>name</tt> - The callback to be added
-
# * <tt>options</tt> - A hash of options to be used when adding the callback
-
1
def _insert_callbacks(callbacks, block = nil)
-
4
options = callbacks.extract_options!
-
4
_normalize_callback_options(options)
-
4
callbacks.push(block) if block
-
4
callbacks.each do |callback|
-
4
yield callback, options
-
end
-
end
-
-
##
-
# :method: before_action
-
#
-
# :call-seq: before_action(names, block)
-
#
-
# Append a callback before actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: prepend_before_action
-
#
-
# :call-seq: prepend_before_action(names, block)
-
#
-
# Prepend a callback before actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: skip_before_action
-
#
-
# :call-seq: skip_before_action(names)
-
#
-
# Skip a callback before actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: append_before_action
-
#
-
# :call-seq: append_before_action(names, block)
-
#
-
# Append a callback before actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: after_action
-
#
-
# :call-seq: after_action(names, block)
-
#
-
# Append a callback after actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: prepend_after_action
-
#
-
# :call-seq: prepend_after_action(names, block)
-
#
-
# Prepend a callback after actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: skip_after_action
-
#
-
# :call-seq: skip_after_action(names)
-
#
-
# Skip a callback after actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: append_after_action
-
#
-
# :call-seq: append_after_action(names, block)
-
#
-
# Append a callback after actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: around_action
-
#
-
# :call-seq: around_action(names, block)
-
#
-
# Append a callback around actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: prepend_around_action
-
#
-
# :call-seq: prepend_around_action(names, block)
-
#
-
# Prepend a callback around actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: skip_around_action
-
#
-
# :call-seq: skip_around_action(names)
-
#
-
# Skip a callback around actions. See _insert_callbacks for parameter details.
-
-
##
-
# :method: append_around_action
-
#
-
# :call-seq: append_around_action(names, block)
-
#
-
# Append a callback around actions. See _insert_callbacks for parameter details.
-
-
# set up before_action, prepend_before_action, skip_before_action, etc.
-
# for each of before, after, and around.
-
1
[:before, :after, :around].each do |callback|
-
3
define_method "#{callback}_action" do |*names, &blk|
-
3
_insert_callbacks(names, blk) do |name, options|
-
3
set_callback(:process_action, callback, name, options)
-
end
-
end
-
3
alias_method :"#{callback}_filter", :"#{callback}_action"
-
-
3
define_method "prepend_#{callback}_action" do |*names, &blk|
-
1
_insert_callbacks(names, blk) do |name, options|
-
1
set_callback(:process_action, callback, name, options.merge(:prepend => true))
-
end
-
end
-
3
alias_method :"prepend_#{callback}_filter", :"prepend_#{callback}_action"
-
-
# Skip a before, after or around callback. See _insert_callbacks
-
# for details on the allowed parameters.
-
3
define_method "skip_#{callback}_action" do |*names|
-
_insert_callbacks(names) do |name, options|
-
skip_callback(:process_action, callback, name, options)
-
end
-
end
-
3
alias_method :"skip_#{callback}_filter", :"skip_#{callback}_action"
-
-
# *_action is the same as append_*_action
-
3
alias_method :"append_#{callback}_action", :"#{callback}_action"
-
3
alias_method :"append_#{callback}_filter", :"#{callback}_action"
-
end
-
end
-
end
-
end
-
1
require "action_dispatch/http/mime_type"
-
-
1
module AbstractController
-
1
module Collector
-
1
def self.generate_method_for_mime(mime)
-
22
sym = mime.is_a?(Symbol) ? mime : mime.to_sym
-
22
const = sym.upcase
-
22
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{sym}(*args, &block) # def html(*args, &block)
-
custom(Mime::#{const}, *args, &block) # custom(Mime::HTML, *args, &block)
-
end # end
-
RUBY
-
end
-
-
1
Mime::SET.each do |mime|
-
22
generate_method_for_mime(mime)
-
end
-
-
1
Mime::Type.register_callback do |mime|
-
generate_method_for_mime(mime) unless self.instance_methods.include?(mime.to_sym)
-
end
-
-
1
protected
-
-
1
def method_missing(symbol, &block)
-
const_name = symbol.upcase
-
-
unless Mime.const_defined?(const_name)
-
raise NoMethodError, "To respond to a custom format, register it as a MIME type first: " \
-
"http://guides.rubyonrails.org/action_controller_overview.html#restful-downloads. " \
-
"If you meant to respond to a variant like :tablet or :phone, not a custom format, " \
-
"be sure to nest your variant response within a format response: " \
-
"format.html { |html| html.tablet { ... } }"
-
end
-
-
mime_constant = Mime.const_get(const_name)
-
-
if Mime::SET.include?(mime_constant)
-
AbstractController::Collector.generate_method_for_mime(mime_constant)
-
send(symbol, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
1
require 'active_support/dependencies'
-
-
1
module AbstractController
-
1
module Helpers
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
2
class_attribute :_helpers
-
2
self._helpers = Module.new
-
-
2
class_attribute :_helper_methods
-
2
self._helper_methods = Array.new
-
end
-
-
1
class MissingHelperError < LoadError
-
1
def initialize(error, path)
-
@error = error
-
@path = "helpers/#{path}.rb"
-
set_backtrace error.backtrace
-
-
if error.path =~ /^#{path}(\.rb)?$/
-
super("Missing helper file helpers/%s.rb" % path)
-
else
-
raise error
-
end
-
end
-
end
-
-
1
module ClassMethods
-
# When a class is inherited, wrap its helper module in a new module.
-
# This ensures that the parent class's module can be changed
-
# independently of the child class's.
-
1
def inherited(klass)
-
6
helpers = _helpers
-
12
klass._helpers = Module.new { include helpers }
-
12
klass.class_eval { default_helper_module! } unless klass.anonymous?
-
6
super
-
end
-
-
# Declare a controller method as a helper. For example, the following
-
# makes the +current_user+ controller method available to the view:
-
# class ApplicationController < ActionController::Base
-
# helper_method :current_user, :logged_in?
-
#
-
# def current_user
-
# @current_user ||= User.find_by(id: session[:user])
-
# end
-
#
-
# def logged_in?
-
# current_user != nil
-
# end
-
# end
-
#
-
# In a view:
-
# <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>
-
#
-
# ==== Parameters
-
# * <tt>method[, method]</tt> - A name or names of a method on the controller
-
# to be made available on the view.
-
1
def helper_method(*meths)
-
9
meths.flatten!
-
9
self._helper_methods += meths
-
-
9
meths.each do |meth|
-
12
_helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
-
def #{meth}(*args, &blk) # def current_user(*args, &blk)
-
controller.send(%(#{meth}), *args, &blk) # controller.send(:current_user, *args, &blk)
-
end # end
-
ruby_eval
-
end
-
end
-
-
# The +helper+ class method can take a series of helper module names, a block, or both.
-
#
-
# ==== Options
-
# * <tt>*args</tt> - Module, Symbol, String
-
# * <tt>block</tt> - A block defining helper methods
-
#
-
# When the argument is a module it will be included directly in the template class.
-
# helper FooHelper # => includes FooHelper
-
#
-
# When the argument is a string or symbol, the method will provide the "_helper" suffix, require the file
-
# and include the module in the template class. The second form illustrates how to include custom helpers
-
# when working with namespaced controllers, or other cases where the file containing the helper definition is not
-
# in one of Rails' standard load paths:
-
# helper :foo # => requires 'foo_helper' and includes FooHelper
-
# helper 'resources/foo' # => requires 'resources/foo_helper' and includes Resources::FooHelper
-
#
-
# Additionally, the +helper+ class method can receive and evaluate a block, making the methods defined available
-
# to the template.
-
#
-
# # One line
-
# helper { def hello() "Hello, world!" end }
-
#
-
# # Multi-line
-
# helper do
-
# def foo(bar)
-
# "#{bar} is the very best"
-
# end
-
# end
-
#
-
# Finally, all the above styles can be mixed together, and the +helper+ method can be invoked with a mix of
-
# +symbols+, +strings+, +modules+ and blocks.
-
#
-
# helper(:three, BlindHelper) { def mice() 'mice' end }
-
#
-
1
def helper(*args, &block)
-
8
modules_for_helpers(args).each do |mod|
-
14
add_template_helper(mod)
-
end
-
-
8
_helpers.module_eval(&block) if block_given?
-
end
-
-
# Clears up all existing helpers in this class, only keeping the helper
-
# with the same name as this class.
-
1
def clear_helpers
-
inherited_helper_methods = _helper_methods
-
self._helpers = Module.new
-
self._helper_methods = Array.new
-
-
inherited_helper_methods.each { |meth| helper_method meth }
-
default_helper_module! unless anonymous?
-
end
-
-
# Returns a list of modules, normalized from the acceptable kinds of
-
# helpers with the following behavior:
-
#
-
# String or Symbol:: :FooBar or "FooBar" becomes "foo_bar_helper",
-
# and "foo_bar_helper.rb" is loaded using require_dependency.
-
#
-
# Module:: No further processing
-
#
-
# After loading the appropriate files, the corresponding modules
-
# are returned.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - An array of helpers
-
#
-
# ==== Returns
-
# * <tt>Array</tt> - A normalized list of modules for the list of
-
# helpers provided.
-
1
def modules_for_helpers(args)
-
8
args.flatten.map! do |arg|
-
14
case arg
-
when String, Symbol
-
13
file_name = "#{arg.to_s.underscore}_helper"
-
13
begin
-
13
require_dependency(file_name)
-
rescue LoadError => e
-
raise AbstractController::Helpers::MissingHelperError.new(e, file_name)
-
end
-
-
13
mod_name = file_name.camelize
-
13
begin
-
13
mod_name.constantize
-
rescue LoadError
-
# dependencies.rb gives a similar error message but its wording is
-
# not as clear because it mentions autoloading. To the user all it
-
# matters is that a helper module couldn't be loaded, autoloading
-
# is an internal mechanism that should not leak.
-
raise NameError, "Couldn't find #{mod_name}, expected it to be defined in helpers/#{file_name}.rb"
-
end
-
when Module
-
1
arg
-
else
-
raise ArgumentError, "helper must be a String, Symbol, or Module"
-
end
-
end
-
end
-
-
1
private
-
# Makes all the (instance) methods in the helper module available to templates
-
# rendered through this controller.
-
#
-
# ==== Parameters
-
# * <tt>module</tt> - The module to include into the current helper module
-
# for the class
-
1
def add_template_helper(mod)
-
28
_helpers.module_eval { include mod }
-
end
-
-
1
def default_helper_module!
-
6
module_name = name.sub(/Controller$/, '')
-
6
module_path = module_name.underscore
-
6
helper module_path
-
rescue MissingSourceFile => e
-
raise e unless e.is_missing? "helpers/#{module_path}_helper"
-
rescue NameError => e
-
raise e unless e.missing_name? "#{module_name}Helper"
-
end
-
end
-
end
-
end
-
1
require "active_support/benchmarkable"
-
-
1
module AbstractController
-
1
module Logger #:nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
2
config_accessor :logger
-
2
include ActiveSupport::Benchmarkable
-
end
-
end
-
end
-
1
module AbstractController
-
1
module Railties
-
1
module RoutesHelpers
-
1
def self.with(routes, include_path_helpers = true)
-
2
Module.new do
-
2
define_method(:inherited) do |klass|
-
6
super(klass)
-
12
if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_routes_url_helpers) }
-
klass.send(:include, namespace.railtie_routes_url_helpers(include_path_helpers))
-
else
-
6
klass.send(:include, routes.url_helpers(include_path_helpers))
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'action_view'
-
1
require 'action_view/view_paths'
-
1
require 'set'
-
-
1
module AbstractController
-
1
class DoubleRenderError < Error
-
1
DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\"."
-
-
1
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
1
module Rendering
-
1
extend ActiveSupport::Concern
-
1
include ActionView::ViewPaths
-
-
# Normalize arguments, options and then delegates render_to_body and
-
# sticks the result in self.response_body.
-
# :api: public
-
1
def render(*args, &block)
-
55
options = _normalize_render(*args, &block)
-
55
self.response_body = render_to_body(options)
-
55
_process_format(rendered_format, options) if rendered_format
-
55
self.response_body
-
end
-
-
# Raw rendering of a template to a string.
-
#
-
# It is similar to render, except that it does not
-
# set the response_body and it should be guaranteed
-
# to always return a string.
-
#
-
# If a component extends the semantics of response_body
-
# (as Action Controller extends it to be anything that
-
# responds to the method each), this method needs to be
-
# overridden in order to still return a string.
-
# :api: plugin
-
1
def render_to_string(*args, &block)
-
options = _normalize_render(*args, &block)
-
render_to_body(options)
-
end
-
-
# Performs the actual template rendering.
-
# :api: public
-
1
def render_to_body(options = {})
-
end
-
-
# Returns Content-Type of rendered content
-
# :api: public
-
1
def rendered_format
-
Mime::TEXT
-
end
-
-
1
DEFAULT_PROTECTED_INSTANCE_VARIABLES = Set.new %w(
-
@_action_name @_response_body @_formats @_prefixes @_config
-
@_view_context_class @_view_renderer @_lookup_context
-
@_routes @_db_runtime
-
).map(&:to_sym)
-
-
# This method should return a hash with assigns.
-
# You can overwrite this configuration per controller.
-
# :api: public
-
1
def view_assigns
-
55
protected_vars = _protected_ivars
-
55
variables = instance_variables
-
-
954
variables.reject! { |s| protected_vars.include? s }
-
55
variables.each_with_object({}) { |name, hash|
-
97
hash[name.slice(1, name.length)] = instance_variable_get(name)
-
}
-
end
-
-
# Normalize args by converting render "foo" to render :action => "foo" and
-
# render "foo/bar" to render :file => "foo/bar".
-
# :api: plugin
-
1
def _normalize_args(action=nil, options={})
-
55
if action.is_a? Hash
-
action
-
else
-
55
options
-
end
-
end
-
-
# Normalize options.
-
# :api: plugin
-
1
def _normalize_options(options)
-
55
options
-
end
-
-
# Process extra options.
-
# :api: plugin
-
1
def _process_options(options)
-
55
options
-
end
-
-
# Process the rendered format.
-
# :api: private
-
1
def _process_format(format, options = {})
-
end
-
-
# Normalize args and options.
-
# :api: private
-
1
def _normalize_render(*args, &block)
-
55
options = _normalize_args(*args, &block)
-
#TODO: remove defined? when we restore AP <=> AV dependency
-
55
if defined?(request) && request && request.variant.present?
-
options[:variant] = request.variant
-
end
-
55
_normalize_options(options)
-
55
options
-
end
-
-
1
def _protected_ivars # :nodoc:
-
DEFAULT_PROTECTED_INSTANCE_VARIABLES
-
end
-
end
-
end
-
1
module AbstractController
-
1
module Translation
-
# Delegates to <tt>I18n.translate</tt>. Also aliased as <tt>t</tt>.
-
#
-
# When the given key starts with a period, it will be scoped by the current
-
# controller and action. So if you call <tt>translate(".foo")</tt> from
-
# <tt>PeopleController#index</tt>, it will convert the call to
-
# <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
-
# to translate many keys within the same controller / action and gives you a
-
# simple framework for scoping them consistently.
-
1
def translate(*args)
-
key = args.first
-
if key.is_a?(String) && (key[0] == '.')
-
key = "#{ controller_path.tr('/', '.') }.#{ action_name }#{ key }"
-
args[0] = key
-
end
-
-
I18n.translate(*args)
-
end
-
1
alias :t :translate
-
-
# Delegates to <tt>I18n.localize</tt>. Also aliased as <tt>l</tt>.
-
1
def localize(*args)
-
I18n.localize(*args)
-
end
-
1
alias :l :localize
-
end
-
end
-
1
module AbstractController
-
# Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class
-
# has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an
-
# exception will be raised.
-
#
-
# Note that this module is completely decoupled from HTTP - the only requirement is a valid
-
# <tt>_routes</tt> implementation.
-
1
module UrlFor
-
1
extend ActiveSupport::Concern
-
1
include ActionDispatch::Routing::UrlFor
-
-
1
def _routes
-
raise "In order to use #url_for, you must include routing helpers explicitly. " \
-
"For instance, `include Rails.application.routes.url_helpers`."
-
end
-
-
1
module ClassMethods
-
1
def _routes
-
nil
-
end
-
-
1
def action_methods
-
@action_methods ||= begin
-
5
if _routes
-
5
super - _routes.named_routes.helper_names
-
else
-
super
-
end
-
66
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/rails'
-
1
require 'abstract_controller'
-
1
require 'action_dispatch'
-
1
require 'action_controller/metal/live'
-
1
require 'action_controller/metal/strong_parameters'
-
-
1
module ActionController
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Base
-
1
autoload :Caching
-
1
autoload :Metal
-
1
autoload :Middleware
-
-
1
autoload_under "metal" do
-
1
autoload :Compatibility
-
1
autoload :ConditionalGet
-
1
autoload :Cookies
-
1
autoload :DataStreaming
-
1
autoload :EtagWithTemplateDigest
-
1
autoload :Flash
-
1
autoload :ForceSSL
-
1
autoload :Head
-
1
autoload :Helpers
-
1
autoload :HideActions
-
1
autoload :HttpAuthentication
-
1
autoload :ImplicitRender
-
1
autoload :Instrumentation
-
1
autoload :MimeResponds
-
1
autoload :ParamsWrapper
-
1
autoload :RackDelegation
-
1
autoload :Redirecting
-
1
autoload :Renderers
-
1
autoload :Rendering
-
1
autoload :RequestForgeryProtection
-
1
autoload :Rescue
-
1
autoload :Streaming
-
1
autoload :StrongParameters
-
1
autoload :Testing
-
1
autoload :UrlFor
-
end
-
-
1
autoload :TestCase, 'action_controller/test_case'
-
1
autoload :TemplateAssertions, 'action_controller/test_case'
-
-
1
def self.eager_load!
-
super
-
ActionController::Caching.eager_load!
-
end
-
end
-
-
# Common Active Support usage in Action Controller
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/load_error'
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/name_error'
-
1
require 'active_support/core_ext/uri'
-
1
require 'active_support/inflector'
-
1
require 'action_view'
-
1
require "action_controller/log_subscriber"
-
1
require "action_controller/metal/params_wrapper"
-
-
1
module ActionController
-
# Action Controllers are the core of a web request in \Rails. They are made up of one or more actions that are executed
-
# on request and then either it renders a template or redirects to another action. An action is defined as a public method
-
# on the controller, which will automatically be made accessible to the web-server through \Rails Routes.
-
#
-
# By default, only the ApplicationController in a \Rails application inherits from <tt>ActionController::Base</tt>. All other
-
# controllers in turn inherit from ApplicationController. This gives you one class to configure things such as
-
# request forgery protection and filtering of sensitive request parameters.
-
#
-
# A sample controller could look like this:
-
#
-
# class PostsController < ApplicationController
-
# def index
-
# @posts = Post.all
-
# end
-
#
-
# def create
-
# @post = Post.create params[:post]
-
# redirect_to posts_path
-
# end
-
# end
-
#
-
# Actions, by default, render a template in the <tt>app/views</tt> directory corresponding to the name of the controller and action
-
# after executing code in the action. For example, the +index+ action of the PostsController would render the
-
# template <tt>app/views/posts/index.html.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
-
#
-
# Unlike index, the create action will not render a template. After performing its main purpose (creating a
-
# new post), it initiates a redirect instead. This redirect works by returning an external
-
# "302 Moved" HTTP response that takes the user to the index action.
-
#
-
# These two methods represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect.
-
# Most actions are variations on these themes.
-
#
-
# == Requests
-
#
-
# For every request, the router determines the value of the +controller+ and +action+ keys. These determine which controller
-
# and action are called. The remaining request parameters, the session (if one is available), and the full request with
-
# all the HTTP headers are made available to the action through accessor methods. Then the action is performed.
-
#
-
# The full request object is available via the request accessor and is primarily used to query for HTTP headers:
-
#
-
# def server_ip
-
# location = request.env["REMOTE_ADDR"]
-
# render plain: "This server hosted at #{location}"
-
# end
-
#
-
# == Parameters
-
#
-
# All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method
-
# which returns a hash. For example, an action that was performed through <tt>/posts?category=All&limit=5</tt> will include
-
# <tt>{ "category" => "All", "limit" => "5" }</tt> in params.
-
#
-
# It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
-
#
-
# <input type="text" name="post[name]" value="david">
-
# <input type="text" name="post[address]" value="hyacintvej">
-
#
-
# A request stemming from a form holding these inputs will include <tt>{ "post" => { "name" => "david", "address" => "hyacintvej" } }</tt>.
-
# If the address input had been named <tt>post[address][street]</tt>, the params would have included
-
# <tt>{ "post" => { "address" => { "street" => "hyacintvej" } } }</tt>. There's no limit to the depth of the nesting.
-
#
-
# == Sessions
-
#
-
# Sessions allow you to store objects in between requests. This is useful for objects that are not yet ready to be persisted,
-
# such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such
-
# as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely
-
# they could be changed unknowingly. It's usually too much work to keep it all synchronized -- something databases already excel at.
-
#
-
# You can place objects in the session by using the <tt>session</tt> method, which accesses a hash:
-
#
-
# session[:person] = Person.authenticate(user_name, password)
-
#
-
# And retrieved again through the same hash:
-
#
-
# Hello #{session[:person]}
-
#
-
# For removing objects from the session, you can either assign a single key to +nil+:
-
#
-
# # removes :person from session
-
# session[:person] = nil
-
#
-
# or you can remove the entire session with +reset_session+.
-
#
-
# Sessions are stored by default in a browser cookie that's cryptographically signed, but unencrypted.
-
# This prevents the user from tampering with the session but also allows them to see its contents.
-
#
-
# Do not put secret information in cookie-based sessions!
-
#
-
# == Responses
-
#
-
# Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response
-
# object is generated automatically through the use of renders and redirects and requires no user intervention.
-
#
-
# == Renders
-
#
-
# Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering
-
# of a template. Included in the Action Pack is the Action View, which enables rendering of ERB templates. It's automatically configured.
-
# The controller passes objects to the view by assigning instance variables:
-
#
-
# def show
-
# @post = Post.find(params[:id])
-
# end
-
#
-
# Which are then automatically available to the view:
-
#
-
# Title: <%= @post.title %>
-
#
-
# You don't have to rely on the automated rendering. For example, actions that could result in the rendering of different templates
-
# will use the manual rendering methods:
-
#
-
# def search
-
# @results = Search.find(params[:query])
-
# case @results.count
-
# when 0 then render action: "no_results"
-
# when 1 then render action: "show"
-
# when 2..10 then render action: "show_many"
-
# end
-
# end
-
#
-
# Read more about writing ERB and Builder templates in ActionView::Base.
-
#
-
# == Redirects
-
#
-
# Redirects are used to move from one action to another. For example, after a <tt>create</tt> action, which stores a blog entry to the
-
# database, we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're
-
# going to reuse (and redirect to) a <tt>show</tt> action that we'll assume has already been created. The code might look like this:
-
#
-
# def create
-
# @entry = Entry.new(params[:entry])
-
# if @entry.save
-
# # The entry was saved correctly, redirect to show
-
# redirect_to action: 'show', id: @entry.id
-
# else
-
# # things didn't go so well, do something else
-
# end
-
# end
-
#
-
# In this case, after saving our new entry to the database, the user is redirected to the <tt>show</tt> method, which is then executed.
-
# Note that this is an external HTTP-level redirection which will cause the browser to make a second request (a GET to the show action),
-
# and not some internal re-routing which calls both "create" and then "show" within one request.
-
#
-
# Learn more about <tt>redirect_to</tt> and what options you have in ActionController::Redirecting.
-
#
-
# == Calling multiple redirects or renders
-
#
-
# An action may contain only a single render or a single redirect. Attempting to try to do either again will result in a DoubleRenderError:
-
#
-
# def do_something
-
# redirect_to action: "elsewhere"
-
# render action: "overthere" # raises DoubleRenderError
-
# end
-
#
-
# If you need to redirect on the condition of something, then be sure to add "and return" to halt execution.
-
#
-
# def do_something
-
# redirect_to(action: "elsewhere") and return if monkeys.nil?
-
# render action: "overthere" # won't be called if monkeys is nil
-
# end
-
#
-
1
class Base < Metal
-
1
abstract!
-
-
# We document the request and response methods here because albeit they are
-
# implemented in ActionController::Metal, the type of the returned objects
-
# is unknown at that level.
-
-
##
-
# :method: request
-
#
-
# Returns an ActionDispatch::Request instance that represents the
-
# current request.
-
-
##
-
# :method: response
-
#
-
# Returns an ActionDispatch::Response that represents the current
-
# response.
-
-
# Shortcut helper that returns all the modules included in
-
# ActionController::Base except the ones passed as arguments:
-
#
-
# class MyBaseController < ActionController::Metal
-
# ActionController::Base.without_modules(:ParamsWrapper, :Streaming).each do |left|
-
# include left
-
# end
-
# end
-
#
-
# This gives better control over what you want to exclude and makes it
-
# easier to create a bare controller class, instead of listing the modules
-
# required manually.
-
1
def self.without_modules(*modules)
-
modules = modules.map do |m|
-
m.is_a?(Symbol) ? ActionController.const_get(m) : m
-
end
-
-
MODULES - modules
-
end
-
-
1
MODULES = [
-
AbstractController::Rendering,
-
AbstractController::Translation,
-
AbstractController::AssetPaths,
-
-
Helpers,
-
HideActions,
-
UrlFor,
-
Redirecting,
-
ActionView::Layouts,
-
Rendering,
-
Renderers::All,
-
ConditionalGet,
-
EtagWithTemplateDigest,
-
RackDelegation,
-
Caching,
-
MimeResponds,
-
ImplicitRender,
-
StrongParameters,
-
-
Cookies,
-
Flash,
-
RequestForgeryProtection,
-
ForceSSL,
-
Streaming,
-
DataStreaming,
-
HttpAuthentication::Basic::ControllerMethods,
-
HttpAuthentication::Digest::ControllerMethods,
-
HttpAuthentication::Token::ControllerMethods,
-
-
# Before callbacks should also be executed the earliest as possible, so
-
# also include them at the bottom.
-
AbstractController::Callbacks,
-
-
# Append rescue at the bottom to wrap as much as possible.
-
Rescue,
-
-
# Add instrumentations hooks at the bottom, to ensure they instrument
-
# all the methods properly.
-
Instrumentation,
-
-
# Params wrapper should come before instrumentation so they are
-
# properly showed in logs
-
ParamsWrapper
-
]
-
-
1
MODULES.each do |mod|
-
30
include mod
-
end
-
-
# Define some internal variables that should not be propagated to the view.
-
1
PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [
-
:@_status, :@_headers, :@_params, :@_env, :@_response, :@_request,
-
:@_view_runtime, :@_stream, :@_url_options, :@_action_has_layout ]
-
-
1
def _protected_ivars # :nodoc:
-
55
PROTECTED_IVARS
-
end
-
-
1
def self.protected_instance_variables
-
PROTECTED_IVARS
-
end
-
-
1
ActiveSupport.run_load_hooks(:action_controller, self)
-
end
-
end
-
1
require 'fileutils'
-
1
require 'uri'
-
1
require 'set'
-
-
1
module ActionController
-
# \Caching is a cheap way of speeding up slow applications by keeping the result of
-
# calculations, renderings, and database calls around for subsequent requests.
-
#
-
# You can read more about each approach by clicking the modules below.
-
#
-
# Note: To turn off all caching, set
-
# config.action_controller.perform_caching = false
-
#
-
# == \Caching stores
-
#
-
# All the caching stores from ActiveSupport::Cache are available to be used as backends
-
# for Action Controller caching.
-
#
-
# Configuration examples (FileStore is the default):
-
#
-
# config.action_controller.cache_store = :memory_store
-
# config.action_controller.cache_store = :file_store, '/path/to/cache/directory'
-
# config.action_controller.cache_store = :mem_cache_store, 'localhost'
-
# config.action_controller.cache_store = :mem_cache_store, Memcached::Rails.new('localhost:11211')
-
# config.action_controller.cache_store = MyOwnStore.new('parameter')
-
1
module Caching
-
1
extend ActiveSupport::Concern
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Fragments
-
end
-
-
1
module ConfigMethods
-
1
def cache_store
-
config.cache_store
-
end
-
-
1
def cache_store=(store)
-
1
config.cache_store = ActiveSupport::Cache.lookup_store(store)
-
end
-
-
1
private
-
1
def cache_configured?
-
perform_caching && cache_store
-
end
-
end
-
-
1
include RackDelegation
-
1
include AbstractController::Callbacks
-
-
1
include ConfigMethods
-
1
include Fragments
-
-
1
included do
-
1
extend ConfigMethods
-
-
1
config_accessor :default_static_extension
-
1
self.default_static_extension ||= '.html'
-
-
1
config_accessor :perform_caching
-
1
self.perform_caching = true if perform_caching.nil?
-
-
1
class_attribute :_view_cache_dependencies
-
1
self._view_cache_dependencies = []
-
1
helper_method :view_cache_dependencies if respond_to?(:helper_method)
-
end
-
-
1
module ClassMethods
-
1
def view_cache_dependency(&dependency)
-
self._view_cache_dependencies += [dependency]
-
end
-
end
-
-
1
def view_cache_dependencies
-
self.class._view_cache_dependencies.map { |dep| instance_exec(&dep) }.compact
-
end
-
-
1
protected
-
# Convenience accessor.
-
1
def cache(key, options = {}, &block)
-
if cache_configured?
-
cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block)
-
else
-
yield
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module Caching
-
# Fragment caching is used for caching various blocks within
-
# views without caching the entire action as a whole. This is
-
# useful when certain elements of an action change frequently or
-
# depend on complicated state while other parts rarely change or
-
# can be shared amongst multiple parties. The caching is done using
-
# the +cache+ helper available in the Action View. See
-
# ActionView::Helpers::CacheHelper for more information.
-
#
-
# While it's strongly recommended that you use key-based cache
-
# expiration (see links in CacheHelper for more information),
-
# it is also possible to manually expire caches. For example:
-
#
-
# expire_fragment('name_of_cache')
-
1
module Fragments
-
# Given a key (as described in +expire_fragment+), returns
-
# a key suitable for use in reading, writing, or expiring a
-
# cached fragment. All keys are prefixed with <tt>views/</tt> and uses
-
# ActiveSupport::Cache.expand_cache_key for the expansion.
-
1
def fragment_cache_key(key)
-
ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
-
end
-
-
# Writes +content+ to the location signified by
-
# +key+ (see +expire_fragment+ for acceptable formats).
-
1
def write_fragment(key, content, options = nil)
-
return content unless cache_configured?
-
-
key = fragment_cache_key(key)
-
instrument_fragment_cache :write_fragment, key do
-
content = content.to_str
-
cache_store.write(key, content, options)
-
end
-
content
-
end
-
-
# Reads a cached fragment from the location signified by +key+
-
# (see +expire_fragment+ for acceptable formats).
-
1
def read_fragment(key, options = nil)
-
return unless cache_configured?
-
-
key = fragment_cache_key(key)
-
instrument_fragment_cache :read_fragment, key do
-
result = cache_store.read(key, options)
-
result.respond_to?(:html_safe) ? result.html_safe : result
-
end
-
end
-
-
# Check if a cached fragment from the location signified by
-
# +key+ exists (see +expire_fragment+ for acceptable formats).
-
1
def fragment_exist?(key, options = nil)
-
return unless cache_configured?
-
key = fragment_cache_key(key)
-
-
instrument_fragment_cache :exist_fragment?, key do
-
cache_store.exist?(key, options)
-
end
-
end
-
-
# Removes fragments from the cache.
-
#
-
# +key+ can take one of three forms:
-
#
-
# * String - This would normally take the form of a path, like
-
# <tt>pages/45/notes</tt>.
-
# * Hash - Treated as an implicit call to +url_for+, like
-
# <tt>{ controller: 'pages', action: 'notes', id: 45}</tt>
-
# * Regexp - Will remove any fragment that matches, so
-
# <tt>%r{pages/\d*/notes}</tt> might remove all notes. Make sure you
-
# don't use anchors in the regex (<tt>^</tt> or <tt>$</tt>) because
-
# the actual filename matched looks like
-
# <tt>./cache/filename/path.cache</tt>. Note: Regexp expiration is
-
# only supported on caches that can iterate over all keys (unlike
-
# memcached).
-
#
-
# +options+ is passed through to the cache store's +delete+
-
# method (or <tt>delete_matched</tt>, for Regexp keys).
-
1
def expire_fragment(key, options = nil)
-
return unless cache_configured?
-
key = fragment_cache_key(key) unless key.is_a?(Regexp)
-
-
instrument_fragment_cache :expire_fragment, key do
-
if key.is_a?(Regexp)
-
cache_store.delete_matched(key, options)
-
else
-
cache_store.delete(key, options)
-
end
-
end
-
end
-
-
1
def instrument_fragment_cache(name, key) # :nodoc:
-
payload = {
-
controller: controller_name,
-
action: action_name,
-
key: key
-
}
-
-
ActiveSupport::Notifications.instrument("#{name}.action_controller", payload) { yield }
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
class LogSubscriber < ActiveSupport::LogSubscriber
-
1
INTERNAL_PARAMS = %w(controller action format _method only_path)
-
-
1
def start_processing(event)
-
66
return unless logger.info?
-
-
66
payload = event.payload
-
66
params = payload[:params].except(*INTERNAL_PARAMS)
-
66
format = payload[:format]
-
66
format = format.to_s.upcase if format.is_a?(Symbol)
-
-
66
info "Processing by #{payload[:controller]}##{payload[:action]} as #{format}"
-
66
info " Parameters: #{params.inspect}" unless params.empty?
-
end
-
-
1
def process_action(event)
-
66
info do
-
66
payload = event.payload
-
66
additions = ActionController::Base.log_process_action(payload)
-
-
66
status = payload[:status]
-
66
if status.nil? && payload[:exception].present?
-
exception_class_name = payload[:exception].first
-
status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
-
end
-
66
message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{event.duration.round}ms"
-
66
message << " (#{additions.join(" | ")})" unless additions.blank?
-
66
message
-
end
-
end
-
-
1
def halted_callback(event)
-
info { "Filter chain halted as #{event.payload[:filter].inspect} rendered or redirected" }
-
end
-
-
1
def send_file(event)
-
info { "Sent file #{event.payload[:path]} (#{event.duration.round(1)}ms)" }
-
end
-
-
1
def redirect_to(event)
-
22
info { "Redirected to #{event.payload[:location]}" }
-
end
-
-
1
def send_data(event)
-
info { "Sent data #{event.payload[:filename]} (#{event.duration.round(1)}ms)" }
-
end
-
-
1
def unpermitted_parameters(event)
-
debug do
-
unpermitted_keys = event.payload[:keys]
-
"Unpermitted parameter#{'s' if unpermitted_keys.size > 1}: #{unpermitted_keys.join(", ")}"
-
end
-
end
-
-
1
def deep_munge(event)
-
debug do
-
"Value for params[:#{event.payload[:keys].join('][:')}] was set "\
-
"to nil, because it was one of [], [null] or [null, null, ...]. "\
-
"Go to http://guides.rubyonrails.org/security.html#unsafe-query-generation "\
-
"for more information."\
-
end
-
end
-
-
%w(write_fragment read_fragment exist_fragment?
-
1
expire_fragment expire_page write_page).each do |method|
-
6
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{method}(event)
-
return unless logger.info?
-
key_or_path = event.payload[:key] || event.payload[:path]
-
human_name = #{method.to_s.humanize.inspect}
-
info("\#{human_name} \#{key_or_path} (\#{event.duration.round(1)}ms)")
-
end
-
METHOD
-
end
-
-
1
def logger
-
690
ActionController::Base.logger
-
end
-
end
-
end
-
-
1
ActionController::LogSubscriber.attach_to :action_controller
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'action_dispatch/middleware/stack'
-
-
1
module ActionController
-
# Extend ActionDispatch middleware stack to make it aware of options
-
# allowing the following syntax in controllers:
-
#
-
# class PostsController < ApplicationController
-
# use AuthenticationMiddleware, except: [:index, :show]
-
# end
-
#
-
1
class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc:
-
1
class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc:
-
1
def initialize(klass, *args, &block)
-
options = args.extract_options!
-
@only = Array(options.delete(:only)).map(&:to_s)
-
@except = Array(options.delete(:except)).map(&:to_s)
-
args << options unless options.empty?
-
super
-
end
-
-
1
def valid?(action)
-
if @only.present?
-
@only.include?(action)
-
elsif @except.present?
-
!@except.include?(action)
-
else
-
true
-
end
-
end
-
end
-
-
1
def build(action, app = Proc.new)
-
action = action.to_s
-
-
middlewares.reverse.inject(app) do |a, middleware|
-
middleware.valid?(action) ? middleware.build(a) : a
-
end
-
end
-
end
-
-
# <tt>ActionController::Metal</tt> is the simplest possible controller, providing a
-
# valid Rack interface without the additional niceties provided by
-
# <tt>ActionController::Base</tt>.
-
#
-
# A sample metal controller might look like this:
-
#
-
# class HelloController < ActionController::Metal
-
# def index
-
# self.response_body = "Hello World!"
-
# end
-
# end
-
#
-
# And then to route requests to your metal controller, you would add
-
# something like this to <tt>config/routes.rb</tt>:
-
#
-
# get 'hello', to: HelloController.action(:index)
-
#
-
# The +action+ method returns a valid Rack application for the \Rails
-
# router to dispatch to.
-
#
-
# == Rendering Helpers
-
#
-
# <tt>ActionController::Metal</tt> by default provides no utilities for rendering
-
# views, partials, or other responses aside from explicitly calling of
-
# <tt>response_body=</tt>, <tt>content_type=</tt>, and <tt>status=</tt>. To
-
# add the render helpers you're used to having in a normal controller, you
-
# can do the following:
-
#
-
# class HelloController < ActionController::Metal
-
# include AbstractController::Rendering
-
# include ActionView::Layouts
-
# append_view_path "#{Rails.root}/app/views"
-
#
-
# def index
-
# render "hello/index"
-
# end
-
# end
-
#
-
# == Redirection Helpers
-
#
-
# To add redirection helpers to your metal controller, do the following:
-
#
-
# class HelloController < ActionController::Metal
-
# include ActionController::Redirecting
-
# include Rails.application.routes.url_helpers
-
#
-
# def index
-
# redirect_to root_url
-
# end
-
# end
-
#
-
# == Other Helpers
-
#
-
# You can refer to the modules included in <tt>ActionController::Base</tt> to see
-
# other features you can bring into your metal controller.
-
#
-
1
class Metal < AbstractController::Base
-
1
abstract!
-
-
1
attr_internal_writer :env
-
-
1
def env
-
276
@_env ||= {}
-
end
-
-
# Returns the last part of the controller's name, underscored, without the ending
-
# <tt>Controller</tt>. For instance, PostsController returns <tt>posts</tt>.
-
# Namespaces are left out, so Admin::PostsController returns <tt>posts</tt> as well.
-
#
-
# ==== Returns
-
# * <tt>string</tt>
-
1
def self.controller_name
-
@controller_name ||= name.demodulize.sub(/Controller$/, '').underscore
-
end
-
-
# Delegates to the class' <tt>controller_name</tt>
-
1
def controller_name
-
self.class.controller_name
-
end
-
-
# The details below can be overridden to support a specific
-
# Request and Response object. The default ActionController::Base
-
# implementation includes RackDelegation, which makes a request
-
# and response object available. You might wish to control the
-
# environment and response manually for performance reasons.
-
-
1
attr_internal :headers, :response, :request
-
1
delegate :session, :to => "@_request"
-
-
1
def initialize
-
66
@_headers = {"Content-Type" => "text/html"}
-
66
@_status = 200
-
66
@_request = nil
-
66
@_response = nil
-
66
@_routes = nil
-
66
super
-
end
-
-
1
def params
-
@_params ||= request.parameters
-
end
-
-
1
def params=(val)
-
@_params = val
-
end
-
-
# Basic implementations for content_type=, location=, and headers are
-
# provided to reduce the dependency on the RackDelegation module
-
# in Renderer and Redirector.
-
-
1
def content_type=(type)
-
headers["Content-Type"] = type.to_s
-
end
-
-
1
def content_type
-
headers["Content-Type"]
-
end
-
-
1
def location
-
headers["Location"]
-
end
-
-
1
def location=(url)
-
headers["Location"] = url
-
end
-
-
# Basic url_for that can be overridden for more robust functionality
-
1
def url_for(string)
-
string
-
end
-
-
1
def status
-
@_status
-
end
-
1
alias :response_code :status # :nodoc:
-
-
1
def status=(status)
-
@_status = Rack::Utils.status_code(status)
-
end
-
-
1
def response_body=(body)
-
66
body = [body] unless body.nil? || body.respond_to?(:each)
-
66
super
-
end
-
-
# Tests if render or redirect has already happened.
-
1
def performed?
-
66
response_body || (response && response.committed?)
-
end
-
-
1
def dispatch(name, request) #:nodoc:
-
66
@_request = request
-
66
@_env = request.env
-
66
@_env['action_controller.instance'] = self
-
66
process(name)
-
66
to_a
-
end
-
-
1
def to_a #:nodoc:
-
66
response ? response.to_a : [status, headers, response_body]
-
end
-
-
1
class_attribute :middleware_stack
-
1
self.middleware_stack = ActionController::MiddlewareStack.new
-
-
1
def self.inherited(base) # :nodoc:
-
7
base.middleware_stack = middleware_stack.dup
-
7
super
-
end
-
-
# Pushes the given Rack middleware and its arguments to the bottom of the
-
# middleware stack.
-
1
def self.use(*args, &block)
-
middleware_stack.use(*args, &block)
-
end
-
-
# Alias for +middleware_stack+.
-
1
def self.middleware
-
middleware_stack
-
end
-
-
# Makes the controller a Rack endpoint that runs the action in the given
-
# +env+'s +action_dispatch.request.path_parameters+ key.
-
1
def self.call(env)
-
req = ActionDispatch::Request.new env
-
action(req.path_parameters[:action]).call(env)
-
end
-
-
# Returns a Rack endpoint for the given action name.
-
1
def self.action(name, klass = ActionDispatch::Request)
-
66
if middleware_stack.any?
-
middleware_stack.build(name) do |env|
-
new.dispatch(name, klass.new(env))
-
end
-
else
-
132
lambda { |env| new.dispatch(name, klass.new(env)) }
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActionController
-
1
module ConditionalGet
-
1
extend ActiveSupport::Concern
-
-
1
include RackDelegation
-
1
include Head
-
-
1
included do
-
1
class_attribute :etaggers
-
1
self.etaggers = []
-
end
-
-
1
module ClassMethods
-
# Allows you to consider additional controller-wide information when generating an ETag.
-
# For example, if you serve pages tailored depending on who's logged in at the moment, you
-
# may want to add the current user id to be part of the ETag to prevent authorized displaying
-
# of cached pages.
-
#
-
# class InvoicesController < ApplicationController
-
# etag { current_user.try :id }
-
#
-
# def show
-
# # Etag will differ even for the same invoice when it's viewed by a different current_user
-
# @invoice = Invoice.find(params[:id])
-
# fresh_when(@invoice)
-
# end
-
# end
-
1
def etag(&etagger)
-
1
self.etaggers += [etagger]
-
end
-
end
-
-
# Sets the +etag+, +last_modified+, or both on the response and renders a
-
# <tt>304 Not Modified</tt> response if the request is already fresh.
-
#
-
# === Parameters:
-
#
-
# * <tt>:etag</tt>.
-
# * <tt>:last_modified</tt>.
-
# * <tt>:public</tt> By default the Cache-Control header is private, set this to
-
# +true+ if you want your application to be cachable by other devices (proxy caches).
-
# * <tt>:template</tt> By default, the template digest for the current
-
# controller/action is included in ETags. If the action renders a
-
# different template, you can include its digest instead. If the action
-
# doesn't render a template at all, you can pass <tt>template: false</tt>
-
# to skip any attempt to check for a template digest.
-
#
-
# === Example:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(etag: @article, last_modified: @article.created_at, public: true)
-
# end
-
#
-
# This will render the show template if the request isn't sending a matching ETag or
-
# If-Modified-Since header and just a <tt>304 Not Modified</tt> response if there's a match.
-
#
-
# You can also just pass a record where +last_modified+ will be set by calling
-
# +updated_at+ and the +etag+ by passing the object itself.
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(@article)
-
# end
-
#
-
# When passing a record, you can still set whether the public header:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(@article, public: true)
-
# end
-
#
-
# When rendering a different template than the default controller/action
-
# style, you can indicate which digest to include in the ETag:
-
#
-
# before_action { fresh_when @article, template: 'widgets/show' }
-
#
-
1
def fresh_when(record_or_options, additional_options = {})
-
if record_or_options.is_a? Hash
-
options = record_or_options
-
options.assert_valid_keys(:etag, :last_modified, :public, :template)
-
else
-
record = record_or_options
-
options = { etag: record, last_modified: record.try(:updated_at) }.merge!(additional_options)
-
end
-
-
response.etag = combine_etags(options) if options[:etag] || options[:template]
-
response.last_modified = options[:last_modified] if options[:last_modified]
-
response.cache_control[:public] = true if options[:public]
-
-
head :not_modified if request.fresh?(response)
-
end
-
-
# Sets the +etag+ and/or +last_modified+ on the response and checks it against
-
# the client request. If the request doesn't match the options provided, the
-
# request is considered stale and should be generated from scratch. Otherwise,
-
# it's fresh and we don't need to generate anything and a reply of <tt>304 Not Modified</tt> is sent.
-
#
-
# === Parameters:
-
#
-
# * <tt>:etag</tt>.
-
# * <tt>:last_modified</tt>.
-
# * <tt>:public</tt> By default the Cache-Control header is private, set this to
-
# +true+ if you want your application to be cachable by other devices (proxy caches).
-
# * <tt>:template</tt> By default, the template digest for the current
-
# controller/action is included in ETags. If the action renders a
-
# different template, you can include its digest instead. If the action
-
# doesn't render a template at all, you can pass <tt>template: false</tt>
-
# to skip any attempt to check for a template digest.
-
#
-
# === Example:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(etag: @article, last_modified: @article.created_at)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
#
-
# You can also just pass a record where +last_modified+ will be set by calling
-
# +updated_at+ and the +etag+ by passing the object itself.
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(@article)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
#
-
# When passing a record, you can still set whether the public header:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(@article, public: true)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
#
-
# When rendering a different template than the default controller/action
-
# style, you can indicate which digest to include in the ETag:
-
#
-
# def show
-
# super if stale? @article, template: 'widgets/show'
-
# end
-
#
-
1
def stale?(record_or_options, additional_options = {})
-
fresh_when(record_or_options, additional_options)
-
!request.fresh?(response)
-
end
-
-
# Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a +private+
-
# instruction, so that intermediate caches must not cache the response.
-
#
-
# expires_in 20.minutes
-
# expires_in 3.hours, public: true
-
# expires_in 3.hours, public: true, must_revalidate: true
-
#
-
# This method will overwrite an existing Cache-Control header.
-
# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities.
-
#
-
# The method will also ensure a HTTP Date header for client compatibility.
-
1
def expires_in(seconds, options = {})
-
response.cache_control.merge!(
-
:max_age => seconds,
-
:public => options.delete(:public),
-
:must_revalidate => options.delete(:must_revalidate)
-
)
-
options.delete(:private)
-
-
response.cache_control[:extras] = options.map {|k,v| "#{k}=#{v}"}
-
response.date = Time.now unless response.date?
-
end
-
-
# Sets a HTTP 1.1 Cache-Control header of <tt>no-cache</tt> so no caching should
-
# occur by the browser or intermediate caches (like caching proxy servers).
-
1
def expires_now
-
response.cache_control.replace(:no_cache => true)
-
end
-
-
1
private
-
1
def combine_etags(options)
-
etags = etaggers.map { |etagger| instance_exec(options, &etagger) }.compact
-
etags.unshift options[:etag]
-
end
-
end
-
end
-
1
module ActionController #:nodoc:
-
1
module Cookies
-
1
extend ActiveSupport::Concern
-
-
1
include RackDelegation
-
-
1
included do
-
1
helper_method :cookies
-
end
-
-
1
private
-
1
def cookies
-
request.cookie_jar
-
end
-
end
-
end
-
1
require 'action_controller/metal/exceptions'
-
-
1
module ActionController #:nodoc:
-
# Methods for sending arbitrary data and for streaming files to the browser,
-
# instead of rendering.
-
1
module DataStreaming
-
1
extend ActiveSupport::Concern
-
-
1
include ActionController::Rendering
-
-
1
DEFAULT_SEND_FILE_TYPE = 'application/octet-stream'.freeze #:nodoc:
-
1
DEFAULT_SEND_FILE_DISPOSITION = 'attachment'.freeze #:nodoc:
-
-
1
protected
-
# Sends the file. This uses a server-appropriate method (such as X-Sendfile)
-
# via the Rack::Sendfile middleware. The header to use is set via
-
# +config.action_dispatch.x_sendfile_header+.
-
# Your server can also configure this for you by setting the X-Sendfile-Type header.
-
#
-
# Be careful to sanitize the path parameter if it is coming from a web
-
# page. <tt>send_file(params[:path])</tt> allows a malicious user to
-
# download any file on your server.
-
#
-
# Options:
-
# * <tt>:filename</tt> - suggests a filename for the browser to use.
-
# Defaults to <tt>File.basename(path)</tt>.
-
# * <tt>:type</tt> - specifies an HTTP content type.
-
# You can specify either a string or a symbol for a registered type register with
-
# <tt>Mime::Type.register</tt>, for example :json
-
# If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
-
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
-
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
-
# Valid values are 'inline' and 'attachment' (default).
-
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
-
# * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from
-
# the URL, which is necessary for i18n filenames on certain browsers
-
# (setting <tt>:filename</tt> overrides this option).
-
#
-
# The default Content-Type and Content-Disposition headers are
-
# set to download arbitrary binary files in as many browsers as
-
# possible. IE versions 4, 5, 5.5, and 6 are all known to have
-
# a variety of quirks (especially when downloading over SSL).
-
#
-
# Simple download:
-
#
-
# send_file '/path/to.zip'
-
#
-
# Show a JPEG in the browser:
-
#
-
# send_file '/path/to.jpeg', type: 'image/jpeg', disposition: 'inline'
-
#
-
# Show a 404 page in the browser:
-
#
-
# send_file '/path/to/404.html', type: 'text/html; charset=utf-8', status: 404
-
#
-
# Read about the other Content-* HTTP headers if you'd like to
-
# provide the user with more information (such as Content-Description) in
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11.
-
#
-
# Also be aware that the document may be cached by proxies and browsers.
-
# The Pragma and Cache-Control headers declare how the file may be cached
-
# by intermediaries. They default to require clients to validate with
-
# the server before releasing cached responses. See
-
# http://www.mnot.net/cache_docs/ for an overview of web caching and
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
-
# for the Cache-Control header spec.
-
1
def send_file(path, options = {}) #:doc:
-
raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)
-
-
options[:filename] ||= File.basename(path) unless options[:url_based_filename]
-
send_file_headers! options
-
-
self.status = options[:status] || 200
-
self.content_type = options[:content_type] if options.key?(:content_type)
-
self.response_body = FileBody.new(path)
-
end
-
-
# Avoid having to pass an open file handle as the response body.
-
# Rack::Sendfile will usually intercept the response and uses
-
# the path directly, so there is no reason to open the file.
-
1
class FileBody #:nodoc:
-
1
attr_reader :to_path
-
-
1
def initialize(path)
-
@to_path = path
-
end
-
-
# Stream the file's contents if Rack::Sendfile isn't present.
-
1
def each
-
File.open(to_path, 'rb') do |file|
-
while chunk = file.read(16384)
-
yield chunk
-
end
-
end
-
end
-
end
-
-
# Sends the given binary data to the browser. This method is similar to
-
# <tt>render plain: data</tt>, but also allows you to specify whether
-
# the browser should display the response as a file attachment (i.e. in a
-
# download dialog) or as inline data. You may also set the content type,
-
# the apparent file name, and other things.
-
#
-
# Options:
-
# * <tt>:filename</tt> - suggests a filename for the browser to use.
-
# * <tt>:type</tt> - specifies an HTTP content type. Defaults to 'application/octet-stream'. You can specify
-
# either a string or a symbol for a registered type register with <tt>Mime::Type.register</tt>, for example :json
-
# If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
-
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
-
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
-
# Valid values are 'inline' and 'attachment' (default).
-
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
-
#
-
# Generic data download:
-
#
-
# send_data buffer
-
#
-
# Download a dynamically-generated tarball:
-
#
-
# send_data generate_tgz('dir'), filename: 'dir.tgz'
-
#
-
# Display an image Active Record in the browser:
-
#
-
# send_data image.data, type: image.content_type, disposition: 'inline'
-
#
-
# See +send_file+ for more information on HTTP Content-* headers and caching.
-
1
def send_data(data, options = {}) #:doc:
-
send_file_headers! options
-
render options.slice(:status, :content_type).merge(:text => data)
-
end
-
-
1
private
-
1
def send_file_headers!(options)
-
type_provided = options.has_key?(:type)
-
-
content_type = options.fetch(:type, DEFAULT_SEND_FILE_TYPE)
-
raise ArgumentError, ":type option required" if content_type.nil?
-
-
if content_type.is_a?(Symbol)
-
extension = Mime[content_type]
-
raise ArgumentError, "Unknown MIME type #{options[:type]}" unless extension
-
self.content_type = extension
-
else
-
if !type_provided && options[:filename]
-
# If type wasn't provided, try guessing from file extension.
-
content_type = Mime::Type.lookup_by_extension(File.extname(options[:filename]).downcase.delete('.')) || content_type
-
end
-
self.content_type = content_type
-
end
-
-
disposition = options.fetch(:disposition, DEFAULT_SEND_FILE_DISPOSITION)
-
unless disposition.nil?
-
disposition = disposition.to_s
-
disposition += %(; filename="#{options[:filename]}") if options[:filename]
-
headers['Content-Disposition'] = disposition
-
end
-
-
headers['Content-Transfer-Encoding'] = 'binary'
-
-
response.sending_file = true
-
-
# Fix a problem with IE 6.0 on opening downloaded files:
-
# If Cache-Control: no-cache is set (which Rails does by default),
-
# IE removes the file it just downloaded from its cache immediately
-
# after it displays the "open/save" dialog, which means that if you
-
# hit "open" the file isn't there anymore when the application that
-
# is called for handling the download is run, so let's workaround that
-
response.cache_control[:public] ||= false
-
end
-
end
-
end
-
1
module ActionController
-
# When our views change, they should bubble up into HTTP cache freshness
-
# and bust browser caches. So the template digest for the current action
-
# is automatically included in the ETag.
-
#
-
# Enabled by default for apps that use Action View. Disable by setting
-
#
-
# config.action_controller.etag_with_template_digest = false
-
#
-
# Override the template to digest by passing +:template+ to +fresh_when+
-
# and +stale?+ calls. For example:
-
#
-
# # We're going to render widgets/show, not posts/show
-
# fresh_when @post, template: 'widgets/show'
-
#
-
# # We're not going to render a template, so omit it from the ETag.
-
# fresh_when @post, template: false
-
#
-
1
module EtagWithTemplateDigest
-
1
extend ActiveSupport::Concern
-
-
1
include ActionController::ConditionalGet
-
-
1
included do
-
1
class_attribute :etag_with_template_digest
-
1
self.etag_with_template_digest = true
-
-
1
ActiveSupport.on_load :action_view, yield: true do |action_view_base|
-
1
etag do |options|
-
determine_template_etag(options) if etag_with_template_digest
-
end
-
end
-
end
-
-
1
private
-
1
def determine_template_etag(options)
-
if template = pick_template_for_etag(options)
-
lookup_and_digest_template(template)
-
end
-
end
-
-
1
def pick_template_for_etag(options)
-
options.fetch(:template) { "#{controller_name}/#{action_name}" }
-
end
-
-
1
def lookup_and_digest_template(template)
-
ActionView::Digestor.digest name: template, finder: lookup_context
-
end
-
end
-
end
-
1
module ActionController
-
1
class ActionControllerError < StandardError #:nodoc:
-
end
-
-
1
class BadRequest < ActionControllerError #:nodoc:
-
1
attr_reader :original_exception
-
-
1
def initialize(type = nil, e = nil)
-
return super() unless type && e
-
-
super("Invalid #{type} parameters: #{e.message}")
-
@original_exception = e
-
set_backtrace e.backtrace
-
end
-
end
-
-
1
class RenderError < ActionControllerError #:nodoc:
-
end
-
-
1
class RoutingError < ActionControllerError #:nodoc:
-
1
attr_reader :failures
-
1
def initialize(message, failures=[])
-
super(message)
-
@failures = failures
-
end
-
end
-
-
1
class ActionController::UrlGenerationError < ActionControllerError #:nodoc:
-
end
-
-
1
class MethodNotAllowed < ActionControllerError #:nodoc:
-
1
def initialize(*allowed_methods)
-
super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
-
end
-
end
-
-
1
class NotImplemented < MethodNotAllowed #:nodoc:
-
end
-
-
1
class UnknownController < ActionControllerError #:nodoc:
-
end
-
-
1
class MissingFile < ActionControllerError #:nodoc:
-
end
-
-
1
class SessionOverflowError < ActionControllerError #:nodoc:
-
1
DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
-
-
1
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
1
class UnknownHttpMethod < ActionControllerError #:nodoc:
-
end
-
-
1
class UnknownFormat < ActionControllerError #:nodoc:
-
end
-
end
-
1
module ActionController #:nodoc:
-
1
module Flash
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :_flash_types, instance_accessor: false
-
1
self._flash_types = []
-
-
1
delegate :flash, to: :request
-
1
add_flash_types(:alert, :notice)
-
end
-
-
1
module ClassMethods
-
# Creates new flash types. You can pass as many types as you want to create
-
# flash types other than the default <tt>alert</tt> and <tt>notice</tt> in
-
# your controllers and views. For instance:
-
#
-
# # in application_controller.rb
-
# class ApplicationController < ActionController::Base
-
# add_flash_types :warning
-
# end
-
#
-
# # in your controller
-
# redirect_to user_path(@user), warning: "Incomplete profile"
-
#
-
# # in your view
-
# <%= warning %>
-
#
-
# This method will automatically define a new method for each of the given
-
# names, and it will be available in your views.
-
1
def add_flash_types(*types)
-
1
types.each do |type|
-
2
next if _flash_types.include?(type)
-
-
2
define_method(type) do
-
3
request.flash[type]
-
end
-
2
helper_method type
-
-
2
self._flash_types += [type]
-
end
-
end
-
end
-
-
1
protected
-
1
def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
-
11
self.class._flash_types.each do |flash_type|
-
22
if type = response_status_and_flash.delete(flash_type)
-
3
flash[flash_type] = type
-
end
-
end
-
-
11
if other_flashes = response_status_and_flash.delete(:flash)
-
flash.update(other_flashes)
-
end
-
-
11
super(options, response_status_and_flash)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActionController
-
# This module provides a method which will redirect browser to use HTTPS
-
# protocol. This will ensure that user's sensitive information will be
-
# transferred safely over the internet. You _should_ always force browser
-
# to use HTTPS when you're transferring sensitive information such as
-
# user authentication, account information, or credit card information.
-
#
-
# Note that if you are really concerned about your application security,
-
# you might consider using +config.force_ssl+ in your config file instead.
-
# That will ensure all the data transferred via HTTPS protocol and prevent
-
# user from getting session hijacked when accessing the site under unsecured
-
# HTTP protocol.
-
1
module ForceSSL
-
1
extend ActiveSupport::Concern
-
1
include AbstractController::Callbacks
-
-
1
ACTION_OPTIONS = [:only, :except, :if, :unless]
-
1
URL_OPTIONS = [:protocol, :host, :domain, :subdomain, :port, :path]
-
1
REDIRECT_OPTIONS = [:status, :flash, :alert, :notice]
-
-
1
module ClassMethods
-
# Force the request to this particular controller or specified actions to be
-
# under HTTPS protocol.
-
#
-
# If you need to disable this for any reason (e.g. development) then you can use
-
# an +:if+ or +:unless+ condition.
-
#
-
# class AccountsController < ApplicationController
-
# force_ssl if: :ssl_configured?
-
#
-
# def ssl_configured?
-
# !Rails.env.development?
-
# end
-
# end
-
#
-
# ==== URL Options
-
# You can pass any of the following options to affect the redirect url
-
# * <tt>host</tt> - Redirect to a different host name
-
# * <tt>subdomain</tt> - Redirect to a different subdomain
-
# * <tt>domain</tt> - Redirect to a different domain
-
# * <tt>port</tt> - Redirect to a non-standard port
-
# * <tt>path</tt> - Redirect to a different path
-
#
-
# ==== Redirect Options
-
# You can pass any of the following options to affect the redirect status and response
-
# * <tt>status</tt> - Redirect with a custom status (default is 301 Moved Permanently)
-
# * <tt>flash</tt> - Set a flash message when redirecting
-
# * <tt>alert</tt> - Set an alert message when redirecting
-
# * <tt>notice</tt> - Set a notice message when redirecting
-
#
-
# ==== Action Options
-
# You can pass any of the following options to affect the before_action callback
-
# * <tt>only</tt> - The callback should be run only for this action
-
# * <tt>except</tt> - The callback should be run for all actions except this action
-
# * <tt>if</tt> - A symbol naming an instance method or a proc; the callback
-
# will be called only when it returns a true value.
-
# * <tt>unless</tt> - A symbol naming an instance method or a proc; the callback
-
# will be called only when it returns a false value.
-
1
def force_ssl(options = {})
-
action_options = options.slice(*ACTION_OPTIONS)
-
redirect_options = options.except(*ACTION_OPTIONS)
-
before_action(action_options) do
-
force_ssl_redirect(redirect_options)
-
end
-
end
-
end
-
-
# Redirect the existing request to use the HTTPS protocol.
-
#
-
# ==== Parameters
-
# * <tt>host_or_options</tt> - Either a host name or any of the url & redirect options
-
# available to the <tt>force_ssl</tt> method.
-
1
def force_ssl_redirect(host_or_options = nil)
-
unless request.ssl?
-
options = {
-
:protocol => 'https://',
-
:host => request.host,
-
:path => request.fullpath,
-
:status => :moved_permanently
-
}
-
-
if host_or_options.is_a?(Hash)
-
options.merge!(host_or_options)
-
elsif host_or_options
-
options[:host] = host_or_options
-
end
-
-
secure_url = ActionDispatch::Http::URL.url_for(options.slice(*URL_OPTIONS))
-
flash.keep if respond_to?(:flash)
-
redirect_to secure_url, options.slice(*REDIRECT_OPTIONS)
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module Head
-
# Returns a response that has no content (merely headers). The options
-
# argument is interpreted to be a hash of header names and values.
-
# This allows you to easily return a response that consists only of
-
# significant headers:
-
#
-
# head :created, location: person_path(@person)
-
#
-
# head :created, location: @person
-
#
-
# It can also be used to return exceptional conditions:
-
#
-
# return head(:method_not_allowed) unless request.post?
-
# return head(:bad_request) unless valid_request?
-
# render
-
#
-
# See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list of valid +status+ symbols.
-
1
def head(status, options = {})
-
options, status = status, nil if status.is_a?(Hash)
-
status ||= options.delete(:status) || :ok
-
location = options.delete(:location)
-
content_type = options.delete(:content_type)
-
-
options.each do |key, value|
-
headers[key.to_s.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s
-
end
-
-
self.status = status
-
self.location = url_for(location) if location
-
-
self.response_body = ""
-
-
if include_content?(self.response_code)
-
self.content_type = content_type || (Mime[formats.first] if formats)
-
self.response.charset = false if self.response
-
else
-
headers.delete('Content-Type')
-
headers.delete('Content-Length')
-
end
-
-
true
-
end
-
-
1
private
-
# :nodoc:
-
1
def include_content?(status)
-
case status
-
when 100..199
-
false
-
when 204, 205, 304
-
false
-
else
-
true
-
end
-
end
-
end
-
end
-
1
module ActionController
-
# The \Rails framework provides a large number of helpers for working with assets, dates, forms,
-
# numbers and model objects, to name a few. These helpers are available to all templates
-
# by default.
-
#
-
# In addition to using the standard template helpers provided, creating custom helpers to
-
# extract complicated logic or reusable functionality is strongly encouraged. By default, each controller
-
# will include all helpers. These helpers are only accessible on the controller through <tt>.helpers</tt>
-
#
-
# In previous versions of \Rails the controller will include a helper whose
-
# name matches that of the controller, e.g., <tt>MyController</tt> will automatically
-
# include <tt>MyHelper</tt>. To return old behavior set +config.action_controller.include_all_helpers+ to +false+.
-
#
-
# Additional helpers can be specified using the +helper+ class method in ActionController::Base or any
-
# controller which inherits from it.
-
#
-
# The +to_s+ method from the \Time class can be wrapped in a helper method to display a custom message if
-
# a \Time object is blank:
-
#
-
# module FormattedTimeHelper
-
# def format_time(time, format=:long, blank_message=" ")
-
# time.blank? ? blank_message : time.to_s(format)
-
# end
-
# end
-
#
-
# FormattedTimeHelper can now be included in a controller, using the +helper+ class method:
-
#
-
# class EventsController < ActionController::Base
-
# helper FormattedTimeHelper
-
# def index
-
# @events = Event.all
-
# end
-
# end
-
#
-
# Then, in any view rendered by <tt>EventController</tt>, the <tt>format_time</tt> method can be called:
-
#
-
# <% @events.each do |event| -%>
-
# <p>
-
# <%= format_time(event.time, :short, "N/A") %> | <%= event.name %>
-
# </p>
-
# <% end -%>
-
#
-
# Finally, assuming we have two event instances, one which has a time and one which does not,
-
# the output might look like this:
-
#
-
# 23 Aug 11:30 | Carolina Railhawks Soccer Match
-
# N/A | Carolina Railhaws Training Workshop
-
#
-
1
module Helpers
-
1
extend ActiveSupport::Concern
-
-
2
class << self; attr_accessor :helpers_path; end
-
1
include AbstractController::Helpers
-
-
1
included do
-
1
class_attribute :helpers_path, :include_all_helpers
-
1
self.helpers_path ||= []
-
1
self.include_all_helpers = true
-
end
-
-
1
module ClassMethods
-
# Declares helper accessors for controller attributes. For example, the
-
# following adds new +name+ and <tt>name=</tt> instance methods to a
-
# controller and makes them available to the view:
-
# attr_accessor :name
-
# helper_attr :name
-
#
-
# ==== Parameters
-
# * <tt>attrs</tt> - Names of attributes to be converted into helpers.
-
1
def helper_attr(*attrs)
-
attrs.flatten.each { |attr| helper_method(attr, "#{attr}=") }
-
end
-
-
# Provides a proxy to access helpers methods from outside the view.
-
1
def helpers
-
@helper_proxy ||= begin
-
proxy = ActionView::Base.new
-
proxy.config = config.inheritable_copy
-
proxy.extend(_helpers)
-
end
-
end
-
-
# Overwrite modules_for_helpers to accept :all as argument, which loads
-
# all helpers in helpers_path.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - A list of helpers
-
#
-
# ==== Returns
-
# * <tt>array</tt> - A normalized list of modules for the list of helpers provided.
-
1
def modules_for_helpers(args)
-
7
args += all_application_helpers if args.delete(:all)
-
7
super(args)
-
end
-
-
1
def all_helpers_from_path(path)
-
1
helpers = Array(path).flat_map do |_path|
-
1
extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
-
8
names = Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
-
1
names.sort!
-
end
-
1
helpers.uniq!
-
1
helpers
-
end
-
-
1
private
-
# Extract helper names from files in <tt>app/helpers/**/*_helper.rb</tt>
-
1
def all_application_helpers
-
1
all_helpers_from_path(helpers_path)
-
end
-
end
-
end
-
end
-
-
1
module ActionController
-
# Adds the ability to prevent public methods on a controller to be called as actions.
-
1
module HideActions
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :hidden_actions
-
1
self.hidden_actions = Set.new.freeze
-
end
-
-
1
private
-
-
# Overrides AbstractController::Base#action_method? to return false if the
-
# action name is in the list of hidden actions.
-
1
def method_for_action(action_name)
-
66
self.class.visible_action?(action_name) && super
-
end
-
-
1
module ClassMethods
-
# Sets all of the actions passed in as hidden actions.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - A list of actions
-
1
def hide_action(*args)
-
self.hidden_actions = hidden_actions.dup.merge(args.map(&:to_s)).freeze
-
end
-
-
1
def visible_action?(action_name)
-
66
not hidden_actions.include?(action_name)
-
end
-
-
# Overrides AbstractController::Base#action_methods to remove any methods
-
# that are listed as hidden methods.
-
1
def action_methods
-
214
@action_methods ||= Set.new(super.reject { |name| hidden_actions.include?(name) }).freeze
-
end
-
end
-
end
-
end
-
1
require 'base64'
-
-
1
module ActionController
-
# Makes it dead easy to do HTTP Basic, Digest and Token authentication.
-
1
module HttpAuthentication
-
# Makes it dead easy to do HTTP \Basic authentication.
-
#
-
# === Simple \Basic example
-
#
-
# class PostsController < ApplicationController
-
# http_basic_authenticate_with name: "dhh", password: "secret", except: :index
-
#
-
# def index
-
# render plain: "Everyone can see me!"
-
# end
-
#
-
# def edit
-
# render plain: "I'm only accessible if you know the password"
-
# end
-
# end
-
#
-
# === Advanced \Basic example
-
#
-
# Here is a more advanced \Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
-
# the regular HTML interface is protected by a session approach:
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :set_account, :authenticate
-
#
-
# protected
-
# def set_account
-
# @account = Account.find_by(url_name: request.subdomains.first)
-
# end
-
#
-
# def authenticate
-
# case request.format
-
# when Mime::XML, Mime::ATOM
-
# if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
-
# @current_user = user
-
# else
-
# request_http_basic_authentication
-
# end
-
# else
-
# if session_authenticated?
-
# @current_user = @account.users.find(session[:authenticated][:user_id])
-
# else
-
# redirect_to(login_url) and return false
-
# end
-
# end
-
# end
-
# end
-
#
-
# In your integration tests, you can do something like this:
-
#
-
# def test_access_granted_from_xml
-
# @request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
-
# get "/notes/1.xml"
-
#
-
# assert_equal 200, status
-
# end
-
1
module Basic
-
1
extend self
-
-
1
module ControllerMethods
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
1
def http_basic_authenticate_with(options = {})
-
before_action(options.except(:name, :password, :realm)) do
-
authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
-
name == options[:name] && password == options[:password]
-
end
-
end
-
end
-
end
-
-
1
def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
-
authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
-
end
-
-
1
def authenticate_with_http_basic(&login_procedure)
-
HttpAuthentication::Basic.authenticate(request, &login_procedure)
-
end
-
-
1
def request_http_basic_authentication(realm = "Application")
-
HttpAuthentication::Basic.authentication_request(self, realm)
-
end
-
end
-
-
1
def authenticate(request, &login_procedure)
-
if has_basic_credentials?(request)
-
login_procedure.call(*user_name_and_password(request))
-
end
-
end
-
-
1
def has_basic_credentials?(request)
-
request.authorization.present? && (auth_scheme(request) == 'Basic')
-
end
-
-
1
def user_name_and_password(request)
-
decode_credentials(request).split(':', 2)
-
end
-
-
1
def decode_credentials(request)
-
::Base64.decode64(auth_param(request) || '')
-
end
-
-
1
def auth_scheme(request)
-
request.authorization.split(' ', 2).first
-
end
-
-
1
def auth_param(request)
-
request.authorization.split(' ', 2).second
-
end
-
-
1
def encode_credentials(user_name, password)
-
"Basic #{::Base64.strict_encode64("#{user_name}:#{password}")}"
-
end
-
-
1
def authentication_request(controller, realm)
-
controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
-
controller.status = 401
-
controller.response_body = "HTTP Basic: Access denied.\n"
-
end
-
end
-
-
# Makes it dead easy to do HTTP \Digest authentication.
-
#
-
# === Simple \Digest example
-
#
-
# require 'digest/md5'
-
# class PostsController < ApplicationController
-
# REALM = "SuperSecret"
-
# USERS = {"dhh" => "secret", #plain text password
-
# "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password
-
#
-
# before_action :authenticate, except: [:index]
-
#
-
# def index
-
# render plain: "Everyone can see me!"
-
# end
-
#
-
# def edit
-
# render plain: "I'm only accessible if you know the password"
-
# end
-
#
-
# private
-
# def authenticate
-
# authenticate_or_request_with_http_digest(REALM) do |username|
-
# USERS[username]
-
# end
-
# end
-
# end
-
#
-
# === Notes
-
#
-
# The +authenticate_or_request_with_http_digest+ block must return the user's password
-
# or the ha1 digest hash so the framework can appropriately hash to check the user's
-
# credentials. Returning +nil+ will cause authentication to fail.
-
#
-
# Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
-
# the password file or database is compromised, the attacker would be able to use the ha1 hash to
-
# authenticate as the user at this +realm+, but would not have the user's password to try using at
-
# other sites.
-
#
-
# In rare instances, web servers or front proxies strip authorization headers before
-
# they reach your application. You can debug this situation by logging all environment
-
# variables, and check for HTTP_AUTHORIZATION, amongst others.
-
1
module Digest
-
1
extend self
-
-
1
module ControllerMethods
-
1
def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
-
authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm)
-
end
-
-
# Authenticate with HTTP Digest, returns true or false
-
1
def authenticate_with_http_digest(realm = "Application", &password_procedure)
-
HttpAuthentication::Digest.authenticate(request, realm, &password_procedure)
-
end
-
-
# Render output including the HTTP Digest authentication header
-
1
def request_http_digest_authentication(realm = "Application", message = nil)
-
HttpAuthentication::Digest.authentication_request(self, realm, message)
-
end
-
end
-
-
# Returns false on a valid response, true otherwise
-
1
def authenticate(request, realm, &password_procedure)
-
request.authorization && validate_digest_response(request, realm, &password_procedure)
-
end
-
-
# Returns false unless the request credentials response value matches the expected value.
-
# First try the password as a ha1 digest password. If this fails, then try it as a plain
-
# text password.
-
1
def validate_digest_response(request, realm, &password_procedure)
-
secret_key = secret_token(request)
-
credentials = decode_credentials_header(request)
-
valid_nonce = validate_nonce(secret_key, request, credentials[:nonce])
-
-
if valid_nonce && realm == credentials[:realm] && opaque(secret_key) == credentials[:opaque]
-
password = password_procedure.call(credentials[:username])
-
return false unless password
-
-
method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
-
uri = credentials[:uri]
-
-
[true, false].any? do |trailing_question_mark|
-
[true, false].any? do |password_is_ha1|
-
_uri = trailing_question_mark ? uri + "?" : uri
-
expected = expected_response(method, _uri, credentials, password, password_is_ha1)
-
expected == credentials[:response]
-
end
-
end
-
end
-
end
-
-
# Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+
-
# Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead
-
# of a plain-text password.
-
1
def expected_response(http_method, uri, credentials, password, password_is_ha1=true)
-
ha1 = password_is_ha1 ? password : ha1(credentials, password)
-
ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':'))
-
::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':'))
-
end
-
-
1
def ha1(credentials, password)
-
::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':'))
-
end
-
-
1
def encode_credentials(http_method, credentials, password, password_is_ha1)
-
credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
-
"Digest " + credentials.sort_by {|x| x[0].to_s }.map {|v| "#{v[0]}='#{v[1]}'" }.join(', ')
-
end
-
-
1
def decode_credentials_header(request)
-
decode_credentials(request.authorization)
-
end
-
-
1
def decode_credentials(header)
-
ActiveSupport::HashWithIndifferentAccess[header.to_s.gsub(/^Digest\s+/, '').split(',').map do |pair|
-
key, value = pair.split('=', 2)
-
[key.strip, value.to_s.gsub(/^"|"$/,'').delete('\'')]
-
end]
-
end
-
-
1
def authentication_header(controller, realm)
-
secret_key = secret_token(controller.request)
-
nonce = self.nonce(secret_key)
-
opaque = opaque(secret_key)
-
controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
-
end
-
-
1
def authentication_request(controller, realm, message = nil)
-
message ||= "HTTP Digest: Access denied.\n"
-
authentication_header(controller, realm)
-
controller.status = 401
-
controller.response_body = message
-
end
-
-
1
def secret_token(request)
-
key_generator = request.env["action_dispatch.key_generator"]
-
http_auth_salt = request.env["action_dispatch.http_auth_salt"]
-
key_generator.generate_key(http_auth_salt)
-
end
-
-
# Uses an MD5 digest based on time to generate a value to be used only once.
-
#
-
# A server-specified data string which should be uniquely generated each time a 401 response is made.
-
# It is recommended that this string be base64 or hexadecimal data.
-
# Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
-
#
-
# The contents of the nonce are implementation dependent.
-
# The quality of the implementation depends on a good choice.
-
# A nonce might, for example, be constructed as the base 64 encoding of
-
#
-
# time-stamp H(time-stamp ":" ETag ":" private-key)
-
#
-
# where time-stamp is a server-generated time or other non-repeating value,
-
# ETag is the value of the HTTP ETag header associated with the requested entity,
-
# and private-key is data known only to the server.
-
# With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
-
# reject the request if it did not match the nonce from that header or
-
# if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
-
# The inclusion of the ETag prevents a replay request for an updated version of the resource.
-
# (Note: including the IP address of the client in the nonce would appear to offer the server the ability
-
# to limit the reuse of the nonce to the same client that originally got it.
-
# However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
-
# Also, IP address spoofing is not that hard.)
-
#
-
# An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
-
# protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
-
# POST, PUT, or PATCH requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
-
# of this document.
-
#
-
# The nonce is opaque to the client. Composed of Time, and hash of Time with secret
-
# key from the Rails session secret generated upon creation of project. Ensures
-
# the time cannot be modified by client.
-
1
def nonce(secret_key, time = Time.now)
-
t = time.to_i
-
hashed = [t, secret_key]
-
digest = ::Digest::MD5.hexdigest(hashed.join(":"))
-
::Base64.strict_encode64("#{t}:#{digest}")
-
end
-
-
# Might want a shorter timeout depending on whether the request
-
# is a PATCH, PUT, or POST, and if client is browser or web service.
-
# Can be much shorter if the Stale directive is implemented. This would
-
# allow a user to use new nonce without prompting user again for their
-
# username and password.
-
1
def validate_nonce(secret_key, request, value, seconds_to_timeout=5*60)
-
return false if value.nil?
-
t = ::Base64.decode64(value).split(":").first.to_i
-
nonce(secret_key, t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
-
end
-
-
# Opaque based on random generation - but changing each request?
-
1
def opaque(secret_key)
-
::Digest::MD5.hexdigest(secret_key)
-
end
-
-
end
-
-
# Makes it dead easy to do HTTP Token authentication.
-
#
-
# Simple Token example:
-
#
-
# class PostsController < ApplicationController
-
# TOKEN = "secret"
-
#
-
# before_action :authenticate, except: [ :index ]
-
#
-
# def index
-
# render plain: "Everyone can see me!"
-
# end
-
#
-
# def edit
-
# render plain: "I'm only accessible if you know the password"
-
# end
-
#
-
# private
-
# def authenticate
-
# authenticate_or_request_with_http_token do |token, options|
-
# token == TOKEN
-
# end
-
# end
-
# end
-
#
-
#
-
# Here is a more advanced Token example where only Atom feeds and the XML API is protected by HTTP token authentication,
-
# the regular HTML interface is protected by a session approach:
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :set_account, :authenticate
-
#
-
# protected
-
# def set_account
-
# @account = Account.find_by(url_name: request.subdomains.first)
-
# end
-
#
-
# def authenticate
-
# case request.format
-
# when Mime::XML, Mime::ATOM
-
# if user = authenticate_with_http_token { |t, o| @account.users.authenticate(t, o) }
-
# @current_user = user
-
# else
-
# request_http_token_authentication
-
# end
-
# else
-
# if session_authenticated?
-
# @current_user = @account.users.find(session[:authenticated][:user_id])
-
# else
-
# redirect_to(login_url) and return false
-
# end
-
# end
-
# end
-
# end
-
#
-
#
-
# In your integration tests, you can do something like this:
-
#
-
# def test_access_granted_from_xml
-
# get(
-
# "/notes/1.xml", nil,
-
# 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
-
# )
-
#
-
# assert_equal 200, status
-
# end
-
#
-
#
-
# On shared hosts, Apache sometimes doesn't pass authentication headers to
-
# FCGI instances. If your environment matches this description and you cannot
-
# authenticate, try this rule in your Apache setup:
-
#
-
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
-
1
module Token
-
1
TOKEN_KEY = 'token='
-
1
TOKEN_REGEX = /^Token /
-
1
AUTHN_PAIR_DELIMITERS = /(?:,|;|\t+)/
-
1
extend self
-
-
1
module ControllerMethods
-
1
def authenticate_or_request_with_http_token(realm = "Application", &login_procedure)
-
authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm)
-
end
-
-
1
def authenticate_with_http_token(&login_procedure)
-
Token.authenticate(self, &login_procedure)
-
end
-
-
1
def request_http_token_authentication(realm = "Application")
-
Token.authentication_request(self, realm)
-
end
-
end
-
-
# If token Authorization header is present, call the login
-
# procedure with the present token and options.
-
#
-
# [controller]
-
# ActionController::Base instance for the current request.
-
#
-
# [login_procedure]
-
# Proc to call if a token is present. The Proc should take two arguments:
-
#
-
# authenticate(controller) { |token, options| ... }
-
#
-
# Returns the return value of <tt>login_procedure</tt> if a
-
# token is found. Returns <tt>nil</tt> if no token is found.
-
-
1
def authenticate(controller, &login_procedure)
-
token, options = token_and_options(controller.request)
-
unless token.blank?
-
login_procedure.call(token, options)
-
end
-
end
-
-
# Parses the token and options out of the token authorization header. If
-
# the header looks like this:
-
# Authorization: Token token="abc", nonce="def"
-
# Then the returned token is "abc", and the options is {nonce: "def"}
-
#
-
# request - ActionDispatch::Request instance with the current headers.
-
#
-
# Returns an Array of [String, Hash] if a token is present.
-
# Returns nil if no token is found.
-
1
def token_and_options(request)
-
authorization_request = request.authorization.to_s
-
if authorization_request[TOKEN_REGEX]
-
params = token_params_from authorization_request
-
[params.shift[1], Hash[params].with_indifferent_access]
-
end
-
end
-
-
1
def token_params_from(auth)
-
rewrite_param_values params_array_from raw_params auth
-
end
-
-
# Takes raw_params and turns it into an array of parameters
-
1
def params_array_from(raw_params)
-
raw_params.map { |param| param.split %r/=(.+)?/ }
-
end
-
-
# This removes the <tt>"</tt> characters wrapping the value.
-
1
def rewrite_param_values(array_params)
-
array_params.each { |param| (param[1] || "").gsub! %r/^"|"$/, '' }
-
end
-
-
# This method takes an authorization body and splits up the key-value
-
# pairs by the standardized <tt>:</tt>, <tt>;</tt>, or <tt>\t</tt>
-
# delimiters defined in +AUTHN_PAIR_DELIMITERS+.
-
1
def raw_params(auth)
-
_raw_params = auth.sub(TOKEN_REGEX, '').split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/)
-
-
if !(_raw_params.first =~ %r{\A#{TOKEN_KEY}})
-
_raw_params[0] = "#{TOKEN_KEY}#{_raw_params.first}"
-
end
-
-
_raw_params
-
end
-
-
# Encodes the given token and options into an Authorization header value.
-
#
-
# token - String token.
-
# options - optional Hash of the options.
-
#
-
# Returns String.
-
1
def encode_credentials(token, options = {})
-
values = ["#{TOKEN_KEY}#{token.to_s.inspect}"] + options.map do |key, value|
-
"#{key}=#{value.to_s.inspect}"
-
end
-
"Token #{values * ", "}"
-
end
-
-
# Sets a WWW-Authenticate to let the client know a token is desired.
-
#
-
# controller - ActionController::Base instance for the outgoing response.
-
# realm - String realm to use in the header.
-
#
-
# Returns nothing.
-
1
def authentication_request(controller, realm)
-
controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
-
controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module ImplicitRender
-
1
def send_action(method, *args)
-
66
ret = super
-
66
default_render unless performed?
-
66
ret
-
end
-
-
1
def default_render(*args)
-
55
render(*args)
-
end
-
-
1
def method_for_action(action_name)
-
super || if template_exists?(action_name.to_s, _prefixes)
-
"default_render"
-
66
end
-
end
-
end
-
end
-
1
require 'benchmark'
-
1
require 'abstract_controller/logger'
-
-
1
module ActionController
-
# Adds instrumentation to several ends in ActionController::Base. It also provides
-
# some hooks related with process_action, this allows an ORM like Active Record
-
# and/or DataMapper to plug in ActionController and show related information.
-
#
-
# Check ActiveRecord::Railties::ControllerRuntime for an example.
-
1
module Instrumentation
-
1
extend ActiveSupport::Concern
-
-
1
include AbstractController::Logger
-
1
include ActionController::RackDelegation
-
-
1
attr_internal :view_runtime
-
-
1
def process_action(*args)
-
66
raw_payload = {
-
:controller => self.class.name,
-
:action => self.action_name,
-
:params => request.filtered_parameters,
-
:format => request.format.try(:ref),
-
:method => request.request_method,
-
66
:path => (request.fullpath rescue "unknown")
-
}
-
-
66
ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload.dup)
-
-
66
ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|
-
66
begin
-
66
result = super
-
66
payload[:status] = response.status
-
66
result
-
ensure
-
66
append_info_to_payload(payload)
-
end
-
end
-
end
-
-
1
def render(*args)
-
55
render_output = nil
-
55
self.view_runtime = cleanup_view_runtime do
-
110
Benchmark.ms { render_output = super }
-
end
-
55
render_output
-
end
-
-
1
def send_file(path, options={})
-
ActiveSupport::Notifications.instrument("send_file.action_controller",
-
options.merge(:path => path)) do
-
super
-
end
-
end
-
-
1
def send_data(data, options = {})
-
ActiveSupport::Notifications.instrument("send_data.action_controller", options) do
-
super
-
end
-
end
-
-
1
def redirect_to(*args)
-
11
ActiveSupport::Notifications.instrument("redirect_to.action_controller") do |payload|
-
11
result = super
-
11
payload[:status] = response.status
-
11
payload[:location] = response.filtered_location
-
11
result
-
end
-
end
-
-
1
private
-
-
# A hook invoked every time a before callback is halted.
-
1
def halted_callback_hook(filter)
-
ActiveSupport::Notifications.instrument("halted_callback.action_controller", :filter => filter)
-
end
-
-
# A hook which allows you to clean up any time taken into account in
-
# views wrongly, like database querying time.
-
#
-
# def cleanup_view_runtime
-
# super - time_taken_in_something_expensive
-
# end
-
#
-
# :api: plugin
-
1
def cleanup_view_runtime #:nodoc:
-
55
yield
-
end
-
-
# Every time after an action is processed, this method is invoked
-
# with the payload, so you can add more information.
-
# :api: plugin
-
1
def append_info_to_payload(payload) #:nodoc:
-
66
payload[:view_runtime] = view_runtime
-
end
-
-
1
module ClassMethods
-
# A hook which allows other frameworks to log what happened during
-
# controller process action. This method should return an array
-
# with the messages to be added.
-
# :api: plugin
-
1
def log_process_action(payload) #:nodoc:
-
66
messages, view_runtime = [], payload[:view_runtime]
-
66
messages << ("Views: %.1fms" % view_runtime.to_f) if view_runtime
-
66
messages
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/http/response'
-
1
require 'delegate'
-
1
require 'active_support/json'
-
-
1
module ActionController
-
# Mix this module in to your controller, and all actions in that controller
-
# will be able to stream data to the client as it's written.
-
#
-
# class MyController < ActionController::Base
-
# include ActionController::Live
-
#
-
# def stream
-
# response.headers['Content-Type'] = 'text/event-stream'
-
# 100.times {
-
# response.stream.write "hello world\n"
-
# sleep 1
-
# }
-
# ensure
-
# response.stream.close
-
# end
-
# end
-
#
-
# There are a few caveats with this use. You *cannot* write headers after the
-
# response has been committed (Response#committed? will return truthy).
-
# Calling +write+ or +close+ on the response stream will cause the response
-
# object to be committed. Make sure all headers are set before calling write
-
# or close on your stream.
-
#
-
# You *must* call close on your stream when you're finished, otherwise the
-
# socket may be left open forever.
-
#
-
# The final caveat is that your actions are executed in a separate thread than
-
# the main thread. Make sure your actions are thread safe, and this shouldn't
-
# be a problem (don't share state across threads, etc).
-
1
module Live
-
# This class provides the ability to write an SSE (Server Sent Event)
-
# to an IO stream. The class is initialized with a stream and can be used
-
# to either write a JSON string or an object which can be converted to JSON.
-
#
-
# Writing an object will convert it into standard SSE format with whatever
-
# options you have configured. You may choose to set the following options:
-
#
-
# 1) Event. If specified, an event with this name will be dispatched on
-
# the browser.
-
# 2) Retry. The reconnection time in milliseconds used when attempting
-
# to send the event.
-
# 3) Id. If the connection dies while sending an SSE to the browser, then
-
# the server will receive a +Last-Event-ID+ header with value equal to +id+.
-
#
-
# After setting an option in the constructor of the SSE object, all future
-
# SSEs sent across the stream will use those options unless overridden.
-
#
-
# Example Usage:
-
#
-
# class MyController < ActionController::Base
-
# include ActionController::Live
-
#
-
# def index
-
# response.headers['Content-Type'] = 'text/event-stream'
-
# sse = SSE.new(response.stream, retry: 300, event: "event-name")
-
# sse.write({ name: 'John'})
-
# sse.write({ name: 'John'}, id: 10)
-
# sse.write({ name: 'John'}, id: 10, event: "other-event")
-
# sse.write({ name: 'John'}, id: 10, event: "other-event", retry: 500)
-
# ensure
-
# sse.close
-
# end
-
# end
-
#
-
# Note: SSEs are not currently supported by IE. However, they are supported
-
# by Chrome, Firefox, Opera, and Safari.
-
1
class SSE
-
-
1
WHITELISTED_OPTIONS = %w( retry event id )
-
-
1
def initialize(stream, options = {})
-
@stream = stream
-
@options = options
-
end
-
-
1
def close
-
@stream.close
-
end
-
-
1
def write(object, options = {})
-
case object
-
when String
-
perform_write(object, options)
-
else
-
perform_write(ActiveSupport::JSON.encode(object), options)
-
end
-
end
-
-
1
private
-
-
1
def perform_write(json, options)
-
current_options = @options.merge(options).stringify_keys
-
-
WHITELISTED_OPTIONS.each do |option_name|
-
if (option_value = current_options[option_name])
-
@stream.write "#{option_name}: #{option_value}\n"
-
end
-
end
-
-
message = json.gsub(/\n/, "\ndata: ")
-
@stream.write "data: #{message}\n\n"
-
end
-
end
-
-
1
class ClientDisconnected < RuntimeError
-
end
-
-
1
class Buffer < ActionDispatch::Response::Buffer #:nodoc:
-
1
include MonitorMixin
-
-
# Ignore that the client has disconnected.
-
#
-
# If this value is `true`, calling `write` after the client
-
# disconnects will result in the written content being silently
-
# discarded. If this value is `false` (the default), a
-
# ClientDisconnected exception will be raised.
-
1
attr_accessor :ignore_disconnect
-
-
1
def initialize(response)
-
@error_callback = lambda { true }
-
@cv = new_cond
-
@aborted = false
-
@ignore_disconnect = false
-
super(response, SizedQueue.new(10))
-
end
-
-
1
def write(string)
-
unless @response.committed?
-
@response.headers["Cache-Control"] = "no-cache"
-
@response.headers.delete "Content-Length"
-
end
-
-
super
-
-
unless connected?
-
@buf.clear
-
-
unless @ignore_disconnect
-
# Raise ClientDisconnected, which is a RuntimeError (not an
-
# IOError), because that's more appropriate for something beyond
-
# the developer's control.
-
raise ClientDisconnected, "client disconnected"
-
end
-
end
-
end
-
-
1
def each
-
@response.sending!
-
while str = @buf.pop
-
yield str
-
end
-
@response.sent!
-
end
-
-
# Write a 'close' event to the buffer; the producer/writing thread
-
# uses this to notify us that it's finished supplying content.
-
#
-
# See also #abort.
-
1
def close
-
synchronize do
-
super
-
@buf.push nil
-
@cv.broadcast
-
end
-
end
-
-
# Inform the producer/writing thread that the client has
-
# disconnected; the reading thread is no longer interested in
-
# anything that's being written.
-
#
-
# See also #close.
-
1
def abort
-
synchronize do
-
@aborted = true
-
@buf.clear
-
end
-
end
-
-
# Is the client still connected and waiting for content?
-
#
-
# The result of calling `write` when this is `false` is determined
-
# by `ignore_disconnect`.
-
1
def connected?
-
!@aborted
-
end
-
-
1
def await_close
-
synchronize do
-
@cv.wait_until { @closed }
-
end
-
end
-
-
1
def on_error(&block)
-
@error_callback = block
-
end
-
-
1
def call_on_error
-
@error_callback.call
-
end
-
end
-
-
1
class Response < ActionDispatch::Response #:nodoc: all
-
1
class Header < DelegateClass(Hash) # :nodoc:
-
1
def initialize(response, header)
-
@response = response
-
super(header)
-
end
-
-
1
def []=(k,v)
-
if @response.committed?
-
raise ActionDispatch::IllegalStateError, 'header already sent'
-
end
-
-
super
-
end
-
-
1
def merge(other)
-
self.class.new @response, __getobj__.merge(other)
-
end
-
-
1
def to_hash
-
__getobj__.dup
-
end
-
end
-
-
1
private
-
-
1
def before_committed
-
super
-
jar = request.cookie_jar
-
# The response can be committed multiple times
-
jar.write self unless committed?
-
end
-
-
1
def before_sending
-
super
-
request.cookie_jar.commit!
-
headers.freeze
-
end
-
-
1
def build_buffer(response, body)
-
buf = Live::Buffer.new response
-
body.each { |part| buf.write part }
-
buf
-
end
-
-
1
def merge_default_headers(original, default)
-
Header.new self, super
-
end
-
-
1
def handle_conditional_get!
-
super unless committed?
-
end
-
end
-
-
1
def process(name)
-
t1 = Thread.current
-
locals = t1.keys.map { |key| [key, t1[key]] }
-
-
error = nil
-
# This processes the action in a child thread. It lets us return the
-
# response code and headers back up the rack stack, and still process
-
# the body in parallel with sending data to the client
-
Thread.new {
-
t2 = Thread.current
-
t2.abort_on_exception = true
-
-
# Since we're processing the view in a different thread, copy the
-
# thread locals from the main thread to the child thread. :'(
-
locals.each { |k,v| t2[k] = v }
-
-
begin
-
super(name)
-
rescue => e
-
if @_response.committed?
-
begin
-
@_response.stream.write(ActionView::Base.streaming_completion_on_exception) if request.format == :html
-
@_response.stream.call_on_error
-
rescue => exception
-
log_error(exception)
-
ensure
-
log_error(e)
-
@_response.stream.close
-
end
-
else
-
error = e
-
end
-
ensure
-
@_response.commit!
-
end
-
}
-
-
@_response.await_commit
-
raise error if error
-
end
-
-
1
def log_error(exception)
-
logger = ActionController::Base.logger
-
return unless logger
-
-
logger.fatal do
-
message = "\n#{exception.class} (#{exception.message}):\n"
-
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
-
message << " " << exception.backtrace.join("\n ")
-
"#{message}\n\n"
-
end
-
end
-
-
1
def response_body=(body)
-
super
-
response.close if response
-
end
-
-
1
def set_response!(request)
-
if request.env["HTTP_VERSION"] == "HTTP/1.0"
-
super
-
else
-
@_response = Live::Response.new
-
@_response.request = request
-
end
-
end
-
end
-
end
-
1
require 'abstract_controller/collector'
-
-
1
module ActionController #:nodoc:
-
1
module MimeResponds
-
1
extend ActiveSupport::Concern
-
-
# :stopdoc:
-
1
module ClassMethods
-
1
def respond_to(*)
-
raise NoMethodError, "The controller-level `respond_to' feature has " \
-
"been extracted to the `responders` gem. Add it to your Gemfile to " \
-
"continue using this feature:\n" \
-
" gem 'responders', '~> 2.0'\n" \
-
"Consult the Rails upgrade guide for details."
-
end
-
end
-
-
1
def respond_with(*)
-
raise NoMethodError, "The `respond_with' feature has been extracted " \
-
"to the `responders` gem. Add it to your Gemfile to continue using " \
-
"this feature:\n" \
-
" gem 'responders', '~> 2.0'\n" \
-
"Consult the Rails upgrade guide for details."
-
end
-
# :startdoc:
-
-
# Without web-service support, an action which collects the data for displaying a list of people
-
# might look something like this:
-
#
-
# def index
-
# @people = Person.all
-
# end
-
#
-
# Here's the same action, with web-service support baked in:
-
#
-
# def index
-
# @people = Person.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.xml { render xml: @people }
-
# end
-
# end
-
#
-
# What that says is, "if the client wants HTML in response to this action, just respond as we
-
# would have before, but if the client wants XML, return them the list of people in XML format."
-
# (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
-
#
-
# Supposing you have an action that adds a new person, optionally creating their company
-
# (by name) if it does not already exist, without web-services, it might look like this:
-
#
-
# def create
-
# @company = Company.find_or_create_by(name: params[:company][:name])
-
# @person = @company.people.create(params[:person])
-
#
-
# redirect_to(person_list_url)
-
# end
-
#
-
# Here's the same action, with web-service support baked in:
-
#
-
# def create
-
# company = params[:person].delete(:company)
-
# @company = Company.find_or_create_by(name: company[:name])
-
# @person = @company.people.create(params[:person])
-
#
-
# respond_to do |format|
-
# format.html { redirect_to(person_list_url) }
-
# format.js
-
# format.xml { render xml: @person.to_xml(include: @company) }
-
# end
-
# end
-
#
-
# If the client wants HTML, we just redirect them back to the person list. If they want JavaScript,
-
# then it is an Ajax request and we render the JavaScript template associated with this action.
-
# Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also
-
# include the person's company in the rendered XML, so you get something like this:
-
#
-
# <person>
-
# <id>...</id>
-
# ...
-
# <company>
-
# <id>...</id>
-
# <name>...</name>
-
# ...
-
# </company>
-
# </person>
-
#
-
# Note, however, the extra bit at the top of that action:
-
#
-
# company = params[:person].delete(:company)
-
# @company = Company.find_or_create_by(name: company[:name])
-
#
-
# This is because the incoming XML document (if a web-service request is in process) can only contain a
-
# single root-node. So, we have to rearrange things so that the request looks like this (url-encoded):
-
#
-
# person[name]=...&person[company][name]=...&...
-
#
-
# And, like this (xml-encoded):
-
#
-
# <person>
-
# <name>...</name>
-
# <company>
-
# <name>...</name>
-
# </company>
-
# </person>
-
#
-
# In other words, we make the request so that it operates on a single entity's person. Then, in the action,
-
# we extract the company data from the request, find or create the company, and then create the new person
-
# with the remaining data.
-
#
-
# Note that you can define your own XML parameter parser which would allow you to describe multiple entities
-
# in a single request (i.e., by wrapping them all in a single root node), but if you just go with the flow
-
# and accept Rails' defaults, life will be much easier.
-
#
-
# If you need to use a MIME type which isn't supported by default, you can register your own handlers in
-
# config/initializers/mime_types.rb as follows.
-
#
-
# Mime::Type.register "image/jpg", :jpg
-
#
-
# Respond to also allows you to specify a common block for different formats by using any:
-
#
-
# def index
-
# @people = Person.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.any(:xml, :json) { render request.format.to_sym => @people }
-
# end
-
# end
-
#
-
# In the example above, if the format is xml, it will render:
-
#
-
# render xml: @people
-
#
-
# Or if the format is json:
-
#
-
# render json: @people
-
#
-
# Formats can have different variants.
-
#
-
# The request variant is a specialization of the request format, like <tt>:tablet</tt>,
-
# <tt>:phone</tt>, or <tt>:desktop</tt>.
-
#
-
# We often want to render different html/json/xml templates for phones,
-
# tablets, and desktop browsers. Variants make it easy.
-
#
-
# You can set the variant in a +before_action+:
-
#
-
# request.variant = :tablet if request.user_agent =~ /iPad/
-
#
-
# Respond to variants in the action just like you respond to formats:
-
#
-
# respond_to do |format|
-
# format.html do |variant|
-
# variant.tablet # renders app/views/projects/show.html+tablet.erb
-
# variant.phone { extra_setup; render ... }
-
# variant.none { special_setup } # executed only if there is no variant set
-
# end
-
# end
-
#
-
# Provide separate templates for each format and variant:
-
#
-
# app/views/projects/show.html.erb
-
# app/views/projects/show.html+tablet.erb
-
# app/views/projects/show.html+phone.erb
-
#
-
# When you're not sharing any code within the format, you can simplify defining variants
-
# using the inline syntax:
-
#
-
# respond_to do |format|
-
# format.js { render "trash" }
-
# format.html.phone { redirect_to progress_path }
-
# format.html.none { render "trash" }
-
# end
-
#
-
# Variants also support common `any`/`all` block that formats have.
-
#
-
# It works for both inline:
-
#
-
# respond_to do |format|
-
# format.html.any { render text: "any" }
-
# format.html.phone { render text: "phone" }
-
# end
-
#
-
# and block syntax:
-
#
-
# respond_to do |format|
-
# format.html do |variant|
-
# variant.any(:tablet, :phablet){ render text: "any" }
-
# variant.phone { render text: "phone" }
-
# end
-
# end
-
#
-
# You can also set an array of variants:
-
#
-
# request.variant = [:tablet, :phone]
-
#
-
# which will work similarly to formats and MIME types negotiation. If there will be no
-
# :tablet variant declared, :phone variant will be picked:
-
#
-
# respond_to do |format|
-
# format.html.none
-
# format.html.phone # this gets rendered
-
# end
-
#
-
# Be sure to check the documentation of <tt>ActionController::MimeResponds.respond_to</tt>
-
# for more examples.
-
1
def respond_to(*mimes)
-
3
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
-
-
3
collector = Collector.new(mimes, request.variant)
-
3
yield collector if block_given?
-
-
3
if format = collector.negotiate_format(request)
-
3
_process_format(format)
-
3
response = collector.response
-
3
response ? response.call : render({})
-
else
-
raise ActionController::UnknownFormat
-
end
-
end
-
-
# A container for responses available from the current controller for
-
# requests for different mime-types sent to a particular action.
-
#
-
# The public controller methods +respond_to+ may be called with a block
-
# that is used to define responses to different mime-types, e.g.
-
# for +respond_to+ :
-
#
-
# respond_to do |format|
-
# format.html
-
# format.xml { render xml: @people }
-
# end
-
#
-
# In this usage, the argument passed to the block (+format+ above) is an
-
# instance of the ActionController::MimeResponds::Collector class. This
-
# object serves as a container in which available responses can be stored by
-
# calling any of the dynamically generated, mime-type-specific methods such
-
# as +html+, +xml+ etc on the Collector. Each response is represented by a
-
# corresponding block if present.
-
#
-
# A subsequent call to #negotiate_format(request) will enable the Collector
-
# to determine which specific mime-type it should respond with for the current
-
# request, with this response then being accessible by calling #response.
-
1
class Collector
-
1
include AbstractController::Collector
-
1
attr_accessor :format
-
-
1
def initialize(mimes, variant = nil)
-
3
@responses = {}
-
3
@variant = variant
-
-
3
mimes.each { |mime| @responses["Mime::#{mime.upcase}".constantize] = nil }
-
end
-
-
1
def any(*args, &block)
-
if args.any?
-
args.each { |type| send(type, &block) }
-
else
-
custom(Mime::ALL, &block)
-
end
-
end
-
1
alias :all :any
-
-
1
def custom(mime_type, &block)
-
6
mime_type = Mime::Type.lookup(mime_type.to_s) unless mime_type.is_a?(Mime::Type)
-
6
@responses[mime_type] ||= if block_given?
-
6
block
-
else
-
VariantCollector.new(@variant)
-
end
-
end
-
-
1
def response
-
3
response = @responses.fetch(format, @responses[Mime::ALL])
-
3
if response.is_a?(VariantCollector) # `format.html.phone` - variant inline syntax
-
response.variant
-
3
elsif response.nil? || response.arity == 0 # `format.html` - just a format, call its block
-
3
response
-
else # `format.html{ |variant| variant.phone }` - variant block syntax
-
variant_collector = VariantCollector.new(@variant)
-
response.call(variant_collector) # call format block with variants collector
-
variant_collector.variant
-
end
-
end
-
-
1
def negotiate_format(request)
-
3
@format = request.negotiate_mime(@responses.keys)
-
end
-
-
1
class VariantCollector #:nodoc:
-
1
def initialize(variant = nil)
-
@variant = variant
-
@variants = {}
-
end
-
-
1
def any(*args, &block)
-
if block_given?
-
if args.any? && args.none?{ |a| a == @variant }
-
args.each{ |v| @variants[v] = block }
-
else
-
@variants[:any] = block
-
end
-
end
-
end
-
1
alias :all :any
-
-
1
def method_missing(name, *args, &block)
-
@variants[name] = block if block_given?
-
end
-
-
1
def variant
-
if @variant.nil?
-
@variants[:none] || @variants[:any]
-
elsif (@variants.keys & @variant).any?
-
@variant.each do |v|
-
return @variants[v] if @variants.key?(v)
-
end
-
else
-
@variants[:any]
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/struct'
-
1
require 'action_dispatch/http/mime_type'
-
-
1
module ActionController
-
# Wraps the parameters hash into a nested hash. This will allow clients to
-
# submit requests without having to specify any root elements.
-
#
-
# This functionality is enabled in +config/initializers/wrap_parameters.rb+
-
# and can be customized. If you are upgrading to \Rails 3.1, this file will
-
# need to be created for the functionality to be enabled.
-
#
-
# You could also turn it on per controller by setting the format array to
-
# a non-empty array:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters format: [:json, :xml, :url_encoded_form, :multipart_form]
-
# end
-
#
-
# If you enable +ParamsWrapper+ for +:json+ format, instead of having to
-
# send JSON parameters like this:
-
#
-
# {"user": {"name": "Konata"}}
-
#
-
# You can send parameters like this:
-
#
-
# {"name": "Konata"}
-
#
-
# And it will be wrapped into a nested hash with the key name matching the
-
# controller's name. For example, if you're posting to +UsersController+,
-
# your new +params+ hash will look like this:
-
#
-
# {"name" => "Konata", "user" => {"name" => "Konata"}}
-
#
-
# You can also specify the key in which the parameters should be wrapped to,
-
# and also the list of attributes it should wrap by using either +:include+ or
-
# +:exclude+ options like this:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters :person, include: [:username, :password]
-
# end
-
#
-
# On ActiveRecord models with no +:include+ or +:exclude+ option set,
-
# it will only wrap the parameters returned by the class method
-
# <tt>attribute_names</tt>.
-
#
-
# If you're going to pass the parameters to an +ActiveModel+ object (such as
-
# <tt>User.new(params[:user])</tt>), you might consider passing the model class to
-
# the method instead. The +ParamsWrapper+ will actually try to determine the
-
# list of attribute names from the model and only wrap those attributes:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters Person
-
# end
-
#
-
# You still could pass +:include+ and +:exclude+ to set the list of attributes
-
# you want to wrap.
-
#
-
# By default, if you don't specify the key in which the parameters would be
-
# wrapped to, +ParamsWrapper+ will actually try to determine if there's
-
# a model related to it or not. This controller, for example:
-
#
-
# class Admin::UsersController < ApplicationController
-
# end
-
#
-
# will try to check if <tt>Admin::User</tt> or +User+ model exists, and use it to
-
# determine the wrapper key respectively. If both models don't exist,
-
# it will then fallback to use +user+ as the key.
-
1
module ParamsWrapper
-
1
extend ActiveSupport::Concern
-
-
1
EXCLUDE_PARAMETERS = %w(authenticity_token _method utf8)
-
-
1
require 'mutex_m'
-
-
1
class Options < Struct.new(:name, :format, :include, :exclude, :klass, :model) # :nodoc:
-
1
include Mutex_m
-
-
1
def self.from_hash(hash)
-
2
name = hash[:name]
-
2
format = Array(hash[:format])
-
2
include = hash[:include] && Array(hash[:include]).collect(&:to_s)
-
2
exclude = hash[:exclude] && Array(hash[:exclude]).collect(&:to_s)
-
2
new name, format, include, exclude, nil, nil
-
end
-
-
1
def initialize(name, format, include, exclude, klass, model) # nodoc
-
2
super
-
2
@include_set = include
-
2
@name_set = name
-
end
-
-
1
def model
-
super || synchronize { super || self.model = _default_wrap_model }
-
end
-
-
1
def include
-
return super if @include_set
-
-
m = model
-
synchronize do
-
return super if @include_set
-
-
@include_set = true
-
-
unless super || exclude
-
if m.respond_to?(:attribute_names) && m.attribute_names.any?
-
self.include = m.attribute_names
-
end
-
end
-
end
-
end
-
-
1
def name
-
return super if @name_set
-
-
m = model
-
synchronize do
-
return super if @name_set
-
-
@name_set = true
-
-
unless super || klass.anonymous?
-
self.name = m ? m.to_s.demodulize.underscore :
-
klass.controller_name.singularize
-
end
-
end
-
end
-
-
1
private
-
# Determine the wrapper model from the controller's name. By convention,
-
# this could be done by trying to find the defined model that has the
-
# same singularize name as the controller. For example, +UsersController+
-
# will try to find if the +User+ model exists.
-
#
-
# This method also does namespace lookup. Foo::Bar::UsersController will
-
# try to find Foo::Bar::User, Foo::User and finally User.
-
1
def _default_wrap_model #:nodoc:
-
return nil if klass.anonymous?
-
model_name = klass.name.sub(/Controller$/, '').classify
-
-
begin
-
if model_klass = model_name.safe_constantize
-
model_klass
-
else
-
namespaces = model_name.split("::")
-
namespaces.delete_at(-2)
-
break if namespaces.last == model_name
-
model_name = namespaces.join("::")
-
end
-
end until model_klass
-
-
model_klass
-
end
-
end
-
-
1
included do
-
1
class_attribute :_wrapper_options
-
1
self._wrapper_options = Options.from_hash(format: [])
-
end
-
-
1
module ClassMethods
-
1
def _set_wrapper_options(options)
-
self._wrapper_options = Options.from_hash(options)
-
end
-
-
# Sets the name of the wrapper key, or the model which +ParamsWrapper+
-
# would use to determine the attribute names from.
-
#
-
# ==== Examples
-
# wrap_parameters format: :xml
-
# # enables the parameter wrapper for XML format
-
#
-
# wrap_parameters :person
-
# # wraps parameters into +params[:person]+ hash
-
#
-
# wrap_parameters Person
-
# # wraps parameters by determining the wrapper key from Person class
-
# (+person+, in this case) and the list of attribute names
-
#
-
# wrap_parameters include: [:username, :title]
-
# # wraps only +:username+ and +:title+ attributes from parameters.
-
#
-
# wrap_parameters false
-
# # disables parameters wrapping for this controller altogether.
-
#
-
# ==== Options
-
# * <tt>:format</tt> - The list of formats in which the parameters wrapper
-
# will be enabled.
-
# * <tt>:include</tt> - The list of attribute names which parameters wrapper
-
# will wrap into a nested hash.
-
# * <tt>:exclude</tt> - The list of attribute names which parameters wrapper
-
# will exclude from a nested hash.
-
1
def wrap_parameters(name_or_model_or_options, options = {})
-
1
model = nil
-
-
1
case name_or_model_or_options
-
when Hash
-
1
options = name_or_model_or_options
-
when false
-
options = options.merge(:format => [])
-
when Symbol, String
-
options = options.merge(:name => name_or_model_or_options)
-
else
-
model = name_or_model_or_options
-
end
-
-
1
opts = Options.from_hash _wrapper_options.to_h.slice(:format).merge(options)
-
1
opts.model = model
-
1
opts.klass = self
-
-
1
self._wrapper_options = opts
-
end
-
-
# Sets the default wrapper key or model which will be used to determine
-
# wrapper key and attribute names. Will be called automatically when the
-
# module is inherited.
-
1
def inherited(klass)
-
6
if klass._wrapper_options.format.any?
-
6
params = klass._wrapper_options.dup
-
6
params.klass = klass
-
6
klass._wrapper_options = params
-
end
-
6
super
-
end
-
end
-
-
# Performs parameters wrapping upon the request. Will be called automatically
-
# by the metal call stack.
-
1
def process_action(*args)
-
66
if _wrapper_enabled?
-
if request.parameters[_wrapper_key].present?
-
wrapped_hash = _extract_parameters(request.parameters)
-
else
-
wrapped_hash = _wrap_parameters request.request_parameters
-
end
-
-
wrapped_keys = request.request_parameters.keys
-
wrapped_filtered_hash = _wrap_parameters request.filtered_parameters.slice(*wrapped_keys)
-
-
# This will make the wrapped hash accessible from controller and view
-
request.parameters.merge! wrapped_hash
-
request.request_parameters.merge! wrapped_hash
-
-
# This will display the wrapped hash in the log file
-
request.filtered_parameters.merge! wrapped_filtered_hash
-
end
-
66
super
-
end
-
-
1
private
-
-
# Returns the wrapper key which will be used to stored wrapped parameters.
-
1
def _wrapper_key
-
_wrapper_options.name
-
end
-
-
# Returns the list of enabled formats.
-
1
def _wrapper_formats
-
66
_wrapper_options.format
-
end
-
-
# Returns the list of parameters which will be selected for wrapped.
-
1
def _wrap_parameters(parameters)
-
{ _wrapper_key => _extract_parameters(parameters) }
-
end
-
-
1
def _extract_parameters(parameters)
-
if include_only = _wrapper_options.include
-
parameters.slice(*include_only)
-
else
-
exclude = _wrapper_options.exclude || []
-
parameters.except(*(exclude + EXCLUDE_PARAMETERS))
-
end
-
end
-
-
# Checks if we should perform parameters wrapping.
-
1
def _wrapper_enabled?
-
66
ref = request.content_mime_type.try(:ref)
-
66
_wrapper_formats.include?(ref) && _wrapper_key && !request.request_parameters[_wrapper_key]
-
end
-
end
-
end
-
1
require 'action_dispatch/http/request'
-
1
require 'action_dispatch/http/response'
-
-
1
module ActionController
-
1
module RackDelegation
-
1
extend ActiveSupport::Concern
-
-
1
delegate :headers, :status=, :location=, :content_type=,
-
:status, :location, :content_type, :response_code, :to => "@_response"
-
-
1
def dispatch(action, request)
-
66
set_response!(request)
-
66
super(action, request)
-
end
-
-
1
def response_body=(body)
-
66
response.body = body if response
-
66
super
-
end
-
-
1
def reset_session
-
@_request.reset_session
-
end
-
-
1
private
-
-
1
def set_response!(request)
-
66
@_response = ActionDispatch::Response.new
-
66
@_response.request = request
-
end
-
end
-
end
-
1
module ActionController
-
1
class RedirectBackError < AbstractController::Error #:nodoc:
-
1
DEFAULT_MESSAGE = 'No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env["HTTP_REFERER"].'
-
-
1
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
1
module Redirecting
-
1
extend ActiveSupport::Concern
-
-
1
include AbstractController::Logger
-
1
include ActionController::RackDelegation
-
1
include ActionController::UrlFor
-
-
# Redirects the browser to the target specified in +options+. This parameter can be any one of:
-
#
-
# * <tt>Hash</tt> - The URL will be generated by calling url_for with the +options+.
-
# * <tt>Record</tt> - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record.
-
# * <tt>String</tt> starting with <tt>protocol://</tt> (like <tt>http://</tt>) or a protocol relative reference (like <tt>//</tt>) - Is passed straight through as the target for redirection.
-
# * <tt>String</tt> not containing a protocol - The current protocol and host is prepended to the string.
-
# * <tt>Proc</tt> - A block that will be executed in the controller's context. Should return any option accepted by +redirect_to+.
-
# * <tt>:back</tt> - Back to the page that issued the request. Useful for forms that are triggered from multiple places.
-
# Short-hand for <tt>redirect_to(request.env["HTTP_REFERER"])</tt>
-
#
-
# === Examples:
-
#
-
# redirect_to action: "show", id: 5
-
# redirect_to post
-
# redirect_to "http://www.rubyonrails.org"
-
# redirect_to "/images/screenshot.jpg"
-
# redirect_to articles_url
-
# redirect_to :back
-
# redirect_to proc { edit_post_url(@post) }
-
#
-
# The redirection happens as a "302 Found" header unless otherwise specified using the <tt>:status</tt> option:
-
#
-
# redirect_to post_url(@post), status: :found
-
# redirect_to action: 'atom', status: :moved_permanently
-
# redirect_to post_url(@post), status: 301
-
# redirect_to action: 'atom', status: 302
-
#
-
# The status code can either be a standard {HTTP Status code}[http://www.iana.org/assignments/http-status-codes] as an
-
# integer, or a symbol representing the downcased, underscored and symbolized description.
-
# Note that the status code must be a 3xx HTTP code, or redirection will not occur.
-
#
-
# If you are using XHR requests other than GET or POST and redirecting after the
-
# request then some browsers will follow the redirect using the original request
-
# method. This may lead to undesirable behavior such as a double DELETE. To work
-
# around this you can return a <tt>303 See Other</tt> status code which will be
-
# followed using a GET request.
-
#
-
# redirect_to posts_url, status: :see_other
-
# redirect_to action: 'index', status: 303
-
#
-
# It is also possible to assign a flash message as part of the redirection. There are two special accessors for the commonly used flash names
-
# +alert+ and +notice+ as well as a general purpose +flash+ bucket.
-
#
-
# redirect_to post_url(@post), alert: "Watch it, mister!"
-
# redirect_to post_url(@post), status: :found, notice: "Pay attention to the road"
-
# redirect_to post_url(@post), status: 301, flash: { updated_post_id: @post.id }
-
# redirect_to({ action: 'atom' }, alert: "Something serious happened")
-
#
-
# When using <tt>redirect_to :back</tt>, if there is no referrer,
-
# <tt>ActionController::RedirectBackError</tt> will be raised. You
-
# may specify some fallback behavior for this case by rescuing
-
# <tt>ActionController::RedirectBackError</tt>.
-
1
def redirect_to(options = {}, response_status = {}) #:doc:
-
11
raise ActionControllerError.new("Cannot redirect to nil!") unless options
-
11
raise ActionControllerError.new("Cannot redirect to a parameter hash!") if options.is_a?(ActionController::Parameters)
-
11
raise AbstractController::DoubleRenderError if response_body
-
-
11
self.status = _extract_redirect_to_status(options, response_status)
-
11
self.location = _compute_redirect_to_location(request, options)
-
11
self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.unwrapped_html_escape(location)}\">redirected</a>.</body></html>"
-
end
-
-
1
def _compute_redirect_to_location(request, options) #:nodoc:
-
case options
-
# The scheme name consist of a letter followed by any combination of
-
# letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
-
# characters; and is terminated by a colon (":").
-
# See http://tools.ietf.org/html/rfc3986#section-3.1
-
# The protocol relative scheme starts with a double slash "//".
-
when /\A([a-z][a-z\d\-+\.]*:|\/\/).*/i
-
1
options
-
when String
-
3
request.protocol + request.host_with_port + options
-
when :back
-
request.headers["Referer"] or raise RedirectBackError
-
when Proc
-
_compute_redirect_to_location request, options.call
-
else
-
7
url_for(options)
-
11
end.delete("\0\r\n")
-
end
-
1
module_function :_compute_redirect_to_location
-
1
public :_compute_redirect_to_location
-
-
1
private
-
1
def _extract_redirect_to_status(options, response_status)
-
11
if options.is_a?(Hash) && options.key?(:status)
-
Rack::Utils.status_code(options.delete(:status))
-
11
elsif response_status.key?(:status)
-
Rack::Utils.status_code(response_status[:status])
-
else
-
11
302
-
end
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module ActionController
-
# See <tt>Renderers.add</tt>
-
1
def self.add_renderer(key, &block)
-
Renderers.add(key, &block)
-
end
-
-
# See <tt>Renderers.remove</tt>
-
1
def self.remove_renderer(key)
-
Renderers.remove(key)
-
end
-
-
1
class MissingRenderer < LoadError
-
1
def initialize(format)
-
super "No renderer defined for format: #{format}"
-
end
-
end
-
-
1
module Renderers
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :_renderers
-
1
self._renderers = Set.new.freeze
-
end
-
-
1
module ClassMethods
-
1
def use_renderers(*args)
-
renderers = _renderers + args
-
self._renderers = renderers.freeze
-
end
-
1
alias use_renderer use_renderers
-
end
-
-
1
def render_to_body(options)
-
55
_render_to_body_with_renderer(options) || super
-
end
-
-
1
def _render_to_body_with_renderer(options)
-
55
_renderers.each do |name|
-
165
if options.key?(name)
-
_process_options(options)
-
method_name = Renderers._render_with_renderer_method_name(name)
-
return send(method_name, options.delete(name), options)
-
end
-
end
-
nil
-
end
-
-
# A Set containing renderer names that correspond to available renderer procs.
-
# Default values are <tt>:json</tt>, <tt>:js</tt>, <tt>:xml</tt>.
-
1
RENDERERS = Set.new
-
-
1
def self._render_with_renderer_method_name(key)
-
3
"_render_with_renderer_#{key}"
-
end
-
-
# Adds a new renderer to call within controller actions.
-
# A renderer is invoked by passing its name as an option to
-
# <tt>AbstractController::Rendering#render</tt>. To create a renderer
-
# pass it a name and a block. The block takes two arguments, the first
-
# is the value paired with its key and the second is the remaining
-
# hash of options passed to +render+.
-
#
-
# Create a csv renderer:
-
#
-
# ActionController::Renderers.add :csv do |obj, options|
-
# filename = options[:filename] || 'data'
-
# str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s
-
# send_data str, type: Mime::CSV,
-
# disposition: "attachment; filename=#{filename}.csv"
-
# end
-
#
-
# Note that we used Mime::CSV for the csv mime type as it comes with Rails.
-
# For a custom renderer, you'll need to register a mime type with
-
# <tt>Mime::Type.register</tt>.
-
#
-
# To use the csv renderer in a controller action:
-
#
-
# def show
-
# @csvable = Csvable.find(params[:id])
-
# respond_to do |format|
-
# format.html
-
# format.csv { render csv: @csvable, filename: @csvable.name }
-
# end
-
# end
-
# To use renderers and their mime types in more concise ways, see
-
# <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt>
-
1
def self.add(key, &block)
-
3
define_method(_render_with_renderer_method_name(key), &block)
-
3
RENDERERS << key.to_sym
-
end
-
-
# This method is the opposite of add method.
-
#
-
# Usage:
-
#
-
# ActionController::Renderers.remove(:csv)
-
1
def self.remove(key)
-
RENDERERS.delete(key.to_sym)
-
method_name = _render_with_renderer_method_name(key)
-
remove_method(method_name) if method_defined?(method_name)
-
end
-
-
1
module All
-
1
extend ActiveSupport::Concern
-
1
include Renderers
-
-
1
included do
-
1
self._renderers = RENDERERS
-
end
-
end
-
-
1
add :json do |json, options|
-
json = json.to_json(options) unless json.kind_of?(String)
-
-
if options[:callback].present?
-
if content_type.nil? || content_type == Mime::JSON
-
self.content_type = Mime::JS
-
end
-
-
"/**/#{options[:callback]}(#{json})"
-
else
-
self.content_type ||= Mime::JSON
-
json
-
end
-
end
-
-
1
add :js do |js, options|
-
self.content_type ||= Mime::JS
-
js.respond_to?(:to_js) ? js.to_js(options) : js
-
end
-
-
1
add :xml do |xml, options|
-
self.content_type ||= Mime::XML
-
xml.respond_to?(:to_xml) ? xml.to_xml(options) : xml
-
end
-
end
-
end
-
1
module ActionController
-
1
module Rendering
-
1
extend ActiveSupport::Concern
-
-
1
RENDER_FORMATS_IN_PRIORITY = [:body, :text, :plain, :html]
-
-
# Before processing, set the request formats in current controller formats.
-
1
def process_action(*) #:nodoc:
-
66
self.formats = request.formats.map(&:ref).compact
-
66
super
-
end
-
-
# Check for double render errors and set the content_type after rendering.
-
1
def render(*args) #:nodoc:
-
55
raise ::AbstractController::DoubleRenderError if self.response_body
-
55
super
-
end
-
-
# Overwrite render_to_string because body can now be set to a rack body.
-
1
def render_to_string(*)
-
result = super
-
if result.respond_to?(:each)
-
string = ""
-
result.each { |r| string << r }
-
string
-
else
-
result
-
end
-
end
-
-
1
def render_to_body(options = {})
-
55
super || _render_in_priorities(options) || ' '
-
end
-
-
1
private
-
-
1
def _render_in_priorities(options)
-
RENDER_FORMATS_IN_PRIORITY.each do |format|
-
return options[format] if options.key?(format)
-
end
-
-
nil
-
end
-
-
1
def _process_format(format, options = {})
-
58
super
-
-
58
if options[:plain]
-
self.content_type = Mime::TEXT
-
else
-
58
self.content_type ||= format.to_s
-
end
-
end
-
-
# Normalize arguments by catching blocks and setting them on :update.
-
1
def _normalize_args(action=nil, options={}, &blk) #:nodoc:
-
55
options = super
-
55
options[:update] = blk if block_given?
-
55
options
-
end
-
-
# Normalize both text and status options.
-
1
def _normalize_options(options) #:nodoc:
-
55
_normalize_text(options)
-
-
55
if options[:html]
-
options[:html] = ERB::Util.html_escape(options[:html])
-
end
-
-
55
if options.delete(:nothing)
-
options[:body] = nil
-
end
-
-
55
if options[:status]
-
options[:status] = Rack::Utils.status_code(options[:status])
-
end
-
-
55
super
-
end
-
-
1
def _normalize_text(options)
-
55
RENDER_FORMATS_IN_PRIORITY.each do |format|
-
220
if options.key?(format) && options[format].respond_to?(:to_text)
-
options[format] = options[format].to_text
-
end
-
end
-
end
-
-
# Process controller specific options, as status, content-type and location.
-
1
def _process_options(options) #:nodoc:
-
55
status, content_type, location = options.values_at(:status, :content_type, :location)
-
-
55
self.status = status if status
-
55
self.content_type = content_type if content_type
-
55
self.headers["Location"] = url_for(location) if location
-
-
55
super
-
end
-
end
-
end
-
1
require 'rack/session/abstract/id'
-
1
require 'action_controller/metal/exceptions'
-
1
require 'active_support/security_utils'
-
-
1
module ActionController #:nodoc:
-
1
class InvalidAuthenticityToken < ActionControllerError #:nodoc:
-
end
-
-
1
class InvalidCrossOriginRequest < ActionControllerError #:nodoc:
-
end
-
-
# Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks
-
# by including a token in the rendered HTML for your application. This token is
-
# stored as a random string in the session, to which an attacker does not have
-
# access. When a request reaches your application, \Rails verifies the received
-
# token with the token in the session. Only HTML and JavaScript requests are checked,
-
# so this will not protect your XML API (presumably you'll have a different
-
# authentication scheme there anyway).
-
#
-
# GET requests are not protected since they don't have side effects like writing
-
# to the database and don't leak sensitive information. JavaScript requests are
-
# an exception: a third-party site can use a <script> tag to reference a JavaScript
-
# URL on your site. When your JavaScript response loads on their site, it executes.
-
# With carefully crafted JavaScript on their end, sensitive data in your JavaScript
-
# response may be extracted. To prevent this, only XmlHttpRequest (known as XHR or
-
# Ajax) requests are allowed to make GET requests for JavaScript responses.
-
#
-
# It's important to remember that XML or JSON requests are also affected and if
-
# you're building an API you'll need something like:
-
#
-
# class ApplicationController < ActionController::Base
-
# protect_from_forgery
-
# skip_before_action :verify_authenticity_token, if: :json_request?
-
#
-
# protected
-
#
-
# def json_request?
-
# request.format.json?
-
# end
-
# end
-
#
-
# CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
-
# which checks the token and resets the session if it doesn't match what was expected.
-
# A call to this method is generated for new \Rails applications by default.
-
#
-
# The token parameter is named <tt>authenticity_token</tt> by default. The name and
-
# value of this token must be added to every layout that renders forms by including
-
# <tt>csrf_meta_tags</tt> in the HTML +head+.
-
#
-
# Learn more about CSRF attacks and securing your application in the
-
# {Ruby on Rails Security Guide}[http://guides.rubyonrails.org/security.html].
-
1
module RequestForgeryProtection
-
1
extend ActiveSupport::Concern
-
-
1
include AbstractController::Helpers
-
1
include AbstractController::Callbacks
-
-
1
included do
-
# Sets the token parameter name for RequestForgery. Calling +protect_from_forgery+
-
# sets it to <tt>:authenticity_token</tt> by default.
-
1
config_accessor :request_forgery_protection_token
-
1
self.request_forgery_protection_token ||= :authenticity_token
-
-
# Holds the class which implements the request forgery protection.
-
1
config_accessor :forgery_protection_strategy
-
1
self.forgery_protection_strategy = nil
-
-
# Controls whether request forgery protection is turned on or not. Turned off by default only in test mode.
-
1
config_accessor :allow_forgery_protection
-
1
self.allow_forgery_protection = true if allow_forgery_protection.nil?
-
-
# Controls whether a CSRF failure logs a warning. On by default.
-
1
config_accessor :log_warning_on_csrf_failure
-
1
self.log_warning_on_csrf_failure = true
-
-
1
helper_method :form_authenticity_token
-
1
helper_method :protect_against_forgery?
-
end
-
-
1
module ClassMethods
-
# Turn on request forgery protection. Bear in mind that GET and HEAD requests are not checked.
-
#
-
# class ApplicationController < ActionController::Base
-
# protect_from_forgery
-
# end
-
#
-
# class FooController < ApplicationController
-
# protect_from_forgery except: :index
-
#
-
# You can disable CSRF protection on controller by skipping the verification before_action:
-
# skip_before_action :verify_authenticity_token
-
#
-
# Valid Options:
-
#
-
# * <tt>:only/:except</tt> - Passed to the <tt>before_action</tt> call. Set which actions are verified.
-
# * <tt>:with</tt> - Set the method to handle unverified request.
-
#
-
# Valid unverified request handling methods are:
-
# * <tt>:exception</tt> - Raises ActionController::InvalidAuthenticityToken exception.
-
# * <tt>:reset_session</tt> - Resets the session.
-
# * <tt>:null_session</tt> - Provides an empty session during request but doesn't reset it completely. Used as default if <tt>:with</tt> option is not specified.
-
1
def protect_from_forgery(options = {})
-
1
self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
-
1
self.request_forgery_protection_token ||= :authenticity_token
-
1
prepend_before_action :verify_authenticity_token, options
-
1
append_after_action :verify_same_origin_request
-
end
-
-
1
private
-
-
1
def protection_method_class(name)
-
1
ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)
-
rescue NameError
-
raise ArgumentError, 'Invalid request forgery protection method, use :null_session, :exception, or :reset_session'
-
end
-
end
-
-
1
module ProtectionMethods
-
1
class NullSession
-
1
def initialize(controller)
-
@controller = controller
-
end
-
-
# This is the method that defines the application behavior when a request is found to be unverified.
-
1
def handle_unverified_request
-
request = @controller.request
-
request.session = NullSessionHash.new(request.env)
-
request.env['action_dispatch.request.flash_hash'] = nil
-
request.env['rack.session.options'] = { skip: true }
-
request.env['action_dispatch.cookies'] = NullCookieJar.build(request)
-
end
-
-
1
protected
-
-
1
class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc:
-
1
def initialize(env)
-
super(nil, env)
-
@data = {}
-
@loaded = true
-
end
-
-
# no-op
-
1
def destroy; end
-
-
1
def exists?
-
true
-
end
-
end
-
-
1
class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc:
-
1
def self.build(request)
-
key_generator = request.env[ActionDispatch::Cookies::GENERATOR_KEY]
-
host = request.host
-
secure = request.ssl?
-
-
new(key_generator, host, secure, options_for_env({}))
-
end
-
-
1
def write(*)
-
# nothing
-
end
-
end
-
end
-
-
1
class ResetSession
-
1
def initialize(controller)
-
@controller = controller
-
end
-
-
1
def handle_unverified_request
-
@controller.reset_session
-
end
-
end
-
-
1
class Exception
-
1
def initialize(controller)
-
@controller = controller
-
end
-
-
1
def handle_unverified_request
-
raise ActionController::InvalidAuthenticityToken
-
end
-
end
-
end
-
-
1
protected
-
# The actual before_action that is used to verify the CSRF token.
-
# Don't override this directly. Provide your own forgery protection
-
# strategy instead. If you override, you'll disable same-origin
-
# `<script>` verification.
-
#
-
# Lean on the protect_from_forgery declaration to mark which actions are
-
# due for same-origin request verification. If protect_from_forgery is
-
# enabled on an action, this before_action flags its after_action to
-
# verify that JavaScript responses are for XHR requests, ensuring they
-
# follow the browser's same-origin policy.
-
1
def verify_authenticity_token
-
66
mark_for_same_origin_verification!
-
-
66
if !verified_request?
-
if logger && log_warning_on_csrf_failure
-
logger.warn "Can't verify CSRF token authenticity"
-
end
-
handle_unverified_request
-
end
-
end
-
-
1
def handle_unverified_request
-
forgery_protection_strategy.new(self).handle_unverified_request
-
end
-
-
#:nodoc:
-
1
CROSS_ORIGIN_JAVASCRIPT_WARNING = "Security warning: an embedded " \
-
"<script> tag on another site requested protected JavaScript. " \
-
"If you know what you're doing, go ahead and disable forgery " \
-
"protection on this action to permit cross-origin JavaScript embedding."
-
1
private_constant :CROSS_ORIGIN_JAVASCRIPT_WARNING
-
-
# If `verify_authenticity_token` was run (indicating that we have
-
# forgery protection enabled for this request) then also verify that
-
# we aren't serving an unauthorized cross-origin response.
-
1
def verify_same_origin_request
-
66
if marked_for_same_origin_verification? && non_xhr_javascript_response?
-
logger.warn CROSS_ORIGIN_JAVASCRIPT_WARNING if logger
-
raise ActionController::InvalidCrossOriginRequest, CROSS_ORIGIN_JAVASCRIPT_WARNING
-
end
-
end
-
-
# GET requests are checked for cross-origin JavaScript after rendering.
-
1
def mark_for_same_origin_verification!
-
66
@marked_for_same_origin_verification = request.get?
-
end
-
-
# If the `verify_authenticity_token` before_action ran, verify that
-
# JavaScript responses are only served to same-origin GET requests.
-
1
def marked_for_same_origin_verification?
-
66
@marked_for_same_origin_verification ||= false
-
end
-
-
# Check for cross-origin JavaScript responses.
-
1
def non_xhr_javascript_response?
-
55
content_type =~ %r(\Atext/javascript) && !request.xhr?
-
end
-
-
1
AUTHENTICITY_TOKEN_LENGTH = 32
-
-
# Returns true or false if a request is verified. Checks:
-
#
-
# * is it a GET or HEAD request? Gets should be safe and idempotent
-
# * Does the form_authenticity_token match the given token value from the params?
-
# * Does the X-CSRF-Token header match the form_authenticity_token
-
1
def verified_request?
-
66
!protect_against_forgery? || request.get? || request.head? ||
-
valid_authenticity_token?(session, form_authenticity_param) ||
-
valid_authenticity_token?(session, request.headers['X-CSRF-Token'])
-
end
-
-
# Sets the token value for the current session.
-
1
def form_authenticity_token
-
masked_authenticity_token(session)
-
end
-
-
# Creates a masked version of the authenticity token that varies
-
# on each request. The masking is used to mitigate SSL attacks
-
# like BREACH.
-
1
def masked_authenticity_token(session)
-
one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)
-
encrypted_csrf_token = xor_byte_strings(one_time_pad, real_csrf_token(session))
-
masked_token = one_time_pad + encrypted_csrf_token
-
Base64.strict_encode64(masked_token)
-
end
-
-
# Checks the client's masked token to see if it matches the
-
# session token. Essentially the inverse of
-
# +masked_authenticity_token+.
-
1
def valid_authenticity_token?(session, encoded_masked_token)
-
if encoded_masked_token.nil? || encoded_masked_token.empty? || !encoded_masked_token.is_a?(String)
-
return false
-
end
-
-
begin
-
masked_token = Base64.strict_decode64(encoded_masked_token)
-
rescue ArgumentError # encoded_masked_token is invalid Base64
-
return false
-
end
-
-
# See if it's actually a masked token or not. In order to
-
# deploy this code, we should be able to handle any unmasked
-
# tokens that we've issued without error.
-
-
if masked_token.length == AUTHENTICITY_TOKEN_LENGTH
-
# This is actually an unmasked token. This is expected if
-
# you have just upgraded to masked tokens, but should stop
-
# happening shortly after installing this gem
-
compare_with_real_token masked_token, session
-
-
elsif masked_token.length == AUTHENTICITY_TOKEN_LENGTH * 2
-
# Split the token into the one-time pad and the encrypted
-
# value and decrypt it
-
one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH]
-
encrypted_csrf_token = masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]
-
csrf_token = xor_byte_strings(one_time_pad, encrypted_csrf_token)
-
-
compare_with_real_token csrf_token, session
-
-
else
-
false # Token is malformed
-
end
-
end
-
-
1
def compare_with_real_token(token, session)
-
ActiveSupport::SecurityUtils.secure_compare(token, real_csrf_token(session))
-
end
-
-
1
def real_csrf_token(session)
-
session[:_csrf_token] ||= SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH)
-
Base64.strict_decode64(session[:_csrf_token])
-
end
-
-
1
def xor_byte_strings(s1, s2)
-
s1.bytes.zip(s2.bytes).map { |(c1,c2)| c1 ^ c2 }.pack('c*')
-
end
-
-
# The form's authenticity parameter. Override to provide your own.
-
1
def form_authenticity_param
-
params[request_forgery_protection_token]
-
end
-
-
# Checks if the controller allows forgery protection.
-
1
def protect_against_forgery?
-
129
allow_forgery_protection
-
end
-
end
-
end
-
1
module ActionController #:nodoc:
-
# This module is responsible to provide `rescue_from` helpers
-
# to controllers and configure when detailed exceptions must be
-
# shown.
-
1
module Rescue
-
1
extend ActiveSupport::Concern
-
1
include ActiveSupport::Rescuable
-
-
1
def rescue_with_handler(exception)
-
if (exception.respond_to?(:original_exception) &&
-
(orig_exception = exception.original_exception) &&
-
handler_for_rescue(orig_exception))
-
exception = orig_exception
-
end
-
super(exception)
-
end
-
-
# Override this method if you want to customize when detailed
-
# exceptions must be shown. This method is only called when
-
# consider_all_requests_local is false. By default, it returns
-
# false, but someone may set it to `request.local?` so local
-
# requests in production still shows the detailed exception pages.
-
1
def show_detailed_exceptions?
-
false
-
end
-
-
1
private
-
1
def process_action(*args)
-
66
super
-
rescue Exception => exception
-
request.env['action_dispatch.show_detailed_exceptions'] ||= show_detailed_exceptions?
-
rescue_with_handler(exception) || raise(exception)
-
end
-
end
-
end
-
1
require 'rack/chunked'
-
-
1
module ActionController #:nodoc:
-
# Allows views to be streamed back to the client as they are rendered.
-
#
-
# The default way Rails renders views is by first rendering the template
-
# and then the layout. The response is sent to the client after the whole
-
# template is rendered, all queries are made, and the layout is processed.
-
#
-
# Streaming inverts the rendering flow by rendering the layout first and
-
# streaming each part of the layout as they are processed. This allows the
-
# header of the HTML (which is usually in the layout) to be streamed back
-
# to client very quickly, allowing JavaScripts and stylesheets to be loaded
-
# earlier than usual.
-
#
-
# This approach was introduced in Rails 3.1 and is still improving. Several
-
# Rack middlewares may not work and you need to be careful when streaming.
-
# Those points are going to be addressed soon.
-
#
-
# In order to use streaming, you will need to use a Ruby version that
-
# supports fibers (fibers are supported since version 1.9.2 of the main
-
# Ruby implementation).
-
#
-
# Streaming can be added to a given template easily, all you need to do is
-
# to pass the :stream option.
-
#
-
# class PostsController
-
# def index
-
# @posts = Post.all
-
# render stream: true
-
# end
-
# end
-
#
-
# == When to use streaming
-
#
-
# Streaming may be considered to be overkill for lightweight actions like
-
# +new+ or +edit+. The real benefit of streaming is on expensive actions
-
# that, for example, do a lot of queries on the database.
-
#
-
# In such actions, you want to delay queries execution as much as you can.
-
# For example, imagine the following +dashboard+ action:
-
#
-
# def dashboard
-
# @posts = Post.all
-
# @pages = Page.all
-
# @articles = Article.all
-
# end
-
#
-
# Most of the queries here are happening in the controller. In order to benefit
-
# from streaming you would want to rewrite it as:
-
#
-
# def dashboard
-
# # Allow lazy execution of the queries
-
# @posts = Post.all
-
# @pages = Page.all
-
# @articles = Article.all
-
# render stream: true
-
# end
-
#
-
# Notice that :stream only works with templates. Rendering :json
-
# or :xml with :stream won't work.
-
#
-
# == Communication between layout and template
-
#
-
# When streaming, rendering happens top-down instead of inside-out.
-
# Rails starts with the layout, and the template is rendered later,
-
# when its +yield+ is reached.
-
#
-
# This means that, if your application currently relies on instance
-
# variables set in the template to be used in the layout, they won't
-
# work once you move to streaming. The proper way to communicate
-
# between layout and template, regardless of whether you use streaming
-
# or not, is by using +content_for+, +provide+ and +yield+.
-
#
-
# Take a simple example where the layout expects the template to tell
-
# which title to use:
-
#
-
# <html>
-
# <head><title><%= yield :title %></title></head>
-
# <body><%= yield %></body>
-
# </html>
-
#
-
# You would use +content_for+ in your template to specify the title:
-
#
-
# <%= content_for :title, "Main" %>
-
# Hello
-
#
-
# And the final result would be:
-
#
-
# <html>
-
# <head><title>Main</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# However, if +content_for+ is called several times, the final result
-
# would have all calls concatenated. For instance, if we have the following
-
# template:
-
#
-
# <%= content_for :title, "Main" %>
-
# Hello
-
# <%= content_for :title, " page" %>
-
#
-
# The final result would be:
-
#
-
# <html>
-
# <head><title>Main page</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# This means that, if you have <code>yield :title</code> in your layout
-
# and you want to use streaming, you would have to render the whole template
-
# (and eventually trigger all queries) before streaming the title and all
-
# assets, which kills the purpose of streaming. For this reason Rails 3.1
-
# introduces a new helper called +provide+ that does the same as +content_for+
-
# but tells the layout to stop searching for other entries and continue rendering.
-
#
-
# For instance, the template above using +provide+ would be:
-
#
-
# <%= provide :title, "Main" %>
-
# Hello
-
# <%= content_for :title, " page" %>
-
#
-
# Giving:
-
#
-
# <html>
-
# <head><title>Main</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# That said, when streaming, you need to properly check your templates
-
# and choose when to use +provide+ and +content_for+.
-
#
-
# == Headers, cookies, session and flash
-
#
-
# When streaming, the HTTP headers are sent to the client right before
-
# it renders the first line. This means that, modifying headers, cookies,
-
# session or flash after the template starts rendering will not propagate
-
# to the client.
-
#
-
# == Middlewares
-
#
-
# Middlewares that need to manipulate the body won't work with streaming.
-
# You should disable those middlewares whenever streaming in development
-
# or production. For instance, <tt>Rack::Bug</tt> won't work when streaming as it
-
# needs to inject contents in the HTML body.
-
#
-
# Also <tt>Rack::Cache</tt> won't work with streaming as it does not support
-
# streaming bodies yet. Whenever streaming Cache-Control is automatically
-
# set to "no-cache".
-
#
-
# == Errors
-
#
-
# When it comes to streaming, exceptions get a bit more complicated. This
-
# happens because part of the template was already rendered and streamed to
-
# the client, making it impossible to render a whole exception page.
-
#
-
# Currently, when an exception happens in development or production, Rails
-
# will automatically stream to the client:
-
#
-
# "><script>window.location = "/500.html"</script></html>
-
#
-
# The first two characters (">) are required in case the exception happens
-
# while rendering attributes for a given tag. You can check the real cause
-
# for the exception in your logger.
-
#
-
# == Web server support
-
#
-
# Not all web servers support streaming out-of-the-box. You need to check
-
# the instructions for each of them.
-
#
-
# ==== Unicorn
-
#
-
# Unicorn supports streaming but it needs to be configured. For this, you
-
# need to create a config file as follow:
-
#
-
# # unicorn.config.rb
-
# listen 3000, tcp_nopush: false
-
#
-
# And use it on initialization:
-
#
-
# unicorn_rails --config-file unicorn.config.rb
-
#
-
# You may also want to configure other parameters like <tt>:tcp_nodelay</tt>.
-
# Please check its documentation for more information: http://unicorn.bogomips.org/Unicorn/Configurator.html#method-i-listen
-
#
-
# If you are using Unicorn with NGINX, you may need to tweak NGINX.
-
# Streaming should work out of the box on Rainbows.
-
#
-
# ==== Passenger
-
#
-
# To be described.
-
#
-
1
module Streaming
-
1
extend ActiveSupport::Concern
-
-
1
protected
-
-
# Set proper cache control and transfer encoding when streaming
-
1
def _process_options(options) #:nodoc:
-
55
super
-
55
if options[:stream]
-
if env["HTTP_VERSION"] == "HTTP/1.0"
-
options.delete(:stream)
-
else
-
headers["Cache-Control"] ||= "no-cache"
-
headers["Transfer-Encoding"] = "chunked"
-
headers.delete("Content-Length")
-
end
-
end
-
end
-
-
# Call render_body if we are streaming instead of usual +render+.
-
1
def _render_template(options) #:nodoc:
-
55
if options.delete(:stream)
-
Rack::Chunked::Body.new view_renderer.render_body(view_context, options)
-
else
-
55
super
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'active_support/deprecation'
-
1
require 'active_support/rescuable'
-
1
require 'action_dispatch/http/upload'
-
1
require 'stringio'
-
1
require 'set'
-
-
1
module ActionController
-
# Raised when a required parameter is missing.
-
#
-
# params = ActionController::Parameters.new(a: {})
-
# params.fetch(:b)
-
# # => ActionController::ParameterMissing: param not found: b
-
# params.require(:a)
-
# # => ActionController::ParameterMissing: param not found: a
-
1
class ParameterMissing < KeyError
-
1
attr_reader :param # :nodoc:
-
-
1
def initialize(param) # :nodoc:
-
@param = param
-
super("param is missing or the value is empty: #{param}")
-
end
-
end
-
-
# Raised when a supplied parameter is not expected and
-
# ActionController::Parameters.action_on_unpermitted_parameters
-
# is set to <tt>:raise</tt>.
-
#
-
# params = ActionController::Parameters.new(a: "123", b: "456")
-
# params.permit(:c)
-
# # => ActionController::UnpermittedParameters: found unpermitted parameters: a, b
-
1
class UnpermittedParameters < IndexError
-
1
attr_reader :params # :nodoc:
-
-
1
def initialize(params) # :nodoc:
-
@params = params
-
super("found unpermitted parameter#{'s' if params.size > 1 }: #{params.join(", ")}")
-
end
-
end
-
-
# == Action Controller \Parameters
-
#
-
# Allows to choose which attributes should be whitelisted for mass updating
-
# and thus prevent accidentally exposing that which shouldn't be exposed.
-
# Provides two methods for this purpose: #require and #permit. The former is
-
# used to mark parameters as required. The latter is used to set the parameter
-
# as permitted and limit which attributes should be allowed for mass updating.
-
#
-
# params = ActionController::Parameters.new({
-
# person: {
-
# name: 'Francesco',
-
# age: 22,
-
# role: 'admin'
-
# }
-
# })
-
#
-
# permitted = params.require(:person).permit(:name, :age)
-
# permitted # => {"name"=>"Francesco", "age"=>22}
-
# permitted.class # => ActionController::Parameters
-
# permitted.permitted? # => true
-
#
-
# Person.first.update!(permitted)
-
# # => #<Person id: 1, name: "Francesco", age: 22, role: "user">
-
#
-
# It provides two options that controls the top-level behavior of new instances:
-
#
-
# * +permit_all_parameters+ - If it's +true+, all the parameters will be
-
# permitted by default. The default is +false+.
-
# * +action_on_unpermitted_parameters+ - Allow to control the behavior when parameters
-
# that are not explicitly permitted are found. The values can be <tt>:log</tt> to
-
# write a message on the logger or <tt>:raise</tt> to raise
-
# ActionController::UnpermittedParameters exception. The default value is <tt>:log</tt>
-
# in test and development environments, +false+ otherwise.
-
#
-
# Examples:
-
#
-
# params = ActionController::Parameters.new
-
# params.permitted? # => false
-
#
-
# ActionController::Parameters.permit_all_parameters = true
-
#
-
# params = ActionController::Parameters.new
-
# params.permitted? # => true
-
#
-
# params = ActionController::Parameters.new(a: "123", b: "456")
-
# params.permit(:c)
-
# # => {}
-
#
-
# ActionController::Parameters.action_on_unpermitted_parameters = :raise
-
#
-
# params = ActionController::Parameters.new(a: "123", b: "456")
-
# params.permit(:c)
-
# # => ActionController::UnpermittedParameters: found unpermitted keys: a, b
-
#
-
# Please note that these options *are not thread-safe*. In a multi-threaded
-
# environment they should only be set once at boot-time and never mutated at
-
# runtime.
-
#
-
# <tt>ActionController::Parameters</tt> inherits from
-
# <tt>ActiveSupport::HashWithIndifferentAccess</tt>, this means
-
# that you can fetch values using either <tt>:key</tt> or <tt>"key"</tt>.
-
#
-
# params = ActionController::Parameters.new(key: 'value')
-
# params[:key] # => "value"
-
# params["key"] # => "value"
-
1
class Parameters < ActiveSupport::HashWithIndifferentAccess
-
1
cattr_accessor :permit_all_parameters, instance_accessor: false
-
1
cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false
-
-
# By default, never raise an UnpermittedParameters exception if these
-
# params are present. The default includes both 'controller' and 'action'
-
# because they are added by Rails and should be of no concern. One way
-
# to change these is to specify `always_permitted_parameters` in your
-
# config. For instance:
-
#
-
# config.always_permitted_parameters = %w( controller action format )
-
1
cattr_accessor :always_permitted_parameters
-
1
self.always_permitted_parameters = %w( controller action )
-
-
1
def self.const_missing(const_name)
-
super unless const_name == :NEVER_UNPERMITTED_PARAMS
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
`ActionController::Parameters::NEVER_UNPERMITTED_PARAMS` has been deprecated.
-
Use `ActionController::Parameters.always_permitted_parameters` instead.
-
MSG
-
-
always_permitted_parameters
-
end
-
-
# Returns a new instance of <tt>ActionController::Parameters</tt>.
-
# Also, sets the +permitted+ attribute to the default value of
-
# <tt>ActionController::Parameters.permit_all_parameters</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# params = ActionController::Parameters.new(name: 'Francesco')
-
# params.permitted? # => false
-
# Person.new(params) # => ActiveModel::ForbiddenAttributesError
-
#
-
# ActionController::Parameters.permit_all_parameters = true
-
#
-
# params = ActionController::Parameters.new(name: 'Francesco')
-
# params.permitted? # => true
-
# Person.new(params) # => #<Person id: nil, name: "Francesco">
-
1
def initialize(attributes = nil)
-
90
super(attributes)
-
90
@permitted = self.class.permit_all_parameters
-
end
-
-
# Returns a safe +Hash+ representation of this parameter with all
-
# unpermitted keys removed.
-
#
-
# params = ActionController::Parameters.new({
-
# name: 'Senjougahara Hitagi',
-
# oddity: 'Heavy stone crab'
-
# })
-
# params.to_h # => {}
-
#
-
# safe_params = params.permit(:name)
-
# safe_params.to_h # => {"name"=>"Senjougahara Hitagi"}
-
1
def to_h
-
if permitted?
-
to_hash
-
else
-
slice(*self.class.always_permitted_parameters).permit!.to_h
-
end
-
end
-
-
# Returns an unsafe, unfiltered +Hash+ representation of this parameter.
-
1
def to_unsafe_h
-
to_hash
-
end
-
1
alias_method :to_unsafe_hash, :to_unsafe_h
-
-
# Convert all hashes in values into parameters, then yield each pair like
-
# the same way as <tt>Hash#each_pair</tt>
-
1
def each_pair(&block)
-
16
super do |key, value|
-
60
convert_hashes_to_parameters(key, value)
-
end
-
-
16
super
-
end
-
-
1
alias_method :each, :each_pair
-
-
# Attribute that keeps track of converted arrays, if any, to avoid double
-
# looping in the common use case permit + mass-assignment. Defined in a
-
# method to instantiate it only if needed.
-
#
-
# Testing membership still loops, but it's going to be faster than our own
-
# loop that converts values. Also, we are not going to build a new array
-
# object per fetch.
-
1
def converted_arrays
-
@converted_arrays ||= Set.new
-
end
-
-
# Returns +true+ if the parameter is permitted, +false+ otherwise.
-
#
-
# params = ActionController::Parameters.new
-
# params.permitted? # => false
-
# params.permit!
-
# params.permitted? # => true
-
1
def permitted?
-
8
@permitted
-
end
-
-
# Sets the +permitted+ attribute to +true+. This can be used to pass
-
# mass assignment. Returns +self+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# params = ActionController::Parameters.new(name: 'Francesco')
-
# params.permitted? # => false
-
# Person.new(params) # => ActiveModel::ForbiddenAttributesError
-
# params.permit!
-
# params.permitted? # => true
-
# Person.new(params) # => #<Person id: nil, name: "Francesco">
-
1
def permit!
-
8
each_pair do |key, value|
-
30
Array.wrap(value).each do |v|
-
30
v.permit! if v.respond_to? :permit!
-
end
-
end
-
-
8
@permitted = true
-
8
self
-
end
-
-
# Ensures that a parameter is present. If it's present, returns
-
# the parameter at the given +key+, otherwise raises an
-
# <tt>ActionController::ParameterMissing</tt> error.
-
#
-
# ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person)
-
# # => {"name"=>"Francesco"}
-
#
-
# ActionController::Parameters.new(person: nil).require(:person)
-
# # => ActionController::ParameterMissing: param not found: person
-
#
-
# ActionController::Parameters.new(person: {}).require(:person)
-
# # => ActionController::ParameterMissing: param not found: person
-
1
def require(key)
-
8
value = self[key]
-
8
if value.present? || value == false
-
8
value
-
else
-
raise ParameterMissing.new(key)
-
end
-
end
-
-
# Alias of #require.
-
1
alias :required :require
-
-
# Returns a new <tt>ActionController::Parameters</tt> instance that
-
# includes only the given +filters+ and sets the +permitted+ attribute
-
# for the object to +true+. This is useful for limiting which attributes
-
# should be allowed for mass updating.
-
#
-
# params = ActionController::Parameters.new(user: { name: 'Francesco', age: 22, role: 'admin' })
-
# permitted = params.require(:user).permit(:name, :age)
-
# permitted.permitted? # => true
-
# permitted.has_key?(:name) # => true
-
# permitted.has_key?(:age) # => true
-
# permitted.has_key?(:role) # => false
-
#
-
# Only permitted scalars pass the filter. For example, given
-
#
-
# params.permit(:name)
-
#
-
# +:name+ passes it is a key of +params+ whose associated value is of type
-
# +String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+,
-
# +Date+, +Time+, +DateTime+, +StringIO+, +IO+,
-
# +ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+.
-
# Otherwise, the key +:name+ is filtered out.
-
#
-
# You may declare that the parameter should be an array of permitted scalars
-
# by mapping it to an empty array:
-
#
-
# params = ActionController::Parameters.new(tags: ['rails', 'parameters'])
-
# params.permit(tags: [])
-
#
-
# You can also use +permit+ on nested parameters, like:
-
#
-
# params = ActionController::Parameters.new({
-
# person: {
-
# name: 'Francesco',
-
# age: 22,
-
# pets: [{
-
# name: 'Purplish',
-
# category: 'dogs'
-
# }]
-
# }
-
# })
-
#
-
# permitted = params.permit(person: [ :name, { pets: :name } ])
-
# permitted.permitted? # => true
-
# permitted[:person][:name] # => "Francesco"
-
# permitted[:person][:age] # => nil
-
# permitted[:person][:pets][0][:name] # => "Purplish"
-
# permitted[:person][:pets][0][:category] # => nil
-
#
-
# Note that if you use +permit+ in a key that points to a hash,
-
# it won't allow all the hash. You also need to specify which
-
# attributes inside the hash should be whitelisted.
-
#
-
# params = ActionController::Parameters.new({
-
# person: {
-
# contact: {
-
# email: 'none@test.com',
-
# phone: '555-1234'
-
# }
-
# }
-
# })
-
#
-
# params.require(:person).permit(:contact)
-
# # => {}
-
#
-
# params.require(:person).permit(contact: :phone)
-
# # => {"contact"=>{"phone"=>"555-1234"}}
-
#
-
# params.require(:person).permit(contact: [ :email, :phone ])
-
# # => {"contact"=>{"email"=>"none@test.com", "phone"=>"555-1234"}}
-
1
def permit(*filters)
-
8
params = self.class.new
-
-
8
filters.flatten.each do |filter|
-
26
case filter
-
when Symbol, String
-
26
permitted_scalar_filter(params, filter)
-
when Hash then
-
hash_filter(params, filter)
-
end
-
end
-
-
8
unpermitted_parameters!(params) if self.class.action_on_unpermitted_parameters
-
-
8
params.permit!
-
end
-
-
# Returns a parameter for the given +key+. If not found,
-
# returns +nil+.
-
#
-
# params = ActionController::Parameters.new(person: { name: 'Francesco' })
-
# params[:person] # => {"name"=>"Francesco"}
-
# params[:none] # => nil
-
1
def [](key)
-
426
convert_hashes_to_parameters(key, super)
-
end
-
-
# Returns a parameter for the given +key+. If the +key+
-
# can't be found, there are several options: With no other arguments,
-
# it will raise an <tt>ActionController::ParameterMissing</tt> error;
-
# if more arguments are given, then that will be returned; if a block
-
# is given, then that will be run and its result returned.
-
#
-
# params = ActionController::Parameters.new(person: { name: 'Francesco' })
-
# params.fetch(:person) # => {"name"=>"Francesco"}
-
# params.fetch(:none) # => ActionController::ParameterMissing: param not found: none
-
# params.fetch(:none, 'Francesco') # => "Francesco"
-
# params.fetch(:none) { 'Francesco' } # => "Francesco"
-
1
def fetch(key, *args)
-
convert_hashes_to_parameters(key, super, false)
-
rescue KeyError
-
raise ActionController::ParameterMissing.new(key)
-
end
-
-
# Returns a new <tt>ActionController::Parameters</tt> instance that
-
# includes only the given +keys+. If the given +keys+
-
# don't exist, returns an empty hash.
-
#
-
# params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
-
# params.slice(:a, :b) # => {"a"=>1, "b"=>2}
-
# params.slice(:d) # => {}
-
1
def slice(*keys)
-
new_instance_with_inherited_permitted_status(super)
-
end
-
-
# Removes and returns the key/value pairs matching the given keys.
-
#
-
# params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
-
# params.extract!(:a, :b) # => {"a"=>1, "b"=>2}
-
# params # => {"c"=>3}
-
1
def extract!(*keys)
-
new_instance_with_inherited_permitted_status(super)
-
end
-
-
# Returns a new <tt>ActionController::Parameters</tt> with the results of
-
# running +block+ once for every value. The keys are unchanged.
-
#
-
# params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
-
# params.transform_values { |x| x * 2 }
-
# # => {"a"=>2, "b"=>4, "c"=>6}
-
1
def transform_values
-
if block_given?
-
new_instance_with_inherited_permitted_status(super)
-
else
-
super
-
end
-
end
-
-
# This method is here only to make sure that the returned object has the
-
# correct +permitted+ status. It should not matter since the parent of
-
# this object is +HashWithIndifferentAccess+
-
1
def transform_keys # :nodoc:
-
if block_given?
-
new_instance_with_inherited_permitted_status(super)
-
else
-
super
-
end
-
end
-
-
# Deletes and returns a key-value pair from +Parameters+ whose key is equal
-
# to key. If the key is not found, returns the default value. If the
-
# optional code block is given and the key is not found, pass in the key
-
# and return the result of block.
-
1
def delete(key, &block)
-
convert_hashes_to_parameters(key, super, false)
-
end
-
-
# Equivalent to Hash#keep_if, but returns nil if no changes were made.
-
1
def select!(&block)
-
convert_value_to_parameters(super)
-
end
-
-
# Returns an exact copy of the <tt>ActionController::Parameters</tt>
-
# instance. +permitted+ state is kept on the duped object.
-
#
-
# params = ActionController::Parameters.new(a: 1)
-
# params.permit!
-
# params.permitted? # => true
-
# copy_params = params.dup # => {"a"=>1}
-
# copy_params.permitted? # => true
-
1
def dup
-
8
super.tap do |duplicate|
-
8
duplicate.permitted = @permitted
-
end
-
end
-
-
1
protected
-
1
def permitted=(new_permitted)
-
8
@permitted = new_permitted
-
end
-
-
1
private
-
1
def new_instance_with_inherited_permitted_status(hash)
-
self.class.new(hash).tap do |new_instance|
-
new_instance.permitted = @permitted
-
end
-
end
-
-
1
def convert_hashes_to_parameters(key, value, assign_if_converted=true)
-
486
converted = convert_value_to_parameters(value)
-
486
self[key] = converted if assign_if_converted && !converted.equal?(value)
-
486
converted
-
end
-
-
1
def convert_value_to_parameters(value)
-
486
if value.is_a?(Array) && !converted_arrays.member?(value)
-
converted = value.map { |_| convert_value_to_parameters(_) }
-
converted_arrays << converted
-
converted
-
486
elsif value.is_a?(Parameters) || !value.is_a?(Hash)
-
478
value
-
else
-
8
self.class.new(value)
-
end
-
end
-
-
1
def each_element(object)
-
if object.is_a?(Array)
-
object.map { |el| yield el }.compact
-
elsif fields_for_style?(object)
-
hash = object.class.new
-
object.each { |k,v| hash[k] = yield v }
-
hash
-
else
-
yield object
-
end
-
end
-
-
1
def fields_for_style?(object)
-
object.is_a?(Hash) && object.all? { |k, v| k =~ /\A-?\d+\z/ && v.is_a?(Hash) }
-
end
-
-
1
def unpermitted_parameters!(params)
-
8
unpermitted_keys = unpermitted_keys(params)
-
8
if unpermitted_keys.any?
-
case self.class.action_on_unpermitted_parameters
-
when :log
-
name = "unpermitted_parameters.action_controller"
-
ActiveSupport::Notifications.instrument(name, keys: unpermitted_keys)
-
when :raise
-
raise ActionController::UnpermittedParameters.new(unpermitted_keys)
-
end
-
end
-
end
-
-
1
def unpermitted_keys(params)
-
8
self.keys - params.keys - self.always_permitted_parameters
-
end
-
-
#
-
# --- Filtering ----------------------------------------------------------
-
#
-
-
# This is a white list of permitted scalar types that includes the ones
-
# supported in XML and JSON requests.
-
#
-
# This list is in particular used to filter ordinary requests, String goes
-
# as first element to quickly short-circuit the common case.
-
#
-
# If you modify this collection please update the API of +permit+ above.
-
1
PERMITTED_SCALAR_TYPES = [
-
String,
-
Symbol,
-
NilClass,
-
Numeric,
-
TrueClass,
-
FalseClass,
-
Date,
-
Time,
-
# DateTimes are Dates, we document the type but avoid the redundant check.
-
StringIO,
-
IO,
-
ActionDispatch::Http::UploadedFile,
-
Rack::Test::UploadedFile,
-
]
-
-
1
def permitted_scalar?(value)
-
60
PERMITTED_SCALAR_TYPES.any? {|type| value.is_a?(type)}
-
end
-
-
1
def permitted_scalar_filter(params, key)
-
26
if has_key?(key) && permitted_scalar?(self[key])
-
24
params[key] = self[key]
-
end
-
-
26
keys.grep(/\A#{Regexp.escape(key)}\(\d+[if]?\)\z/) do |k|
-
6
if permitted_scalar?(self[k])
-
6
params[k] = self[k]
-
end
-
end
-
end
-
-
1
def array_of_permitted_scalars?(value)
-
if value.is_a?(Array)
-
value.all? {|element| permitted_scalar?(element)}
-
end
-
end
-
-
1
def array_of_permitted_scalars_filter(params, key)
-
if has_key?(key) && array_of_permitted_scalars?(self[key])
-
params[key] = self[key]
-
end
-
end
-
-
1
EMPTY_ARRAY = []
-
1
def hash_filter(params, filter)
-
filter = filter.with_indifferent_access
-
-
# Slicing filters out non-declared keys.
-
slice(*filter.keys).each do |key, value|
-
next unless value
-
-
if filter[key] == EMPTY_ARRAY
-
# Declaration { comment_ids: [] }.
-
array_of_permitted_scalars_filter(params, key)
-
else
-
# Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
-
params[key] = each_element(value) do |element|
-
if element.is_a?(Hash)
-
element = self.class.new(element) unless element.respond_to?(:permit)
-
element.permit(*Array.wrap(filter[key]))
-
end
-
end
-
end
-
end
-
end
-
end
-
-
# == Strong \Parameters
-
#
-
# It provides an interface for protecting attributes from end-user
-
# assignment. This makes Action Controller parameters forbidden
-
# to be used in Active Model mass assignment until they have been
-
# whitelisted.
-
#
-
# In addition, parameters can be marked as required and flow through a
-
# predefined raise/rescue flow to end up as a 400 Bad Request with no
-
# effort.
-
#
-
# class PeopleController < ActionController::Base
-
# # Using "Person.create(params[:person])" would raise an
-
# # ActiveModel::ForbiddenAttributes exception because it'd
-
# # be using mass assignment without an explicit permit step.
-
# # This is the recommended form:
-
# def create
-
# Person.create(person_params)
-
# end
-
#
-
# # This will pass with flying colors as long as there's a person key in the
-
# # parameters, otherwise it'll raise an ActionController::MissingParameter
-
# # exception, which will get caught by ActionController::Base and turned
-
# # into a 400 Bad Request reply.
-
# def update
-
# redirect_to current_account.people.find(params[:id]).tap { |person|
-
# person.update!(person_params)
-
# }
-
# end
-
#
-
# private
-
# # Using a private method to encapsulate the permissible parameters is
-
# # just a good pattern since you'll be able to reuse the same permit
-
# # list between create and update. Also, you can specialize this method
-
# # with per-user checking of permissible attributes.
-
# def person_params
-
# params.require(:person).permit(:name, :age)
-
# end
-
# end
-
#
-
# In order to use <tt>accepts_nested_attributes_for</tt> with Strong \Parameters, you
-
# will need to specify which nested attributes should be whitelisted.
-
#
-
# class Person
-
# has_many :pets
-
# accepts_nested_attributes_for :pets
-
# end
-
#
-
# class PeopleController < ActionController::Base
-
# def create
-
# Person.create(person_params)
-
# end
-
#
-
# ...
-
#
-
# private
-
#
-
# def person_params
-
# # It's mandatory to specify the nested attributes that should be whitelisted.
-
# # If you use `permit` with just the key that points to the nested attributes hash,
-
# # it will return an empty hash.
-
# params.require(:person).permit(:name, :age, pets_attributes: [ :name, :category ])
-
# end
-
# end
-
#
-
# See ActionController::Parameters.require and ActionController::Parameters.permit
-
# for more information.
-
1
module StrongParameters
-
1
extend ActiveSupport::Concern
-
1
include ActiveSupport::Rescuable
-
-
# Returns a new ActionController::Parameters object that
-
# has been instantiated with the <tt>request.parameters</tt>.
-
1
def params
-
288
@_params ||= Parameters.new(request.parameters)
-
end
-
-
# Assigns the given +value+ to the +params+ hash. If +value+
-
# is a Hash, this will create an ActionController::Parameters
-
# object that has been instantiated with the given +value+ hash.
-
1
def params=(value)
-
@_params = value.is_a?(Hash) ? Parameters.new(value) : value
-
end
-
end
-
end
-
1
module ActionController
-
# Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing
-
# the <tt>_routes</tt> method. Otherwise, an exception will be raised.
-
#
-
# In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define
-
# url options like the +host+. In order to do so, this module requires the host class
-
# to implement +env+ and +request+, which need to be a Rack-compatible.
-
#
-
# class RootUrl
-
# include ActionController::UrlFor
-
# include Rails.application.routes.url_helpers
-
#
-
# delegate :env, :request, to: :controller
-
#
-
# def initialize(controller)
-
# @controller = controller
-
# @url = root_path # named route from the application.
-
# end
-
# end
-
1
module UrlFor
-
1
extend ActiveSupport::Concern
-
-
1
include AbstractController::UrlFor
-
-
1
def url_options
-
@_url_options ||= {
-
:host => request.host,
-
:port => request.optional_port,
-
:protocol => request.protocol,
-
:_recall => request.path_parameters
-
276
}.merge!(super).freeze
-
-
276
if (same_origin = _routes.equal?(env["action_dispatch.routes".freeze])) ||
-
276
(script_name = env["ROUTES_#{_routes.object_id}_SCRIPT_NAME"]) ||
-
(original_script_name = env['ORIGINAL_SCRIPT_NAME'.freeze])
-
-
276
options = @_url_options.dup
-
276
if original_script_name
-
options[:original_script_name] = original_script_name
-
else
-
276
options[:script_name] = same_origin ? request.script_name.dup : script_name
-
end
-
276
options.freeze
-
else
-
@_url_options
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module ModelNaming
-
# Converts the given object to an ActiveModel compliant one.
-
1
def convert_to_model(object)
-
40
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
-
1
def model_name_from_record_or_class(record_or_class)
-
24
convert_to_model(record_or_class).model_name
-
end
-
end
-
end
-
1
require "rails"
-
1
require "action_controller"
-
1
require "action_dispatch/railtie"
-
1
require "abstract_controller/railties/routes_helpers"
-
1
require "action_controller/railties/helpers"
-
1
require "action_view/railtie"
-
-
1
module ActionController
-
1
class Railtie < Rails::Railtie #:nodoc:
-
1
config.action_controller = ActiveSupport::OrderedOptions.new
-
-
1
config.eager_load_namespaces << ActionController
-
-
1
initializer "action_controller.assets_config", :group => :all do |app|
-
1
app.config.action_controller.assets_dir ||= app.config.paths["public"].first
-
end
-
-
1
initializer "action_controller.set_helpers_path" do |app|
-
1
ActionController::Helpers.helpers_path = app.helpers_paths
-
end
-
-
1
initializer "action_controller.parameters_config" do |app|
-
1
options = app.config.action_controller
-
-
2
ActionController::Parameters.permit_all_parameters = options.delete(:permit_all_parameters) { false }
-
1
if app.config.action_controller[:always_permitted_parameters]
-
ActionController::Parameters.always_permitted_parameters =
-
app.config.action_controller.delete(:always_permitted_parameters)
-
end
-
1
ActionController::Parameters.action_on_unpermitted_parameters = options.delete(:action_on_unpermitted_parameters) do
-
1
(Rails.env.test? || Rails.env.development?) ? :log : false
-
end
-
end
-
-
1
initializer "action_controller.set_configs" do |app|
-
1
paths = app.config.paths
-
1
options = app.config.action_controller
-
-
1
options.logger ||= Rails.logger
-
1
options.cache_store ||= Rails.cache
-
-
1
options.javascripts_dir ||= paths["public/javascripts"].first
-
1
options.stylesheets_dir ||= paths["public/stylesheets"].first
-
-
# Ensure readers methods get compiled
-
1
options.asset_host ||= app.config.asset_host
-
1
options.relative_url_root ||= app.config.relative_url_root
-
-
1
ActiveSupport.on_load(:action_controller) do
-
1
include app.routes.mounted_helpers
-
1
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
-
1
extend ::ActionController::Railties::Helpers
-
-
1
options.each do |k,v|
-
9
k = "#{k}="
-
9
if respond_to?(k)
-
9
send(k, v)
-
elsif !Base.respond_to?(k)
-
raise "Invalid option key: #{k}"
-
end
-
end
-
end
-
end
-
-
1
initializer "action_controller.compile_config_methods" do
-
1
ActiveSupport.on_load(:action_controller) do
-
1
config.compile_methods! if config.respond_to?(:compile_methods!)
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module Railties
-
1
module Helpers
-
1
def inherited(klass)
-
6
super
-
6
return unless klass.respond_to?(:helpers_path=)
-
-
12
if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) }
-
paths = namespace.railtie_helpers_paths
-
else
-
6
paths = ActionController::Helpers.helpers_path
-
end
-
-
6
klass.helpers_path = paths
-
-
6
if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers
-
1
klass.helper :all
-
end
-
end
-
end
-
end
-
end
-
1
require 'rack/session/abstract/id'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/deprecation'
-
-
1
require 'rails-dom-testing'
-
-
1
module ActionController
-
1
module TemplateAssertions
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
2
setup :setup_subscriptions
-
2
teardown :teardown_subscriptions
-
end
-
-
1
RENDER_TEMPLATE_INSTANCE_VARIABLES = %w{partials templates layouts files}.freeze
-
-
1
def setup_subscriptions
-
RENDER_TEMPLATE_INSTANCE_VARIABLES.each do |instance_variable|
-
instance_variable_set("@_#{instance_variable}", Hash.new(0))
-
end
-
-
@_subscribers = []
-
-
@_subscribers << ActiveSupport::Notifications.subscribe("render_template.action_view") do |_name, _start, _finish, _id, payload|
-
path = payload[:layout]
-
if path
-
@_layouts[path] += 1
-
if path =~ /^layouts\/(.*)/
-
@_layouts[$1] += 1
-
end
-
end
-
end
-
-
@_subscribers << ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload|
-
if virtual_path = payload[:virtual_path]
-
partial = virtual_path =~ /^.*\/_[^\/]*$/
-
-
if partial
-
@_partials[virtual_path] += 1
-
@_partials[virtual_path.split("/").last] += 1
-
end
-
-
@_templates[virtual_path] += 1
-
else
-
path = payload[:identifier]
-
if path
-
@_files[path] += 1
-
@_files[path.split("/").last] += 1
-
end
-
end
-
end
-
end
-
-
1
def teardown_subscriptions
-
return unless defined?(@_subscribers)
-
-
@_subscribers.each do |subscriber|
-
ActiveSupport::Notifications.unsubscribe(subscriber)
-
end
-
end
-
-
1
def process(*args)
-
reset_template_assertion
-
super
-
end
-
-
1
def reset_template_assertion
-
RENDER_TEMPLATE_INSTANCE_VARIABLES.each do |instance_variable|
-
ivar_name = "@_#{instance_variable}"
-
if instance_variable_defined?(ivar_name)
-
instance_variable_get(ivar_name).clear
-
end
-
end
-
end
-
-
# Asserts that the request was rendered with the appropriate template file or partials.
-
#
-
# # assert that the "new" view template was rendered
-
# assert_template "new"
-
#
-
# # assert that the exact template "admin/posts/new" was rendered
-
# assert_template %r{\Aadmin/posts/new\Z}
-
#
-
# # assert that the layout 'admin' was rendered
-
# assert_template layout: 'admin'
-
# assert_template layout: 'layouts/admin'
-
# assert_template layout: :admin
-
#
-
# # assert that no layout was rendered
-
# assert_template layout: nil
-
# assert_template layout: false
-
#
-
# # assert that the "_customer" partial was rendered twice
-
# assert_template partial: '_customer', count: 2
-
#
-
# # assert that no partials were rendered
-
# assert_template partial: false
-
#
-
# # assert that a file was rendered
-
# assert_template file: "README.rdoc"
-
#
-
# # assert that no file was rendered
-
# assert_template file: nil
-
# assert_template file: false
-
#
-
# In a view test case, you can also assert that specific locals are passed
-
# to partials:
-
#
-
# # assert that the "_customer" partial was rendered with a specific object
-
# assert_template partial: '_customer', locals: { customer: @customer }
-
1
def assert_template(options = {}, message = nil)
-
# Force body to be read in case the template is being streamed.
-
response.body
-
-
case options
-
when NilClass, Regexp, String, Symbol
-
options = options.to_s if Symbol === options
-
rendered = @_templates
-
msg = message || sprintf("expecting <%s> but rendering with <%s>",
-
options.inspect, rendered.keys)
-
matches_template =
-
case options
-
when String
-
!options.empty? && rendered.any? do |t, num|
-
options_splited = options.split(File::SEPARATOR)
-
t_splited = t.split(File::SEPARATOR)
-
t_splited.last(options_splited.size) == options_splited
-
end
-
when Regexp
-
rendered.any? { |t,num| t.match(options) }
-
when NilClass
-
rendered.blank?
-
end
-
assert matches_template, msg
-
when Hash
-
options.assert_valid_keys(:layout, :partial, :locals, :count, :file)
-
-
if options.key?(:layout)
-
expected_layout = options[:layout]
-
msg = message || sprintf("expecting layout <%s> but action rendered <%s>",
-
expected_layout, @_layouts.keys)
-
-
case expected_layout
-
when String, Symbol
-
assert_includes @_layouts.keys, expected_layout.to_s, msg
-
when Regexp
-
assert(@_layouts.keys.any? {|l| l =~ expected_layout }, msg)
-
when nil, false
-
assert(@_layouts.empty?, msg)
-
end
-
end
-
-
if options[:file]
-
assert_includes @_files.keys, options[:file]
-
elsif options.key?(:file)
-
assert @_files.blank?, "expected no files but #{@_files.keys} was rendered"
-
end
-
-
if expected_partial = options[:partial]
-
if expected_locals = options[:locals]
-
if defined?(@_rendered_views)
-
view = expected_partial.to_s.sub(/^_/, '').sub(/\/_(?=[^\/]+\z)/, '/')
-
-
partial_was_not_rendered_msg = "expected %s to be rendered but it was not." % view
-
assert_includes @_rendered_views.rendered_views, view, partial_was_not_rendered_msg
-
-
msg = 'expecting %s to be rendered with %s but was with %s' % [expected_partial,
-
expected_locals,
-
@_rendered_views.locals_for(view)]
-
assert(@_rendered_views.view_rendered?(view, options[:locals]), msg)
-
else
-
warn "the :locals option to #assert_template is only supported in a ActionView::TestCase"
-
end
-
elsif expected_count = options[:count]
-
actual_count = @_partials[expected_partial]
-
msg = message || sprintf("expecting %s to be rendered %s time(s) but rendered %s time(s)",
-
expected_partial, expected_count, actual_count)
-
assert(actual_count == expected_count.to_i, msg)
-
else
-
msg = message || sprintf("expecting partial <%s> but action rendered <%s>",
-
options[:partial], @_partials.keys)
-
assert_includes @_partials, expected_partial, msg
-
end
-
elsif options.key?(:partial)
-
assert @_partials.empty?,
-
"Expected no partials to be rendered"
-
end
-
else
-
raise ArgumentError, "assert_template only accepts a String, Symbol, Hash, Regexp, or nil"
-
end
-
end
-
end
-
-
1
class TestRequest < ActionDispatch::TestRequest #:nodoc:
-
1
DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
-
1
DEFAULT_ENV.delete 'PATH_INFO'
-
-
1
def initialize(env = {})
-
super
-
-
self.session = TestSession.new
-
self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => SecureRandom.hex(16))
-
end
-
-
1
def assign_parameters(routes, controller_path, action, parameters = {})
-
parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action)
-
extra_keys = routes.extra_keys(parameters)
-
non_path_parameters = get? ? query_parameters : request_parameters
-
parameters.each do |key, value|
-
if value.is_a?(Array) && (value.frozen? || value.any?(&:frozen?))
-
value = value.map{ |v| v.duplicable? ? v.dup : v }
-
elsif value.is_a?(Hash) && (value.frozen? || value.any?{ |k,v| v.frozen? })
-
value = Hash[value.map{ |k,v| [k, v.duplicable? ? v.dup : v] }]
-
elsif value.frozen? && value.duplicable?
-
value = value.dup
-
end
-
-
if extra_keys.include?(key)
-
non_path_parameters[key] = value
-
else
-
if value.is_a?(Array)
-
value = value.map(&:to_param)
-
else
-
value = value.to_param
-
end
-
-
path_parameters[key] = value
-
end
-
end
-
-
# Clear the combined params hash in case it was already referenced.
-
@env.delete("action_dispatch.request.parameters")
-
-
# Clear the filter cache variables so they're not stale
-
@filtered_parameters = @filtered_env = @filtered_path = nil
-
-
params = self.request_parameters.dup
-
%w(controller action only_path).each do |k|
-
params.delete(k)
-
params.delete(k.to_sym)
-
end
-
data = params.to_query
-
-
@env['CONTENT_LENGTH'] = data.length.to_s
-
@env['rack.input'] = StringIO.new(data)
-
end
-
-
1
def recycle!
-
@formats = nil
-
@env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
-
@env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
-
@method = @request_method = nil
-
@fullpath = @ip = @remote_ip = @protocol = nil
-
@env['action_dispatch.request.query_parameters'] = {}
-
@set_cookies ||= {}
-
@set_cookies.update(Hash[cookie_jar.instance_variable_get("@set_cookies").map{ |k,o| [k,o[:value]] }])
-
deleted_cookies = cookie_jar.instance_variable_get("@delete_cookies")
-
@set_cookies.reject!{ |k,v| deleted_cookies.include?(k) }
-
cookie_jar.update(rack_cookies)
-
cookie_jar.update(cookies)
-
cookie_jar.update(@set_cookies)
-
cookie_jar.recycle!
-
end
-
-
1
private
-
-
1
def default_env
-
DEFAULT_ENV
-
end
-
end
-
-
1
class TestResponse < ActionDispatch::TestResponse
-
1
def recycle!
-
initialize
-
end
-
end
-
-
1
class LiveTestResponse < Live::Response
-
1
def recycle!
-
@body = nil
-
initialize
-
end
-
-
1
def body
-
@body ||= super
-
end
-
-
# Was the response successful?
-
1
alias_method :success?, :successful?
-
-
# Was the URL not found?
-
1
alias_method :missing?, :not_found?
-
-
# Were we redirected?
-
1
alias_method :redirect?, :redirection?
-
-
# Was there a server-side error?
-
1
alias_method :error?, :server_error?
-
end
-
-
# Methods #destroy and #load! are overridden to avoid calling methods on the
-
# @store object, which does not exist for the TestSession class.
-
1
class TestSession < Rack::Session::Abstract::SessionHash #:nodoc:
-
1
DEFAULT_OPTIONS = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
-
-
1
def initialize(session = {})
-
super(nil, nil)
-
@id = SecureRandom.hex(16)
-
@data = stringify_keys(session)
-
@loaded = true
-
end
-
-
1
def exists?
-
true
-
end
-
-
1
def keys
-
@data.keys
-
end
-
-
1
def values
-
@data.values
-
end
-
-
1
def destroy
-
clear
-
end
-
-
1
def fetch(key, *args, &block)
-
@data.fetch(key.to_s, *args, &block)
-
end
-
-
1
private
-
-
1
def load!
-
@id
-
end
-
end
-
-
# Superclass for ActionController functional tests. Functional tests allow you to
-
# test a single controller action per test method. This should not be confused with
-
# integration tests (see ActionDispatch::IntegrationTest), which are more like
-
# "stories" that can involve multiple controllers and multiple actions (i.e. multiple
-
# different HTTP requests).
-
#
-
# == Basic example
-
#
-
# Functional tests are written as follows:
-
# 1. First, one uses the +get+, +post+, +patch+, +put+, +delete+ or +head+ method to simulate
-
# an HTTP request.
-
# 2. Then, one asserts whether the current state is as expected. "State" can be anything:
-
# the controller's HTTP response, the database contents, etc.
-
#
-
# For example:
-
#
-
# class BooksControllerTest < ActionController::TestCase
-
# def test_create
-
# # Simulate a POST response with the given HTTP parameters.
-
# post(:create, book: { title: "Love Hina" })
-
#
-
# # Assert that the controller tried to redirect us to
-
# # the created book's URI.
-
# assert_response :found
-
#
-
# # Assert that the controller really put the book in the database.
-
# assert_not_nil Book.find_by(title: "Love Hina")
-
# end
-
# end
-
#
-
# You can also send a real document in the simulated HTTP request.
-
#
-
# def test_create
-
# json = {book: { title: "Love Hina" }}.to_json
-
# post :create, json
-
# end
-
#
-
# == Special instance variables
-
#
-
# ActionController::TestCase will also automatically provide the following instance
-
# variables for use in the tests:
-
#
-
# <b>@controller</b>::
-
# The controller instance that will be tested.
-
# <b>@request</b>::
-
# An ActionController::TestRequest, representing the current HTTP
-
# request. You can modify this object before sending the HTTP request. For example,
-
# you might want to set some session properties before sending a GET request.
-
# <b>@response</b>::
-
# An ActionController::TestResponse object, representing the response
-
# of the last HTTP response. In the above example, <tt>@response</tt> becomes valid
-
# after calling +post+. If the various assert methods are not sufficient, then you
-
# may use this object to inspect the HTTP response in detail.
-
#
-
# (Earlier versions of \Rails required each functional test to subclass
-
# Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
-
#
-
# == Controller is automatically inferred
-
#
-
# ActionController::TestCase will automatically infer the controller under test
-
# from the test class name. If the controller cannot be inferred from the test
-
# class name, you can explicitly set it with +tests+.
-
#
-
# class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
-
# tests WidgetController
-
# end
-
#
-
# == \Testing controller internals
-
#
-
# In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
-
# can be used against. These collections are:
-
#
-
# * assigns: Instance variables assigned in the action that are available for the view.
-
# * session: Objects being saved in the session.
-
# * flash: The flash objects currently in the session.
-
# * cookies: \Cookies being sent to the user on this request.
-
#
-
# These collections can be used just like any other hash:
-
#
-
# assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
-
# assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
-
# assert flash.empty? # makes sure that there's nothing in the flash
-
#
-
# For historic reasons, the assigns hash uses string-based keys. So <tt>assigns[:person]</tt> won't work, but <tt>assigns["person"]</tt> will. To
-
# appease our yearning for symbols, though, an alternative accessor has been devised using a method call instead of index referencing.
-
# So <tt>assigns(:person)</tt> will work just like <tt>assigns["person"]</tt>, but again, <tt>assigns[:person]</tt> will not work.
-
#
-
# On top of the collections, you have the complete url that a given action redirected to available in <tt>redirect_to_url</tt>.
-
#
-
# For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
-
# action call which can then be asserted against.
-
#
-
# == Manipulating session and cookie variables
-
#
-
# Sometimes you need to set up the session and cookie variables for a test.
-
# To do this just assign a value to the session or cookie collection:
-
#
-
# session[:key] = "value"
-
# cookies[:key] = "value"
-
#
-
# To clear the cookies for a test just clear the cookie collection:
-
#
-
# cookies.clear
-
#
-
# == \Testing named routes
-
#
-
# If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case.
-
#
-
# assert_redirected_to page_url(title: 'foo')
-
1
class TestCase < ActiveSupport::TestCase
-
1
module Behavior
-
1
extend ActiveSupport::Concern
-
1
include ActionDispatch::TestProcess
-
1
include ActiveSupport::Testing::ConstantLookup
-
1
include Rails::Dom::Testing::Assertions
-
-
1
attr_reader :response, :request
-
-
1
module ClassMethods
-
-
# Sets the controller class name. Useful if the name can't be inferred from test class.
-
# Normalizes +controller_class+ before using.
-
#
-
# tests WidgetController
-
# tests :widget
-
# tests 'widget'
-
1
def tests(controller_class)
-
case controller_class
-
when String, Symbol
-
self.controller_class = "#{controller_class.to_s.camelize}Controller".constantize
-
when Class
-
self.controller_class = controller_class
-
else
-
raise ArgumentError, "controller class must be a String, Symbol, or Class"
-
end
-
end
-
-
1
def controller_class=(new_class)
-
self._controller_class = new_class
-
end
-
-
1
def controller_class
-
if current_controller_class = self._controller_class
-
current_controller_class
-
else
-
self.controller_class = determine_default_controller_class(name)
-
end
-
end
-
-
1
def determine_default_controller_class(name)
-
determine_constant_from_test_name(name) do |constant|
-
Class === constant && constant < ActionController::Metal
-
end
-
end
-
end
-
-
# Simulate a GET request with the given parameters.
-
#
-
# - +action+: The controller action to call.
-
# - +parameters+: The HTTP parameters that you want to pass. This may
-
# be +nil+, a hash, or a string that is appropriately encoded
-
# (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
-
# - +session+: A hash of parameters to store in the session. This may be +nil+.
-
# - +flash+: A hash of parameters to store in the flash. This may be +nil+.
-
#
-
# You can also simulate POST, PATCH, PUT, DELETE, and HEAD requests with
-
# +post+, +patch+, +put+, +delete+, and +head+.
-
#
-
# Note that the request method is not verified. The different methods are
-
# available to make the tests more expressive.
-
1
def get(action, *args)
-
process(action, "GET", *args)
-
end
-
-
# Simulate a POST request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
1
def post(action, *args)
-
process(action, "POST", *args)
-
end
-
-
# Simulate a PATCH request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
1
def patch(action, *args)
-
process(action, "PATCH", *args)
-
end
-
-
# Simulate a PUT request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
1
def put(action, *args)
-
process(action, "PUT", *args)
-
end
-
-
# Simulate a DELETE request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
1
def delete(action, *args)
-
process(action, "DELETE", *args)
-
end
-
-
# Simulate a HEAD request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
1
def head(action, *args)
-
process(action, "HEAD", *args)
-
end
-
-
1
def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)
-
@request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
-
@request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
-
__send__(request_method, action, parameters, session, flash).tap do
-
@request.env.delete 'HTTP_X_REQUESTED_WITH'
-
@request.env.delete 'HTTP_ACCEPT'
-
end
-
end
-
1
alias xhr :xml_http_request
-
-
1
def paramify_values(hash_or_array_or_value)
-
case hash_or_array_or_value
-
when Hash
-
Hash[hash_or_array_or_value.map{|key, value| [key, paramify_values(value)] }]
-
when Array
-
hash_or_array_or_value.map {|i| paramify_values(i)}
-
when Rack::Test::UploadedFile, ActionDispatch::Http::UploadedFile
-
hash_or_array_or_value
-
else
-
hash_or_array_or_value.to_param
-
end
-
end
-
-
# Simulate a HTTP request to +action+ by specifying request method,
-
# parameters and set/volley the response.
-
#
-
# - +action+: The controller action to call.
-
# - +http_method+: Request method used to send the http request. Possible values
-
# are +GET+, +POST+, +PATCH+, +PUT+, +DELETE+, +HEAD+. Defaults to +GET+.
-
# - +parameters+: The HTTP parameters. This may be +nil+, a hash, or a
-
# string that is appropriately encoded (+application/x-www-form-urlencoded+
-
# or +multipart/form-data+).
-
# - +session+: A hash of parameters to store in the session. This may be +nil+.
-
# - +flash+: A hash of parameters to store in the flash. This may be +nil+.
-
#
-
# Example calling +create+ action and sending two params:
-
#
-
# process :create, 'POST', user: { name: 'Gaurish Sharma', email: 'user@example.com' }
-
#
-
# Example sending parameters, +nil+ session and setting a flash message:
-
#
-
# process :view, 'GET', { id: 7 }, nil, { notice: 'This is flash message' }
-
#
-
# To simulate +GET+, +POST+, +PATCH+, +PUT+, +DELETE+ and +HEAD+ requests
-
# prefer using #get, #post, #patch, #put, #delete and #head methods
-
# respectively which will make tests more expressive.
-
#
-
# Note that the request method is not verified.
-
1
def process(action, http_method = 'GET', *args)
-
check_required_ivars
-
-
if args.first.is_a?(String) && http_method != 'HEAD'
-
@request.env['RAW_POST_DATA'] = args.shift
-
end
-
-
parameters, session, flash = args
-
parameters ||= {}
-
-
# Ensure that numbers and symbols passed as params are converted to
-
# proper params, as is the case when engaging rack.
-
parameters = paramify_values(parameters) if html_format?(parameters)
-
-
@html_document = nil
-
@html_scanner_document = nil
-
-
unless @controller.respond_to?(:recycle!)
-
@controller.extend(Testing::Functional)
-
end
-
-
@request.recycle!
-
@response.recycle!
-
@controller.recycle!
-
-
@request.env['REQUEST_METHOD'] = http_method
-
-
controller_class_name = @controller.class.anonymous? ?
-
"anonymous" :
-
@controller.class.controller_path
-
-
@request.assign_parameters(@routes, controller_class_name, action.to_s, parameters)
-
-
@request.session.update(session) if session
-
@request.flash.update(flash || {})
-
-
@controller.request = @request
-
@controller.response = @response
-
-
build_request_uri(action, parameters)
-
-
name = @request.parameters[:action]
-
-
@controller.recycle!
-
@controller.process(name)
-
-
if cookies = @request.env['action_dispatch.cookies']
-
unless @response.committed?
-
cookies.write(@response)
-
end
-
end
-
@response.prepare!
-
-
@assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {}
-
-
if flash_value = @request.flash.to_session_value
-
@request.session['flash'] = flash_value
-
end
-
-
@response
-
end
-
-
1
def setup_controller_request_and_response
-
@controller = nil unless defined? @controller
-
-
response_klass = TestResponse
-
-
if klass = self.class.controller_class
-
if klass < ActionController::Live
-
response_klass = LiveTestResponse
-
end
-
unless @controller
-
begin
-
@controller = klass.new
-
rescue
-
warn "could not construct controller #{klass}" if $VERBOSE
-
end
-
end
-
end
-
-
@request = build_request
-
@response = build_response response_klass
-
@response.request = @request
-
-
if @controller
-
@controller.request = @request
-
@controller.params = {}
-
end
-
end
-
-
1
def build_request
-
TestRequest.new
-
end
-
-
1
def build_response(klass)
-
klass.new
-
end
-
-
1
included do
-
1
include ActionController::TemplateAssertions
-
1
include ActionDispatch::Assertions
-
1
class_attribute :_controller_class
-
1
setup :setup_controller_request_and_response
-
end
-
-
1
private
-
-
1
def document_root_element
-
html_document.root
-
end
-
-
1
def check_required_ivars
-
# Sanity check for required instance variables so we can give an
-
# understandable error message.
-
[:@routes, :@controller, :@request, :@response].each do |iv_name|
-
if !instance_variable_defined?(iv_name) || instance_variable_get(iv_name).nil?
-
raise "#{iv_name} is nil: make sure you set it in your test's setup method."
-
end
-
end
-
end
-
-
1
def build_request_uri(action, parameters)
-
unless @request.env["PATH_INFO"]
-
options = @controller.respond_to?(:url_options) ? @controller.__send__(:url_options).merge(parameters) : parameters
-
options.update(
-
:action => action,
-
:relative_url_root => nil,
-
:_recall => @request.path_parameters)
-
-
if route_name = options.delete(:use_route)
-
ActiveSupport::Deprecation.warn <<-MSG.squish
-
Passing the `use_route` option in functional tests are deprecated.
-
Support for this option in the `process` method (and the related
-
`get`, `head`, `post`, `patch`, `put` and `delete` helpers) will
-
be removed in the next version without replacement.
-
-
Functional tests are essentially unit tests for controllers and
-
they should not require knowledge to how the application's routes
-
are configured. Instead, you should explicitly pass the appropiate
-
params to the `process` method.
-
-
Previously the engines guide also contained an incorrect example
-
that recommended using this option to test an engine's controllers
-
within the dummy application. That recommendation was incorrect
-
and has since been corrected. Instead, you should override the
-
`@routes` variable in the test case with `Foo::Engine.routes`. See
-
the updated engines guide for details.
-
MSG
-
end
-
-
url, query_string = @routes.path_for(options, route_name).split("?", 2)
-
-
@request.env["SCRIPT_NAME"] = @controller.config.relative_url_root
-
@request.env["PATH_INFO"] = url
-
@request.env["QUERY_STRING"] = query_string || ""
-
end
-
end
-
-
1
def html_format?(parameters)
-
return true unless parameters.key?(:format)
-
Mime.fetch(parameters[:format]) { Mime['html'] }.html?
-
end
-
end
-
-
1
include Behavior
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
require 'action_pack'
-
1
require 'rack'
-
-
1
module Rack
-
1
autoload :Test, 'rack/test'
-
end
-
-
1
module ActionDispatch
-
1
extend ActiveSupport::Autoload
-
-
1
class IllegalStateError < StandardError
-
end
-
-
1
eager_autoload do
-
1
autoload_under 'http' do
-
1
autoload :Request
-
1
autoload :Response
-
end
-
end
-
-
1
autoload_under 'middleware' do
-
1
autoload :RequestId
-
1
autoload :Callbacks
-
1
autoload :Cookies
-
1
autoload :DebugExceptions
-
1
autoload :ExceptionWrapper
-
1
autoload :Flash
-
1
autoload :ParamsParser
-
1
autoload :PublicExceptions
-
1
autoload :Reloader
-
1
autoload :RemoteIp
-
1
autoload :ShowExceptions
-
1
autoload :SSL
-
1
autoload :Static
-
end
-
-
1
autoload :Journey
-
1
autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
-
1
autoload :Routing
-
-
1
module Http
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Cache
-
1
autoload :Headers
-
1
autoload :MimeNegotiation
-
1
autoload :Parameters
-
1
autoload :ParameterFilter
-
1
autoload :Upload
-
1
autoload :UploadedFile, 'action_dispatch/http/upload'
-
1
autoload :URL
-
end
-
-
1
module Session
-
1
autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
-
1
autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
-
1
autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
-
1
autoload :CacheStore, 'action_dispatch/middleware/session/cache_store'
-
end
-
-
1
mattr_accessor :test_app
-
-
1
autoload_under 'testing' do
-
1
autoload :Assertions
-
1
autoload :Integration
-
1
autoload :IntegrationTest, 'action_dispatch/testing/integration'
-
1
autoload :TestProcess
-
1
autoload :TestRequest
-
1
autoload :TestResponse
-
end
-
end
-
-
1
autoload :Mime, 'action_dispatch/http/mime_type'
-
-
1
ActiveSupport.on_load(:action_view) do
-
1
ActionView::Base.default_formats ||= Mime::SET.symbols
-
1
ActionView::Template::Types.delegate_to Mime
-
end
-
-
1
module ActionDispatch
-
1
module Http
-
1
module Cache
-
1
module Request
-
-
1
HTTP_IF_MODIFIED_SINCE = 'HTTP_IF_MODIFIED_SINCE'.freeze
-
1
HTTP_IF_NONE_MATCH = 'HTTP_IF_NONE_MATCH'.freeze
-
-
1
def if_modified_since
-
if since = env[HTTP_IF_MODIFIED_SINCE]
-
Time.rfc2822(since) rescue nil
-
end
-
end
-
-
1
def if_none_match
-
env[HTTP_IF_NONE_MATCH]
-
end
-
-
1
def if_none_match_etags
-
(if_none_match ? if_none_match.split(/\s*,\s*/) : []).collect do |etag|
-
etag.gsub(/^\"|\"$/, "")
-
end
-
end
-
-
1
def not_modified?(modified_at)
-
if_modified_since && modified_at && if_modified_since >= modified_at
-
end
-
-
1
def etag_matches?(etag)
-
if etag
-
etag = etag.gsub(/^\"|\"$/, "")
-
if_none_match_etags.include?(etag)
-
end
-
end
-
-
# Check response freshness (Last-Modified and ETag) against request
-
# If-Modified-Since and If-None-Match conditions. If both headers are
-
# supplied, both must match, or the request is not considered fresh.
-
1
def fresh?(response)
-
last_modified = if_modified_since
-
etag = if_none_match
-
-
return false unless last_modified || etag
-
-
success = true
-
success &&= not_modified?(response.last_modified) if last_modified
-
success &&= etag_matches?(response.etag) if etag
-
success
-
end
-
end
-
-
1
module Response
-
1
attr_reader :cache_control, :etag
-
1
alias :etag? :etag
-
-
1
def last_modified
-
if last = headers[LAST_MODIFIED]
-
Time.httpdate(last)
-
end
-
end
-
-
1
def last_modified?
-
66
headers.include?(LAST_MODIFIED)
-
end
-
-
1
def last_modified=(utc_time)
-
headers[LAST_MODIFIED] = utc_time.httpdate
-
end
-
-
1
def date
-
if date_header = headers[DATE]
-
Time.httpdate(date_header)
-
end
-
end
-
-
1
def date?
-
headers.include?(DATE)
-
end
-
-
1
def date=(utc_time)
-
headers[DATE] = utc_time.httpdate
-
end
-
-
1
def etag=(etag)
-
key = ActiveSupport::Cache.expand_cache_key(etag)
-
@etag = self[ETAG] = %("#{Digest::MD5.hexdigest(key)}")
-
end
-
-
1
private
-
-
1
DATE = 'Date'.freeze
-
1
LAST_MODIFIED = "Last-Modified".freeze
-
1
ETAG = "ETag".freeze
-
1
CACHE_CONTROL = "Cache-Control".freeze
-
1
SPECIAL_KEYS = Set.new(%w[extras no-cache max-age public must-revalidate])
-
-
1
def cache_control_segments
-
66
if cache_control = self[CACHE_CONTROL]
-
cache_control.delete(' ').split(',')
-
else
-
66
[]
-
end
-
end
-
-
1
def cache_control_headers
-
66
cache_control = {}
-
-
66
cache_control_segments.each do |segment|
-
directive, argument = segment.split('=', 2)
-
-
if SPECIAL_KEYS.include? directive
-
key = directive.tr('-', '_')
-
cache_control[key.to_sym] = argument || true
-
else
-
cache_control[:extras] ||= []
-
cache_control[:extras] << segment
-
end
-
end
-
-
66
cache_control
-
end
-
-
1
def prepare_cache_control!
-
66
@cache_control = cache_control_headers
-
66
@etag = self[ETAG]
-
end
-
-
1
def handle_conditional_get!
-
66
if etag? || last_modified? || !@cache_control.empty?
-
set_conditional_cache_control!
-
end
-
end
-
-
1
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze
-
1
NO_CACHE = "no-cache".freeze
-
1
PUBLIC = "public".freeze
-
1
PRIVATE = "private".freeze
-
1
MUST_REVALIDATE = "must-revalidate".freeze
-
-
1
def set_conditional_cache_control!
-
control = {}
-
cc_headers = cache_control_headers
-
if extras = cc_headers.delete(:extras)
-
@cache_control[:extras] ||= []
-
@cache_control[:extras] += extras
-
@cache_control[:extras].uniq!
-
end
-
-
control.merge! cc_headers
-
control.merge! @cache_control
-
-
if control.empty?
-
headers[CACHE_CONTROL] = DEFAULT_CACHE_CONTROL
-
elsif control[:no_cache]
-
headers[CACHE_CONTROL] = NO_CACHE
-
if control[:extras]
-
headers[CACHE_CONTROL] += ", #{control[:extras].join(', ')}"
-
end
-
else
-
extras = control[:extras]
-
max_age = control[:max_age]
-
-
options = []
-
options << "max-age=#{max_age.to_i}" if max_age
-
options << (control[:public] ? PUBLIC : PRIVATE)
-
options << MUST_REVALIDATE if control[:must_revalidate]
-
options.concat(extras) if extras
-
-
headers[CACHE_CONTROL] = options.join(", ")
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'action_dispatch/http/parameter_filter'
-
-
1
module ActionDispatch
-
1
module Http
-
# Allows you to specify sensitive parameters which will be replaced from
-
# the request log by looking in the query string of the request and all
-
# sub-hashes of the params hash to filter. If a block is given, each key and
-
# value of the params hash and all sub-hashes is passed to it, the value
-
# or key can be replaced using String#replace or similar method.
-
#
-
# env["action_dispatch.parameter_filter"] = [:password]
-
# => replaces the value to all keys matching /password/i with "[FILTERED]"
-
#
-
# env["action_dispatch.parameter_filter"] = [:foo, "bar"]
-
# => replaces the value to all keys matching /foo|bar/i with "[FILTERED]"
-
#
-
# env["action_dispatch.parameter_filter"] = lambda do |k,v|
-
# v.reverse! if k =~ /secret/i
-
# end
-
# => reverses the value to all keys matching /secret/i
-
1
module FilterParameters
-
1
ENV_MATCH = [/RAW_POST_DATA/, "rack.request.form_vars"] # :nodoc:
-
1
NULL_PARAM_FILTER = ParameterFilter.new # :nodoc:
-
1
NULL_ENV_FILTER = ParameterFilter.new ENV_MATCH # :nodoc:
-
-
1
def initialize(env)
-
341
super
-
341
@filtered_parameters = nil
-
341
@filtered_env = nil
-
341
@filtered_path = nil
-
end
-
-
# Return a hash of parameters with all sensitive data replaced.
-
1
def filtered_parameters
-
66
@filtered_parameters ||= parameter_filter.filter(parameters)
-
end
-
-
# Return a hash of request.env with all sensitive data replaced.
-
1
def filtered_env
-
@filtered_env ||= env_filter.filter(@env)
-
end
-
-
# Reconstructed a path with all sensitive GET parameters replaced.
-
1
def filtered_path
-
66
@filtered_path ||= query_string.empty? ? path : "#{path}?#{filtered_query_string}"
-
end
-
-
1
protected
-
-
1
def parameter_filter
-
66
parameter_filter_for @env.fetch("action_dispatch.parameter_filter") {
-
return NULL_PARAM_FILTER
-
}
-
end
-
-
1
def env_filter
-
user_key = @env.fetch("action_dispatch.parameter_filter") {
-
return NULL_ENV_FILTER
-
}
-
parameter_filter_for(Array(user_key) + ENV_MATCH)
-
end
-
-
1
def parameter_filter_for(filters)
-
66
ParameterFilter.new(filters)
-
end
-
-
1
KV_RE = '[^&;=]+'
-
1
PAIR_RE = %r{(#{KV_RE})=(#{KV_RE})}
-
1
def filtered_query_string
-
query_string.gsub(PAIR_RE) do |_|
-
parameter_filter.filter([[$1, $2]]).first.join("=")
-
end
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Http
-
1
module FilterRedirect
-
-
1
FILTERED = '[FILTERED]'.freeze # :nodoc:
-
-
1
def filtered_location
-
11
filters = location_filter
-
11
if !filters.empty? && location_filter_match?(filters)
-
FILTERED
-
else
-
11
location
-
end
-
end
-
-
1
private
-
-
1
def location_filter
-
11
if request
-
11
request.env['action_dispatch.redirect_filter'] || []
-
else
-
[]
-
end
-
end
-
-
1
def location_filter_match?(filters)
-
filters.any? do |filter|
-
if String === filter
-
location.include?(filter)
-
elsif Regexp === filter
-
location.match(filter)
-
end
-
end
-
end
-
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Http
-
# Provides access to the request's HTTP headers from the environment.
-
#
-
# env = { "CONTENT_TYPE" => "text/plain" }
-
# headers = ActionDispatch::Http::Headers.new(env)
-
# headers["Content-Type"] # => "text/plain"
-
1
class Headers
-
1
CGI_VARIABLES = Set.new(%W[
-
AUTH_TYPE
-
CONTENT_LENGTH
-
CONTENT_TYPE
-
GATEWAY_INTERFACE
-
HTTPS
-
PATH_INFO
-
PATH_TRANSLATED
-
QUERY_STRING
-
REMOTE_ADDR
-
REMOTE_HOST
-
REMOTE_IDENT
-
REMOTE_USER
-
REQUEST_METHOD
-
SCRIPT_NAME
-
SERVER_NAME
-
SERVER_PORT
-
SERVER_PROTOCOL
-
SERVER_SOFTWARE
-
]).freeze
-
-
1
HTTP_HEADER = /\A[A-Za-z0-9-]+\z/
-
-
1
include Enumerable
-
1
attr_reader :env
-
-
1
def initialize(env = {}) # :nodoc:
-
11
@env = env
-
end
-
-
# Returns the value for the given key mapped to @env.
-
1
def [](key)
-
11
@env[env_name(key)]
-
end
-
-
# Sets the given value for the key mapped to @env.
-
1
def []=(key, value)
-
@env[env_name(key)] = value
-
end
-
-
1
def key?(key)
-
@env.key? env_name(key)
-
end
-
1
alias :include? :key?
-
-
# Returns the value for the given key mapped to @env.
-
#
-
# If the key is not found and an optional code block is not provided,
-
# raises a <tt>KeyError</tt> exception.
-
#
-
# If the code block is provided, then it will be run and
-
# its result returned.
-
1
def fetch(key, *args, &block)
-
@env.fetch env_name(key), *args, &block
-
end
-
-
1
def each(&block)
-
@env.each(&block)
-
end
-
-
# Returns a new Http::Headers instance containing the contents of
-
# <tt>headers_or_env</tt> and the original instance.
-
1
def merge(headers_or_env)
-
headers = Http::Headers.new(env.dup)
-
headers.merge!(headers_or_env)
-
headers
-
end
-
-
# Adds the contents of <tt>headers_or_env</tt> to original instance
-
# entries; duplicate keys are overwritten with the values from
-
# <tt>headers_or_env</tt>.
-
1
def merge!(headers_or_env)
-
headers_or_env.each do |key, value|
-
self[env_name(key)] = value
-
end
-
end
-
-
1
private
-
# Converts a HTTP header name to an environment variable name if it is
-
# not contained within the headers hash.
-
1
def env_name(key)
-
11
key = key.to_s
-
11
if key =~ HTTP_HEADER
-
11
key = key.upcase.tr('-', '_')
-
11
key = "HTTP_" + key unless CGI_VARIABLES.include?(key)
-
end
-
11
key
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
module ActionDispatch
-
1
module Http
-
1
module MimeNegotiation
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
mattr_accessor :ignore_accept_header
-
1
self.ignore_accept_header = false
-
end
-
-
1
attr_reader :variant
-
-
# The MIME type of the HTTP request, such as Mime::XML.
-
#
-
# For backward compatibility, the post \format is extracted from the
-
# X-Post-Data-Format HTTP header if present.
-
1
def content_mime_type
-
187
@env["action_dispatch.request.content_type"] ||= begin
-
176
if @env['CONTENT_TYPE'] =~ /^([^,\;]*)/
-
11
Mime::Type.lookup($1.strip.downcase)
-
else
-
165
nil
-
end
-
end
-
end
-
-
1
def content_type
-
content_mime_type && content_mime_type.to_s
-
end
-
-
# Returns the accepted MIME type for the request.
-
1
def accepts
-
@env["action_dispatch.request.accepts"] ||= begin
-
header = @env['HTTP_ACCEPT'].to_s.strip
-
-
if header.empty?
-
[content_mime_type]
-
else
-
Mime::Type.parse(header)
-
end
-
end
-
end
-
-
# Returns the MIME type for the \format used in the request.
-
#
-
# GET /posts/5.xml | request.format => Mime::XML
-
# GET /posts/5.xhtml | request.format => Mime::HTML
-
# GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first
-
#
-
1
def format(view_path = [])
-
66
formats.first || Mime::NullType.instance
-
end
-
-
1
def formats
-
135
@env["action_dispatch.request.formats"] ||= begin
-
66
params_readable = begin
-
66
parameters[:format]
-
rescue ActionController::BadRequest
-
false
-
end
-
-
66
if params_readable
-
Array(Mime[parameters[:format]])
-
elsif use_accept_header && valid_accept_header
-
accepts
-
elsif xhr?
-
[Mime::JS]
-
else
-
66
[Mime::HTML]
-
end
-
end
-
end
-
-
# Sets the \variant for template.
-
1
def variant=(variant)
-
if variant.is_a?(Symbol)
-
@variant = [variant]
-
elsif variant.nil? || variant.is_a?(Array) && variant.any? && variant.all?{ |v| v.is_a?(Symbol) }
-
@variant = variant
-
else
-
raise ArgumentError, "request.variant must be set to a Symbol or an Array of Symbols, not a #{variant.class}. " \
-
"For security reasons, never directly set the variant to a user-provided value, " \
-
"like params[:variant].to_sym. Check user-provided value against a whitelist first, " \
-
"then set the variant: request.variant = :tablet if params[:variant] == 'tablet'"
-
end
-
end
-
-
# Sets the \format by string extension, which can be used to force custom formats
-
# that are not controlled by the extension.
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :adjust_format_for_iphone
-
#
-
# private
-
# def adjust_format_for_iphone
-
# request.format = :iphone if request.env["HTTP_USER_AGENT"][/iPhone/]
-
# end
-
# end
-
1
def format=(extension)
-
parameters[:format] = extension.to_s
-
@env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])]
-
end
-
-
# Sets the \formats by string extensions. This differs from #format= by allowing you
-
# to set multiple, ordered formats, which is useful when you want to have a fallback.
-
#
-
# In this example, the :iphone format will be used if it's available, otherwise it'll fallback
-
# to the :html format.
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :adjust_format_for_iphone_with_html_fallback
-
#
-
# private
-
# def adjust_format_for_iphone_with_html_fallback
-
# request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/]
-
# end
-
# end
-
1
def formats=(extensions)
-
parameters[:format] = extensions.first.to_s
-
@env["action_dispatch.request.formats"] = extensions.collect do |extension|
-
Mime::Type.lookup_by_extension(extension)
-
end
-
end
-
-
# Receives an array of mimes and return the first user sent mime that
-
# matches the order array.
-
#
-
1
def negotiate_mime(order)
-
3
formats.each do |priority|
-
3
if priority == Mime::ALL
-
return order.first
-
elsif order.include?(priority)
-
3
return priority
-
end
-
end
-
-
order.include?(Mime::ALL) ? format : nil
-
end
-
-
1
protected
-
-
1
BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/
-
-
1
def valid_accept_header
-
66
(xhr? && (accept.present? || content_mime_type)) ||
-
132
(accept.present? && accept !~ BROWSER_LIKE_ACCEPTS)
-
end
-
-
1
def use_accept_header
-
66
!self.class.ignore_accept_header
-
end
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'singleton'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/string/starts_ends_with'
-
-
1
module Mime
-
1
class Mimes < Array
-
1
def symbols
-
78
@symbols ||= map { |m| m.to_sym }
-
end
-
-
%w(<< concat shift unshift push pop []= clear compact! collect!
-
delete delete_at delete_if flatten! map! insert reject! reverse!
-
1
replace slice! sort! uniq!).each do |method|
-
22
module_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{method}(*)
-
@symbols = nil
-
super
-
end
-
CODE
-
end
-
end
-
-
1
SET = Mimes.new
-
1
EXTENSION_LOOKUP = {}
-
1
LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k.blank? }
-
-
1
class << self
-
1
def [](type)
-
155
return type if type.is_a?(Type)
-
155
Type.lookup_by_extension(type)
-
end
-
-
1
def fetch(type)
-
return type if type.is_a?(Type)
-
EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k }
-
end
-
end
-
-
# Encapsulates the notion of a mime type. Can be used at render time, for example, with:
-
#
-
# class PostsController < ActionController::Base
-
# def show
-
# @post = Post.find(params[:id])
-
#
-
# respond_to do |format|
-
# format.html
-
# format.ics { render text: @post.to_ics, mime_type: Mime::Type["text/calendar"] }
-
# format.xml { render xml: @post }
-
# end
-
# end
-
# end
-
1
class Type
-
1
@@html_types = Set.new [:html, :all]
-
1
cattr_reader :html_types
-
-
1
attr_reader :symbol
-
-
1
@register_callbacks = []
-
-
# A simple helper class used in parsing the accept header
-
1
class AcceptItem #:nodoc:
-
1
attr_accessor :index, :name, :q
-
1
alias :to_s :name
-
-
1
def initialize(index, name, q = nil)
-
@index = index
-
@name = name
-
q ||= 0.0 if @name == Mime::ALL.to_s # default wildcard match to end of list
-
@q = ((q || 1.0).to_f * 100).to_i
-
end
-
-
1
def <=>(item)
-
result = item.q <=> @q
-
result = @index <=> item.index if result == 0
-
result
-
end
-
-
1
def ==(item)
-
@name == item.to_s
-
end
-
end
-
-
1
class AcceptList < Array #:nodoc:
-
1
def assort!
-
sort!
-
-
# Take care of the broken text/xml entry by renaming or deleting it
-
if text_xml_idx && app_xml_idx
-
app_xml.q = [text_xml.q, app_xml.q].max # set the q value to the max of the two
-
exchange_xml_items if app_xml_idx > text_xml_idx # make sure app_xml is ahead of text_xml in the list
-
delete_at(text_xml_idx) # delete text_xml from the list
-
elsif text_xml_idx
-
text_xml.name = Mime::XML.to_s
-
end
-
-
# Look for more specific XML-based types and sort them ahead of app/xml
-
if app_xml_idx
-
idx = app_xml_idx
-
-
while idx < length
-
type = self[idx]
-
break if type.q < app_xml.q
-
-
if type.name.ends_with? '+xml'
-
self[app_xml_idx], self[idx] = self[idx], app_xml
-
@app_xml_idx = idx
-
end
-
idx += 1
-
end
-
end
-
-
map! { |i| Mime::Type.lookup(i.name) }.uniq!
-
to_a
-
end
-
-
1
private
-
1
def text_xml_idx
-
@text_xml_idx ||= index('text/xml')
-
end
-
-
1
def app_xml_idx
-
@app_xml_idx ||= index(Mime::XML.to_s)
-
end
-
-
1
def text_xml
-
self[text_xml_idx]
-
end
-
-
1
def app_xml
-
self[app_xml_idx]
-
end
-
-
1
def exchange_xml_items
-
self[app_xml_idx], self[text_xml_idx] = text_xml, app_xml
-
@app_xml_idx, @text_xml_idx = text_xml_idx, app_xml_idx
-
end
-
end
-
-
1
class << self
-
1
TRAILING_STAR_REGEXP = /(text|application)\/\*/
-
1
PARAMETER_SEPARATOR_REGEXP = /;\s*\w+="?\w+"?/
-
-
1
def register_callback(&block)
-
1
@register_callbacks << block
-
end
-
-
1
def lookup(string)
-
11
LOOKUP[string]
-
end
-
-
1
def lookup_by_extension(extension)
-
155
EXTENSION_LOOKUP[extension.to_s]
-
end
-
-
# Registers an alias that's not used on mime type lookup, but can be referenced directly. Especially useful for
-
# rendering different HTML versions depending on the user agent, like an iPhone.
-
1
def register_alias(string, symbol, extension_synonyms = [])
-
register(string, symbol, [], extension_synonyms, true)
-
end
-
-
1
def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], skip_lookup = false)
-
22
Mime.const_set(symbol.upcase, Type.new(string, symbol, mime_type_synonyms))
-
-
22
new_mime = Mime.const_get(symbol.upcase)
-
22
SET << new_mime
-
-
52
([string] + mime_type_synonyms).each { |str| LOOKUP[str] = SET.last } unless skip_lookup
-
60
([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = SET.last }
-
-
22
@register_callbacks.each do |callback|
-
callback.call(new_mime)
-
end
-
end
-
-
1
def parse(accept_header)
-
if !accept_header.include?(',')
-
accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first
-
parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)].compact
-
else
-
list, index = AcceptList.new, 0
-
accept_header.split(',').each do |header|
-
params, q = header.split(PARAMETER_SEPARATOR_REGEXP)
-
if params.present?
-
params.strip!
-
-
params = parse_trailing_star(params) || [params]
-
-
params.each do |m|
-
list << AcceptItem.new(index, m.to_s, q)
-
index += 1
-
end
-
end
-
end
-
list.assort!
-
end
-
end
-
-
1
def parse_trailing_star(accept_header)
-
parse_data_with_trailing_star($1) if accept_header =~ TRAILING_STAR_REGEXP
-
end
-
-
# For an input of <tt>'text'</tt>, returns <tt>[Mime::JSON, Mime::XML, Mime::ICS,
-
# Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT]</tt>.
-
#
-
# For an input of <tt>'application'</tt>, returns <tt>[Mime::HTML, Mime::JS,
-
# Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM]</tt>.
-
1
def parse_data_with_trailing_star(input)
-
Mime::SET.select { |m| m =~ input }
-
end
-
-
# This method is opposite of register method.
-
#
-
# Usage:
-
#
-
# Mime::Type.unregister(:mobile)
-
1
def unregister(symbol)
-
symbol = symbol.upcase
-
mime = Mime.const_get(symbol)
-
Mime.instance_eval { remove_const(symbol) }
-
-
SET.delete_if { |v| v.eql?(mime) }
-
LOOKUP.delete_if { |_,v| v.eql?(mime) }
-
EXTENSION_LOOKUP.delete_if { |_,v| v.eql?(mime) }
-
end
-
end
-
-
1
def initialize(string, symbol = nil, synonyms = [])
-
23
@symbol, @synonyms = symbol, synonyms
-
23
@string = string
-
end
-
-
1
def to_s
-
212
@string
-
end
-
-
1
def to_str
-
to_s
-
end
-
-
1
def to_sym
-
416
@symbol
-
end
-
-
1
def ref
-
165
to_sym || to_s
-
end
-
-
1
def ===(list)
-
if list.is_a?(Array)
-
(@synonyms + [ self ]).any? { |synonym| list.include?(synonym) }
-
else
-
super
-
end
-
end
-
-
1
def ==(mime_type)
-
140
return false if mime_type.blank?
-
140
(@synonyms + [ self ]).any? do |synonym|
-
280
synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym
-
end
-
end
-
-
1
def =~(mime_type)
-
return false if mime_type.blank?
-
regexp = Regexp.new(Regexp.quote(mime_type.to_s))
-
(@synonyms + [ self ]).any? do |synonym|
-
synonym.to_s =~ regexp
-
end
-
end
-
-
1
def html?
-
@@html_types.include?(to_sym) || @string =~ /html/
-
end
-
-
-
1
private
-
-
1
def to_ary; end
-
1
def to_a; end
-
-
1
def method_missing(method, *args)
-
3
if method.to_s.ends_with? '?'
-
3
method[0..-2].downcase.to_sym == to_sym
-
else
-
super
-
end
-
end
-
-
1
def respond_to_missing?(method, include_private = false) #:nodoc:
-
3
method.to_s.ends_with? '?'
-
end
-
end
-
-
1
class NullType
-
1
include Singleton
-
-
1
def nil?
-
true
-
end
-
-
1
def ref; end
-
-
1
def respond_to_missing?(method, include_private = false)
-
method.to_s.ends_with? '?'
-
end
-
-
1
private
-
1
def method_missing(method, *args)
-
false if method.to_s.ends_with? '?'
-
end
-
end
-
end
-
-
1
require 'action_dispatch/http/mime_types'
-
# Build list of Mime types for HTTP responses
-
# http://www.iana.org/assignments/media-types/
-
-
1
Mime::Type.register "text/html", :html, %w( application/xhtml+xml ), %w( xhtml )
-
1
Mime::Type.register "text/plain", :text, [], %w(txt)
-
1
Mime::Type.register "text/javascript", :js, %w( application/javascript application/x-javascript )
-
1
Mime::Type.register "text/css", :css
-
1
Mime::Type.register "text/calendar", :ics
-
1
Mime::Type.register "text/csv", :csv
-
1
Mime::Type.register "text/vcard", :vcf
-
-
1
Mime::Type.register "image/png", :png, [], %w(png)
-
1
Mime::Type.register "image/jpeg", :jpeg, [], %w(jpg jpeg jpe pjpeg)
-
1
Mime::Type.register "image/gif", :gif, [], %w(gif)
-
1
Mime::Type.register "image/bmp", :bmp, [], %w(bmp)
-
1
Mime::Type.register "image/tiff", :tiff, [], %w(tif tiff)
-
-
1
Mime::Type.register "video/mpeg", :mpeg, [], %w(mpg mpeg mpe)
-
-
1
Mime::Type.register "application/xml", :xml, %w( text/xml application/x-xml )
-
1
Mime::Type.register "application/rss+xml", :rss
-
1
Mime::Type.register "application/atom+xml", :atom
-
1
Mime::Type.register "application/x-yaml", :yaml, %w( text/yaml )
-
-
1
Mime::Type.register "multipart/form-data", :multipart_form
-
1
Mime::Type.register "application/x-www-form-urlencoded", :url_encoded_form
-
-
# http://www.ietf.org/rfc/rfc4627.txt
-
# http://www.json.org/JSONRequest.html
-
1
Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest )
-
-
1
Mime::Type.register "application/pdf", :pdf, [], %w(pdf)
-
1
Mime::Type.register "application/zip", :zip, [], %w(zip)
-
-
# Create Mime::ALL but do not add it to the SET.
-
1
Mime::ALL = Mime::Type.new("*/*", :all, [])
-
1
module ActionDispatch
-
1
module Http
-
1
class ParameterFilter
-
1
FILTERED = '[FILTERED]'.freeze # :nodoc:
-
-
1
def initialize(filters = [])
-
68
@filters = filters
-
end
-
-
1
def filter(params)
-
66
compiled_filter.call(params)
-
end
-
-
1
private
-
-
1
def compiled_filter
-
66
@compiled_filter ||= CompiledFilter.compile(@filters)
-
end
-
-
1
class CompiledFilter # :nodoc:
-
1
def self.compile(filters)
-
66
return lambda { |params| params.dup } if filters.empty?
-
-
66
strings, regexps, blocks = [], [], []
-
-
66
filters.each do |item|
-
66
case item
-
when Proc
-
blocks << item
-
when Regexp
-
regexps << item
-
else
-
66
strings << item.to_s
-
end
-
end
-
-
66
regexps << Regexp.new(strings.join('|'), true) unless strings.empty?
-
66
new regexps, blocks
-
end
-
-
1
attr_reader :regexps, :blocks
-
-
1
def initialize(regexps, blocks)
-
66
@regexps = regexps
-
66
@blocks = blocks
-
end
-
-
1
def call(original_params)
-
74
filtered_params = {}
-
-
74
original_params.each do |key, value|
-
430
if regexps.any? { |r| key =~ r }
-
value = FILTERED
-
elsif value.is_a?(Hash)
-
8
value = call(value)
-
elsif value.is_a?(Array)
-
value = value.map { |v| v.is_a?(Hash) ? call(v) : v }
-
elsif blocks.any?
-
key = key.dup if key.duplicable?
-
value = value.dup if value.duplicable?
-
blocks.each { |b| b.call(key, value) }
-
end
-
-
215
filtered_params[key] = value
-
end
-
-
74
filtered_params
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/deprecation'
-
-
1
module ActionDispatch
-
1
module Http
-
1
module Parameters
-
1
PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
-
-
# Returns both GET and POST \parameters in a single hash.
-
1
def parameters
-
198
@env["action_dispatch.request.parameters"] ||= begin
-
66
params = begin
-
66
request_parameters.merge(query_parameters)
-
rescue EOFError
-
query_parameters.dup
-
end
-
66
params.merge!(path_parameters)
-
end
-
end
-
1
alias :params :parameters
-
-
1
def path_parameters=(parameters) #:nodoc:
-
66
@env.delete('action_dispatch.request.parameters')
-
66
@env[PARAMETERS_KEY] = parameters
-
end
-
-
1
def symbolized_path_parameters
-
ActiveSupport::Deprecation.warn(
-
'`symbolized_path_parameters` is deprecated. Please use `path_parameters`.'
-
)
-
path_parameters
-
end
-
-
# Returns a hash with the \parameters used to form the \path of the request.
-
# Returned hash keys are strings:
-
#
-
# {'action' => 'my_action', 'controller' => 'my_controller'}
-
1
def path_parameters
-
330
@env[PARAMETERS_KEY] ||= {}
-
end
-
-
1
private
-
-
# Convert nested Hash to HashWithIndifferentAccess.
-
#
-
1
def normalize_encode_params(params)
-
193
case params
-
when Hash
-
140
if params.has_key?(:tempfile)
-
UploadedFile.new(params)
-
else
-
params.each_with_object({}) do |(key, val), new_hash|
-
61
new_hash[key] = if val.is_a?(Array)
-
val.map! { |el| normalize_encode_params(el) }
-
else
-
61
normalize_encode_params(val)
-
end
-
140
end.with_indifferent_access
-
end
-
else
-
53
params
-
end
-
end
-
end
-
end
-
end
-
1
require 'stringio'
-
-
1
require 'active_support/inflector'
-
1
require 'action_dispatch/http/headers'
-
1
require 'action_controller/metal/exceptions'
-
1
require 'rack/request'
-
1
require 'action_dispatch/http/cache'
-
1
require 'action_dispatch/http/mime_negotiation'
-
1
require 'action_dispatch/http/parameters'
-
1
require 'action_dispatch/http/filter_parameters'
-
1
require 'action_dispatch/http/upload'
-
1
require 'action_dispatch/http/url'
-
1
require 'active_support/core_ext/array/conversions'
-
-
1
module ActionDispatch
-
1
class Request < Rack::Request
-
1
include ActionDispatch::Http::Cache::Request
-
1
include ActionDispatch::Http::MimeNegotiation
-
1
include ActionDispatch::Http::Parameters
-
1
include ActionDispatch::Http::FilterParameters
-
1
include ActionDispatch::Http::URL
-
-
1
autoload :Session, 'action_dispatch/request/session'
-
1
autoload :Utils, 'action_dispatch/request/utils'
-
-
1
LOCALHOST = Regexp.union [/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, /^::1$/, /^0:0:0:0:0:0:0:1(%.*)?$/]
-
-
1
ENV_METHODS = %w[ AUTH_TYPE GATEWAY_INTERFACE
-
PATH_TRANSLATED REMOTE_HOST
-
REMOTE_IDENT REMOTE_USER REMOTE_ADDR
-
SERVER_NAME SERVER_PROTOCOL
-
-
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
-
HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM
-
HTTP_NEGOTIATE HTTP_PRAGMA ].freeze
-
-
1
ENV_METHODS.each do |env|
-
17
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset
-
@env["#{env}"] # @env["HTTP_ACCEPT_CHARSET"]
-
end # end
-
METHOD
-
end
-
-
1
def initialize(env)
-
341
super
-
341
@method = nil
-
341
@request_method = nil
-
341
@remote_ip = nil
-
341
@original_fullpath = nil
-
341
@fullpath = nil
-
341
@ip = nil
-
341
@uuid = nil
-
end
-
-
1
def check_path_parameters!
-
# If any of the path parameters has an invalid encoding then
-
# raise since it's likely to trigger errors further on.
-
66
path_parameters.each do |key, value|
-
154
next unless value.respond_to?(:valid_encoding?)
-
154
unless value.valid_encoding?
-
raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
-
end
-
end
-
end
-
-
1
def key?(key)
-
@env.key?(key)
-
end
-
-
# List of HTTP request methods from the following RFCs:
-
# Hypertext Transfer Protocol -- HTTP/1.1 (http://www.ietf.org/rfc/rfc2616.txt)
-
# HTTP Extensions for Distributed Authoring -- WEBDAV (http://www.ietf.org/rfc/rfc2518.txt)
-
# Versioning Extensions to WebDAV (http://www.ietf.org/rfc/rfc3253.txt)
-
# Ordered Collections Protocol (WebDAV) (http://www.ietf.org/rfc/rfc3648.txt)
-
# Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol (http://www.ietf.org/rfc/rfc3744.txt)
-
# Web Distributed Authoring and Versioning (WebDAV) SEARCH (http://www.ietf.org/rfc/rfc5323.txt)
-
# Calendar Extensions to WebDAV (http://www.ietf.org/rfc/rfc4791.txt)
-
# PATCH Method for HTTP (http://www.ietf.org/rfc/rfc5789.txt)
-
1
RFC2616 = %w(OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT)
-
1
RFC2518 = %w(PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK)
-
1
RFC3253 = %w(VERSION-CONTROL REPORT CHECKOUT CHECKIN UNCHECKOUT MKWORKSPACE UPDATE LABEL MERGE BASELINE-CONTROL MKACTIVITY)
-
1
RFC3648 = %w(ORDERPATCH)
-
1
RFC3744 = %w(ACL)
-
1
RFC5323 = %w(SEARCH)
-
1
RFC4791 = %w(MKCALENDAR)
-
1
RFC5789 = %w(PATCH)
-
-
1
HTTP_METHODS = RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC4791 + RFC5789
-
-
1
HTTP_METHOD_LOOKUP = {}
-
-
# Populate the HTTP method lookup cache
-
1
HTTP_METHODS.each { |method|
-
31
HTTP_METHOD_LOOKUP[method] = method.underscore.to_sym
-
}
-
-
# Returns the HTTP \method that the application should see.
-
# In the case where the \method was overridden by a middleware
-
# (for instance, if a HEAD request was converted to a GET,
-
# or if a _method parameter was used to determine the \method
-
# the application should use), this \method returns the overridden
-
# value, not the original.
-
1
def request_method
-
427
@request_method ||= check_method(env["REQUEST_METHOD"])
-
end
-
-
1
def request_method=(request_method) #:nodoc:
-
if check_method(request_method)
-
@request_method = env["REQUEST_METHOD"] = request_method
-
end
-
end
-
-
# Returns a symbol form of the #request_method
-
1
def request_method_symbol
-
HTTP_METHOD_LOOKUP[request_method]
-
end
-
-
# Returns the original value of the environment's REQUEST_METHOD,
-
# even if it was overridden by middleware. See #request_method for
-
# more information.
-
1
def method
-
@method ||= check_method(env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'])
-
end
-
-
# Returns a symbol form of the #method
-
1
def method_symbol
-
HTTP_METHOD_LOOKUP[method]
-
end
-
-
# Is this a GET (or HEAD) request?
-
# Equivalent to <tt>request.request_method_symbol == :get</tt>.
-
1
def get?
-
66
HTTP_METHOD_LOOKUP[request_method] == :get
-
end
-
-
# Is this a POST request?
-
# Equivalent to <tt>request.request_method_symbol == :post</tt>.
-
1
def post?
-
HTTP_METHOD_LOOKUP[request_method] == :post
-
end
-
-
# Is this a PATCH request?
-
# Equivalent to <tt>request.request_method == :patch</tt>.
-
1
def patch?
-
HTTP_METHOD_LOOKUP[request_method] == :patch
-
end
-
-
# Is this a PUT request?
-
# Equivalent to <tt>request.request_method_symbol == :put</tt>.
-
1
def put?
-
HTTP_METHOD_LOOKUP[request_method] == :put
-
end
-
-
# Is this a DELETE request?
-
# Equivalent to <tt>request.request_method_symbol == :delete</tt>.
-
1
def delete?
-
HTTP_METHOD_LOOKUP[request_method] == :delete
-
end
-
-
# Is this a HEAD request?
-
# Equivalent to <tt>request.request_method_symbol == :head</tt>.
-
1
def head?
-
HTTP_METHOD_LOOKUP[request_method] == :head
-
end
-
-
# Provides access to the request's HTTP headers, for example:
-
#
-
# request.headers["Content-Type"] # => "text/plain"
-
1
def headers
-
11
Http::Headers.new(@env)
-
end
-
-
# Returns a +String+ with the last requested path including their params.
-
#
-
# # get '/foo'
-
# request.original_fullpath # => '/foo'
-
#
-
# # get '/foo?bar'
-
# request.original_fullpath # => '/foo?bar'
-
1
def original_fullpath
-
@original_fullpath ||= (env["ORIGINAL_FULLPATH"] || fullpath)
-
end
-
-
# Returns the +String+ full path including params of the last URL requested.
-
#
-
# # get "/articles"
-
# request.fullpath # => "/articles"
-
#
-
# # get "/articles?page=2"
-
# request.fullpath # => "/articles?page=2"
-
1
def fullpath
-
66
@fullpath ||= super
-
end
-
-
# Returns the original request URL as a +String+.
-
#
-
# # get "/articles?page=2"
-
# request.original_url # => "http://www.example.com/articles?page=2"
-
1
def original_url
-
base_url + original_fullpath
-
end
-
-
# The +String+ MIME type of the request.
-
#
-
# # get "/articles"
-
# request.media_type # => "application/x-www-form-urlencoded"
-
1
def media_type
-
55
content_mime_type.to_s
-
end
-
-
# Returns the content length of the request as an integer.
-
1
def content_length
-
66
super.to_i
-
end
-
-
# Returns true if the "X-Requested-With" header contains "XMLHttpRequest"
-
# (case-insensitive), which may need to be manually added depending on the
-
# choice of JavaScript libraries and frameworks.
-
1
def xml_http_request?
-
143
@env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i
-
end
-
1
alias :xhr? :xml_http_request?
-
-
1
def ip
-
66
@ip ||= super
-
end
-
-
# Originating IP address, usually set by the RemoteIp middleware.
-
1
def remote_ip
-
110
@remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
-
end
-
-
# Returns the unique request id, which is based on either the X-Request-Id header that can
-
# be generated by a firewall, load balancer, or web server or by the RequestId middleware
-
# (which sets the action_dispatch.request_id environment variable).
-
#
-
# This unique ID is useful for tracing a request from end-to-end as part of logging or debugging.
-
# This relies on the rack variable set by the ActionDispatch::RequestId middleware.
-
1
def uuid
-
@uuid ||= env["action_dispatch.request_id"]
-
end
-
-
# Returns the lowercase name of the HTTP server software.
-
1
def server_software
-
(@env['SERVER_SOFTWARE'] && /^([a-zA-Z]+)/ =~ @env['SERVER_SOFTWARE']) ? $1.downcase : nil
-
end
-
-
# Read the request \body. This is useful for web services that need to
-
# work with raw requests directly.
-
1
def raw_post
-
unless @env.include? 'RAW_POST_DATA'
-
raw_post_body = body
-
@env['RAW_POST_DATA'] = raw_post_body.read(content_length)
-
raw_post_body.rewind if raw_post_body.respond_to?(:rewind)
-
end
-
@env['RAW_POST_DATA']
-
end
-
-
# The request body is an IO input stream. If the RAW_POST_DATA environment
-
# variable is already set, wrap it in a StringIO.
-
1
def body
-
if raw_post = @env['RAW_POST_DATA']
-
raw_post.force_encoding(Encoding::BINARY)
-
StringIO.new(raw_post)
-
else
-
@env['rack.input']
-
end
-
end
-
-
1
def form_data?
-
55
FORM_DATA_MEDIA_TYPES.include?(content_mime_type.to_s)
-
end
-
-
1
def body_stream #:nodoc:
-
@env['rack.input']
-
end
-
-
# TODO This should be broken apart into AD::Request::Session and probably
-
# be included by the session middleware.
-
1
def reset_session
-
if session && session.respond_to?(:destroy)
-
session.destroy
-
else
-
self.session = {}
-
end
-
@env['action_dispatch.request.flash_hash'] = nil
-
end
-
-
1
def session=(session) #:nodoc:
-
Session.set @env, session
-
end
-
-
1
def session_options=(options)
-
Session::Options.set @env, options
-
end
-
-
# Override Rack's GET method to support indifferent access
-
1
def GET
-
66
@env["action_dispatch.request.query_parameters"] ||= Utils.deep_munge(normalize_encode_params(super || {}))
-
rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
-
raise ActionController::BadRequest.new(:query, e)
-
end
-
1
alias :query_parameters :GET
-
-
# Override Rack's POST method to support indifferent access
-
1
def POST
-
66
@env["action_dispatch.request.request_parameters"] ||= Utils.deep_munge(normalize_encode_params(super || {}))
-
rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
-
raise ActionController::BadRequest.new(:request, e)
-
end
-
1
alias :request_parameters :POST
-
-
# Returns the authorization header regardless of whether it was specified directly or through one of the
-
# proxy alternatives.
-
1
def authorization
-
@env['HTTP_AUTHORIZATION'] ||
-
@env['X-HTTP_AUTHORIZATION'] ||
-
@env['X_HTTP_AUTHORIZATION'] ||
-
@env['REDIRECT_X_HTTP_AUTHORIZATION']
-
end
-
-
# True if the request came from localhost, 127.0.0.1.
-
1
def local?
-
110
LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip
-
end
-
-
# Extracted into ActionDispatch::Request::Utils.deep_munge, but kept here for backwards compatibility.
-
1
def deep_munge(hash)
-
ActiveSupport::Deprecation.warn(
-
'This method has been extracted into `ActionDispatch::Request::Utils.deep_munge`. Please start using that instead.'
-
)
-
-
Utils.deep_munge(hash)
-
end
-
-
1
protected
-
1
def parse_query(qs)
-
66
Utils.deep_munge(super)
-
end
-
-
1
private
-
1
def check_method(name)
-
198
HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS[0...-1].join(', ')}, and #{HTTP_METHODS[-1]}")
-
198
name
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'active_support/deprecation'
-
1
require 'action_dispatch/http/filter_redirect'
-
1
require 'monitor'
-
-
1
module ActionDispatch # :nodoc:
-
# Represents an HTTP response generated by a controller action. Use it to
-
# retrieve the current state of the response, or customize the response. It can
-
# either represent a real HTTP response (i.e. one that is meant to be sent
-
# back to the web browser) or a TestResponse (i.e. one that is generated
-
# from integration tests).
-
#
-
# \Response is mostly a Ruby on \Rails framework implementation detail, and
-
# should never be used directly in controllers. Controllers should use the
-
# methods defined in ActionController::Base instead. For example, if you want
-
# to set the HTTP response's content MIME type, then use
-
# ActionControllerBase#headers instead of Response#headers.
-
#
-
# Nevertheless, integration tests may want to inspect controller responses in
-
# more detail, and that's when \Response can be useful for application
-
# developers. Integration test methods such as
-
# ActionDispatch::Integration::Session#get and
-
# ActionDispatch::Integration::Session#post return objects of type
-
# TestResponse (which are of course also of type \Response).
-
#
-
# For example, the following demo integration test prints the body of the
-
# controller response to the console:
-
#
-
# class DemoControllerTest < ActionDispatch::IntegrationTest
-
# def test_print_root_path_to_console
-
# get('/')
-
# puts response.body
-
# end
-
# end
-
1
class Response
-
# The request that the response is responding to.
-
1
attr_accessor :request
-
-
# The HTTP status code.
-
1
attr_reader :status
-
-
1
attr_writer :sending_file
-
-
# Get and set headers for this response.
-
1
attr_accessor :header
-
-
1
alias_method :headers=, :header=
-
1
alias_method :headers, :header
-
-
1
delegate :[], :[]=, :to => :@header
-
1
delegate :each, :to => :@stream
-
-
# Sets the HTTP response's content MIME type. For example, in the controller
-
# you could write this:
-
#
-
# response.content_type = "text/plain"
-
#
-
# If a character set has been defined for this response (see charset=) then
-
# the character set information will also be included in the content type
-
# information.
-
1
attr_reader :content_type
-
-
# The charset of the response. HTML wants to know the encoding of the
-
# content you're giving them, so we need to send that along.
-
1
attr_accessor :charset
-
-
1
CONTENT_TYPE = "Content-Type".freeze
-
1
SET_COOKIE = "Set-Cookie".freeze
-
1
LOCATION = "Location".freeze
-
1
NO_CONTENT_CODES = [204, 304]
-
-
3
cattr_accessor(:default_charset) { "utf-8" }
-
1
cattr_accessor(:default_headers)
-
-
1
include Rack::Response::Helpers
-
1
include ActionDispatch::Http::FilterRedirect
-
1
include ActionDispatch::Http::Cache::Response
-
1
include MonitorMixin
-
-
1
class Buffer # :nodoc:
-
1
def initialize(response, buf)
-
132
@response = response
-
132
@buf = buf
-
132
@closed = false
-
end
-
-
1
def write(string)
-
raise IOError, "closed stream" if closed?
-
-
@response.commit!
-
@buf.push string
-
end
-
-
1
def each(&block)
-
66
@response.sending!
-
66
x = @buf.each(&block)
-
66
@response.sent!
-
66
x
-
end
-
-
1
def abort
-
end
-
-
1
def close
-
@response.commit!
-
@closed = true
-
end
-
-
1
def closed?
-
@closed
-
end
-
end
-
-
# The underlying body, as a streamable object.
-
1
attr_reader :stream
-
-
1
def initialize(status = 200, header = {}, body = [], options = {})
-
66
super()
-
-
66
default_headers = options.fetch(:default_headers, self.class.default_headers)
-
66
header = merge_default_headers(header, default_headers)
-
-
66
self.body, self.header, self.status = body, header, status
-
-
66
@sending_file = false
-
66
@blank = false
-
66
@cv = new_cond
-
66
@committed = false
-
66
@sending = false
-
66
@sent = false
-
66
@content_type = nil
-
66
@charset = nil
-
-
66
if content_type = self[CONTENT_TYPE]
-
type, charset = content_type.split(/;\s*charset=/)
-
@content_type = Mime::Type.lookup(type)
-
@charset = charset || self.class.default_charset
-
end
-
-
66
prepare_cache_control!
-
-
66
yield self if block_given?
-
end
-
-
1
def await_commit
-
synchronize do
-
@cv.wait_until { @committed }
-
end
-
end
-
-
1
def await_sent
-
synchronize { @cv.wait_until { @sent } }
-
end
-
-
1
def commit!
-
synchronize do
-
before_committed
-
@committed = true
-
@cv.broadcast
-
end
-
end
-
-
1
def sending!
-
66
synchronize do
-
66
before_sending
-
66
@sending = true
-
66
@cv.broadcast
-
end
-
end
-
-
1
def sent!
-
66
synchronize do
-
66
@sent = true
-
66
@cv.broadcast
-
end
-
end
-
-
1
def sending?; synchronize { @sending }; end
-
111
def committed?; synchronize { @committed }; end
-
1
def sent?; synchronize { @sent }; end
-
-
# Sets the HTTP status code.
-
1
def status=(status)
-
77
@status = Rack::Utils.status_code(status)
-
end
-
-
# Sets the HTTP content type.
-
1
def content_type=(content_type)
-
58
@content_type = content_type.to_s
-
end
-
-
# The response code of the request.
-
1
def response_code
-
@status
-
end
-
-
# Returns a string to ensure compatibility with <tt>Net::HTTPResponse</tt>.
-
1
def code
-
@status.to_s
-
end
-
-
# Returns the corresponding message for the current HTTP status code:
-
#
-
# response.status = 200
-
# response.message # => "OK"
-
#
-
# response.status = 404
-
# response.message # => "Not Found"
-
#
-
1
def message
-
Rack::Utils::HTTP_STATUS_CODES[@status]
-
end
-
1
alias_method :status_message, :message
-
-
# Returns the content of the response as a string. This contains the contents
-
# of any calls to <tt>render</tt>.
-
1
def body
-
strings = []
-
each { |part| strings << part.to_s }
-
strings.join
-
end
-
-
1
EMPTY = " "
-
-
# Allows you to manually set or override the response body.
-
1
def body=(body)
-
132
@blank = true if body == EMPTY
-
-
132
if body.respond_to?(:to_path)
-
@stream = body
-
else
-
132
synchronize do
-
132
@stream = build_buffer self, munge_body_object(body)
-
end
-
end
-
end
-
-
1
def body_parts
-
parts = []
-
@stream.each { |x| parts << x }
-
parts
-
end
-
-
1
def set_cookie(key, value)
-
::Rack::Utils.set_cookie_header!(header, key, value)
-
end
-
-
1
def delete_cookie(key, value={})
-
::Rack::Utils.delete_cookie_header!(header, key, value)
-
end
-
-
# The location header we'll be responding with.
-
1
def location
-
22
headers[LOCATION]
-
end
-
1
alias_method :redirect_url, :location
-
-
# Sets the location header we'll be responding with.
-
1
def location=(url)
-
11
headers[LOCATION] = url
-
end
-
-
1
def close
-
stream.close if stream.respond_to?(:close)
-
end
-
-
1
def abort
-
66
if stream.respond_to?(:abort)
-
66
stream.abort
-
elsif stream.respond_to?(:close)
-
# `stream.close` should really be reserved for a close from the
-
# other direction, but we must fall back to it for
-
# compatibility.
-
stream.close
-
end
-
end
-
-
# Turns the Response into a Rack-compatible array of the status, headers,
-
# and body. Allows explict splatting:
-
#
-
# status, headers, body = *response
-
1
def to_a
-
66
rack_response @status, @header.to_hash
-
end
-
1
alias prepare! to_a
-
-
# Be super clear that a response object is not an Array. Defining this
-
# would make implicit splatting work, but it also makes adding responses
-
# as arrays work, and "flattening" responses, cascading to the rack body!
-
# Not sensible behavior.
-
1
def to_ary
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
`ActionDispatch::Response#to_ary` no longer performs implicit conversion
-
to an array. Please use `response.to_a` instead, or a splat like `status,
-
headers, body = *response`.
-
MSG
-
-
to_a
-
end
-
-
# Returns the response cookies, converted to a Hash of (name => value) pairs
-
#
-
# assert_equal 'AuthorOfNewPage', r.cookies['author']
-
1
def cookies
-
cookies = {}
-
if header = self[SET_COOKIE]
-
header = header.split("\n") if header.respond_to?(:to_str)
-
header.each do |cookie|
-
if pair = cookie.split(';').first
-
key, value = pair.split("=").map { |v| Rack::Utils.unescape(v) }
-
cookies[key] = value
-
end
-
end
-
end
-
cookies
-
end
-
-
1
private
-
-
1
def before_committed
-
end
-
-
1
def before_sending
-
end
-
-
1
def merge_default_headers(original, default)
-
66
default.respond_to?(:merge) ? default.merge(original) : original
-
end
-
-
1
def build_buffer(response, body)
-
132
Buffer.new response, body
-
end
-
-
1
def munge_body_object(body)
-
132
body.respond_to?(:each) ? body : [body]
-
end
-
-
1
def assign_default_content_type_and_charset!(headers)
-
66
return if headers[CONTENT_TYPE].present?
-
-
66
@content_type ||= Mime::HTML
-
66
@charset ||= self.class.default_charset unless @charset == false
-
-
66
type = @content_type.to_s.dup
-
66
type << "; charset=#{@charset}" if append_charset?
-
-
66
headers[CONTENT_TYPE] = type
-
end
-
-
1
def append_charset?
-
66
!@sending_file && @charset != false
-
end
-
-
1
class RackBody
-
1
def initialize(response)
-
66
@response = response
-
end
-
-
1
def each(*args, &block)
-
66
@response.each(*args, &block)
-
end
-
-
1
def close
-
# Rack "close" maps to Response#abort, and *not* Response#close
-
# (which is used when the controller's finished writing)
-
66
@response.abort
-
end
-
-
1
def body
-
@response.body
-
end
-
-
1
def respond_to?(method, include_private = false)
-
143
if method.to_s == 'to_path'
-
66
@response.stream.respond_to?(method)
-
else
-
77
super
-
end
-
end
-
-
1
def to_path
-
@response.stream.to_path
-
end
-
-
1
def to_ary
-
nil
-
end
-
end
-
-
1
def rack_response(status, header)
-
66
assign_default_content_type_and_charset!(header)
-
66
handle_conditional_get!
-
-
66
header[SET_COOKIE] = header[SET_COOKIE].join("\n") if header[SET_COOKIE].respond_to?(:join)
-
-
66
if NO_CONTENT_CODES.include?(@status)
-
header.delete CONTENT_TYPE
-
[status, header, []]
-
else
-
66
[status, header, RackBody.new(self)]
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Http
-
# Models uploaded files.
-
#
-
# The actual file is accessible via the +tempfile+ accessor, though some
-
# of its interface is available directly for convenience.
-
#
-
# Uploaded files are temporary files whose lifespan is one request. When
-
# the object is finalized Ruby unlinks the file, so there is no need to
-
# clean them with a separate maintenance task.
-
1
class UploadedFile
-
# The basename of the file in the client.
-
1
attr_accessor :original_filename
-
-
# A string with the MIME type of the file.
-
1
attr_accessor :content_type
-
-
# A +Tempfile+ object with the actual uploaded file. Note that some of
-
# its interface is available directly.
-
1
attr_accessor :tempfile
-
1
alias :to_io :tempfile
-
-
# A string with the headers of the multipart request.
-
1
attr_accessor :headers
-
-
1
def initialize(hash) # :nodoc:
-
@tempfile = hash[:tempfile]
-
raise(ArgumentError, ':tempfile is required') unless @tempfile
-
-
@original_filename = hash[:filename]
-
if @original_filename
-
begin
-
@original_filename.encode!(Encoding::UTF_8)
-
rescue EncodingError
-
@original_filename.force_encoding(Encoding::UTF_8)
-
end
-
end
-
@content_type = hash[:type]
-
@headers = hash[:head]
-
end
-
-
# Shortcut for +tempfile.read+.
-
1
def read(length=nil, buffer=nil)
-
@tempfile.read(length, buffer)
-
end
-
-
# Shortcut for +tempfile.open+.
-
1
def open
-
@tempfile.open
-
end
-
-
# Shortcut for +tempfile.close+.
-
1
def close(unlink_now=false)
-
@tempfile.close(unlink_now)
-
end
-
-
# Shortcut for +tempfile.path+.
-
1
def path
-
@tempfile.path
-
end
-
-
# Shortcut for +tempfile.rewind+.
-
1
def rewind
-
@tempfile.rewind
-
end
-
-
# Shortcut for +tempfile.size+.
-
1
def size
-
@tempfile.size
-
end
-
-
# Shortcut for +tempfile.eof?+.
-
1
def eof?
-
@tempfile.eof?
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActionDispatch
-
1
module Http
-
1
module URL
-
1
IP_HOST_REGEXP = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
-
1
HOST_REGEXP = /(^[^:]+:\/\/)?(\[[^\]]+\]|[^:]+)(?::(\d+$))?/
-
1
PROTOCOL_REGEXP = /^([^:]+)(:)?(\/\/)?$/
-
-
1
mattr_accessor :tld_length
-
1
self.tld_length = 1
-
-
1
class << self
-
1
def extract_domain(host, tld_length)
-
extract_domain_from(host, tld_length) if named_host?(host)
-
end
-
-
1
def extract_subdomains(host, tld_length)
-
if named_host?(host)
-
extract_subdomains_from(host, tld_length)
-
else
-
[]
-
end
-
end
-
-
1
def extract_subdomain(host, tld_length)
-
extract_subdomains(host, tld_length).join('.')
-
end
-
-
1
def url_for(options)
-
155
if options[:only_path]
-
147
path_for options
-
else
-
8
full_url_for options
-
end
-
end
-
-
1
def full_url_for(options)
-
8
host = options[:host]
-
8
protocol = options[:protocol]
-
8
port = options[:port]
-
-
8
unless host
-
raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true'
-
end
-
-
8
build_host_url(host, port, protocol, options, path_for(options))
-
end
-
-
1
def path_for(options)
-
277
path = options[:script_name].to_s.chomp("/")
-
277
path << options[:path] if options.key?(:path)
-
-
277
add_trailing_slash(path) if options[:trailing_slash]
-
277
add_params(path, options[:params]) if options.key?(:params)
-
277
add_anchor(path, options[:anchor]) if options.key?(:anchor)
-
-
277
path
-
end
-
-
1
private
-
-
1
def add_params(path, params)
-
148
params = { params: params } unless params.is_a?(Hash)
-
228
params.reject! { |_,v| v.to_param.nil? }
-
148
path << "?#{params.to_query}" unless params.empty?
-
end
-
-
1
def add_anchor(path, anchor)
-
if anchor
-
path << "##{Journey::Router::Utils.escape_fragment(anchor.to_param)}"
-
end
-
end
-
-
1
def extract_domain_from(host, tld_length)
-
host.split('.').last(1 + tld_length).join('.')
-
end
-
-
1
def extract_subdomains_from(host, tld_length)
-
parts = host.split('.')
-
parts[0..-(tld_length + 2)]
-
end
-
-
1
def add_trailing_slash(path)
-
# includes querysting
-
if path.include?('?')
-
path.sub!(/\?/, '/\&')
-
# does not have a .format
-
elsif !path.include?(".")
-
path.sub!(/[^\/]\z|\A\z/, '\&/')
-
end
-
end
-
-
1
def build_host_url(host, port, protocol, options, path)
-
8
if match = host.match(HOST_REGEXP)
-
8
protocol ||= match[1] unless protocol == false
-
8
host = match[2]
-
8
port = match[3] unless options.key? :port
-
end
-
-
8
protocol = normalize_protocol protocol
-
8
host = normalize_host(host, options)
-
-
8
result = protocol.dup
-
-
8
if options[:user] && options[:password]
-
result << "#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@"
-
end
-
-
8
result << host
-
8
normalize_port(port, protocol) { |normalized_port|
-
result << ":#{normalized_port}"
-
}
-
-
8
result.concat path
-
end
-
-
1
def named_host?(host)
-
8
IP_HOST_REGEXP !~ host
-
end
-
-
1
def normalize_protocol(protocol)
-
8
case protocol
-
when nil
-
"http://"
-
when false, "//"
-
"//"
-
when PROTOCOL_REGEXP
-
8
"#{$1}://"
-
else
-
raise ArgumentError, "Invalid :protocol option: #{protocol.inspect}"
-
end
-
end
-
-
1
def normalize_host(_host, options)
-
8
return _host unless named_host?(_host)
-
-
8
tld_length = options[:tld_length] || @@tld_length
-
8
subdomain = options.fetch :subdomain, true
-
8
domain = options[:domain]
-
-
8
host = ""
-
8
if subdomain == true
-
8
return _host if domain.nil?
-
-
host << extract_subdomains_from(_host, tld_length).join('.')
-
elsif subdomain
-
host << subdomain.to_param
-
end
-
host << "." unless host.empty?
-
host << (domain || extract_domain_from(_host, tld_length))
-
host
-
end
-
-
1
def normalize_port(port, protocol)
-
8
return unless port
-
-
case protocol
-
when "//" then yield port
-
when "https://"
-
yield port unless port.to_i == 443
-
else
-
yield port unless port.to_i == 80
-
end
-
end
-
end
-
-
1
def initialize(env)
-
341
super
-
341
@protocol = nil
-
341
@port = nil
-
end
-
-
# Returns the complete URL used for this request.
-
1
def url
-
protocol + host_with_port + fullpath
-
end
-
-
# Returns 'https://' if this is an SSL request and 'http://' otherwise.
-
1
def protocol
-
204
@protocol ||= ssl? ? 'https://' : 'http://'
-
end
-
-
# Returns the \host for this request, such as "example.com".
-
1
def raw_host_with_port
-
201
if forwarded = env["HTTP_X_FORWARDED_HOST"].presence
-
forwarded.split(/,\s?/).last
-
else
-
201
env['HTTP_HOST'] || "#{env['SERVER_NAME'] || env['SERVER_ADDR']}:#{env['SERVER_PORT']}"
-
end
-
end
-
-
# Returns the host for this request, such as example.com.
-
1
def host
-
135
raw_host_with_port.sub(/:\d+$/, '')
-
end
-
-
# Returns a \host:\port string for this request, such as "example.com" or
-
# "example.com:8080".
-
1
def host_with_port
-
3
"#{host}#{port_string}"
-
end
-
-
# Returns the port number of this request as an integer.
-
1
def port
-
@port ||= begin
-
66
if raw_host_with_port =~ /:(\d+)$/
-
$1.to_i
-
else
-
66
standard_port
-
end
-
69
end
-
end
-
-
# Returns the standard \port number for this request's protocol.
-
1
def standard_port
-
135
case protocol
-
when 'https://' then 443
-
135
else 80
-
end
-
end
-
-
# Returns whether this request is using the standard port
-
1
def standard_port?
-
69
port == standard_port
-
end
-
-
# Returns a number \port suffix like 8080 if the \port number of this request
-
# is not the default HTTP \port 80 or HTTPS \port 443.
-
1
def optional_port
-
66
standard_port? ? nil : port
-
end
-
-
# Returns a string \port suffix, including colon, like ":8080" if the \port
-
# number of this request is not the default HTTP \port 80 or HTTPS \port 443.
-
1
def port_string
-
3
standard_port? ? '' : ":#{port}"
-
end
-
-
1
def server_port
-
@env['SERVER_PORT'].to_i
-
end
-
-
# Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify
-
# a different <tt>tld_length</tt>, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk".
-
1
def domain(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_domain(host, tld_length)
-
end
-
-
# Returns all the \subdomains as an array, so <tt>["dev", "www"]</tt> would be
-
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
-
# such as 2 to catch <tt>["www"]</tt> instead of <tt>["www", "rubyonrails"]</tt>
-
# in "www.rubyonrails.co.uk".
-
1
def subdomains(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_subdomains(host, tld_length)
-
end
-
-
# Returns all the \subdomains as a string, so <tt>"dev.www"</tt> would be
-
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
-
# such as 2 to catch <tt>"www"</tt> instead of <tt>"www.rubyonrails"</tt>
-
# in "www.rubyonrails.co.uk".
-
1
def subdomain(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_subdomain(host, tld_length)
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/router'
-
1
require 'action_dispatch/journey/gtg/builder'
-
1
require 'action_dispatch/journey/gtg/simulator'
-
1
require 'action_dispatch/journey/nfa/builder'
-
1
require 'action_dispatch/journey/nfa/simulator'
-
1
require 'action_controller/metal/exceptions'
-
1
require 'active_support/deprecation'
-
-
1
module ActionDispatch
-
1
module Journey
-
# The Formatter class is used for formatting URLs. For example, parameters
-
# passed to +url_for+ in Rails will eventually call Formatter#generate.
-
1
class Formatter # :nodoc:
-
1
attr_reader :routes
-
-
1
def initialize(routes)
-
1
@routes = routes
-
1
@cache = nil
-
end
-
-
1
def generate(name, options, path_parameters, parameterize = nil)
-
148
constraints = path_parameters.merge(options)
-
148
missing_keys = []
-
-
148
match_route(name, constraints) do |route|
-
148
parameterized_parts = extract_parameterized_parts(route, options, path_parameters, parameterize)
-
-
# Skip this route unless a name has been provided or it is a
-
# standard Rails route since we can't determine whether an options
-
# hash passed to url_for matches a Rack application or a redirect.
-
148
next unless name || route.dispatcher?
-
-
148
missing_keys = missing_keys(route, parameterized_parts)
-
148
next unless missing_keys.empty?
-
148
params = options.dup.delete_if do |key, _|
-
229
parameterized_parts.key?(key) || route.defaults.key?(key)
-
end
-
-
148
defaults = route.defaults
-
148
required_parts = route.required_parts
-
148
parameterized_parts.delete_if do |key, value|
-
1
value.to_s == defaults[key].to_s && !required_parts.include?(key)
-
end
-
-
148
return [route.format(parameterized_parts), params]
-
end
-
-
message = "No route matches #{Hash[constraints.sort_by{|k,v| k.to_s}].inspect}"
-
message << " missing required keys: #{missing_keys.sort.inspect}" unless missing_keys.empty?
-
-
raise ActionController::UrlGenerationError, message
-
end
-
-
1
def clear
-
1
@cache = nil
-
end
-
-
1
private
-
-
1
def extract_parameterized_parts(route, options, recall, parameterize = nil)
-
148
parameterized_parts = recall.merge(options)
-
-
148
keys_to_keep = route.parts.reverse.drop_while { |part|
-
94
!options.key?(part) || (options[part] || recall[part]).nil?
-
} | route.required_parts
-
-
148
(parameterized_parts.keys - keys_to_keep).each do |bad_key|
-
391
parameterized_parts.delete(bad_key)
-
end
-
-
148
if parameterize
-
148
parameterized_parts.each do |k, v|
-
1
parameterized_parts[k] = parameterize.call(k, v)
-
end
-
end
-
-
149
parameterized_parts.keep_if { |_, v| v }
-
148
parameterized_parts
-
end
-
-
1
def named_routes
-
149
routes.named_routes
-
end
-
-
1
def match_route(name, options)
-
148
if named_routes.key?(name)
-
1
yield named_routes[name]
-
else
-
# Make sure we don't show the deprecation warning more than once
-
147
warned = false
-
-
147
routes = non_recursive(cache, options)
-
-
496
hash = routes.group_by { |_, r| r.score(options) }
-
-
147
hash.keys.sort.reverse_each do |score|
-
147
break if score < 0
-
-
349
hash[score].sort_by { |i, _| i }.each do |_, route|
-
147
if name && !warned
-
ActiveSupport::Deprecation.warn <<-MSG.squish
-
You are trying to generate the URL for a named route called
-
#{name.inspect} but no such route was found. In the future,
-
this will result in an `ActionController::UrlGenerationError`
-
exception.
-
MSG
-
-
warned = true
-
end
-
-
147
yield route
-
end
-
end
-
end
-
end
-
-
1
def non_recursive(cache, options)
-
147
routes = []
-
147
queue = [cache]
-
-
147
while queue.any?
-
441
c = queue.shift
-
441
routes.concat(c[:___routes]) if c.key?(:___routes)
-
-
441
options.each do |pair|
-
1167
queue << c[pair] if c.key?(pair)
-
end
-
end
-
-
147
routes
-
end
-
-
# Returns an array populated with missing keys if any are present.
-
1
def missing_keys(route, parts)
-
148
missing_keys = []
-
148
tests = route.path.requirements
-
148
route.required_parts.each { |key|
-
1
if tests.key?(key)
-
missing_keys << key unless /\A#{tests[key]}\Z/ === parts[key]
-
else
-
1
missing_keys << key unless parts[key]
-
end
-
}
-
148
missing_keys
-
end
-
-
1
def possibles(cache, options, depth = 0)
-
cache.fetch(:___routes) { [] } + options.find_all { |pair|
-
cache.key?(pair)
-
}.flat_map { |pair|
-
possibles(cache[pair], options, depth + 1)
-
}
-
end
-
-
1
def build_cache
-
1
root = { ___routes: [] }
-
1
routes.each_with_index do |route, i|
-
35
leaf = route.required_defaults.inject(root) do |h, tuple|
-
68
h[tuple] ||= {}
-
end
-
35
(leaf[:___routes] ||= []) << [i, route]
-
end
-
1
root
-
end
-
-
1
def cache
-
147
@cache ||= build_cache
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/gtg/transition_table'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module GTG # :nodoc:
-
1
class Builder # :nodoc:
-
1
DUMMY = Nodes::Dummy.new
-
-
1
attr_reader :root, :ast, :endpoints
-
-
1
def initialize(root)
-
36
@root = root
-
36
@ast = Nodes::Cat.new root, DUMMY
-
36
@followpos = nil
-
end
-
-
1
def transition_table
-
1
dtrans = TransitionTable.new
-
1
marked = {}
-
64
state_id = Hash.new { |h,k| h[k] = h.length }
-
-
1
start = firstpos(root)
-
1
dstates = [start]
-
1
until dstates.empty?
-
63
s = dstates.shift
-
63
next if marked[s]
-
49
marked[s] = true # mark s
-
-
281
s.group_by { |state| symbol(state) }.each do |sym, ps|
-
315
u = ps.flat_map { |l| followpos(l) }
-
83
next if u.empty?
-
-
62
if u.uniq == [DUMMY]
-
17
from = state_id[s]
-
17
to = state_id[Object.new]
-
17
dtrans[from, to] = sym
-
-
17
dtrans.add_accepting(to)
-
50
ps.each { |state| dtrans.add_memo(to, state.memo) }
-
else
-
45
dtrans[state_id[s], state_id[u]] = sym
-
-
45
if u.include?(DUMMY)
-
18
to = state_id[u]
-
-
113
accepting = ps.find_all { |l| followpos(l).include?(DUMMY) }
-
-
18
accepting.each { |accepting_state|
-
34
dtrans.add_memo(to, accepting_state.memo)
-
}
-
-
18
dtrans.add_accepting(state_id[u])
-
end
-
end
-
-
62
dstates << u
-
end
-
end
-
-
1
dtrans
-
end
-
-
1
def nullable?(node)
-
1710
case node
-
when Nodes::Group
-
66
true
-
when Nodes::Star
-
true
-
when Nodes::Or
-
node.children.any? { |c| nullable?(c) }
-
when Nodes::Cat
-
182
nullable?(node.left) && nullable?(node.right)
-
when Nodes::Terminal
-
1462
!node.left
-
when Nodes::Unary
-
nullable?(node.left)
-
else
-
raise ArgumentError, 'unknown nullable: %s' % node.class.name
-
end
-
end
-
-
1
def firstpos(node)
-
831
case node
-
when Nodes::Star
-
firstpos(node.left)
-
when Nodes::Cat
-
281
if nullable?(node.left)
-
firstpos(node.left) | firstpos(node.right)
-
else
-
281
firstpos(node.left)
-
end
-
when Nodes::Or
-
35
node.children.flat_map { |c| firstpos(c) }.uniq
-
when Nodes::Unary
-
66
firstpos(node.left)
-
when Nodes::Terminal
-
483
nullable?(node) ? [] : [node]
-
else
-
raise ArgumentError, 'unknown firstpos: %s' % node.class.name
-
end
-
end
-
-
1
def lastpos(node)
-
831
case node
-
when Nodes::Star
-
firstpos(node.left)
-
when Nodes::Or
-
35
node.children.flat_map { |c| lastpos(c) }.uniq
-
when Nodes::Cat
-
315
if nullable?(node.right)
-
66
lastpos(node.left) | lastpos(node.right)
-
else
-
249
lastpos(node.right)
-
end
-
when Nodes::Terminal
-
449
nullable?(node) ? [] : [node]
-
when Nodes::Unary
-
66
lastpos(node.left)
-
else
-
raise ArgumentError, 'unknown lastpos: %s' % node.class.name
-
end
-
end
-
-
1
def followpos(node)
-
423
followpos_table[node]
-
end
-
-
1
private
-
-
1
def followpos_table
-
423
@followpos ||= build_followpos
-
end
-
-
1
def build_followpos
-
419
table = Hash.new { |h, k| h[k] = [] }
-
35
@ast.each do |n|
-
835
case n
-
when Nodes::Cat
-
350
lastpos(n.left).each do |i|
-
449
table[i] += firstpos(n.right)
-
end
-
when Nodes::Star
-
lastpos(n).each do |i|
-
table[i] += firstpos(n)
-
end
-
end
-
end
-
35
table
-
end
-
-
1
def symbol(edge)
-
232
case edge
-
when Journey::Nodes::Symbol
-
53
edge.regexp
-
else
-
179
edge.left
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'strscan'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module GTG # :nodoc:
-
1
class MatchData # :nodoc:
-
1
attr_reader :memos
-
-
1
def initialize(memos)
-
@memos = memos
-
end
-
end
-
-
1
class Simulator # :nodoc:
-
1
attr_reader :tt
-
-
1
def initialize(transition_table)
-
1
@tt = transition_table
-
end
-
-
1
def simulate(string)
-
ms = memos(string) { return }
-
MatchData.new(ms)
-
end
-
-
1
alias :=~ :simulate
-
1
alias :match :simulate
-
-
1
def memos(string)
-
66
input = StringScanner.new(string)
-
66
state = [0]
-
66
while sym = input.scan(%r([/.?]|[^/.?]+))
-
218
state = tt.move(state, sym)
-
end
-
-
66
acceptance_states = state.find_all { |s|
-
70
tt.accepting? s
-
}
-
-
66
return yield if acceptance_states.empty?
-
-
136
acceptance_states.flat_map { |x| tt.memo(x) }.compact
-
end
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/nfa/dot'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module GTG # :nodoc:
-
1
class TransitionTable # :nodoc:
-
1
include Journey::NFA::Dot
-
-
1
attr_reader :memos
-
-
1
def initialize
-
1
@regexp_states = {}
-
1
@string_states = {}
-
1
@accepting = {}
-
36
@memos = Hash.new { |h,k| h[k] = [] }
-
end
-
-
1
def add_accepting(state)
-
35
@accepting[state] = true
-
end
-
-
1
def accepting_states
-
@accepting.keys
-
end
-
-
1
def accepting?(state)
-
70
@accepting[state]
-
end
-
-
1
def add_memo(idx, memo)
-
67
@memos[idx] << memo
-
end
-
-
1
def memo(idx)
-
70
@memos[idx]
-
end
-
-
1
def eclosure(t)
-
Array(t)
-
end
-
-
1
def move(t, a)
-
218
return [] if t.empty?
-
-
218
regexps = []
-
-
t.map { |s|
-
218
if states = @regexp_states[s]
-
52
regexps.concat states.map { |re, v| re === a ? v : nil }
-
end
-
-
218
if states = @string_states[s]
-
218
states[a]
-
end
-
218
}.compact.concat regexps
-
end
-
-
1
def as_json(options = nil)
-
simple_regexp = Hash.new { |h,k| h[k] = {} }
-
-
@regexp_states.each do |from, hash|
-
hash.each do |re, to|
-
simple_regexp[from][re.source] = to
-
end
-
end
-
-
{
-
regexp_states: simple_regexp,
-
string_states: @string_states,
-
accepting: @accepting
-
}
-
end
-
-
1
def to_svg
-
svg = IO.popen('dot -Tsvg', 'w+') { |f|
-
f.write(to_dot)
-
f.close_write
-
f.readlines
-
}
-
3.times { svg.shift }
-
svg.join.sub(/width="[^"]*"/, '').sub(/height="[^"]*"/, '')
-
end
-
-
1
def visualizer(paths, title = 'FSM')
-
viz_dir = File.join File.dirname(__FILE__), '..', 'visualizer'
-
fsm_js = File.read File.join(viz_dir, 'fsm.js')
-
fsm_css = File.read File.join(viz_dir, 'fsm.css')
-
erb = File.read File.join(viz_dir, 'index.html.erb')
-
states = "function tt() { return #{to_json}; }"
-
-
fun_routes = paths.sample(3).map do |ast|
-
ast.map { |n|
-
case n
-
when Nodes::Symbol
-
case n.left
-
when ':id' then rand(100).to_s
-
when ':format' then %w{ xml json }.sample
-
else
-
'omg'
-
end
-
when Nodes::Terminal then n.symbol
-
else
-
nil
-
end
-
}.compact.join
-
end
-
-
stylesheets = [fsm_css]
-
svg = to_svg
-
javascripts = [states, fsm_js]
-
-
# Annoying hack for 1.9 warnings
-
fun_routes = fun_routes
-
stylesheets = stylesheets
-
svg = svg
-
javascripts = javascripts
-
-
require 'erb'
-
template = ERB.new erb
-
template.result(binding)
-
end
-
-
1
def []=(from, to, sym)
-
62
to_mappings = states_hash_for(sym)[from] ||= {}
-
62
to_mappings[sym] = to
-
end
-
-
1
def states
-
ss = @string_states.keys + @string_states.values.flat_map(&:values)
-
rs = @regexp_states.keys + @regexp_states.values.flat_map(&:values)
-
(ss + rs).uniq
-
end
-
-
1
def transitions
-
@string_states.flat_map { |from, hash|
-
hash.map { |s, to| [from, s, to] }
-
} + @regexp_states.flat_map { |from, hash|
-
hash.map { |s, to| [from, s, to] }
-
}
-
end
-
-
1
private
-
-
1
def states_hash_for(sym)
-
62
case sym
-
when String
-
41
@string_states
-
when Regexp
-
21
@regexp_states
-
else
-
raise ArgumentError, 'unknown symbol: %s' % sym.class
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/nfa/transition_table'
-
1
require 'action_dispatch/journey/gtg/transition_table'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module NFA # :nodoc:
-
1
class Visitor < Visitors::Visitor # :nodoc:
-
1
def initialize(tt)
-
@tt = tt
-
@i = -1
-
end
-
-
1
def visit_CAT(node)
-
left = visit(node.left)
-
right = visit(node.right)
-
-
@tt.merge(left.last, right.first)
-
-
[left.first, right.last]
-
end
-
-
1
def visit_GROUP(node)
-
from = @i += 1
-
left = visit(node.left)
-
to = @i += 1
-
-
@tt.accepting = to
-
-
@tt[from, left.first] = nil
-
@tt[left.last, to] = nil
-
@tt[from, to] = nil
-
-
[from, to]
-
end
-
-
1
def visit_OR(node)
-
from = @i += 1
-
children = node.children.map { |c| visit(c) }
-
to = @i += 1
-
-
children.each do |child|
-
@tt[from, child.first] = nil
-
@tt[child.last, to] = nil
-
end
-
-
@tt.accepting = to
-
-
[from, to]
-
end
-
-
1
def terminal(node)
-
from_i = @i += 1 # new state
-
to_i = @i += 1 # new state
-
-
@tt[from_i, to_i] = node
-
@tt.accepting = to_i
-
@tt.add_memo(to_i, node.memo)
-
-
[from_i, to_i]
-
end
-
end
-
-
1
class Builder # :nodoc:
-
1
def initialize(ast)
-
@ast = ast
-
end
-
-
1
def transition_table
-
tt = TransitionTable.new
-
Visitor.new(tt).accept(@ast)
-
tt
-
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module NFA # :nodoc:
-
1
module Dot # :nodoc:
-
1
def to_dot
-
edges = transitions.map { |from, sym, to|
-
" #{from} -> #{to} [label=\"#{sym || 'ε'}\"];"
-
}
-
-
#memo_nodes = memos.values.flatten.map { |n|
-
# label = n
-
# if Journey::Route === n
-
# label = "#{n.verb.source} #{n.path.spec}"
-
# end
-
# " #{n.object_id} [label=\"#{label}\", shape=box];"
-
#}
-
#memo_edges = memos.flat_map { |k, memos|
-
# (memos || []).map { |v| " #{k} -> #{v.object_id};" }
-
#}.uniq
-
-
<<-eodot
-
digraph nfa {
-
rankdir=LR;
-
node [shape = doublecircle];
-
#{accepting_states.join ' '};
-
node [shape = circle];
-
#{edges.join "\n"}
-
}
-
eodot
-
end
-
end
-
end
-
end
-
end
-
1
require 'strscan'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module NFA # :nodoc:
-
1
class MatchData # :nodoc:
-
1
attr_reader :memos
-
-
1
def initialize(memos)
-
@memos = memos
-
end
-
end
-
-
1
class Simulator # :nodoc:
-
1
attr_reader :tt
-
-
1
def initialize(transition_table)
-
@tt = transition_table
-
end
-
-
1
def simulate(string)
-
input = StringScanner.new(string)
-
state = tt.eclosure(0)
-
until input.eos?
-
sym = input.scan(%r([/.?]|[^/.?]+))
-
-
# FIXME: tt.eclosure is not needed for the GTG
-
state = tt.eclosure(tt.move(state, sym))
-
end
-
-
acceptance_states = state.find_all { |s|
-
tt.accepting?(tt.eclosure(s).sort.last)
-
}
-
-
return if acceptance_states.empty?
-
-
memos = acceptance_states.flat_map { |x| tt.memo(x) }.compact
-
-
MatchData.new(memos)
-
end
-
-
1
alias :=~ :simulate
-
1
alias :match :simulate
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/nfa/dot'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module NFA # :nodoc:
-
1
class TransitionTable # :nodoc:
-
1
include Journey::NFA::Dot
-
-
1
attr_accessor :accepting
-
1
attr_reader :memos
-
-
1
def initialize
-
@table = Hash.new { |h,f| h[f] = {} }
-
@memos = {}
-
@accepting = nil
-
@inverted = nil
-
end
-
-
1
def accepting?(state)
-
accepting == state
-
end
-
-
1
def accepting_states
-
[accepting]
-
end
-
-
1
def add_memo(idx, memo)
-
@memos[idx] = memo
-
end
-
-
1
def memo(idx)
-
@memos[idx]
-
end
-
-
1
def []=(i, f, s)
-
@table[f][i] = s
-
end
-
-
1
def merge(left, right)
-
@memos[right] = @memos.delete(left)
-
@table[right] = @table.delete(left)
-
end
-
-
1
def states
-
(@table.keys + @table.values.flat_map(&:keys)).uniq
-
end
-
-
# Returns a generalized transition graph with reduced states. The states
-
# are reduced like a DFA, but the table must be simulated like an NFA.
-
#
-
# Edges of the GTG are regular expressions.
-
1
def generalized_table
-
gt = GTG::TransitionTable.new
-
marked = {}
-
state_id = Hash.new { |h,k| h[k] = h.length }
-
alphabet = self.alphabet
-
-
stack = [eclosure(0)]
-
-
until stack.empty?
-
state = stack.pop
-
next if marked[state] || state.empty?
-
-
marked[state] = true
-
-
alphabet.each do |alpha|
-
next_state = eclosure(following_states(state, alpha))
-
next if next_state.empty?
-
-
gt[state_id[state], state_id[next_state]] = alpha
-
stack << next_state
-
end
-
end
-
-
final_groups = state_id.keys.find_all { |s|
-
s.sort.last == accepting
-
}
-
-
final_groups.each do |states|
-
id = state_id[states]
-
-
gt.add_accepting(id)
-
save = states.find { |s|
-
@memos.key?(s) && eclosure(s).sort.last == accepting
-
}
-
-
gt.add_memo(id, memo(save))
-
end
-
-
gt
-
end
-
-
# Returns set of NFA states to which there is a transition on ast symbol
-
# +a+ from some state +s+ in +t+.
-
1
def following_states(t, a)
-
Array(t).flat_map { |s| inverted[s][a] }.uniq
-
end
-
-
# Returns set of NFA states to which there is a transition on ast symbol
-
# +a+ from some state +s+ in +t+.
-
1
def move(t, a)
-
Array(t).map { |s|
-
inverted[s].keys.compact.find_all { |sym|
-
sym === a
-
}.map { |sym| inverted[s][sym] }
-
}.flatten.uniq
-
end
-
-
1
def alphabet
-
inverted.values.flat_map(&:keys).compact.uniq.sort_by { |x| x.to_s }
-
end
-
-
# Returns a set of NFA states reachable from some NFA state +s+ in set
-
# +t+ on nil-transitions alone.
-
1
def eclosure(t)
-
stack = Array(t)
-
seen = {}
-
children = []
-
-
until stack.empty?
-
s = stack.pop
-
next if seen[s]
-
-
seen[s] = true
-
children << s
-
-
stack.concat(inverted[s][nil])
-
end
-
-
children.uniq
-
end
-
-
1
def transitions
-
@table.flat_map { |to, hash|
-
hash.map { |from, sym| [from, sym, to] }
-
}
-
end
-
-
1
private
-
-
1
def inverted
-
return @inverted if @inverted
-
-
@inverted = Hash.new { |h, from|
-
h[from] = Hash.new { |j, s| j[s] = [] }
-
}
-
-
@table.each { |to, hash|
-
hash.each { |from, sym|
-
if sym
-
sym = Nodes::Symbol === sym ? sym.regexp : sym.left
-
end
-
-
@inverted[from][sym] << to
-
}
-
}
-
-
@inverted
-
end
-
end
-
end
-
end
-
end
-
#
-
# DO NOT MODIFY!!!!
-
# This file is automatically generated by Racc 1.4.11
-
# from Racc grammer file "".
-
#
-
-
1
require 'racc/parser.rb'
-
-
-
1
require 'action_dispatch/journey/parser_extras'
-
1
module ActionDispatch
-
1
module Journey
-
1
class Parser < Racc::Parser
-
##### State transition tables begin ###
-
-
1
racc_action_table = [
-
13, 15, 14, 7, 21, 16, 8, 19, 13, 15,
-
14, 7, 17, 16, 8, 13, 15, 14, 7, 24,
-
16, 8, 13, 15, 14, 7, 19, 16, 8 ]
-
-
1
racc_action_check = [
-
2, 2, 2, 2, 17, 2, 2, 2, 0, 0,
-
0, 0, 1, 0, 0, 19, 19, 19, 19, 20,
-
19, 19, 7, 7, 7, 7, 22, 7, 7 ]
-
-
1
racc_action_pointer = [
-
6, 12, -2, nil, nil, nil, nil, 20, nil, nil,
-
nil, nil, nil, nil, nil, nil, nil, 4, nil, 13,
-
13, nil, 17, nil, nil ]
-
-
1
racc_action_default = [
-
-19, -19, -2, -3, -4, -5, -6, -19, -10, -11,
-
-12, -13, -14, -15, -16, -17, -18, -19, -1, -19,
-
-19, 25, -8, -9, -7 ]
-
-
1
racc_goto_table = [
-
1, 22, 18, 23, nil, nil, nil, 20 ]
-
-
1
racc_goto_check = [
-
1, 2, 1, 3, nil, nil, nil, 1 ]
-
-
1
racc_goto_pointer = [
-
nil, 0, -18, -16, nil, nil, nil, nil, nil, nil,
-
nil ]
-
-
1
racc_goto_default = [
-
nil, nil, 2, 3, 4, 5, 6, 9, 10, 11,
-
12 ]
-
-
1
racc_reduce_table = [
-
0, 0, :racc_error,
-
2, 11, :_reduce_1,
-
1, 11, :_reduce_2,
-
1, 11, :_reduce_none,
-
1, 12, :_reduce_none,
-
1, 12, :_reduce_none,
-
1, 12, :_reduce_none,
-
3, 15, :_reduce_7,
-
3, 13, :_reduce_8,
-
3, 13, :_reduce_9,
-
1, 16, :_reduce_10,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 19, :_reduce_15,
-
1, 17, :_reduce_16,
-
1, 18, :_reduce_17,
-
1, 20, :_reduce_18 ]
-
-
1
racc_reduce_n = 19
-
-
1
racc_shift_n = 25
-
-
1
racc_token_table = {
-
false => 0,
-
:error => 1,
-
:SLASH => 2,
-
:LITERAL => 3,
-
:SYMBOL => 4,
-
:LPAREN => 5,
-
:RPAREN => 6,
-
:DOT => 7,
-
:STAR => 8,
-
:OR => 9 }
-
-
1
racc_nt_base = 10
-
-
1
racc_use_result_var = false
-
-
1
Racc_arg = [
-
racc_action_table,
-
racc_action_check,
-
racc_action_default,
-
racc_action_pointer,
-
racc_goto_table,
-
racc_goto_check,
-
racc_goto_default,
-
racc_goto_pointer,
-
racc_nt_base,
-
racc_reduce_table,
-
racc_token_table,
-
racc_shift_n,
-
racc_reduce_n,
-
racc_use_result_var ]
-
-
1
Racc_token_to_s_table = [
-
"$end",
-
"error",
-
"SLASH",
-
"LITERAL",
-
"SYMBOL",
-
"LPAREN",
-
"RPAREN",
-
"DOT",
-
"STAR",
-
"OR",
-
"$start",
-
"expressions",
-
"expression",
-
"or",
-
"terminal",
-
"group",
-
"star",
-
"symbol",
-
"literal",
-
"slash",
-
"dot" ]
-
-
1
Racc_debug_parser = false
-
-
##### State transition tables end #####
-
-
# reduce 0 omitted
-
-
1
def _reduce_1(val, _values)
-
158
Cat.new(val.first, val.last)
-
end
-
-
1
def _reduce_2(val, _values)
-
68
val.first
-
end
-
-
# reduce 3 omitted
-
-
# reduce 4 omitted
-
-
# reduce 5 omitted
-
-
# reduce 6 omitted
-
-
1
def _reduce_7(val, _values)
-
33
Group.new(val[1])
-
end
-
-
1
def _reduce_8(val, _values)
-
Or.new([val.first, val.last])
-
end
-
-
1
def _reduce_9(val, _values)
-
Or.new([val.first, val.last])
-
end
-
-
1
def _reduce_10(val, _values)
-
Star.new(Symbol.new(val.last))
-
end
-
-
# reduce 11 omitted
-
-
# reduce 12 omitted
-
-
# reduce 13 omitted
-
-
# reduce 14 omitted
-
-
1
def _reduce_15(val, _values)
-
64
Slash.new('/')
-
end
-
-
1
def _reduce_16(val, _values)
-
53
Symbol.new(val.first)
-
end
-
-
1
def _reduce_17(val, _values)
-
43
Literal.new(val.first)
-
end
-
-
1
def _reduce_18(val, _values)
-
33
Dot.new(val.first)
-
end
-
-
1
def _reduce_none(val, _values)
-
val[0]
-
end
-
-
end # class Parser
-
end # module Journey
-
end # module ActionDispatch
-
1
require 'action_dispatch/journey/scanner'
-
1
require 'action_dispatch/journey/nodes/node'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Parser < Racc::Parser # :nodoc:
-
1
include Journey::Nodes
-
-
1
def initialize
-
35
@scanner = Scanner.new
-
end
-
-
1
def parse(string)
-
35
@scanner.scan_setup(string)
-
35
do_parse
-
end
-
-
1
def next_token
-
294
@scanner.next_token
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/router/strexp'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module Path # :nodoc:
-
1
class Pattern # :nodoc:
-
1
attr_reader :spec, :requirements, :anchored
-
-
1
def self.from_string string
-
new Journey::Router::Strexp.build(string, {}, ["/.?"], true)
-
end
-
-
1
def initialize(strexp)
-
35
@spec = strexp.ast
-
35
@requirements = strexp.requirements
-
35
@separators = strexp.separators.join
-
35
@anchored = strexp.anchor
-
-
35
@names = nil
-
35
@optional_names = nil
-
35
@required_names = nil
-
35
@re = nil
-
35
@offsets = nil
-
end
-
-
1
def build_formatter
-
35
Visitors::FormatBuilder.new.accept(spec)
-
end
-
-
1
def ast
-
34
@spec.grep(Nodes::Symbol).each do |node|
-
53
re = @requirements[node.to_sym]
-
53
node.regexp = re if re
-
end
-
-
34
@spec.grep(Nodes::Star).each do |node|
-
node = node.left
-
node.regexp = @requirements[node.to_sym] || /(.+)/
-
end
-
-
34
@spec
-
end
-
-
1
def names
-
560
@names ||= spec.grep(Nodes::Symbol).map { |n| n.name }
-
end
-
-
1
def required_names
-
367
@required_names ||= names - optional_names
-
end
-
-
1
def optional_names
-
@optional_names ||= spec.grep(Nodes::Group).flat_map { |group|
-
17
group.grep(Nodes::Symbol)
-
36
}.map { |n| n.name }.uniq
-
end
-
-
1
class RegexpOffsets < Journey::Visitors::Visitor # :nodoc:
-
1
attr_reader :offsets
-
-
1
def initialize(matchers)
-
28
@matchers = matchers
-
28
@capture_count = [0]
-
end
-
-
1
def visit(node)
-
320
super
-
320
@capture_count
-
end
-
-
1
def visit_SYMBOL(node)
-
43
node = node.to_sym
-
-
43
if @matchers.key?(node)
-
re = /#{@matchers[node]}|/
-
@capture_count.push((re.match('').length - 1) + (@capture_count.last || 0))
-
else
-
43
@capture_count << (@capture_count.last || 0)
-
end
-
end
-
end
-
-
1
class AnchoredRegexp < Journey::Visitors::Visitor # :nodoc:
-
1
def initialize(separator, matchers)
-
29
@separator = separator
-
29
@matchers = matchers
-
29
@separator_re = "([^#{separator}]+)"
-
29
super()
-
end
-
-
1
def accept(node)
-
28
%r{\A#{visit node}\Z}
-
end
-
-
1
def visit_CAT(node)
-
133
[visit(node.left), visit(node.right)].join
-
end
-
-
1
def visit_SYMBOL(node)
-
43
node = node.to_sym
-
-
43
return @separator_re unless @matchers.key?(node)
-
-
re = @matchers[node]
-
"(#{re})"
-
end
-
-
1
def visit_GROUP(node)
-
28
"(?:#{visit node.left})?"
-
end
-
-
1
def visit_LITERAL(node)
-
66
Regexp.escape(node.left)
-
end
-
1
alias :visit_DOT :visit_LITERAL
-
-
1
def visit_SLASH(node)
-
53
node.left
-
end
-
-
1
def visit_STAR(node)
-
re = @matchers[node.left.to_sym] || '.+'
-
"(#{re})"
-
end
-
end
-
-
1
class UnanchoredRegexp < AnchoredRegexp # :nodoc:
-
1
def accept(node)
-
1
%r{\A#{visit node}}
-
end
-
end
-
-
1
class MatchData # :nodoc:
-
1
attr_reader :names
-
-
1
def initialize(names, offsets, match)
-
70
@names = names
-
70
@offsets = offsets
-
70
@match = match
-
end
-
-
1
def captures
-
166
(length - 1).times.map { |i| self[i + 1] }
-
end
-
-
1
def [](x)
-
96
idx = @offsets[x - 1] + x
-
96
@match[idx]
-
end
-
-
1
def length
-
70
@offsets.length
-
end
-
-
1
def post_match
-
@match.post_match
-
end
-
-
1
def to_s
-
@match.to_s
-
end
-
end
-
-
1
def match(other)
-
136
return unless match = to_regexp.match(other)
-
70
MatchData.new(names, offsets, match)
-
end
-
1
alias :=~ :match
-
-
1
def source
-
to_regexp.source
-
end
-
-
1
def to_regexp
-
136
@re ||= regexp_visitor.new(@separators, @requirements).accept spec
-
end
-
-
1
private
-
-
1
def regexp_visitor
-
29
@anchored ? AnchoredRegexp : UnanchoredRegexp
-
end
-
-
1
def offsets
-
70
return @offsets if @offsets
-
-
28
viz = RegexpOffsets.new(@requirements)
-
28
@offsets = viz.accept(spec)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Route # :nodoc:
-
1
attr_reader :app, :path, :defaults, :name
-
-
1
attr_reader :constraints
-
1
alias :conditions :constraints
-
-
1
attr_accessor :precedence
-
-
##
-
# +path+ is a path constraint.
-
# +constraints+ is a hash of constraints to be applied to this route.
-
1
def initialize(name, app, path, constraints, defaults = {})
-
35
@name = name
-
35
@app = app
-
35
@path = path
-
-
35
@constraints = constraints
-
35
@defaults = defaults
-
35
@required_defaults = nil
-
35
@required_parts = nil
-
35
@parts = nil
-
35
@decorated_ast = nil
-
35
@precedence = 0
-
35
@path_formatter = @path.build_formatter
-
end
-
-
1
def ast
-
@decorated_ast ||= begin
-
34
decorated_ast = path.ast
-
225
decorated_ast.grep(Nodes::Terminal).each { |n| n.memo = self }
-
34
decorated_ast
-
68
end
-
end
-
-
1
def requirements # :nodoc:
-
# needed for rails `rake routes`
-
@defaults.merge(path.requirements).delete_if { |_,v|
-
/.+?/ == v
-
}
-
end
-
-
1
def segments
-
34
path.names
-
end
-
-
1
def required_keys
-
required_parts + required_defaults.keys
-
end
-
-
1
def score(constraints)
-
349
required_keys = path.required_names
-
1252
supplied_keys = constraints.map { |k,v| v && k.to_s }.compact
-
-
349
return -1 unless (required_keys - supplied_keys).empty?
-
-
349
score = (supplied_keys & path.names).length
-
349
score + (required_defaults.length * 2)
-
end
-
-
1
def parts
-
306
@parts ||= segments.map { |n| n.to_sym }
-
end
-
1
alias :segment_keys :parts
-
-
1
def format(path_options)
-
277
@path_formatter.evaluate path_options
-
end
-
-
1
def optional_parts
-
path.optional_names.map { |n| n.to_sym }
-
end
-
-
1
def required_parts
-
488
@required_parts ||= path.required_names.map { |n| n.to_sym }
-
end
-
-
1
def required_default?(key)
-
68
(constraints[:required_defaults] || []).include?(key)
-
end
-
-
1
def required_defaults
-
@required_defaults ||= @defaults.dup.delete_if do |k,_|
-
68
parts.include?(k) || !required_default?(k)
-
384
end
-
end
-
-
1
def glob?
-
36
!path.spec.grep(Nodes::Star).empty?
-
end
-
-
1
def dispatcher?
-
147
@app.dispatcher?
-
end
-
-
1
def matches?(request)
-
163
constraints.all? do |method, value|
-
326
next true unless request.respond_to?(method)
-
-
163
case value
-
when Regexp, String
-
163
value === request.send(method).to_s
-
when Array
-
value.include?(request.send(method))
-
when TrueClass
-
request.send(method).present?
-
when FalseClass
-
request.send(method).blank?
-
else
-
value === request.send(method)
-
end
-
end
-
end
-
-
1
def ip
-
constraints[:ip] || //
-
end
-
-
1
def verb
-
constraints[:request_method] || //
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/router/utils'
-
1
require 'action_dispatch/journey/router/strexp'
-
1
require 'action_dispatch/journey/routes'
-
1
require 'action_dispatch/journey/formatter'
-
-
1
before = $-w
-
1
$-w = false
-
1
require 'action_dispatch/journey/parser'
-
1
$-w = before
-
-
1
require 'action_dispatch/journey/route'
-
1
require 'action_dispatch/journey/path/pattern'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Router # :nodoc:
-
1
class RoutingError < ::StandardError # :nodoc:
-
end
-
-
# :nodoc:
-
1
VERSION = '2.0.0'
-
-
1
attr_accessor :routes
-
-
1
def initialize(routes)
-
1
@routes = routes
-
end
-
-
1
def serve(req)
-
66
find_routes(req).each do |match, parameters, route|
-
66
set_params = req.path_parameters
-
66
path_info = req.path_info
-
66
script_name = req.script_name
-
-
66
unless route.path.anchored
-
req.script_name = (script_name.to_s + match.to_s).chomp('/')
-
req.path_info = match.post_match
-
req.path_info = "/" + req.path_info unless req.path_info.start_with? "/"
-
end
-
-
66
req.path_parameters = set_params.merge parameters
-
-
66
status, headers, body = route.app.serve(req)
-
-
66
if 'pass' == headers['X-Cascade']
-
req.script_name = script_name
-
req.path_info = path_info
-
req.path_parameters = set_params
-
next
-
end
-
-
66
return [status, headers, body]
-
end
-
-
return [404, {'X-Cascade' => 'pass'}, ['Not Found']]
-
end
-
-
1
def recognize(rails_req)
-
find_routes(rails_req).each do |match, parameters, route|
-
unless route.path.anchored
-
rails_req.script_name = match.to_s
-
rails_req.path_info = match.post_match.sub(/^([^\/])/, '/\1')
-
end
-
-
yield(route, parameters)
-
end
-
end
-
-
1
def visualizer
-
tt = GTG::Builder.new(ast).transition_table
-
groups = partitioned_routes.first.map(&:ast).group_by { |a| a.to_s }
-
asts = groups.values.map { |v| v.first }
-
tt.visualizer(asts)
-
end
-
-
1
private
-
-
1
def partitioned_routes
-
66
routes.partitioned_routes
-
end
-
-
1
def ast
-
66
routes.ast
-
end
-
-
1
def simulator
-
66
routes.simulator
-
end
-
-
1
def custom_routes
-
66
partitioned_routes.last
-
end
-
-
1
def filter_routes(path)
-
66
return [] unless ast
-
66
simulator.memos(path) { [] }
-
end
-
-
1
def find_routes req
-
66
routes = filter_routes(req.path_info).concat custom_routes.find_all { |r|
-
66
r.path.match(req.path_info)
-
}
-
-
66
routes =
-
if req.request_method == "HEAD"
-
match_head_routes(routes, req)
-
else
-
66
match_routes(routes, req)
-
end
-
-
66
routes.sort_by!(&:precedence)
-
-
66
routes.map! { |r|
-
70
match_data = r.path.match(req.path_info)
-
70
path_parameters = r.defaults.dup
-
70
match_data.names.zip(match_data.captures) { |name,val|
-
96
path_parameters[name.to_sym] = Utils.unescape_uri(val) if val
-
}
-
70
[match_data, path_parameters, r]
-
}
-
end
-
-
1
def match_head_routes(routes, req)
-
verb_specific_routes = routes.reject { |route| route.verb == // }
-
head_routes = match_routes(verb_specific_routes, req)
-
-
if head_routes.empty?
-
begin
-
req.request_method = "GET"
-
match_routes(routes, req)
-
ensure
-
req.request_method = "HEAD"
-
end
-
else
-
head_routes
-
end
-
end
-
-
1
def match_routes(routes, req)
-
229
routes.select { |r| r.matches?(req) }
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Router # :nodoc:
-
1
class Strexp # :nodoc:
-
1
class << self
-
1
alias :compile :new
-
end
-
-
1
attr_reader :path, :requirements, :separators, :anchor, :ast
-
-
1
def self.build(path, requirements, separators, anchor = true)
-
parser = Journey::Parser.new
-
ast = parser.parse path
-
new ast, path, requirements, separators, anchor
-
end
-
-
1
def initialize(ast, path, requirements, separators, anchor = true)
-
35
@ast = ast
-
35
@path = path
-
35
@requirements = requirements
-
35
@separators = separators
-
35
@anchor = anchor
-
end
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Router # :nodoc:
-
1
class Utils # :nodoc:
-
# Normalizes URI path.
-
#
-
# Strips off trailing slash and ensures there is a leading slash.
-
# Also converts downcase url encoded string to uppercase.
-
#
-
# normalize_path("/foo") # => "/foo"
-
# normalize_path("/foo/") # => "/foo"
-
# normalize_path("foo") # => "/foo"
-
# normalize_path("") # => "/"
-
# normalize_path("/%ab") # => "/%AB"
-
1
def self.normalize_path(path)
-
132
path = "/#{path}"
-
132
path.squeeze!('/')
-
132
path.sub!(%r{/+\Z}, '')
-
132
path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase }
-
132
path = '/' if path == ''
-
132
path
-
end
-
-
# URI path and fragment escaping
-
# http://tools.ietf.org/html/rfc3986
-
1
class UriEncoder # :nodoc:
-
1
ENCODE = "%%%02X".freeze
-
1
US_ASCII = Encoding::US_ASCII
-
1
UTF_8 = Encoding::UTF_8
-
1
EMPTY = "".force_encoding(US_ASCII).freeze
-
513
DEC2HEX = (0..255).to_a.map{ |i| ENCODE % i }.map{ |s| s.force_encoding(US_ASCII) }
-
-
1
ALPHA = "a-zA-Z".freeze
-
1
DIGIT = "0-9".freeze
-
1
UNRESERVED = "#{ALPHA}#{DIGIT}\\-\\._~".freeze
-
1
SUB_DELIMS = "!\\$&'\\(\\)\\*\\+,;=".freeze
-
-
1
ESCAPED = /%[a-zA-Z0-9]{2}/.freeze
-
-
1
FRAGMENT = /[^#{UNRESERVED}#{SUB_DELIMS}:@\/\?]/.freeze
-
1
SEGMENT = /[^#{UNRESERVED}#{SUB_DELIMS}:@]/.freeze
-
1
PATH = /[^#{UNRESERVED}#{SUB_DELIMS}:@\/]/.freeze
-
-
1
def escape_fragment(fragment)
-
escape(fragment, FRAGMENT)
-
end
-
-
1
def escape_path(path)
-
escape(path, PATH)
-
end
-
-
1
def escape_segment(segment)
-
79
escape(segment, SEGMENT)
-
end
-
-
1
def unescape_uri(uri)
-
26
encoding = uri.encoding == US_ASCII ? UTF_8 : uri.encoding
-
26
uri.gsub(ESCAPED) { [$&[1, 2].hex].pack('C') }.force_encoding(encoding)
-
end
-
-
1
protected
-
1
def escape(component, pattern)
-
79
component.gsub(pattern){ |unsafe| percent_encode(unsafe) }.force_encoding(US_ASCII)
-
end
-
-
1
def percent_encode(unsafe)
-
safe = EMPTY.dup
-
unsafe.each_byte { |b| safe << DEC2HEX[b] }
-
safe
-
end
-
end
-
-
1
ENCODER = UriEncoder.new
-
-
1
def self.escape_path(path)
-
ENCODER.escape_path(path.to_s)
-
end
-
-
1
def self.escape_segment(segment)
-
79
ENCODER.escape_segment(segment.to_s)
-
end
-
-
1
def self.escape_fragment(fragment)
-
ENCODER.escape_fragment(fragment.to_s)
-
end
-
-
1
def self.unescape_uri(uri)
-
26
ENCODER.unescape_uri(uri)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
# The Routing table. Contains all routes for a system. Routes can be
-
# added to the table by calling Routes#add_route.
-
1
class Routes # :nodoc:
-
1
include Enumerable
-
-
1
attr_reader :routes, :named_routes
-
-
1
def initialize
-
1
@routes = []
-
1
@named_routes = {}
-
1
@ast = nil
-
1
@partitioned_routes = nil
-
1
@simulator = nil
-
end
-
-
1
def empty?
-
routes.empty?
-
end
-
-
1
def length
-
routes.length
-
end
-
1
alias :size :length
-
-
1
def last
-
routes.last
-
end
-
-
1
def each(&block)
-
1
routes.each(&block)
-
end
-
-
1
def clear
-
1
routes.clear
-
1
named_routes.clear
-
end
-
-
1
def partitioned_routes
-
@partitioned_routes ||= routes.partition do |r|
-
35
r.path.anchored && r.ast.grep(Nodes::Symbol).all?(&:default_regexp?)
-
67
end
-
end
-
-
1
def ast
-
@ast ||= begin
-
1
asts = partitioned_routes.first.map(&:ast)
-
1
Nodes::Or.new(asts) unless asts.empty?
-
67
end
-
end
-
-
1
def simulator
-
@simulator ||= begin
-
1
gtg = GTG::Builder.new(ast).transition_table
-
1
GTG::Simulator.new(gtg)
-
66
end
-
end
-
-
# Add a route to the routing table.
-
1
def add_route(app, path, conditions, defaults, name = nil)
-
35
route = Route.new(name, app, path, conditions, defaults)
-
-
35
route.precedence = routes.length
-
35
routes << route
-
35
named_routes[name] = route if name && !named_routes[name]
-
35
clear_cache!
-
35
route
-
end
-
-
1
private
-
-
1
def clear_cache!
-
35
@ast = nil
-
35
@partitioned_routes = nil
-
35
@simulator = nil
-
end
-
end
-
end
-
end
-
1
require 'strscan'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Scanner # :nodoc:
-
1
def initialize
-
35
@ss = nil
-
end
-
-
1
def scan_setup(str)
-
35
@ss = StringScanner.new(str)
-
end
-
-
1
def eos?
-
@ss.eos?
-
end
-
-
1
def pos
-
@ss.pos
-
end
-
-
1
def pre_match
-
@ss.pre_match
-
end
-
-
1
def next_token
-
294
return if @ss.eos?
-
-
259
until token = scan || @ss.eos?; end
-
259
token
-
end
-
-
1
private
-
-
1
def scan
-
case
-
# /
-
when text = @ss.scan(/\//)
-
64
[:SLASH, text]
-
when text = @ss.scan(/\*\w+/)
-
[:STAR, text]
-
when text = @ss.scan(/(?<!\\)\(/)
-
33
[:LPAREN, text]
-
when text = @ss.scan(/(?<!\\)\)/)
-
33
[:RPAREN, text]
-
when text = @ss.scan(/\|/)
-
[:OR, text]
-
when text = @ss.scan(/\./)
-
33
[:DOT, text]
-
when text = @ss.scan(/(?<!\\):\w+/)
-
53
[:SYMBOL, text]
-
when text = @ss.scan(/(?:[\w%\-~!$&'*+,;=@]|\\:|\\\(|\\\))+/)
-
43
[:LITERAL, text.tr('\\', '')]
-
# any char
-
when text = @ss.scan(/./)
-
[:LITERAL, text]
-
259
end
-
end
-
end
-
end
-
end
-
-
1
module ActionDispatch
-
# Provides callbacks to be executed before and after dispatching the request.
-
1
class Callbacks
-
1
include ActiveSupport::Callbacks
-
-
1
define_callbacks :call
-
-
1
class << self
-
1
delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader"
-
-
1
def before(*args, &block)
-
set_callback(:call, :before, *args, &block)
-
end
-
-
1
def after(*args, &block)
-
set_callback(:call, :after, *args, &block)
-
end
-
end
-
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
66
error = nil
-
66
result = run_callbacks :call do
-
66
begin
-
66
@app.call(env)
-
rescue => error
-
end
-
end
-
66
raise error if error
-
66
result
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/key_generator'
-
1
require 'active_support/message_verifier'
-
1
require 'active_support/json'
-
-
1
module ActionDispatch
-
1
class Request < Rack::Request
-
1
def cookie_jar
-
77
env['action_dispatch.cookies'] ||= Cookies::CookieJar.build(self)
-
end
-
end
-
-
# \Cookies are read and written through ActionController#cookies.
-
#
-
# The cookies being read are the ones received along with the request, the cookies
-
# being written will be sent out with the response. Reading a cookie does not get
-
# the cookie object itself back, just the value it holds.
-
#
-
# Examples of writing:
-
#
-
# # Sets a simple session cookie.
-
# # This cookie will be deleted when the user's browser is closed.
-
# cookies[:user_name] = "david"
-
#
-
# # Cookie values are String based. Other data types need to be serialized.
-
# cookies[:lat_lon] = JSON.generate([47.68, -122.37])
-
#
-
# # Sets a cookie that expires in 1 hour.
-
# cookies[:login] = { value: "XJ-122", expires: 1.hour.from_now }
-
#
-
# # Sets a signed cookie, which prevents users from tampering with its value.
-
# # The cookie is signed by your app's `secrets.secret_key_base` value.
-
# # It can be read using the signed method `cookies.signed[:name]`
-
# cookies.signed[:user_id] = current_user.id
-
#
-
# # Sets a "permanent" cookie (which expires in 20 years from now).
-
# cookies.permanent[:login] = "XJ-122"
-
#
-
# # You can also chain these methods:
-
# cookies.permanent.signed[:login] = "XJ-122"
-
#
-
# Examples of reading:
-
#
-
# cookies[:user_name] # => "david"
-
# cookies.size # => 2
-
# JSON.parse(cookies[:lat_lon]) # => [47.68, -122.37]
-
# cookies.signed[:login] # => "XJ-122"
-
#
-
# Example for deleting:
-
#
-
# cookies.delete :user_name
-
#
-
# Please note that if you specify a :domain when setting a cookie, you must also specify the domain when deleting the cookie:
-
#
-
# cookies[:name] = {
-
# value: 'a yummy cookie',
-
# expires: 1.year.from_now,
-
# domain: 'domain.com'
-
# }
-
#
-
# cookies.delete(:name, domain: 'domain.com')
-
#
-
# The option symbols for setting cookies are:
-
#
-
# * <tt>:value</tt> - The cookie's value.
-
# * <tt>:path</tt> - The path for which this cookie applies. Defaults to the root
-
# of the application.
-
# * <tt>:domain</tt> - The domain for which this cookie applies so you can
-
# restrict to the domain level. If you use a schema like www.example.com
-
# and want to share session with user.example.com set <tt>:domain</tt>
-
# to <tt>:all</tt>. Make sure to specify the <tt>:domain</tt> option with
-
# <tt>:all</tt> or <tt>Array</tt> again when deleting cookies.
-
#
-
# domain: nil # Does not sets cookie domain. (default)
-
# domain: :all # Allow the cookie for the top most level
-
# # domain and subdomains.
-
# domain: %w(.example.com .example.org) # Allow the cookie
-
# # for concrete domain names.
-
#
-
# * <tt>:expires</tt> - The time at which this cookie expires, as a \Time object.
-
# * <tt>:secure</tt> - Whether this cookie is only transmitted to HTTPS servers.
-
# Default is +false+.
-
# * <tt>:httponly</tt> - Whether this cookie is accessible via scripting or
-
# only HTTP. Defaults to +false+.
-
1
class Cookies
-
1
HTTP_HEADER = "Set-Cookie".freeze
-
1
GENERATOR_KEY = "action_dispatch.key_generator".freeze
-
1
SIGNED_COOKIE_SALT = "action_dispatch.signed_cookie_salt".freeze
-
1
ENCRYPTED_COOKIE_SALT = "action_dispatch.encrypted_cookie_salt".freeze
-
1
ENCRYPTED_SIGNED_COOKIE_SALT = "action_dispatch.encrypted_signed_cookie_salt".freeze
-
1
SECRET_TOKEN = "action_dispatch.secret_token".freeze
-
1
SECRET_KEY_BASE = "action_dispatch.secret_key_base".freeze
-
1
COOKIES_SERIALIZER = "action_dispatch.cookies_serializer".freeze
-
1
COOKIES_DIGEST = "action_dispatch.cookies_digest".freeze
-
-
# Cookies can typically store 4096 bytes.
-
1
MAX_COOKIE_SIZE = 4096
-
-
# Raised when storing more than 4K of session data.
-
1
CookieOverflow = Class.new StandardError
-
-
# Include in a cookie jar to allow chaining, e.g. cookies.permanent.signed
-
1
module ChainedCookieJars
-
# Returns a jar that'll automatically set the assigned cookies to have an expiration date 20 years from now. Example:
-
#
-
# cookies.permanent[:prefers_open_id] = true
-
# # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
#
-
# This jar is only meant for writing. You'll read permanent cookies through the regular accessor.
-
#
-
# This jar allows chaining with the signed jar as well, so you can set permanent, signed cookies. Examples:
-
#
-
# cookies.permanent.signed[:remember_me] = current_user.id
-
# # => Set-Cookie: remember_me=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
1
def permanent
-
@permanent ||= PermanentCookieJar.new(self, @key_generator, @options)
-
end
-
-
# Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from
-
# the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed
-
# cookie was tampered with by the user (or a 3rd party), nil will be returned.
-
#
-
# If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set,
-
# legacy cookies signed with the old key generator will be transparently upgraded.
-
#
-
# This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+.
-
#
-
# Example:
-
#
-
# cookies.signed[:discount] = 45
-
# # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
-
#
-
# cookies.signed[:discount] # => 45
-
1
def signed
-
@signed ||=
-
if @options[:upgrade_legacy_signed_cookies]
-
UpgradeLegacySignedCookieJar.new(self, @key_generator, @options)
-
else
-
SignedCookieJar.new(self, @key_generator, @options)
-
end
-
end
-
-
# Returns a jar that'll automatically encrypt cookie values before sending them to the client and will decrypt them for read.
-
# If the cookie was tampered with by the user (or a 3rd party), nil will be returned.
-
#
-
# If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set,
-
# legacy cookies signed with the old key generator will be transparently upgraded.
-
#
-
# This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+.
-
#
-
# Example:
-
#
-
# cookies.encrypted[:discount] = 45
-
# # => Set-Cookie: discount=ZS9ZZ1R4cG1pcUJ1bm80anhQang3dz09LS1mbDZDSU5scGdOT3ltQ2dTdlhSdWpRPT0%3D--ab54663c9f4e3bc340c790d6d2b71e92f5b60315; path=/
-
#
-
# cookies.encrypted[:discount] # => 45
-
1
def encrypted
-
@encrypted ||=
-
if @options[:upgrade_legacy_signed_cookies]
-
UpgradeLegacyEncryptedCookieJar.new(self, @key_generator, @options)
-
else
-
66
EncryptedCookieJar.new(self, @key_generator, @options)
-
66
end
-
end
-
-
# Returns the +signed+ or +encrypted+ jar, preferring +encrypted+ if +secret_key_base+ is set.
-
# Used by ActionDispatch::Session::CookieStore to avoid the need to introduce new cookie stores.
-
1
def signed_or_encrypted
-
@signed_or_encrypted ||=
-
if @options[:secret_key_base].present?
-
66
encrypted
-
else
-
signed
-
77
end
-
end
-
end
-
-
# Passing the ActiveSupport::MessageEncryptor::NullSerializer downstream
-
# to the Message{Encryptor,Verifier} allows us to handle the
-
# (de)serialization step within the cookie jar, which gives us the
-
# opportunity to detect and migrate legacy cookies.
-
1
module VerifyAndUpgradeLegacySignedMessage # :nodoc:
-
1
def initialize(*args)
-
super
-
@legacy_verifier = ActiveSupport::MessageVerifier.new(@options[:secret_token], serializer: ActiveSupport::MessageEncryptor::NullSerializer)
-
end
-
-
1
def verify_and_upgrade_legacy_signed_message(name, signed_message)
-
deserialize(name, @legacy_verifier.verify(signed_message)).tap do |value|
-
self[name] = { value: value }
-
end
-
rescue ActiveSupport::MessageVerifier::InvalidSignature
-
nil
-
end
-
end
-
-
1
class CookieJar #:nodoc:
-
1
include Enumerable, ChainedCookieJars
-
-
# This regular expression is used to split the levels of a domain.
-
# The top level domain can be any string without a period or
-
# **.**, ***.** style TLDs like co.uk or com.au
-
#
-
# www.example.co.uk gives:
-
# $& => example.co.uk
-
#
-
# example.com gives:
-
# $& => example.com
-
#
-
# lots.of.subdomains.example.local gives:
-
# $& => example.local
-
1
DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/
-
-
1
def self.options_for_env(env) #:nodoc:
-
{ signed_cookie_salt: env[SIGNED_COOKIE_SALT] || '',
-
encrypted_cookie_salt: env[ENCRYPTED_COOKIE_SALT] || '',
-
encrypted_signed_cookie_salt: env[ENCRYPTED_SIGNED_COOKIE_SALT] || '',
-
secret_token: env[SECRET_TOKEN],
-
secret_key_base: env[SECRET_KEY_BASE],
-
upgrade_legacy_signed_cookies: env[SECRET_TOKEN].present? && env[SECRET_KEY_BASE].present?,
-
serializer: env[COOKIES_SERIALIZER],
-
digest: env[COOKIES_DIGEST]
-
66
}
-
end
-
-
1
def self.build(request)
-
66
env = request.env
-
66
key_generator = env[GENERATOR_KEY]
-
66
options = options_for_env env
-
-
66
host = request.host
-
66
secure = request.ssl?
-
-
66
new(key_generator, host, secure, options).tap do |hash|
-
66
hash.update(request.cookies)
-
end
-
end
-
-
1
def initialize(key_generator, host = nil, secure = false, options = {})
-
66
@key_generator = key_generator
-
66
@set_cookies = {}
-
66
@delete_cookies = {}
-
66
@host = host
-
66
@secure = secure
-
66
@options = options
-
66
@cookies = {}
-
66
@committed = false
-
end
-
-
67
def committed?; @committed; end
-
-
1
def commit!
-
@committed = true
-
@set_cookies.freeze
-
@delete_cookies.freeze
-
end
-
-
1
def each(&block)
-
@cookies.each(&block)
-
end
-
-
# Returns the value of the cookie by +name+, or +nil+ if no such cookie exists.
-
1
def [](name)
-
66
@cookies[name.to_s]
-
end
-
-
1
def fetch(name, *args, &block)
-
@cookies.fetch(name.to_s, *args, &block)
-
end
-
-
1
def key?(name)
-
@cookies.key?(name.to_s)
-
end
-
1
alias :has_key? :key?
-
-
1
def update(other_hash)
-
66
@cookies.update other_hash.stringify_keys
-
66
self
-
end
-
-
1
def handle_options(options) #:nodoc:
-
11
options[:path] ||= "/"
-
-
11
if options[:domain] == :all
-
# if there is a provided tld length then we use it otherwise default domain regexp
-
domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP
-
-
# if host is not ip and matches domain regexp
-
# (ip confirms to domain regexp so we explicitly check for ip)
-
options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
-
".#{$&}"
-
end
-
11
elsif options[:domain].is_a? Array
-
# if host matches one of the supplied domains without a dot in front of it
-
options[:domain] = options[:domain].find {|domain| @host.include? domain.sub(/^\./, '') }
-
end
-
end
-
-
# Sets the cookie named +name+. The second argument may be the cookie's
-
# value or a hash of options as documented above.
-
1
def []=(name, options)
-
11
if options.is_a?(Hash)
-
11
options.symbolize_keys!
-
11
value = options[:value]
-
else
-
value = options
-
options = { :value => value }
-
end
-
-
11
handle_options(options)
-
-
11
if @cookies[name.to_s] != value or options[:expires]
-
11
@cookies[name.to_s] = value
-
11
@set_cookies[name.to_s] = options
-
11
@delete_cookies.delete(name.to_s)
-
end
-
-
11
value
-
end
-
-
# Removes the cookie on the client machine by setting the value to an empty string
-
# and the expiration date in the past. Like <tt>[]=</tt>, you can pass in
-
# an options hash to delete cookies with extra data such as a <tt>:path</tt>.
-
1
def delete(name, options = {})
-
return unless @cookies.has_key? name.to_s
-
-
options.symbolize_keys!
-
handle_options(options)
-
-
value = @cookies.delete(name.to_s)
-
@delete_cookies[name.to_s] = options
-
value
-
end
-
-
# Whether the given cookie is to be deleted by this CookieJar.
-
# Like <tt>[]=</tt>, you can pass in an options hash to test if a
-
# deletion applies to a specific <tt>:path</tt>, <tt>:domain</tt> etc.
-
1
def deleted?(name, options = {})
-
options.symbolize_keys!
-
handle_options(options)
-
@delete_cookies[name.to_s] == options
-
end
-
-
# Removes all cookies on the client machine by calling <tt>delete</tt> for each cookie
-
1
def clear(options = {})
-
@cookies.each_key{ |k| delete(k, options) }
-
end
-
-
1
def write(headers)
-
77
@set_cookies.each { |k, v| ::Rack::Utils.set_cookie_header!(headers, k, v) if write_cookie?(v) }
-
66
@delete_cookies.each { |k, v| ::Rack::Utils.delete_cookie_header!(headers, k, v) }
-
end
-
-
1
def recycle! #:nodoc:
-
@set_cookies = {}
-
@delete_cookies = {}
-
end
-
-
1
mattr_accessor :always_write_cookie
-
1
self.always_write_cookie = false
-
-
1
private
-
1
def write_cookie?(cookie)
-
11
@secure || !cookie[:secure] || always_write_cookie
-
end
-
end
-
-
1
class PermanentCookieJar #:nodoc:
-
1
include ChainedCookieJars
-
-
1
def initialize(parent_jar, key_generator, options = {})
-
@parent_jar = parent_jar
-
@key_generator = key_generator
-
@options = options
-
end
-
-
1
def [](name)
-
@parent_jar[name.to_s]
-
end
-
-
1
def []=(name, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
else
-
options = { :value => options }
-
end
-
-
options[:expires] = 20.years.from_now
-
@parent_jar[name] = options
-
end
-
end
-
-
1
class JsonSerializer # :nodoc:
-
1
def self.load(value)
-
6
ActiveSupport::JSON.decode(value)
-
end
-
-
1
def self.dump(value)
-
11
ActiveSupport::JSON.encode(value)
-
end
-
end
-
-
1
module SerializedCookieJars # :nodoc:
-
1
MARSHAL_SIGNATURE = "\x04\x08".freeze
-
-
1
protected
-
1
def needs_migration?(value)
-
6
@options[:serializer] == :hybrid && value.start_with?(MARSHAL_SIGNATURE)
-
end
-
-
1
def serialize(name, value)
-
11
serializer.dump(value)
-
end
-
-
1
def deserialize(name, value)
-
6
if value
-
6
if needs_migration?(value)
-
Marshal.load(value).tap do |v|
-
self[name] = { value: v }
-
end
-
else
-
6
serializer.load(value)
-
end
-
end
-
end
-
-
1
def serializer
-
17
serializer = @options[:serializer] || :marshal
-
17
case serializer
-
when :marshal
-
Marshal
-
when :json, :hybrid
-
17
JsonSerializer
-
else
-
serializer
-
end
-
end
-
-
1
def digest
-
66
@options[:digest] || 'SHA1'
-
end
-
end
-
-
1
class SignedCookieJar #:nodoc:
-
1
include ChainedCookieJars
-
1
include SerializedCookieJars
-
-
1
def initialize(parent_jar, key_generator, options = {})
-
@parent_jar = parent_jar
-
@options = options
-
secret = key_generator.generate_key(@options[:signed_cookie_salt])
-
@verifier = ActiveSupport::MessageVerifier.new(secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
-
end
-
-
1
def [](name)
-
if signed_message = @parent_jar[name]
-
deserialize name, verify(signed_message)
-
end
-
end
-
-
1
def []=(name, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
options[:value] = @verifier.generate(serialize(name, options[:value]))
-
else
-
options = { :value => @verifier.generate(serialize(name, options)) }
-
end
-
-
raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE
-
@parent_jar[name] = options
-
end
-
-
1
private
-
1
def verify(signed_message)
-
@verifier.verify(signed_message)
-
rescue ActiveSupport::MessageVerifier::InvalidSignature
-
nil
-
end
-
end
-
-
# UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if
-
# secrets.secret_token and secrets.secret_key_base are both set. It reads
-
# legacy cookies signed with the old dummy key generator and re-saves
-
# them using the new key generator to provide a smooth upgrade path.
-
1
class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc:
-
1
include VerifyAndUpgradeLegacySignedMessage
-
-
1
def [](name)
-
if signed_message = @parent_jar[name]
-
deserialize(name, verify(signed_message)) || verify_and_upgrade_legacy_signed_message(name, signed_message)
-
end
-
end
-
end
-
-
1
class EncryptedCookieJar #:nodoc:
-
1
include ChainedCookieJars
-
1
include SerializedCookieJars
-
-
1
def initialize(parent_jar, key_generator, options = {})
-
66
if ActiveSupport::LegacyKeyGenerator === key_generator
-
raise "You didn't set secrets.secret_key_base, which is required for this cookie jar. " +
-
"Read the upgrade documentation to learn more about this new config option."
-
end
-
-
66
@parent_jar = parent_jar
-
66
@options = options
-
66
secret = key_generator.generate_key(@options[:encrypted_cookie_salt])
-
66
sign_secret = key_generator.generate_key(@options[:encrypted_signed_cookie_salt])
-
66
@encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
-
end
-
-
1
def [](name)
-
66
if encrypted_message = @parent_jar[name]
-
6
deserialize name, decrypt_and_verify(encrypted_message)
-
end
-
end
-
-
1
def []=(name, options)
-
11
if options.is_a?(Hash)
-
11
options.symbolize_keys!
-
else
-
options = { :value => options }
-
end
-
-
11
options[:value] = @encryptor.encrypt_and_sign(serialize(name, options[:value]))
-
-
11
raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE
-
11
@parent_jar[name] = options
-
end
-
-
1
private
-
1
def decrypt_and_verify(encrypted_message)
-
6
@encryptor.decrypt_and_verify(encrypted_message)
-
rescue ActiveSupport::MessageVerifier::InvalidSignature, ActiveSupport::MessageEncryptor::InvalidMessage
-
nil
-
end
-
end
-
-
# UpgradeLegacyEncryptedCookieJar is used by ActionDispatch::Session::CookieStore
-
# instead of EncryptedCookieJar if secrets.secret_token and secrets.secret_key_base
-
# are both set. It reads legacy cookies signed with the old dummy key generator and
-
# encrypts and re-saves them using the new key generator to provide a smooth upgrade path.
-
1
class UpgradeLegacyEncryptedCookieJar < EncryptedCookieJar #:nodoc:
-
1
include VerifyAndUpgradeLegacySignedMessage
-
-
1
def [](name)
-
if encrypted_or_signed_message = @parent_jar[name]
-
deserialize(name, decrypt_and_verify(encrypted_or_signed_message)) || verify_and_upgrade_legacy_signed_message(name, encrypted_or_signed_message)
-
end
-
end
-
end
-
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
66
status, headers, body = @app.call(env)
-
-
66
if cookie_jar = env['action_dispatch.cookies']
-
66
unless cookie_jar.committed?
-
66
cookie_jar.write(headers)
-
66
if headers[HTTP_HEADER].respond_to?(:join)
-
headers[HTTP_HEADER] = headers[HTTP_HEADER].join("\n")
-
end
-
end
-
end
-
-
66
[status, headers, body]
-
end
-
end
-
end
-
1
require 'action_dispatch/http/request'
-
1
require 'action_dispatch/middleware/exception_wrapper'
-
1
require 'action_dispatch/routing/inspector'
-
-
1
module ActionDispatch
-
# This middleware is responsible for logging exceptions and
-
# showing a debugging page in case the request is local.
-
1
class DebugExceptions
-
1
RESCUES_TEMPLATE_PATH = File.expand_path('../templates', __FILE__)
-
-
1
def initialize(app, routes_app = nil)
-
1
@app = app
-
1
@routes_app = routes_app
-
end
-
-
1
def call(env)
-
66
_, headers, body = response = @app.call(env)
-
-
66
if headers['X-Cascade'] == 'pass'
-
body.close if body.respond_to?(:close)
-
raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
-
end
-
-
66
response
-
rescue Exception => exception
-
raise exception if env['action_dispatch.show_exceptions'] == false
-
render_exception(env, exception)
-
end
-
-
1
private
-
-
1
def render_exception(env, exception)
-
wrapper = ExceptionWrapper.new(env, exception)
-
log_error(env, wrapper)
-
-
if env['action_dispatch.show_detailed_exceptions']
-
request = Request.new(env)
-
traces = wrapper.traces
-
-
trace_to_show = 'Application Trace'
-
if traces[trace_to_show].empty? && wrapper.rescue_template != 'routing_error'
-
trace_to_show = 'Full Trace'
-
end
-
-
if source_to_show = traces[trace_to_show].first
-
source_to_show_id = source_to_show[:id]
-
end
-
-
template = ActionView::Base.new([RESCUES_TEMPLATE_PATH],
-
request: request,
-
exception: wrapper.exception,
-
traces: traces,
-
show_source_idx: source_to_show_id,
-
trace_to_show: trace_to_show,
-
routes_inspector: routes_inspector(exception),
-
source_extracts: wrapper.source_extracts,
-
line_number: wrapper.line_number,
-
file: wrapper.file
-
)
-
file = "rescues/#{wrapper.rescue_template}"
-
-
if request.xhr?
-
body = template.render(template: file, layout: false, formats: [:text])
-
format = "text/plain"
-
else
-
body = template.render(template: file, layout: 'rescues/layout')
-
format = "text/html"
-
end
-
render(wrapper.status_code, body, format)
-
else
-
raise exception
-
end
-
end
-
-
1
def render(status, body, format)
-
[status, {'Content-Type' => "#{format}; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
-
end
-
-
1
def log_error(env, wrapper)
-
logger = logger(env)
-
return unless logger
-
-
exception = wrapper.exception
-
-
trace = wrapper.application_trace
-
trace = wrapper.framework_trace if trace.empty?
-
-
ActiveSupport::Deprecation.silence do
-
message = "\n#{exception.class} (#{exception.message}):\n"
-
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
-
message << " " << trace.join("\n ")
-
logger.fatal("#{message}\n\n")
-
end
-
end
-
-
1
def logger(env)
-
env['action_dispatch.logger'] || stderr_logger
-
end
-
-
1
def stderr_logger
-
@stderr_logger ||= ActiveSupport::Logger.new($stderr)
-
end
-
-
1
def routes_inspector(exception)
-
if @routes_app.respond_to?(:routes) && (exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error))
-
ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes)
-
end
-
end
-
end
-
end
-
1
require 'action_controller/metal/exceptions'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
module ActionDispatch
-
1
class ExceptionWrapper
-
1
cattr_accessor :rescue_responses
-
1
@@rescue_responses = Hash.new(:internal_server_error)
-
1
@@rescue_responses.merge!(
-
'ActionController::RoutingError' => :not_found,
-
'AbstractController::ActionNotFound' => :not_found,
-
'ActionController::MethodNotAllowed' => :method_not_allowed,
-
'ActionController::UnknownHttpMethod' => :method_not_allowed,
-
'ActionController::NotImplemented' => :not_implemented,
-
'ActionController::UnknownFormat' => :not_acceptable,
-
'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
-
'ActionController::InvalidCrossOriginRequest' => :unprocessable_entity,
-
'ActionDispatch::ParamsParser::ParseError' => :bad_request,
-
'ActionController::BadRequest' => :bad_request,
-
'ActionController::ParameterMissing' => :bad_request
-
)
-
-
1
cattr_accessor :rescue_templates
-
1
@@rescue_templates = Hash.new('diagnostics')
-
1
@@rescue_templates.merge!(
-
'ActionView::MissingTemplate' => 'missing_template',
-
'ActionController::RoutingError' => 'routing_error',
-
'AbstractController::ActionNotFound' => 'unknown_action',
-
'ActionView::Template::Error' => 'template_error'
-
)
-
-
1
attr_reader :env, :exception, :line_number, :file
-
-
1
def initialize(env, exception)
-
@env = env
-
@exception = original_exception(exception)
-
-
expand_backtrace if exception.is_a?(SyntaxError) || exception.try(:original_exception).try(:is_a?, SyntaxError)
-
end
-
-
1
def rescue_template
-
@@rescue_templates[@exception.class.name]
-
end
-
-
1
def status_code
-
self.class.status_code_for_exception(@exception.class.name)
-
end
-
-
1
def application_trace
-
clean_backtrace(:silent)
-
end
-
-
1
def framework_trace
-
clean_backtrace(:noise)
-
end
-
-
1
def full_trace
-
clean_backtrace(:all)
-
end
-
-
1
def traces
-
appplication_trace_with_ids = []
-
framework_trace_with_ids = []
-
full_trace_with_ids = []
-
-
full_trace.each_with_index do |trace, idx|
-
trace_with_id = { id: idx, trace: trace }
-
-
if application_trace.include?(trace)
-
appplication_trace_with_ids << trace_with_id
-
else
-
framework_trace_with_ids << trace_with_id
-
end
-
-
full_trace_with_ids << trace_with_id
-
end
-
-
{
-
"Application Trace" => appplication_trace_with_ids,
-
"Framework Trace" => framework_trace_with_ids,
-
"Full Trace" => full_trace_with_ids
-
}
-
end
-
-
1
def self.status_code_for_exception(class_name)
-
Rack::Utils.status_code(@@rescue_responses[class_name])
-
end
-
-
1
def source_extracts
-
backtrace.map do |trace|
-
file, line = trace.split(":")
-
line_number = line.to_i
-
-
{
-
code: source_fragment(file, line_number),
-
line_number: line_number
-
}
-
end
-
end
-
-
1
private
-
-
1
def backtrace
-
Array(@exception.backtrace)
-
end
-
-
1
def original_exception(exception)
-
if registered_original_exception?(exception)
-
exception.original_exception
-
else
-
exception
-
end
-
end
-
-
1
def registered_original_exception?(exception)
-
exception.respond_to?(:original_exception) && @@rescue_responses.has_key?(exception.original_exception.class.name)
-
end
-
-
1
def clean_backtrace(*args)
-
if backtrace_cleaner
-
backtrace_cleaner.clean(backtrace, *args)
-
else
-
backtrace
-
end
-
end
-
-
1
def backtrace_cleaner
-
@backtrace_cleaner ||= @env['action_dispatch.backtrace_cleaner']
-
end
-
-
1
def source_fragment(path, line)
-
return unless Rails.respond_to?(:root) && Rails.root
-
full_path = Rails.root.join(path)
-
if File.exist?(full_path)
-
File.open(full_path, "r") do |file|
-
start = [line - 3, 0].max
-
lines = file.each_line.drop(start).take(6)
-
Hash[*(start+1..(lines.count+start)).zip(lines).flatten]
-
end
-
end
-
end
-
-
1
def expand_backtrace
-
@exception.backtrace.unshift(
-
@exception.to_s.split("\n")
-
).flatten!
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActionDispatch
-
1
class Request < Rack::Request
-
# Access the contents of the flash. Use <tt>flash["notice"]</tt> to
-
# read a notice you put there or <tt>flash["notice"] = "hello"</tt>
-
# to put a new one.
-
1
def flash
-
118
@env[Flash::KEY] ||= Flash::FlashHash.from_session_value(session["flash"])
-
end
-
end
-
-
# The flash provides a way to pass temporary primitive-types (String, Array, Hash) between actions. Anything you place in the flash will be exposed
-
# to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create
-
# action that sets <tt>flash[:notice] = "Post successfully created"</tt> before redirecting to a display action that can
-
# then expose the flash to its template. Actually, that exposure is automatically done.
-
#
-
# class PostsController < ActionController::Base
-
# def create
-
# # save post
-
# flash[:notice] = "Post successfully created"
-
# redirect_to @post
-
# end
-
#
-
# def show
-
# # doesn't need to assign the flash notice to the template, that's done automatically
-
# end
-
# end
-
#
-
# show.html.erb
-
# <% if flash[:notice] %>
-
# <div class="notice"><%= flash[:notice] %></div>
-
# <% end %>
-
#
-
# Since the +notice+ and +alert+ keys are a common idiom, convenience accessors are available:
-
#
-
# flash.alert = "You must be logged in"
-
# flash.notice = "Post successfully created"
-
#
-
# This example places a string in the flash. And of course, you can put as many as you like at a time too. If you want to pass
-
# non-primitive types, you will have to handle that in your application. Example: To show messages with links, you will have to
-
# use sanitize helper.
-
#
-
# Just remember: They'll be gone by the time the next action has been performed.
-
#
-
# See docs on the FlashHash class for more details about the flash.
-
1
class Flash
-
1
KEY = 'action_dispatch.request.flash_hash'.freeze
-
-
1
class FlashNow #:nodoc:
-
1
attr_accessor :flash
-
-
1
def initialize(flash)
-
@flash = flash
-
end
-
-
1
def []=(k, v)
-
k = k.to_s
-
@flash[k] = v
-
@flash.discard(k)
-
v
-
end
-
-
1
def [](k)
-
@flash[k.to_s]
-
end
-
-
# Convenience accessor for <tt>flash.now[:alert]=</tt>.
-
1
def alert=(message)
-
self[:alert] = message
-
end
-
-
# Convenience accessor for <tt>flash.now[:notice]=</tt>.
-
1
def notice=(message)
-
self[:notice] = message
-
end
-
end
-
-
1
class FlashHash
-
1
include Enumerable
-
-
1
def self.from_session_value(value) #:nodoc:
-
60
flash = case value
-
when FlashHash # Rails 3.1, 3.2
-
new(value.instance_variable_get(:@flashes), value.instance_variable_get(:@used))
-
when Hash # Rails 4.0
-
6
new(value['flashes'], value['discard'])
-
else
-
54
new
-
end
-
-
60
flash.tap(&:sweep)
-
end
-
-
# Builds a hash containing the discarded values and the hashes
-
# representing the flashes.
-
# If there are no values in @flashes, returns nil.
-
1
def to_session_value #:nodoc:
-
11
return nil if empty?
-
10
{'discard' => @discard.to_a, 'flashes' => @flashes}
-
end
-
-
1
def initialize(flashes = {}, discard = []) #:nodoc:
-
60
@discard = Set.new(stringify_array(discard))
-
60
@flashes = flashes.stringify_keys
-
60
@now = nil
-
end
-
-
1
def initialize_copy(other)
-
11
if other.now_is_loaded?
-
@now = other.now.dup
-
@now.flash = self
-
end
-
11
super
-
end
-
-
1
def []=(k, v)
-
5
k = k.to_s
-
5
@discard.delete k
-
5
@flashes[k] = v
-
end
-
-
1
def [](k)
-
113
@flashes[k.to_s]
-
end
-
-
1
def update(h) #:nodoc:
-
@discard.subtract stringify_array(h.keys)
-
@flashes.update h.stringify_keys
-
self
-
end
-
-
1
def keys
-
@flashes.keys
-
end
-
-
1
def key?(name)
-
@flashes.key? name.to_s
-
end
-
-
1
def delete(key)
-
key = key.to_s
-
@discard.delete key
-
@flashes.delete key
-
self
-
end
-
-
1
def to_hash
-
@flashes.dup
-
end
-
-
1
def empty?
-
71
@flashes.empty?
-
end
-
-
1
def clear
-
@discard.clear
-
@flashes.clear
-
end
-
-
1
def each(&block)
-
@flashes.each(&block)
-
end
-
-
1
alias :merge! :update
-
-
1
def replace(h) #:nodoc:
-
@discard.clear
-
@flashes.replace h.stringify_keys
-
self
-
end
-
-
# Sets a flash that will not be available to the next action, only to the current.
-
#
-
# flash.now[:message] = "Hello current action"
-
#
-
# This method enables you to use the flash as a central messaging system in your app.
-
# When you need to pass an object to the next action, you use the standard flash assign (<tt>[]=</tt>).
-
# When you need to pass an object to the current action, you use <tt>now</tt>, and your object will
-
# vanish when the current action is done.
-
#
-
# Entries set via <tt>now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
-
#
-
# Also, brings two convenience accessors:
-
#
-
# flash.now.alert = "Beware now!"
-
# # Equivalent to flash.now[:alert] = "Beware now!"
-
#
-
# flash.now.notice = "Good luck now!"
-
# # Equivalent to flash.now[:notice] = "Good luck now!"
-
1
def now
-
@now ||= FlashNow.new(self)
-
end
-
-
# Keeps either the entire current flash or a specific flash entry available for the next action:
-
#
-
# flash.keep # keeps the entire flash
-
# flash.keep(:notice) # keeps only the "notice" entry, the rest of the flash is discarded
-
1
def keep(k = nil)
-
k = k.to_s if k
-
@discard.subtract Array(k || keys)
-
k ? self[k] : self
-
end
-
-
# Marks the entire flash or a single flash entry to be discarded by the end of the current action:
-
#
-
# flash.discard # discard the entire flash at the end of the current action
-
# flash.discard(:warning) # discard only the "warning" entry at the end of the current action
-
1
def discard(k = nil)
-
k = k.to_s if k
-
@discard.merge Array(k || keys)
-
k ? self[k] : self
-
end
-
-
# Mark for removal entries that were kept, and delete unkept ones.
-
#
-
# This method is called automatically by filters, so you generally don't need to care about it.
-
1
def sweep #:nodoc:
-
61
@discard.each { |k| @flashes.delete k }
-
60
@discard.replace @flashes.keys
-
end
-
-
# Convenience accessor for <tt>flash[:alert]</tt>.
-
1
def alert
-
self[:alert]
-
end
-
-
# Convenience accessor for <tt>flash[:alert]=</tt>.
-
1
def alert=(message)
-
self[:alert] = message
-
end
-
-
# Convenience accessor for <tt>flash[:notice]</tt>.
-
1
def notice
-
self[:notice]
-
end
-
-
# Convenience accessor for <tt>flash[:notice]=</tt>.
-
1
def notice=(message)
-
self[:notice] = message
-
end
-
-
1
protected
-
1
def now_is_loaded?
-
11
@now
-
end
-
-
1
def stringify_array(array)
-
60
array.map do |item|
-
1
item.kind_of?(Symbol) ? item.to_s : item
-
end
-
end
-
end
-
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
66
@app.call(env)
-
ensure
-
66
session = Request::Session.find(env) || {}
-
66
flash_hash = env[KEY]
-
-
66
if flash_hash && (flash_hash.present? || session.key?('flash'))
-
11
session["flash"] = flash_hash.to_session_value
-
11
env[KEY] = flash_hash.dup
-
end
-
-
if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?)
-
66
session.key?('flash') && session['flash'].nil?
-
1
session.delete('flash')
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'action_dispatch/http/request'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActionDispatch
-
1
class ParamsParser
-
1
class ParseError < StandardError
-
1
attr_reader :original_exception
-
-
1
def initialize(message, original_exception)
-
super(message)
-
@original_exception = original_exception
-
end
-
end
-
-
1
DEFAULT_PARSERS = { Mime::JSON => :json }
-
-
1
def initialize(app, parsers = {})
-
1
@app, @parsers = app, DEFAULT_PARSERS.merge(parsers)
-
end
-
-
1
def call(env)
-
66
if params = parse_formatted_parameters(env)
-
env["action_dispatch.request.request_parameters"] = params
-
end
-
-
66
@app.call(env)
-
end
-
-
1
private
-
1
def parse_formatted_parameters(env)
-
66
request = Request.new(env)
-
-
66
return false if request.content_length.zero?
-
-
11
strategy = @parsers[request.content_mime_type]
-
-
11
return false unless strategy
-
-
case strategy
-
when Proc
-
strategy.call(request.raw_post)
-
when :json
-
data = ActiveSupport::JSON.decode(request.raw_post)
-
data = {:_json => data} unless data.is_a?(Hash)
-
Request::Utils.deep_munge(data).with_indifferent_access
-
else
-
false
-
end
-
rescue => e # JSON or Ruby code block errors
-
logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
-
-
raise ParseError.new(e.message, e)
-
end
-
-
1
def logger(env)
-
env['action_dispatch.logger'] || ActiveSupport::Logger.new($stderr)
-
end
-
end
-
end
-
1
module ActionDispatch
-
# When called, this middleware renders an error page. By default if an HTML
-
# response is expected it will render static error pages from the `/public`
-
# directory. For example when this middleware receives a 500 response it will
-
# render the template found in `/public/500.html`.
-
# If an internationalized locale is set, this middleware will attempt to render
-
# the template in `/public/500.<locale>.html`. If an internationalized template
-
# is not found it will fall back on `/public/500.html`.
-
#
-
# When a request with a content type other than HTML is made, this middleware
-
# will attempt to convert error information into the appropriate response type.
-
1
class PublicExceptions
-
1
attr_accessor :public_path
-
-
1
def initialize(public_path)
-
1
@public_path = public_path
-
end
-
-
1
def call(env)
-
status = env["PATH_INFO"][1..-1]
-
request = ActionDispatch::Request.new(env)
-
content_type = request.formats.first
-
body = { :status => status, :error => Rack::Utils::HTTP_STATUS_CODES.fetch(status.to_i, Rack::Utils::HTTP_STATUS_CODES[500]) }
-
-
render(status, content_type, body)
-
end
-
-
1
private
-
-
1
def render(status, content_type, body)
-
format = "to_#{content_type.to_sym}" if content_type
-
if format && body.respond_to?(format)
-
render_format(status, content_type, body.public_send(format))
-
else
-
render_html(status)
-
end
-
end
-
-
1
def render_format(status, content_type, body)
-
[status, {'Content-Type' => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
-
'Content-Length' => body.bytesize.to_s}, [body]]
-
end
-
-
1
def render_html(status)
-
path = "#{public_path}/#{status}.#{I18n.locale}.html"
-
path = "#{public_path}/#{status}.html" unless (found = File.exist?(path))
-
-
if found || File.exist?(path)
-
render_format(status, 'text/html', File.read(path))
-
else
-
[404, { "X-Cascade" => "pass" }, []]
-
end
-
end
-
end
-
end
-
1
require 'active_support/deprecation/reporting'
-
-
1
module ActionDispatch
-
# ActionDispatch::Reloader provides prepare and cleanup callbacks,
-
# intended to assist with code reloading during development.
-
#
-
# Prepare callbacks are run before each request, and cleanup callbacks
-
# after each request. In this respect they are analogs of ActionDispatch::Callback's
-
# before and after callbacks. However, cleanup callbacks are not called until the
-
# request is fully complete -- that is, after #close has been called on
-
# the response body. This is important for streaming responses such as the
-
# following:
-
#
-
# self.response_body = lambda { |response, output|
-
# # code here which refers to application models
-
# }
-
#
-
# Cleanup callbacks will not be called until after the response_body lambda
-
# is evaluated, ensuring that it can refer to application models and other
-
# classes before they are unloaded.
-
#
-
# By default, ActionDispatch::Reloader is included in the middleware stack
-
# only in the development environment; specifically, when +config.cache_classes+
-
# is false. Callbacks may be registered even when it is not included in the
-
# middleware stack, but are executed only when <tt>ActionDispatch::Reloader.prepare!</tt>
-
# or <tt>ActionDispatch::Reloader.cleanup!</tt> are called manually.
-
#
-
1
class Reloader
-
1
include ActiveSupport::Callbacks
-
1
include ActiveSupport::Deprecation::Reporting
-
-
1
define_callbacks :prepare
-
1
define_callbacks :cleanup
-
-
# Add a prepare callback. Prepare callbacks are run before each request, prior
-
# to ActionDispatch::Callback's before callbacks.
-
1
def self.to_prepare(*args, &block)
-
4
unless block_given?
-
warn "to_prepare without a block is deprecated. Please use a block"
-
end
-
4
set_callback(:prepare, *args, &block)
-
end
-
-
# Add a cleanup callback. Cleanup callbacks are run after each request is
-
# complete (after #close is called on the response body).
-
1
def self.to_cleanup(*args, &block)
-
unless block_given?
-
warn "to_cleanup without a block is deprecated. Please use a block"
-
end
-
set_callback(:cleanup, *args, &block)
-
end
-
-
# Execute all prepare callbacks.
-
1
def self.prepare!
-
1
new(nil).prepare!
-
end
-
-
# Execute all cleanup callbacks.
-
1
def self.cleanup!
-
new(nil).cleanup!
-
end
-
-
1
def initialize(app, condition=nil)
-
1
@app = app
-
1
@condition = condition || lambda { true }
-
1
@validated = true
-
end
-
-
1
def call(env)
-
@validated = @condition.call
-
prepare!
-
-
response = @app.call(env)
-
response[2] = ::Rack::BodyProxy.new(response[2]) { cleanup! }
-
-
response
-
rescue Exception
-
cleanup!
-
raise
-
end
-
-
1
def prepare! #:nodoc:
-
1
run_callbacks :prepare if validated?
-
end
-
-
1
def cleanup! #:nodoc:
-
run_callbacks :cleanup if validated?
-
ensure
-
@validated = true
-
end
-
-
1
private
-
-
1
def validated? #:nodoc:
-
1
@validated
-
end
-
end
-
end
-
1
require 'ipaddr'
-
-
1
module ActionDispatch
-
# This middleware calculates the IP address of the remote client that is
-
# making the request. It does this by checking various headers that could
-
# contain the address, and then picking the last-set address that is not
-
# on the list of trusted IPs. This follows the precedent set by e.g.
-
# {the Tomcat server}[https://issues.apache.org/bugzilla/show_bug.cgi?id=50453],
-
# with {reasoning explained at length}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection]
-
# by @gingerlime. A more detailed explanation of the algorithm is given
-
# at GetIp#calculate_ip.
-
#
-
# Some Rack servers concatenate repeated headers, like {HTTP RFC 2616}[http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2]
-
# requires. Some Rack servers simply drop preceding headers, and only report
-
# the value that was {given in the last header}[http://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers].
-
# If you are behind multiple proxy servers (like NGINX to HAProxy to Unicorn)
-
# then you should test your Rack server to make sure your data is good.
-
#
-
# IF YOU DON'T USE A PROXY, THIS MAKES YOU VULNERABLE TO IP SPOOFING.
-
# This middleware assumes that there is at least one proxy sitting around
-
# and setting headers with the client's remote IP address. If you don't use
-
# a proxy, because you are hosted on e.g. Heroku without SSL, any client can
-
# claim to have any IP address by setting the X-Forwarded-For header. If you
-
# care about that, then you need to explicitly drop or ignore those headers
-
# sometime before this middleware runs.
-
1
class RemoteIp
-
1
class IpSpoofAttackError < StandardError; end
-
-
# The default trusted IPs list simply includes IP addresses that are
-
# guaranteed by the IP specification to be private addresses. Those will
-
# not be the ultimate client IP in production, and so are discarded. See
-
# http://en.wikipedia.org/wiki/Private_network for details.
-
1
TRUSTED_PROXIES = [
-
"127.0.0.1", # localhost IPv4
-
"::1", # localhost IPv6
-
"fc00::/7", # private IPv6 range fc00::/7
-
"10.0.0.0/8", # private IPv4 range 10.x.x.x
-
"172.16.0.0/12", # private IPv4 range 172.16.0.0 .. 172.31.255.255
-
"192.168.0.0/16", # private IPv4 range 192.168.x.x
-
6
].map { |proxy| IPAddr.new(proxy) }
-
-
1
attr_reader :check_ip, :proxies
-
-
# Create a new +RemoteIp+ middleware instance.
-
#
-
# The +check_ip_spoofing+ option is on by default. When on, an exception
-
# is raised if it looks like the client is trying to lie about its own IP
-
# address. It makes sense to turn off this check on sites aimed at non-IP
-
# clients (like WAP devices), or behind proxies that set headers in an
-
# incorrect or confusing way (like AWS ELB).
-
#
-
# The +custom_proxies+ argument can take an Array of string, IPAddr, or
-
# Regexp objects which will be used instead of +TRUSTED_PROXIES+. If a
-
# single string, IPAddr, or Regexp object is provided, it will be used in
-
# addition to +TRUSTED_PROXIES+. Any proxy setup will put the value you
-
# want in the middle (or at the beginning) of the X-Forwarded-For list,
-
# with your proxy servers after it. If your proxies aren't removed, pass
-
# them in via the +custom_proxies+ parameter. That way, the middleware will
-
# ignore those IP addresses, and return the one that you want.
-
1
def initialize(app, check_ip_spoofing = true, custom_proxies = nil)
-
1
@app = app
-
1
@check_ip = check_ip_spoofing
-
1
@proxies = if custom_proxies.blank?
-
1
TRUSTED_PROXIES
-
elsif custom_proxies.respond_to?(:any?)
-
custom_proxies
-
else
-
Array(custom_proxies) + TRUSTED_PROXIES
-
end
-
end
-
-
# Since the IP address may not be needed, we store the object here
-
# without calculating the IP to keep from slowing down the majority of
-
# requests. For those requests that do need to know the IP, the
-
# GetIp#calculate_ip method will calculate the memoized client IP address.
-
1
def call(env)
-
66
env["action_dispatch.remote_ip"] = GetIp.new(env, self)
-
66
@app.call(env)
-
end
-
-
# The GetIp class exists as a way to defer processing of the request data
-
# into an actual IP address. If the ActionDispatch::Request#remote_ip method
-
# is called, this class will calculate the value and then memoize it.
-
1
class GetIp
-
1
def initialize(env, middleware)
-
66
@env = env
-
66
@check_ip = middleware.check_ip
-
66
@proxies = middleware.proxies
-
end
-
-
# Sort through the various IP address headers, looking for the IP most
-
# likely to be the address of the actual remote client making this
-
# request.
-
#
-
# REMOTE_ADDR will be correct if the request is made directly against the
-
# Ruby process, on e.g. Heroku. When the request is proxied by another
-
# server like HAProxy or NGINX, the IP address that made the original
-
# request will be put in an X-Forwarded-For header. If there are multiple
-
# proxies, that header may contain a list of IPs. Other proxy services
-
# set the Client-Ip header instead, so we check that too.
-
#
-
# As discussed in {this post about Rails IP Spoofing}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/],
-
# while the first IP in the list is likely to be the "originating" IP,
-
# it could also have been set by the client maliciously.
-
#
-
# In order to find the first address that is (probably) accurate, we
-
# take the list of IPs, remove known and trusted proxies, and then take
-
# the last address left, which was presumably set by one of those proxies.
-
1
def calculate_ip
-
# Set by the Rack web server, this is a single value.
-
55
remote_addr = ips_from('REMOTE_ADDR').last
-
-
# Could be a CSV list and/or repeated headers that were concatenated.
-
55
client_ips = ips_from('HTTP_CLIENT_IP').reverse
-
55
forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR').reverse
-
-
# +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set.
-
# If they are both set, it means that this request passed through two
-
# proxies with incompatible IP header conventions, and there is no way
-
# for us to determine which header is the right one after the fact.
-
# Since we have no idea, we give up and explode.
-
55
should_check_ip = @check_ip && client_ips.last && forwarded_ips.last
-
55
if should_check_ip && !forwarded_ips.include?(client_ips.last)
-
# We don't know which came from the proxy, and which from the user
-
raise IpSpoofAttackError, "IP spoofing attack?! " +
-
"HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect} " +
-
"HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}"
-
end
-
-
# We assume these things about the IP headers:
-
#
-
# - X-Forwarded-For will be a list of IPs, one per proxy, or blank
-
# - Client-Ip is propagated from the outermost proxy, or is blank
-
# - REMOTE_ADDR will be the IP that made the request to Rack
-
55
ips = [forwarded_ips, client_ips, remote_addr].flatten.compact
-
-
# If every single IP option is in the trusted list, just return REMOTE_ADDR
-
55
filter_proxies(ips).first || remote_addr
-
end
-
-
# Memoizes the value returned by #calculate_ip and returns it for
-
# ActionDispatch::Request to use.
-
1
def to_s
-
55
@ip ||= calculate_ip
-
end
-
-
1
protected
-
-
1
def ips_from(header)
-
# Split the comma-separated list into an array of strings
-
165
ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : []
-
165
ips.select do |ip|
-
55
begin
-
# Only return IPs that are valid according to the IPAddr#new method
-
55
range = IPAddr.new(ip).to_range
-
# we want to make sure nobody is sneaking a netmask in
-
55
range.begin == range.end
-
rescue ArgumentError
-
nil
-
end
-
end
-
end
-
-
1
def filter_proxies(ips)
-
55
ips.reject do |ip|
-
110
@proxies.any? { |proxy| proxy === ip }
-
end
-
end
-
-
end
-
-
end
-
end
-
1
require 'securerandom'
-
1
require 'active_support/core_ext/string/access'
-
-
1
module ActionDispatch
-
# Makes a unique request id available to the action_dispatch.request_id env variable (which is then accessible through
-
# ActionDispatch::Request#uuid) and sends the same id to the client via the X-Request-Id header.
-
#
-
# The unique request id is either based on the X-Request-Id header in the request, which would typically be generated
-
# by a firewall, load balancer, or the web server, or, if this header is not available, a random uuid. If the
-
# header is accepted from the outside world, we sanitize it to a max of 255 chars and alphanumeric and dashes only.
-
#
-
# The unique request id can be used to trace a request end-to-end and would typically end up being part of log files
-
# from multiple pieces of the stack.
-
1
class RequestId
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
66
env["action_dispatch.request_id"] = external_request_id(env) || internal_request_id
-
132
@app.call(env).tap { |_status, headers, _body| headers["X-Request-Id"] = env["action_dispatch.request_id"] }
-
end
-
-
1
private
-
1
def external_request_id(env)
-
66
if request_id = env["HTTP_X_REQUEST_ID"].presence
-
request_id.gsub(/[^\w\-]/, "").first(255)
-
end
-
end
-
-
1
def internal_request_id
-
66
SecureRandom.uuid
-
end
-
end
-
end
-
1
require 'rack/utils'
-
1
require 'rack/request'
-
1
require 'rack/session/abstract/id'
-
1
require 'action_dispatch/middleware/cookies'
-
1
require 'action_dispatch/request/session'
-
-
1
module ActionDispatch
-
1
module Session
-
1
class SessionRestoreError < StandardError #:nodoc:
-
1
attr_reader :original_exception
-
-
1
def initialize(const_error)
-
@original_exception = const_error
-
-
super("Session contains objects whose class definition isn't available.\n" +
-
"Remember to require the classes for all objects kept in the session.\n" +
-
"(Original exception: #{const_error.message} [#{const_error.class}])\n")
-
end
-
end
-
-
1
module Compatibility
-
1
def initialize(app, options = {})
-
1
options[:key] ||= '_session_id'
-
1
super
-
end
-
-
1
def generate_sid
-
5
sid = SecureRandom.hex(16)
-
5
sid.encode!(Encoding::UTF_8)
-
5
sid
-
end
-
-
1
protected
-
-
1
def initialize_sid
-
1
@default_options.delete(:sidbits)
-
1
@default_options.delete(:secure_random)
-
end
-
end
-
-
1
module StaleSessionCheck
-
1
def load_session(env)
-
stale_session_check! { super }
-
end
-
-
1
def extract_session_id(env)
-
stale_session_check! { super }
-
end
-
-
1
def stale_session_check!
-
143
yield
-
rescue ArgumentError => argument_error
-
if argument_error.message =~ %r{undefined class/module ([\w:]*\w)}
-
begin
-
# Note that the regexp does not allow $1 to end with a ':'
-
$1.constantize
-
rescue LoadError, NameError => e
-
raise ActionDispatch::Session::SessionRestoreError, e, e.backtrace
-
end
-
retry
-
else
-
raise
-
end
-
end
-
end
-
-
1
module SessionObject # :nodoc:
-
1
def prepare_session(env)
-
66
Request::Session.create(self, env, @default_options)
-
end
-
-
1
def loaded_session?(session)
-
77
!session.is_a?(Request::Session) || session.loaded?
-
end
-
end
-
-
1
class AbstractStore < Rack::Session::Abstract::ID
-
1
include Compatibility
-
1
include StaleSessionCheck
-
1
include SessionObject
-
-
1
private
-
-
1
def set_cookie(env, session_id, cookie)
-
request = ActionDispatch::Request.new(env)
-
request.cookie_jar[key] = cookie
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'action_dispatch/middleware/session/abstract_store'
-
1
require 'rack/session/cookie'
-
-
1
module ActionDispatch
-
1
module Session
-
# This cookie-based session store is the Rails default. It is
-
# dramatically faster than the alternatives.
-
#
-
# Sessions typically contain at most a user_id and flash message; both fit
-
# within the 4K cookie size limit. A CookieOverflow exception is raised if
-
# you attempt to store more than 4K of data.
-
#
-
# The cookie jar used for storage is automatically configured to be the
-
# best possible option given your application's configuration.
-
#
-
# If you only have secret_token set, your cookies will be signed, but
-
# not encrypted. This means a user cannot alter their +user_id+ without
-
# knowing your app's secret key, but can easily read their +user_id+. This
-
# was the default for Rails 3 apps.
-
#
-
# If you have secret_key_base set, your cookies will be encrypted. This
-
# goes a step further than signed cookies in that encrypted cookies cannot
-
# be altered or read by users. This is the default starting in Rails 4.
-
#
-
# If you have both secret_token and secret_key base set, your cookies will
-
# be encrypted, and signed cookies generated by Rails 3 will be
-
# transparently read and encrypted to provide a smooth upgrade path.
-
#
-
# Configure your session store in config/initializers/session_store.rb:
-
#
-
# Rails.application.config.session_store :cookie_store, key: '_your_app_session'
-
#
-
# Configure your secret key in config/secrets.yml:
-
#
-
# development:
-
# secret_key_base: 'secret key'
-
#
-
# To generate a secret key for an existing application, run `rake secret`.
-
#
-
# If you are upgrading an existing Rails 3 app, you should leave your
-
# existing secret_token in place and simply add the new secret_key_base.
-
# Note that you should wait to set secret_key_base until you have 100% of
-
# your userbase on Rails 4 and are reasonably sure you will not need to
-
# rollback to Rails 3. This is because cookies signed based on the new
-
# secret_key_base in Rails 4 are not backwards compatible with Rails 3.
-
# You are free to leave your existing secret_token in place, not set the
-
# new secret_key_base, and ignore the deprecation warnings until you are
-
# reasonably sure that your upgrade is otherwise complete. Additionally,
-
# you should take care to make sure you are not relying on the ability to
-
# decode signed cookies generated by your app in external applications or
-
# JavaScript before upgrading.
-
#
-
# Note that changing the secret key will invalidate all existing sessions!
-
1
class CookieStore < Rack::Session::Abstract::ID
-
1
include Compatibility
-
1
include StaleSessionCheck
-
1
include SessionObject
-
-
1
def initialize(app, options={})
-
1
super(app, options.merge!(:cookie_only => true))
-
end
-
-
1
def destroy_session(env, session_id, options)
-
new_sid = generate_sid unless options[:drop]
-
# Reset hash and Assign the new session id
-
env["action_dispatch.request.unsigned_session_cookie"] = new_sid ? { "session_id" => new_sid } : {}
-
new_sid
-
end
-
-
1
def load_session(env)
-
11
stale_session_check! do
-
11
data = unpacked_cookie_data(env)
-
11
data = persistent_session_id!(data)
-
11
[data["session_id"], data]
-
end
-
end
-
-
1
private
-
-
1
def extract_session_id(env)
-
66
stale_session_check! do
-
66
unpacked_cookie_data(env)["session_id"]
-
end
-
end
-
-
1
def unpacked_cookie_data(env)
-
77
env["action_dispatch.request.unsigned_session_cookie"] ||= begin
-
66
stale_session_check! do
-
66
if data = get_cookie(env)
-
6
data.stringify_keys!
-
end
-
66
data || {}
-
end
-
end
-
end
-
-
1
def persistent_session_id!(data, sid=nil)
-
11
data ||= {}
-
11
data["session_id"] ||= sid || generate_sid
-
11
data
-
end
-
-
1
def set_session(env, sid, session_data, options)
-
11
session_data["session_id"] = sid
-
11
session_data
-
end
-
-
1
def set_cookie(env, session_id, cookie)
-
11
cookie_jar(env)[@key] = cookie
-
end
-
-
1
def get_cookie(env)
-
66
cookie_jar(env)[@key]
-
end
-
-
1
def cookie_jar(env)
-
77
request = ActionDispatch::Request.new(env)
-
77
request.cookie_jar.signed_or_encrypted
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/http/request'
-
1
require 'action_dispatch/middleware/exception_wrapper'
-
-
1
module ActionDispatch
-
# This middleware rescues any exception returned by the application
-
# and calls an exceptions app that will wrap it in a format for the end user.
-
#
-
# The exceptions app should be passed as parameter on initialization
-
# of ShowExceptions. Every time there is an exception, ShowExceptions will
-
# store the exception in env["action_dispatch.exception"], rewrite the
-
# PATH_INFO to the exception status code and call the rack app.
-
#
-
# If the application returns a "X-Cascade" pass response, this middleware
-
# will send an empty response as result with the correct status code.
-
# If any exception happens inside the exceptions app, this middleware
-
# catches the exceptions and returns a FAILSAFE_RESPONSE.
-
1
class ShowExceptions
-
1
FAILSAFE_RESPONSE = [500, { 'Content-Type' => 'text/plain' },
-
["500 Internal Server Error\n" \
-
"If you are the administrator of this website, then please read this web " \
-
"application's log file and/or the web server's log file to find out what " \
-
"went wrong."]]
-
-
1
def initialize(app, exceptions_app)
-
1
@app = app
-
1
@exceptions_app = exceptions_app
-
end
-
-
1
def call(env)
-
66
@app.call(env)
-
rescue Exception => exception
-
if env['action_dispatch.show_exceptions'] == false
-
raise exception
-
else
-
render_exception(env, exception)
-
end
-
end
-
-
1
private
-
-
1
def render_exception(env, exception)
-
wrapper = ExceptionWrapper.new(env, exception)
-
status = wrapper.status_code
-
env["action_dispatch.exception"] = wrapper.exception
-
env["action_dispatch.original_path"] = env["PATH_INFO"]
-
env["PATH_INFO"] = "/#{status}"
-
response = @exceptions_app.call(env)
-
response[1]['X-Cascade'] == 'pass' ? pass_response(status) : response
-
rescue Exception => failsafe_error
-
$stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}"
-
FAILSAFE_RESPONSE
-
end
-
-
1
def pass_response(status)
-
[status, {"Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0"}, []]
-
end
-
end
-
end
-
1
require "active_support/inflector/methods"
-
1
require "active_support/dependencies"
-
-
1
module ActionDispatch
-
1
class MiddlewareStack
-
1
class Middleware
-
1
attr_reader :args, :block, :name, :classcache
-
-
1
def initialize(klass_or_name, *args, &block)
-
21
@klass = nil
-
-
21
if klass_or_name.respond_to?(:name)
-
19
@klass = klass_or_name
-
19
@name = @klass.name
-
else
-
2
@name = klass_or_name.to_s
-
end
-
-
21
@classcache = ActiveSupport::Dependencies::Reference
-
21
@args, @block = args, block
-
end
-
-
1
def klass
-
21
@klass || classcache[@name]
-
end
-
-
1
def ==(middleware)
-
26
case middleware
-
when Middleware
-
klass == middleware.klass
-
when Class
-
klass == middleware
-
else
-
26
normalize(@name) == normalize(middleware)
-
end
-
end
-
-
1
def inspect
-
klass.to_s
-
end
-
-
1
def build(app)
-
21
klass.new(app, *args, &block)
-
end
-
-
1
private
-
-
1
def normalize(object)
-
52
object.to_s.strip.sub(/^::/, '')
-
end
-
end
-
-
1
include Enumerable
-
-
1
attr_accessor :middlewares
-
-
1
def initialize(*args)
-
2
@middlewares = []
-
2
yield(self) if block_given?
-
end
-
-
1
def each
-
66
@middlewares.each { |x| yield x }
-
end
-
-
1
def size
-
middlewares.size
-
end
-
-
1
def last
-
middlewares.last
-
end
-
-
1
def [](i)
-
middlewares[i]
-
end
-
-
1
def unshift(*args, &block)
-
middleware = self.class::Middleware.new(*args, &block)
-
middlewares.unshift(middleware)
-
end
-
-
1
def initialize_copy(other)
-
7
self.middlewares = other.middlewares.dup
-
end
-
-
1
def insert(index, *args, &block)
-
3
index = assert_index(index, :before)
-
3
middleware = self.class::Middleware.new(*args, &block)
-
3
middlewares.insert(index, middleware)
-
end
-
-
1
alias_method :insert_before, :insert
-
-
1
def insert_after(index, *args, &block)
-
2
index = assert_index(index, :after)
-
2
insert(index + 1, *args, &block)
-
end
-
-
1
def swap(target, *args, &block)
-
index = assert_index(target, :before)
-
insert(index, *args, &block)
-
middlewares.delete_at(index + 1)
-
end
-
-
1
def delete(target)
-
middlewares.delete target
-
end
-
-
1
def use(*args, &block)
-
18
middleware = self.class::Middleware.new(*args, &block)
-
18
middlewares.push(middleware)
-
end
-
-
1
def build(app = nil, &block)
-
1
app ||= block
-
1
raise "MiddlewareStack#build requires an app" unless app
-
22
middlewares.freeze.reverse.inject(app) { |a, e| e.build(a) }
-
end
-
-
1
protected
-
-
1
def assert_index(index, where)
-
5
i = index.is_a?(Integer) ? index : middlewares.index(index)
-
5
raise "No such middleware to insert #{where}: #{index.inspect}" unless i
-
5
i
-
end
-
end
-
end
-
1
require 'rack/utils'
-
1
require 'active_support/core_ext/uri'
-
-
1
module ActionDispatch
-
# This middleware returns a file's contents from disk in the body response.
-
# When initialized it can accept an optional 'Cache-Control' header which
-
# will be set when a response containing a file's contents is delivered.
-
#
-
# This middleware will render the file specified in `env["PATH_INFO"]`
-
# where the base path is in the +root+ directory. For example if the +root+
-
# is set to `public/` then a request with `env["PATH_INFO"]` of
-
# `assets/application.js` will return a response with contents of a file
-
# located at `public/assets/application.js` if the file exists. If the file
-
# does not exist a 404 "File not Found" response will be returned.
-
1
class FileHandler
-
1
def initialize(root, cache_control)
-
1
@root = root.chomp('/')
-
1
@compiled_root = /^#{Regexp.escape(root)}/
-
1
headers = cache_control && { 'Cache-Control' => cache_control }
-
1
@file_server = ::Rack::File.new(@root, headers)
-
end
-
-
1
def match?(path)
-
55
path = URI.parser.unescape(path)
-
55
return false unless path.valid_encoding?
-
-
55
paths = [path, "#{path}#{ext}", "#{path}/index#{ext}"].map { |v|
-
165
Rack::Utils.clean_path_info v
-
}
-
-
55
if match = paths.detect { |p|
-
165
path = File.join(@root, p.force_encoding('UTF-8'))
-
165
begin
-
165
File.file?(path) && File.readable?(path)
-
rescue SystemCallError
-
false
-
end
-
-
}
-
return ::Rack::Utils.escape(match)
-
end
-
end
-
-
1
def call(env)
-
path = env['PATH_INFO']
-
gzip_path = gzip_file_path(path)
-
-
if gzip_path && gzip_encoding_accepted?(env)
-
env['PATH_INFO'] = gzip_path
-
status, headers, body = @file_server.call(env)
-
if status == 304
-
return [status, headers, body]
-
end
-
headers['Content-Encoding'] = 'gzip'
-
headers['Content-Type'] = content_type(path)
-
else
-
status, headers, body = @file_server.call(env)
-
end
-
-
headers['Vary'] = 'Accept-Encoding' if gzip_path
-
-
return [status, headers, body]
-
ensure
-
env['PATH_INFO'] = path
-
end
-
-
1
private
-
1
def ext
-
110
::ActionController::Base.default_static_extension
-
end
-
-
1
def content_type(path)
-
::Rack::Mime.mime_type(::File.extname(path), 'text/plain')
-
end
-
-
1
def gzip_encoding_accepted?(env)
-
env['HTTP_ACCEPT_ENCODING'] =~ /\bgzip\b/i
-
end
-
-
1
def gzip_file_path(path)
-
can_gzip_mime = content_type(path) =~ /\A(?:text\/|application\/javascript)/
-
gzip_path = "#{path}.gz"
-
if can_gzip_mime && File.exist?(File.join(@root, ::Rack::Utils.unescape(gzip_path)))
-
gzip_path
-
else
-
false
-
end
-
end
-
end
-
-
# This middleware will attempt to return the contents of a file's body from
-
# disk in the response. If a file is not found on disk, the request will be
-
# delegated to the application stack. This middleware is commonly initialized
-
# to serve assets from a server's `public/` directory.
-
#
-
# This middleware verifies the path to ensure that only files
-
# living in the root directory can be rendered. A request cannot
-
# produce a directory traversal using this middleware. Only 'GET' and 'HEAD'
-
# requests will result in a file being returned.
-
1
class Static
-
1
def initialize(app, path, cache_control=nil)
-
1
@app = app
-
1
@file_handler = FileHandler.new(path, cache_control)
-
end
-
-
1
def call(env)
-
66
case env['REQUEST_METHOD']
-
when 'GET', 'HEAD'
-
55
path = env['PATH_INFO'].chomp('/')
-
55
if match = @file_handler.match?(path)
-
env["PATH_INFO"] = match
-
return @file_handler.call(env)
-
end
-
end
-
-
66
@app.call(env)
-
end
-
end
-
end
-
1
require "action_dispatch"
-
-
1
module ActionDispatch
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.action_dispatch = ActiveSupport::OrderedOptions.new
-
1
config.action_dispatch.x_sendfile_header = nil
-
1
config.action_dispatch.ip_spoofing_check = true
-
1
config.action_dispatch.show_exceptions = true
-
1
config.action_dispatch.tld_length = 1
-
1
config.action_dispatch.ignore_accept_header = false
-
1
config.action_dispatch.rescue_templates = { }
-
1
config.action_dispatch.rescue_responses = { }
-
1
config.action_dispatch.default_charset = nil
-
1
config.action_dispatch.rack_cache = false
-
1
config.action_dispatch.http_auth_salt = 'http authentication'
-
1
config.action_dispatch.signed_cookie_salt = 'signed cookie'
-
1
config.action_dispatch.encrypted_cookie_salt = 'encrypted cookie'
-
1
config.action_dispatch.encrypted_signed_cookie_salt = 'signed encrypted cookie'
-
1
config.action_dispatch.perform_deep_munge = true
-
-
1
config.action_dispatch.default_headers = {
-
'X-Frame-Options' => 'SAMEORIGIN',
-
'X-XSS-Protection' => '1; mode=block',
-
'X-Content-Type-Options' => 'nosniff'
-
}
-
-
1
config.eager_load_namespaces << ActionDispatch
-
-
1
initializer "action_dispatch.configure" do |app|
-
1
ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length
-
1
ActionDispatch::Request.ignore_accept_header = app.config.action_dispatch.ignore_accept_header
-
1
ActionDispatch::Request::Utils.perform_deep_munge = app.config.action_dispatch.perform_deep_munge
-
1
ActionDispatch::Response.default_charset = app.config.action_dispatch.default_charset || app.config.encoding
-
1
ActionDispatch::Response.default_headers = app.config.action_dispatch.default_headers
-
-
1
ActionDispatch::ExceptionWrapper.rescue_responses.merge!(config.action_dispatch.rescue_responses)
-
1
ActionDispatch::ExceptionWrapper.rescue_templates.merge!(config.action_dispatch.rescue_templates)
-
-
1
config.action_dispatch.always_write_cookie = Rails.env.development? if config.action_dispatch.always_write_cookie.nil?
-
1
ActionDispatch::Cookies::CookieJar.always_write_cookie = config.action_dispatch.always_write_cookie
-
-
1
ActionDispatch.test_app = app
-
-
1
ActionDispatch::Routing::RouteSet.relative_url_root = app.config.relative_url_root
-
end
-
end
-
end
-
1
require 'rack/session/abstract/id'
-
-
1
module ActionDispatch
-
1
class Request < Rack::Request
-
# Session is responsible for lazily loading the session from store.
-
1
class Session # :nodoc:
-
1
ENV_SESSION_KEY = Rack::Session::Abstract::ENV_SESSION_KEY # :nodoc:
-
1
ENV_SESSION_OPTIONS_KEY = Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY # :nodoc:
-
-
# Singleton object used to determine if an optional param wasn't specified
-
1
Unspecified = Object.new
-
-
1
def self.create(store, env, default_options)
-
66
session_was = find env
-
66
session = Request::Session.new(store, env)
-
66
session.merge! session_was if session_was
-
-
66
set(env, session)
-
66
Options.set(env, Request::Session::Options.new(store, env, default_options))
-
66
session
-
end
-
-
1
def self.find(env)
-
132
env[ENV_SESSION_KEY]
-
end
-
-
1
def self.set(env, session)
-
66
env[ENV_SESSION_KEY] = session
-
end
-
-
1
class Options #:nodoc:
-
1
def self.set(env, options)
-
66
env[ENV_SESSION_OPTIONS_KEY] = options
-
end
-
-
1
def self.find(env)
-
257
env[ENV_SESSION_OPTIONS_KEY]
-
end
-
-
1
def initialize(by, env, default_options)
-
66
@by = by
-
66
@env = env
-
66
@delegate = default_options.dup
-
end
-
-
1
def [](key)
-
422
if key == :id
-
180
@delegate.fetch(key) {
-
66
@delegate[:id] = @by.send(:extract_session_id, @env)
-
}
-
else
-
242
@delegate[key]
-
end
-
end
-
-
12
def []=(k,v); @delegate[k] = v; end
-
12
def to_hash; @delegate.dup; end
-
56
def values_at(*args); @delegate.values_at(*args); end
-
end
-
-
1
def initialize(by, env)
-
66
@by = by
-
66
@env = env
-
66
@delegate = {}
-
66
@loaded = false
-
66
@exists = nil # we haven't checked yet
-
end
-
-
1
def id
-
180
options[:id]
-
end
-
-
1
def options
-
257
Options.find @env
-
end
-
-
1
def destroy
-
clear
-
options = self.options || {}
-
new_sid = @by.send(:destroy_session, @env, options[:id], options)
-
options[:id] = new_sid # Reset session id with a new value or nil
-
-
# Load the new sid to be written with the response
-
@loaded = false
-
load_for_write!
-
end
-
-
1
def [](key)
-
137
load_for_read!
-
137
@delegate[key.to_s]
-
end
-
-
1
def has_key?(key)
-
61
load_for_read!
-
61
@delegate.key?(key.to_s)
-
end
-
1
alias :key? :has_key?
-
1
alias :include? :has_key?
-
-
1
def keys
-
@delegate.keys
-
end
-
-
1
def values
-
@delegate.values
-
end
-
-
1
def []=(key, value)
-
11
load_for_write!
-
11
@delegate[key.to_s] = value
-
end
-
-
1
def clear
-
load_for_write!
-
@delegate.clear
-
end
-
-
1
def to_hash
-
11
load_for_read!
-
32
@delegate.dup.delete_if { |_,v| v.nil? }
-
end
-
-
1
def update(hash)
-
load_for_write!
-
@delegate.update stringify_keys(hash)
-
end
-
-
1
def delete(key)
-
1
load_for_write!
-
1
@delegate.delete key.to_s
-
end
-
-
1
def fetch(key, default=Unspecified, &block)
-
load_for_read!
-
if default == Unspecified
-
@delegate.fetch(key.to_s, &block)
-
else
-
@delegate.fetch(key.to_s, default, &block)
-
end
-
end
-
-
1
def inspect
-
if loaded?
-
super
-
else
-
"#<#{self.class}:0x#{(object_id << 1).to_s(16)} not yet loaded>"
-
end
-
end
-
-
1
def exists?
-
169
return @exists unless @exists.nil?
-
169
@exists = @by.send(:session_exists?, @env)
-
end
-
-
1
def loaded?
-
364
@loaded
-
end
-
-
1
def empty?
-
load_for_read!
-
@delegate.empty?
-
end
-
-
1
def merge!(other)
-
load_for_write!
-
@delegate.merge!(other)
-
end
-
-
1
private
-
-
1
def load_for_read!
-
209
load! if !loaded? && exists?
-
end
-
-
1
def load_for_write!
-
12
load! unless loaded?
-
end
-
-
1
def load!
-
11
id, session = @by.load_session @env
-
11
options[:id] = id
-
11
@delegate.replace(stringify_keys(session))
-
11
@loaded = true
-
end
-
-
1
def stringify_keys(other)
-
11
other.each_with_object({}) { |(key, value), hash|
-
17
hash[key.to_s] = value
-
}
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
class Request < Rack::Request
-
1
class Utils # :nodoc:
-
-
1
mattr_accessor :perform_deep_munge
-
1
self.perform_deep_munge = true
-
-
1
class << self
-
# Remove nils from the params hash
-
1
def deep_munge(hash, keys = [])
-
206
return hash unless perform_deep_munge
-
-
206
hash.each do |k, v|
-
61
keys << k
-
61
case v
-
when Array
-
v.grep(Hash) { |x| deep_munge(x, keys) }
-
v.compact!
-
if v.empty?
-
hash[k] = nil
-
ActiveSupport::Notifications.instrument("deep_munge.action_controller", keys: keys)
-
end
-
when Hash
-
8
deep_munge(v, keys)
-
end
-
61
keys.pop
-
end
-
-
206
hash
-
end
-
end
-
end
-
end
-
end
-
-
# encoding: UTF-8
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/regexp'
-
1
require 'active_support/dependencies/autoload'
-
-
1
module ActionDispatch
-
# The routing module provides URL rewriting in native Ruby. It's a way to
-
# redirect incoming requests to controllers and actions. This replaces
-
# mod_rewrite rules. Best of all, Rails' \Routing works with any web server.
-
# Routes are defined in <tt>config/routes.rb</tt>.
-
#
-
# Think of creating routes as drawing a map for your requests. The map tells
-
# them where to go based on some predefined pattern:
-
#
-
# Rails.application.routes.draw do
-
# Pattern 1 tells some request to go to one place
-
# Pattern 2 tell them to go to another
-
# ...
-
# end
-
#
-
# The following symbols are special:
-
#
-
# :controller maps to your controller name
-
# :action maps to an action with your controllers
-
#
-
# Other names simply map to a parameter as in the case of <tt>:id</tt>.
-
#
-
# == Resources
-
#
-
# Resource routing allows you to quickly declare all of the common routes
-
# for a given resourceful controller. Instead of declaring separate routes
-
# for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
-
# actions, a resourceful route declares them in a single line of code:
-
#
-
# resources :photos
-
#
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the profile of
-
# the currently logged in user. In this case, you can use a singular resource
-
# to map /profile (rather than /profile/:id) to the show action.
-
#
-
# resource :profile
-
#
-
# It's common to have resources that are logically children of other
-
# resources:
-
#
-
# resources :magazines do
-
# resources :ads
-
# end
-
#
-
# You may wish to organize groups of controllers under a namespace. Most
-
# commonly, you might group a number of administrative controllers under
-
# an +admin+ namespace. You would place these controllers under the
-
# <tt>app/controllers/admin</tt> directory, and you can group them together
-
# in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# Alternately, you can add prefixes to your path without using a separate
-
# directory by using +scope+. +scope+ takes additional options which
-
# apply to all enclosed routes.
-
#
-
# scope path: "/cpanel", as: 'admin' do
-
# resources :posts, :comments
-
# end
-
#
-
# For more, see <tt>Routing::Mapper::Resources#resources</tt>,
-
# <tt>Routing::Mapper::Scoping#namespace</tt>, and
-
# <tt>Routing::Mapper::Scoping#scope</tt>.
-
#
-
# == Non-resourceful routes
-
#
-
# For routes that don't fit the <tt>resources</tt> mold, you can use the HTTP helper
-
# methods <tt>get</tt>, <tt>post</tt>, <tt>patch</tt>, <tt>put</tt> and <tt>delete</tt>.
-
#
-
# get 'post/:id' => 'posts#show'
-
# post 'post/:id' => 'posts#create_comment'
-
#
-
# If your route needs to respond to more than one HTTP method (or all methods) then using the
-
# <tt>:via</tt> option on <tt>match</tt> is preferable.
-
#
-
# match 'post/:id' => 'posts#show', via: [:get, :post]
-
#
-
# Now, if you POST to <tt>/posts/:id</tt>, it will route to the <tt>create_comment</tt> action. A GET on the same
-
# URL will route to the <tt>show</tt> action.
-
#
-
# == Named routes
-
#
-
# Routes can be named by passing an <tt>:as</tt> option,
-
# allowing for easy reference within your source as +name_of_route_url+
-
# for the full URL and +name_of_route_path+ for the URI path.
-
#
-
# Example:
-
#
-
# # In routes.rb
-
# get '/login' => 'accounts#login', as: 'login'
-
#
-
# # With render, redirect_to, tests, etc.
-
# redirect_to login_url
-
#
-
# Arguments can be passed as well.
-
#
-
# redirect_to show_item_path(id: 25)
-
#
-
# Use <tt>root</tt> as a shorthand to name a route for the root path "/".
-
#
-
# # In routes.rb
-
# root to: 'blogs#index'
-
#
-
# # would recognize http://www.example.com/ as
-
# params = { controller: 'blogs', action: 'index' }
-
#
-
# # and provide these named routes
-
# root_url # => 'http://www.example.com/'
-
# root_path # => '/'
-
#
-
# Note: when using +controller+, the route is simply named after the
-
# method you call on the block parameter rather than map.
-
#
-
# # In routes.rb
-
# controller :blog do
-
# get 'blog/show' => :list
-
# get 'blog/delete' => :delete
-
# get 'blog/edit/:id' => :edit
-
# end
-
#
-
# # provides named routes for show, delete, and edit
-
# link_to @article.title, show_path(id: @article.id)
-
#
-
# == Pretty URLs
-
#
-
# Routes can generate pretty URLs. For example:
-
#
-
# get '/articles/:year/:month/:day' => 'articles#find_by_id', constraints: {
-
# year: /\d{4}/,
-
# month: /\d{1,2}/,
-
# day: /\d{1,2}/
-
# }
-
#
-
# Using the route above, the URL "http://localhost:3000/articles/2005/11/06"
-
# maps to
-
#
-
# params = {year: '2005', month: '11', day: '06'}
-
#
-
# == Regular Expressions and parameters
-
# You can specify a regular expression to define a format for a parameter.
-
#
-
# controller 'geocode' do
-
# get 'geocode/:postalcode' => :show, constraints: {
-
# postalcode: /\d{5}(-\d{4})?/
-
# }
-
#
-
# Constraints can include the 'ignorecase' and 'extended syntax' regular
-
# expression modifiers:
-
#
-
# controller 'geocode' do
-
# get 'geocode/:postalcode' => :show, constraints: {
-
# postalcode: /hx\d\d\s\d[a-z]{2}/i
-
# }
-
# end
-
#
-
# controller 'geocode' do
-
# get 'geocode/:postalcode' => :show, constraints: {
-
# postalcode: /# Postcode format
-
# \d{5} #Prefix
-
# (-\d{4})? #Suffix
-
# /x
-
# }
-
# end
-
#
-
# Using the multiline modifier will raise an +ArgumentError+.
-
# Encoding regular expression modifiers are silently ignored. The
-
# match will always use the default encoding or ASCII.
-
#
-
# == External redirects
-
#
-
# You can redirect any path to another path using the redirect helper in your router:
-
#
-
# get "/stories" => redirect("/posts")
-
#
-
# == Unicode character routes
-
#
-
# You can specify unicode character routes in your router:
-
#
-
# get "こんにちは" => "welcome#index"
-
#
-
# == Routing to Rack Applications
-
#
-
# Instead of a String, like <tt>posts#index</tt>, which corresponds to the
-
# index action in the PostsController, you can specify any Rack application
-
# as the endpoint for a matcher:
-
#
-
# get "/application.js" => Sprockets
-
#
-
# == Reloading routes
-
#
-
# You can reload routes if you feel you must:
-
#
-
# Rails.application.reload_routes!
-
#
-
# This will clear all named routes and reload routes.rb if the file has been modified from
-
# last load. To absolutely force reloading, use <tt>reload!</tt>.
-
#
-
# == Testing Routes
-
#
-
# The two main methods for testing your routes:
-
#
-
# === +assert_routing+
-
#
-
# def test_movie_route_properly_splits
-
# opts = {controller: "plugin", action: "checkout", id: "2"}
-
# assert_routing "plugin/checkout/2", opts
-
# end
-
#
-
# +assert_routing+ lets you test whether or not the route properly resolves into options.
-
#
-
# === +assert_recognizes+
-
#
-
# def test_route_has_options
-
# opts = {controller: "plugin", action: "show", id: "12"}
-
# assert_recognizes opts, "/plugins/show/12"
-
# end
-
#
-
# Note the subtle difference between the two: +assert_routing+ tests that
-
# a URL fits options while +assert_recognizes+ tests that a URL
-
# breaks into parameters properly.
-
#
-
# In tests you can simply pass the URL or named route to +get+ or +post+.
-
#
-
# def send_to_jail
-
# get '/jail'
-
# assert_response :success
-
# assert_template "jail/front"
-
# end
-
#
-
# def goes_to_login
-
# get login_url
-
# #...
-
# end
-
#
-
# == View a list of all your routes
-
#
-
# rake routes
-
#
-
# Target specific controllers by prefixing the command with <tt>CONTROLLER=x</tt>.
-
#
-
1
module Routing
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Mapper
-
1
autoload :RouteSet
-
1
autoload :RoutesProxy
-
1
autoload :UrlFor
-
1
autoload :PolymorphicRoutes
-
-
1
SEPARATORS = %w( / . ? ) #:nodoc:
-
1
HTTP_METHODS = [:get, :head, :post, :patch, :put, :delete, :options] #:nodoc:
-
end
-
end
-
1
module ActionDispatch
-
1
module Routing
-
1
class Endpoint # :nodoc:
-
1
def dispatcher?; false; end
-
1
def redirect?; false; end
-
1
def matches?(req); true; end
-
1
def app; self; end
-
end
-
end
-
end
-
1
require 'delegate'
-
1
require 'active_support/core_ext/string/strip'
-
-
1
module ActionDispatch
-
1
module Routing
-
1
class RouteWrapper < SimpleDelegator
-
1
def endpoint
-
app.dispatcher? ? "#{controller}##{action}" : rack_app.inspect
-
end
-
-
1
def constraints
-
requirements.except(:controller, :action)
-
end
-
-
1
def rack_app
-
app.app
-
end
-
-
1
def verb
-
super.source.gsub(/[$^]/, '')
-
end
-
-
1
def path
-
super.spec.to_s
-
end
-
-
1
def name
-
super.to_s
-
end
-
-
1
def regexp
-
__getobj__.path.to_regexp
-
end
-
-
1
def json_regexp
-
str = regexp.inspect.
-
sub('\\A' , '^').
-
sub('\\Z' , '$').
-
sub('\\z' , '$').
-
sub(/^\// , '').
-
sub(/\/[a-z]*$/ , '').
-
gsub(/\(\?#.+\)/ , '').
-
gsub(/\(\?-\w+:/ , '(').
-
gsub(/\s/ , '')
-
Regexp.new(str).source
-
end
-
-
1
def reqs
-
@reqs ||= begin
-
reqs = endpoint
-
reqs += " #{constraints}" unless constraints.empty?
-
reqs
-
end
-
end
-
-
1
def controller
-
requirements[:controller] || ':controller'
-
end
-
-
1
def action
-
requirements[:action] || ':action'
-
end
-
-
1
def internal?
-
controller.to_s =~ %r{\Arails/(info|mailers|welcome)} || path =~ %r{\A#{Rails.application.config.assets.prefix}\z}
-
end
-
-
1
def engine?
-
rack_app.respond_to?(:routes)
-
end
-
end
-
-
##
-
# This class is just used for displaying route information when someone
-
# executes `rake routes` or looks at the RoutingError page.
-
# People should not use this class.
-
1
class RoutesInspector # :nodoc:
-
1
def initialize(routes)
-
@engines = {}
-
@routes = routes
-
end
-
-
1
def format(formatter, filter = nil)
-
routes_to_display = filter_routes(filter)
-
-
routes = collect_routes(routes_to_display)
-
-
if routes.none?
-
formatter.no_routes
-
return formatter.result
-
end
-
-
formatter.header routes
-
formatter.section routes
-
-
@engines.each do |name, engine_routes|
-
formatter.section_title "Routes for #{name}"
-
formatter.section engine_routes
-
end
-
-
formatter.result
-
end
-
-
1
private
-
-
1
def filter_routes(filter)
-
if filter
-
@routes.select { |route| route.defaults[:controller] == filter }
-
else
-
@routes
-
end
-
end
-
-
1
def collect_routes(routes)
-
routes.collect do |route|
-
RouteWrapper.new(route)
-
end.reject do |route|
-
route.internal?
-
end.collect do |route|
-
collect_engine_routes(route)
-
-
{ name: route.name,
-
verb: route.verb,
-
path: route.path,
-
reqs: route.reqs,
-
regexp: route.json_regexp }
-
end
-
end
-
-
1
def collect_engine_routes(route)
-
name = route.endpoint
-
return unless route.engine?
-
return if @engines[name]
-
-
routes = route.rack_app.routes
-
if routes.is_a?(ActionDispatch::Routing::RouteSet)
-
@engines[name] = collect_routes(routes.routes)
-
end
-
end
-
end
-
-
1
class ConsoleFormatter
-
1
def initialize
-
@buffer = []
-
end
-
-
1
def result
-
@buffer.join("\n")
-
end
-
-
1
def section_title(title)
-
@buffer << "\n#{title}:"
-
end
-
-
1
def section(routes)
-
@buffer << draw_section(routes)
-
end
-
-
1
def header(routes)
-
@buffer << draw_header(routes)
-
end
-
-
1
def no_routes
-
@buffer << <<-MESSAGE.strip_heredoc
-
You don't have any routes defined!
-
-
Please add some routes in config/routes.rb.
-
-
For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html.
-
MESSAGE
-
end
-
-
1
private
-
1
def draw_section(routes)
-
header_lengths = ['Prefix', 'Verb', 'URI Pattern'].map(&:length)
-
name_width, verb_width, path_width = widths(routes).zip(header_lengths).map(&:max)
-
-
routes.map do |r|
-
"#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
-
end
-
end
-
-
1
def draw_header(routes)
-
name_width, verb_width, path_width = widths(routes)
-
-
"#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} Controller#Action"
-
end
-
-
1
def widths(routes)
-
[routes.map { |r| r[:name].length }.max || 0,
-
routes.map { |r| r[:verb].length }.max || 0,
-
routes.map { |r| r[:path].length }.max || 0]
-
end
-
end
-
-
1
class HtmlTableFormatter
-
1
def initialize(view)
-
@view = view
-
@buffer = []
-
end
-
-
1
def section_title(title)
-
@buffer << %(<tr><th colspan="4">#{title}</th></tr>)
-
end
-
-
1
def section(routes)
-
@buffer << @view.render(partial: "routes/route", collection: routes)
-
end
-
-
# the header is part of the HTML page, so we don't construct it here.
-
1
def header(routes)
-
end
-
-
1
def no_routes
-
@buffer << <<-MESSAGE.strip_heredoc
-
<p>You don't have any routes defined!</p>
-
<ul>
-
<li>Please add some routes in <tt>config/routes.rb</tt>.</li>
-
<li>
-
For more information about routes, please see the Rails guide
-
<a href="http://guides.rubyonrails.org/routing.html">Rails Routing from the Outside In</a>.
-
</li>
-
</ul>
-
MESSAGE
-
end
-
-
1
def result
-
@view.raw @view.render(layout: "routes/table") {
-
@view.raw @buffer.join("\n")
-
}
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/enumerable'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'active_support/inflector'
-
1
require 'action_dispatch/routing/redirection'
-
1
require 'action_dispatch/routing/endpoint'
-
1
require 'active_support/deprecation'
-
-
1
module ActionDispatch
-
1
module Routing
-
1
class Mapper
-
1
URL_OPTIONS = [:protocol, :subdomain, :domain, :host, :port]
-
-
1
class Constraints < Endpoint #:nodoc:
-
1
attr_reader :app, :constraints
-
-
1
def initialize(app, constraints, dispatcher_p)
-
# Unwrap Constraints objects. I don't actually think it's possible
-
# to pass a Constraints object to this constructor, but there were
-
# multiple places that kept testing children of this object. I
-
# *think* they were just being defensive, but I have no idea.
-
1
if app.is_a?(self.class)
-
constraints += app.constraints
-
app = app.app
-
end
-
-
1
@dispatcher = dispatcher_p
-
-
1
@app, @constraints, = app, constraints
-
end
-
-
1
def dispatcher?; @dispatcher; end
-
-
1
def matches?(req)
-
@constraints.all? do |constraint|
-
(constraint.respond_to?(:matches?) && constraint.matches?(req)) ||
-
(constraint.respond_to?(:call) && constraint.call(*constraint_args(constraint, req)))
-
end
-
end
-
-
1
def serve(req)
-
return [ 404, {'X-Cascade' => 'pass'}, [] ] unless matches?(req)
-
-
if dispatcher?
-
@app.serve req
-
else
-
@app.call req.env
-
end
-
end
-
-
1
private
-
1
def constraint_args(constraint, request)
-
constraint.arity == 1 ? [request] : [request.path_parameters, request]
-
end
-
end
-
-
1
class Mapping #:nodoc:
-
1
ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
-
-
1
attr_reader :requirements, :conditions, :defaults
-
1
attr_reader :to, :default_controller, :default_action, :as, :anchor
-
-
1
def self.build(scope, set, path, as, options)
-
35
options = scope[:options].merge(options) if scope[:options]
-
-
35
options.delete :only
-
35
options.delete :except
-
35
options.delete :shallow_path
-
35
options.delete :shallow_prefix
-
35
options.delete :shallow
-
-
35
defaults = (scope[:defaults] || {}).merge options.delete(:defaults) || {}
-
-
35
new scope, set, path, defaults, as, options
-
end
-
-
1
def initialize(scope, set, path, defaults, as, options)
-
35
@requirements, @conditions = {}, {}
-
35
@defaults = defaults
-
35
@set = set
-
-
35
@to = options.delete :to
-
35
@default_controller = options.delete(:controller) || scope[:controller]
-
35
@default_action = options.delete(:action) || scope[:action]
-
35
@as = as
-
35
@anchor = options.delete :anchor
-
-
35
formatted = options.delete :format
-
35
via = Array(options.delete(:via) { [] })
-
35
options_constraints = options.delete :constraints
-
-
35
path = normalize_path! path, formatted
-
35
ast = path_ast path
-
35
path_params = path_params ast
-
-
35
options = normalize_options!(options, formatted, path_params, ast, scope[:module])
-
-
-
35
split_constraints(path_params, scope[:constraints]) if scope[:constraints]
-
35
constraints = constraints(options, path_params)
-
-
35
split_constraints path_params, constraints
-
-
35
@blocks = blocks(options_constraints, scope[:blocks])
-
-
35
if options_constraints.is_a?(Hash)
-
split_constraints path_params, options_constraints
-
options_constraints.each do |key, default|
-
if URL_OPTIONS.include?(key) && (String === default || Fixnum === default)
-
@defaults[key] ||= default
-
end
-
end
-
end
-
-
35
normalize_format!(formatted)
-
-
35
@conditions[:path_info] = path
-
35
@conditions[:parsed_path_info] = ast
-
-
35
add_request_method(via, @conditions)
-
35
normalize_defaults!(options)
-
end
-
-
1
def to_route
-
35
[ app(@blocks), conditions, requirements, defaults, as, anchor ]
-
end
-
-
1
private
-
-
1
def normalize_path!(path, format)
-
35
path = Mapper.normalize_path(path)
-
-
35
if format == true
-
"#{path}.:format"
-
35
elsif optional_format?(path, format)
-
33
"#{path}(.:format)"
-
else
-
2
path
-
end
-
end
-
-
1
def optional_format?(path, format)
-
35
format != false && !path.include?(':format') && !path.end_with?('/')
-
end
-
-
1
def normalize_options!(options, formatted, path_params, path_ast, modyoule)
-
# Add a constraint for wildcard route to make it non-greedy and match the
-
# optional format part of the route by default
-
35
if formatted != false
-
34
path_ast.grep(Journey::Nodes::Star) do |node|
-
options[node.name.to_sym] ||= /.+?/
-
end
-
end
-
-
35
if path_params.include?(:controller)
-
raise ArgumentError, ":controller segment is not allowed within a namespace block" if modyoule
-
-
# Add a default constraint for :controller path segments that matches namespaced
-
# controllers with default routes like :controller/:action/:id(.:format), e.g:
-
# GET /admin/products/show/1
-
# => { controller: 'admin/products', action: 'show', id: '1' }
-
options[:controller] ||= /.+?/
-
end
-
-
35
if to.respond_to? :call
-
1
options
-
else
-
34
to_endpoint = split_to to
-
34
controller = to_endpoint[0] || default_controller
-
34
action = to_endpoint[1] || default_action
-
-
34
controller = add_controller_module(controller, modyoule)
-
-
34
options.merge! check_controller_and_action(path_params, controller, action)
-
end
-
end
-
-
1
def split_constraints(path_params, constraints)
-
67
constraints.each_pair do |key, requirement|
-
if path_params.include?(key) || key == :controller
-
verify_regexp_requirement(requirement) if requirement.is_a?(Regexp)
-
@requirements[key] = requirement
-
else
-
@conditions[key] = requirement
-
end
-
end
-
end
-
-
1
def normalize_format!(formatted)
-
35
if formatted == true
-
@requirements[:format] ||= /.+/
-
35
elsif Regexp === formatted
-
@requirements[:format] = formatted
-
@defaults[:format] = nil
-
35
elsif String === formatted
-
@requirements[:format] = Regexp.compile(formatted)
-
@defaults[:format] = formatted
-
end
-
end
-
-
1
def verify_regexp_requirement(requirement)
-
if requirement.source =~ ANCHOR_CHARACTERS_REGEX
-
raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
-
end
-
-
if requirement.multiline?
-
raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}"
-
end
-
end
-
-
1
def normalize_defaults!(options)
-
35
options.each_pair do |key, default|
-
68
unless Regexp === default
-
68
@defaults[key] = default
-
end
-
end
-
end
-
-
1
def verify_callable_constraint(callable_constraint)
-
unless callable_constraint.respond_to?(:call) || callable_constraint.respond_to?(:matches?)
-
raise ArgumentError, "Invalid constraint: #{callable_constraint.inspect} must respond to :call or :matches?"
-
end
-
end
-
-
1
def add_request_method(via, conditions)
-
35
return if via == [:all]
-
-
34
if via.empty?
-
msg = "You should not use the `match` method in your router without specifying an HTTP method.\n" \
-
"If you want to expose your action to both GET and POST, add `via: [:get, :post]` option.\n" \
-
"If you want to expose your action to GET, use `get` in the router:\n" \
-
" Instead of: match \"controller#action\"\n" \
-
" Do: get \"controller#action\""
-
raise ArgumentError, msg
-
end
-
-
68
conditions[:request_method] = via.map { |m| m.to_s.dasherize.upcase }
-
end
-
-
1
def app(blocks)
-
35
if to.respond_to?(:call)
-
1
Constraints.new(to, blocks, false)
-
34
elsif blocks.any?
-
Constraints.new(dispatcher(defaults), blocks, true)
-
else
-
34
dispatcher(defaults)
-
end
-
end
-
-
1
def check_controller_and_action(path_params, controller, action)
-
34
hash = check_part(:controller, controller, path_params, {}) do |part|
-
34
translate_controller(part) {
-
message = "'#{part}' is not a supported controller name. This can lead to potential routing problems."
-
message << " See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use"
-
-
raise ArgumentError, message
-
}
-
end
-
-
34
check_part(:action, action, path_params, hash) { |part|
-
34
part.is_a?(Regexp) ? part : part.to_s
-
}
-
end
-
-
1
def check_part(name, part, path_params, hash)
-
68
if part
-
68
hash[name] = yield(part)
-
else
-
unless path_params.include?(name)
-
message = "Missing :#{name} key on routes definition, please check your routes."
-
raise ArgumentError, message
-
end
-
end
-
68
hash
-
end
-
-
1
def split_to(to)
-
34
case to
-
when Symbol
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
Defining a route where `to` is a symbol is deprecated.
-
Please change `to: :#{to}` to `action: :#{to}`.
-
MSG
-
-
[nil, to.to_s]
-
2
when /#/ then to.split('#')
-
when String
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
Defining a route where `to` is a controller without an action is deprecated.
-
Please change `to: '#{to}'` to `controller: '#{to}'`.
-
MSG
-
-
[to, nil]
-
else
-
32
[]
-
end
-
end
-
-
1
def add_controller_module(controller, modyoule)
-
34
if modyoule && !controller.is_a?(Regexp)
-
if controller =~ %r{\A/}
-
controller[1..-1]
-
else
-
[modyoule, controller].compact.join("/")
-
end
-
else
-
34
controller
-
end
-
end
-
-
1
def translate_controller(controller)
-
34
return controller if Regexp === controller
-
34
return controller.to_s if controller =~ /\A[a-z_0-9][a-z_0-9\/]*\z/
-
-
yield
-
end
-
-
1
def blocks(options_constraints, scope_blocks)
-
35
if options_constraints && !options_constraints.is_a?(Hash)
-
verify_callable_constraint(options_constraints)
-
[options_constraints]
-
else
-
35
scope_blocks || []
-
end
-
end
-
-
1
def constraints(options, path_params)
-
35
constraints = {}
-
35
required_defaults = []
-
35
options.each_pair do |key, option|
-
68
if Regexp === option
-
constraints[key] = option
-
else
-
68
required_defaults << key unless path_params.include?(key)
-
end
-
end
-
35
@conditions[:required_defaults] = required_defaults
-
35
constraints
-
end
-
-
1
def path_params(ast)
-
88
ast.grep(Journey::Nodes::Symbol).map { |n| n.name.to_sym }
-
end
-
-
1
def path_ast(path)
-
35
parser = Journey::Parser.new
-
35
parser.parse path
-
end
-
-
1
def dispatcher(defaults)
-
34
@set.dispatcher defaults
-
end
-
end
-
-
# Invokes Journey::Router::Utils.normalize_path and ensure that
-
# (:locale) becomes (/:locale) instead of /(:locale). Except
-
# for root cases, where the latter is the correct one.
-
1
def self.normalize_path(path)
-
66
path = Journey::Router::Utils.normalize_path(path)
-
66
path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$}
-
66
path
-
end
-
-
1
def self.normalize_name(name)
-
7
normalize_path(name)[1..-1].tr("/", "_")
-
end
-
-
1
module Base
-
# You can specify what Rails should route "/" to with the root method:
-
#
-
# root to: 'pages#main'
-
#
-
# For options, see +match+, as +root+ uses it internally.
-
#
-
# You can also pass a string which will expand
-
#
-
# root 'pages#main'
-
#
-
# You should put the root route at the top of <tt>config/routes.rb</tt>,
-
# because this means it will be matched first. As this is the most popular route
-
# of most Rails applications, this is beneficial.
-
1
def root(options = {})
-
1
match '/', { :as => :root, :via => :get }.merge!(options)
-
end
-
-
# Matches a url pattern to one or more routes.
-
#
-
# You should not use the +match+ method in your router
-
# without specifying an HTTP method.
-
#
-
# If you want to expose your action to both GET and POST, use:
-
#
-
# # sets :controller, :action and :id in params
-
# match ':controller/:action/:id', via: [:get, :post]
-
#
-
# Note that +:controller+, +:action+ and +:id+ are interpreted as url
-
# query parameters and thus available through +params+ in an action.
-
#
-
# If you want to expose your action to GET, use +get+ in the router:
-
#
-
# Instead of:
-
#
-
# match ":controller/:action/:id"
-
#
-
# Do:
-
#
-
# get ":controller/:action/:id"
-
#
-
# Two of these symbols are special, +:controller+ maps to the controller
-
# and +:action+ to the controller's action. A pattern can also map
-
# wildcard segments (globs) to params:
-
#
-
# get 'songs/*category/:title', to: 'songs#show'
-
#
-
# # 'songs/rock/classic/stairway-to-heaven' sets
-
# # params[:category] = 'rock/classic'
-
# # params[:title] = 'stairway-to-heaven'
-
#
-
# To match a wildcard parameter, it must have a name assigned to it.
-
# Without a variable name to attach the glob parameter to, the route
-
# can't be parsed.
-
#
-
# When a pattern points to an internal route, the route's +:action+ and
-
# +:controller+ should be set in options or hash shorthand. Examples:
-
#
-
# match 'photos/:id' => 'photos#show', via: :get
-
# match 'photos/:id', to: 'photos#show', via: :get
-
# match 'photos/:id', controller: 'photos', action: 'show', via: :get
-
#
-
# A pattern can also point to a +Rack+ endpoint i.e. anything that
-
# responds to +call+:
-
#
-
# match 'photos/:id', to: lambda {|hash| [200, {}, ["Coming soon"]] }, via: :get
-
# match 'photos/:id', to: PhotoRackApp, via: :get
-
# # Yes, controller actions are just rack endpoints
-
# match 'photos/:id', to: PhotosController.action(:show), via: :get
-
#
-
# Because requesting various HTTP verbs with a single action has security
-
# implications, you must either specify the actions in
-
# the via options or use one of the HttpHelpers[rdoc-ref:HttpHelpers]
-
# instead +match+
-
#
-
# === Options
-
#
-
# Any options not seen here are passed on as params with the url.
-
#
-
# [:controller]
-
# The route's controller.
-
#
-
# [:action]
-
# The route's action.
-
#
-
# [:param]
-
# Overrides the default resource identifier +:id+ (name of the
-
# dynamic segment used to generate the routes).
-
# You can access that segment from your controller using
-
# <tt>params[<:param>]</tt>.
-
#
-
# [:path]
-
# The path prefix for the routes.
-
#
-
# [:module]
-
# The namespace for :controller.
-
#
-
# match 'path', to: 'c#a', module: 'sekret', controller: 'posts', via: :get
-
# # => Sekret::PostsController
-
#
-
# See <tt>Scoping#namespace</tt> for its scope equivalent.
-
#
-
# [:as]
-
# The name used to generate routing helpers.
-
#
-
# [:via]
-
# Allowed HTTP verb(s) for route.
-
#
-
# match 'path', to: 'c#a', via: :get
-
# match 'path', to: 'c#a', via: [:get, :post]
-
# match 'path', to: 'c#a', via: :all
-
#
-
# [:to]
-
# Points to a +Rack+ endpoint. Can be an object that responds to
-
# +call+ or a string representing a controller's action.
-
#
-
# match 'path', to: 'controller#action', via: :get
-
# match 'path', to: lambda { |env| [200, {}, ["Success!"]] }, via: :get
-
# match 'path', to: RackApp, via: :get
-
#
-
# [:on]
-
# Shorthand for wrapping routes in a specific RESTful context. Valid
-
# values are +:member+, +:collection+, and +:new+. Only use within
-
# <tt>resource(s)</tt> block. For example:
-
#
-
# resource :bar do
-
# match 'foo', to: 'c#a', on: :member, via: [:get, :post]
-
# end
-
#
-
# Is equivalent to:
-
#
-
# resource :bar do
-
# member do
-
# match 'foo', to: 'c#a', via: [:get, :post]
-
# end
-
# end
-
#
-
# [:constraints]
-
# Constrains parameters with a hash of regular expressions
-
# or an object that responds to <tt>matches?</tt>. In addition, constraints
-
# other than path can also be specified with any object
-
# that responds to <tt>===</tt> (eg. String, Array, Range, etc.).
-
#
-
# match 'path/:id', constraints: { id: /[A-Z]\d{5}/ }, via: :get
-
#
-
# match 'json_only', constraints: { format: 'json' }, via: :get
-
#
-
# class Whitelist
-
# def matches?(request) request.remote_ip == '1.2.3.4' end
-
# end
-
# match 'path', to: 'c#a', constraints: Whitelist.new, via: :get
-
#
-
# See <tt>Scoping#constraints</tt> for more examples with its scope
-
# equivalent.
-
#
-
# [:defaults]
-
# Sets defaults for parameters
-
#
-
# # Sets params[:format] to 'jpg' by default
-
# match 'path', to: 'c#a', defaults: { format: 'jpg' }, via: :get
-
#
-
# See <tt>Scoping#defaults</tt> for its scope equivalent.
-
#
-
# [:anchor]
-
# Boolean to anchor a <tt>match</tt> pattern. Default is true. When set to
-
# false, the pattern matches any request prefixed with the given path.
-
#
-
# # Matches any request starting with 'path'
-
# match 'path', to: 'c#a', anchor: false, via: :get
-
#
-
# [:format]
-
# Allows you to specify the default value for optional +format+
-
# segment or disable it by supplying +false+.
-
1
def match(path, options=nil)
-
end
-
-
# Mount a Rack-based application to be used within the application.
-
#
-
# mount SomeRackApp, at: "some_route"
-
#
-
# Alternatively:
-
#
-
# mount(SomeRackApp => "some_route")
-
#
-
# For options, see +match+, as +mount+ uses it internally.
-
#
-
# All mounted applications come with routing helpers to access them.
-
# These are named after the class specified, so for the above example
-
# the helper is either +some_rack_app_path+ or +some_rack_app_url+.
-
# To customize this helper's name, use the +:as+ option:
-
#
-
# mount(SomeRackApp => "some_route", as: "exciting")
-
#
-
# This will generate the +exciting_path+ and +exciting_url+ helpers
-
# which can be used to navigate to this mounted app.
-
1
def mount(app, options = nil)
-
1
if options
-
path = options.delete(:at)
-
else
-
1
unless Hash === app
-
raise ArgumentError, "must be called with mount point"
-
end
-
-
1
options = app
-
2
app, path = options.find { |k, _| k.respond_to?(:call) }
-
1
options.delete(app) if app
-
end
-
-
1
raise "A rack application must be specified" unless path
-
-
1
rails_app = rails_app? app
-
1
options[:as] ||= app_name(app, rails_app)
-
-
1
target_as = name_for_action(options[:as], path)
-
1
options[:via] ||= :all
-
-
1
match(path, options.merge(:to => app, :anchor => false, :format => false))
-
-
1
define_generate_prefix(app, target_as) if rails_app
-
1
self
-
end
-
-
1
def default_url_options=(options)
-
@set.default_url_options = options
-
end
-
1
alias_method :default_url_options, :default_url_options=
-
-
1
def with_default_scope(scope, &block)
-
scope(scope) do
-
instance_exec(&block)
-
end
-
end
-
-
# Query if the following named route was already defined.
-
1
def has_named_route?(name)
-
@set.named_routes.routes[name.to_sym]
-
end
-
-
1
private
-
1
def rails_app?(app)
-
1
app.is_a?(Class) && app < Rails::Railtie
-
end
-
-
1
def app_name(app, rails_app)
-
1
if rails_app
-
app.railtie_name
-
1
elsif app.is_a?(Class)
-
class_name = app.name
-
ActiveSupport::Inflector.underscore(class_name).tr("/", "_")
-
end
-
end
-
-
1
def define_generate_prefix(app, name)
-
_route = @set.named_routes.get name
-
_routes = @set
-
app.routes.define_mounted_helper(name)
-
app.routes.extend Module.new {
-
def optimize_routes_generation?; false; end
-
define_method :find_script_name do |options|
-
if options.key? :script_name
-
super(options)
-
else
-
prefix_options = options.slice(*_route.segment_keys)
-
prefix_options[:relative_url_root] = ''.freeze
-
# we must actually delete prefix segment keys to avoid passing them to next url_for
-
_route.segment_keys.each { |k| options.delete(k) }
-
_routes.url_helpers.send("#{name}_path", prefix_options)
-
end
-
end
-
}
-
end
-
end
-
-
1
module HttpHelpers
-
# Define a route that only recognizes HTTP GET.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# get 'bacon', to: 'food#bacon'
-
1
def get(*args, &block)
-
17
map_method(:get, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP POST.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# post 'bacon', to: 'food#bacon'
-
1
def post(*args, &block)
-
4
map_method(:post, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP PATCH.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# patch 'bacon', to: 'food#bacon'
-
1
def patch(*args, &block)
-
4
map_method(:patch, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP PUT.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# put 'bacon', to: 'food#bacon'
-
1
def put(*args, &block)
-
4
map_method(:put, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP DELETE.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# delete 'broccoli', to: 'food#broccoli'
-
1
def delete(*args, &block)
-
4
map_method(:delete, args, &block)
-
end
-
-
1
private
-
1
def map_method(method, args, &block)
-
33
options = args.extract_options!
-
33
options[:via] = method
-
33
match(*args, options, &block)
-
33
self
-
end
-
end
-
-
# You may wish to organize groups of controllers under a namespace.
-
# Most commonly, you might group a number of administrative controllers
-
# under an +admin+ namespace. You would place these controllers under
-
# the <tt>app/controllers/admin</tt> directory, and you can group them
-
# together in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# This will create a number of routes for each of the posts and comments
-
# controller. For <tt>Admin::PostsController</tt>, Rails will create:
-
#
-
# GET /admin/posts
-
# GET /admin/posts/new
-
# POST /admin/posts
-
# GET /admin/posts/1
-
# GET /admin/posts/1/edit
-
# PATCH/PUT /admin/posts/1
-
# DELETE /admin/posts/1
-
#
-
# If you want to route /posts (without the prefix /admin) to
-
# <tt>Admin::PostsController</tt>, you could use
-
#
-
# scope module: "admin" do
-
# resources :posts
-
# end
-
#
-
# or, for a single case
-
#
-
# resources :posts, module: "admin"
-
#
-
# If you want to route /admin/posts to +PostsController+
-
# (without the <tt>Admin::</tt> module prefix), you could use
-
#
-
# scope "/admin" do
-
# resources :posts
-
# end
-
#
-
# or, for a single case
-
#
-
# resources :posts, path: "/admin/posts"
-
#
-
# In each of these cases, the named routes remain the same as if you did
-
# not use scope. In the last case, the following paths map to
-
# +PostsController+:
-
#
-
# GET /admin/posts
-
# GET /admin/posts/new
-
# POST /admin/posts
-
# GET /admin/posts/1
-
# GET /admin/posts/1/edit
-
# PATCH/PUT /admin/posts/1
-
# DELETE /admin/posts/1
-
1
module Scoping
-
# Scopes a set of routes to the given default options.
-
#
-
# Take the following route definition as an example:
-
#
-
# scope path: ":account_id", as: "account" do
-
# resources :projects
-
# end
-
#
-
# This generates helpers such as +account_projects_path+, just like +resources+ does.
-
# The difference here being that the routes generated are like /:account_id/projects,
-
# rather than /accounts/:account_id/projects.
-
#
-
# === Options
-
#
-
# Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>.
-
#
-
# # route /posts (without the prefix /admin) to <tt>Admin::PostsController</tt>
-
# scope module: "admin" do
-
# resources :posts
-
# end
-
#
-
# # prefix the posts resource's requests with '/admin'
-
# scope path: "/admin" do
-
# resources :posts
-
# end
-
#
-
# # prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+
-
# scope as: "sekret" do
-
# resources :posts
-
# end
-
1
def scope(*args)
-
16
options = args.extract_options!.dup
-
16
scope = {}
-
-
16
options[:path] = args.flatten.join('/') if args.any?
-
16
options[:constraints] ||= {}
-
-
16
unless nested_scope?
-
16
options[:shallow_path] ||= options[:path] if options.key?(:path)
-
16
options[:shallow_prefix] ||= options[:as] if options.key?(:as)
-
end
-
-
16
if options[:constraints].is_a?(Hash)
-
16
defaults = options[:constraints].select do
-
|k, v| URL_OPTIONS.include?(k) && (v.is_a?(String) || v.is_a?(Fixnum))
-
end
-
-
16
(options[:defaults] ||= {}).reverse_merge!(defaults)
-
else
-
block, options[:constraints] = options[:constraints], {}
-
end
-
-
16
@scope.options.each do |option|
-
208
if option == :blocks
-
16
value = block
-
elsif option == :options
-
16
value = options
-
else
-
176
value = options.delete(option)
-
end
-
-
208
if value
-
76
scope[option] = send("merge_#{option}_scope", @scope[option], value)
-
end
-
end
-
-
16
@scope = @scope.new scope
-
16
yield
-
16
self
-
ensure
-
16
@scope = @scope.parent
-
end
-
-
# Scopes routes to a specific controller
-
#
-
# controller "food" do
-
# match "bacon", action: "bacon"
-
# end
-
1
def controller(controller, options={})
-
options[:controller] = controller
-
scope(options) { yield }
-
end
-
-
# Scopes routes to a specific namespace. For example:
-
#
-
# namespace :admin do
-
# resources :posts
-
# end
-
#
-
# This generates the following routes:
-
#
-
# admin_posts GET /admin/posts(.:format) admin/posts#index
-
# admin_posts POST /admin/posts(.:format) admin/posts#create
-
# new_admin_post GET /admin/posts/new(.:format) admin/posts#new
-
# edit_admin_post GET /admin/posts/:id/edit(.:format) admin/posts#edit
-
# admin_post GET /admin/posts/:id(.:format) admin/posts#show
-
# admin_post PATCH/PUT /admin/posts/:id(.:format) admin/posts#update
-
# admin_post DELETE /admin/posts/:id(.:format) admin/posts#destroy
-
#
-
# === Options
-
#
-
# The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
-
# options all default to the name of the namespace.
-
#
-
# For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
-
# <tt>Resources#resources</tt>.
-
#
-
# # accessible through /sekret/posts rather than /admin/posts
-
# namespace :admin, path: "sekret" do
-
# resources :posts
-
# end
-
#
-
# # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
-
# namespace :admin, module: "sekret" do
-
# resources :posts
-
# end
-
#
-
# # generates +sekret_posts_path+ rather than +admin_posts_path+
-
# namespace :admin, as: "sekret" do
-
# resources :posts
-
# end
-
1
def namespace(path, options = {})
-
path = path.to_s
-
-
defaults = {
-
module: path,
-
path: options.fetch(:path, path),
-
as: options.fetch(:as, path),
-
shallow_path: options.fetch(:path, path),
-
shallow_prefix: options.fetch(:as, path)
-
}
-
-
scope(defaults.merge!(options)) { yield }
-
end
-
-
# === Parameter Restriction
-
# Allows you to constrain the nested routes based on a set of rules.
-
# For instance, in order to change the routes to allow for a dot character in the +id+ parameter:
-
#
-
# constraints(id: /\d+\.\d+/) do
-
# resources :posts
-
# end
-
#
-
# Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be.
-
# The +id+ parameter must match the constraint passed in for this example.
-
#
-
# You may use this to also restrict other parameters:
-
#
-
# resources :posts do
-
# constraints(post_id: /\d+\.\d+/) do
-
# resources :comments
-
# end
-
# end
-
#
-
# === Restricting based on IP
-
#
-
# Routes can also be constrained to an IP or a certain range of IP addresses:
-
#
-
# constraints(ip: /192\.168\.\d+\.\d+/) do
-
# resources :posts
-
# end
-
#
-
# Any user connecting from the 192.168.* range will be able to see this resource,
-
# where as any user connecting outside of this range will be told there is no such route.
-
#
-
# === Dynamic request matching
-
#
-
# Requests to routes can be constrained based on specific criteria:
-
#
-
# constraints(lambda { |req| req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do
-
# resources :iphones
-
# end
-
#
-
# You are able to move this logic out into a class if it is too complex for routes.
-
# This class must have a +matches?+ method defined on it which either returns +true+
-
# if the user should be given access to that route, or +false+ if the user should not.
-
#
-
# class Iphone
-
# def self.matches?(request)
-
# request.env["HTTP_USER_AGENT"] =~ /iPhone/
-
# end
-
# end
-
#
-
# An expected place for this code would be +lib/constraints+.
-
#
-
# This class is then used like this:
-
#
-
# constraints(Iphone) do
-
# resources :iphones
-
# end
-
1
def constraints(constraints = {})
-
scope(:constraints => constraints) { yield }
-
end
-
-
# Allows you to set default parameters for a route, such as this:
-
# defaults id: 'home' do
-
# match 'scoped_pages/(:id)', to: 'pages#show'
-
# end
-
# Using this, the +:id+ parameter here will default to 'home'.
-
1
def defaults(defaults = {})
-
scope(:defaults => defaults) { yield }
-
end
-
-
1
private
-
1
def merge_path_scope(parent, child) #:nodoc:
-
12
Mapper.normalize_path("#{parent}/#{child}")
-
end
-
-
1
def merge_shallow_path_scope(parent, child) #:nodoc:
-
12
Mapper.normalize_path("#{parent}/#{child}")
-
end
-
-
1
def merge_as_scope(parent, child) #:nodoc:
-
parent ? "#{parent}_#{child}" : child
-
end
-
-
1
def merge_shallow_prefix_scope(parent, child) #:nodoc:
-
parent ? "#{parent}_#{child}" : child
-
end
-
-
1
def merge_module_scope(parent, child) #:nodoc:
-
parent ? "#{parent}/#{child}" : child
-
end
-
-
1
def merge_controller_scope(parent, child) #:nodoc:
-
4
child
-
end
-
-
1
def merge_action_scope(parent, child) #:nodoc:
-
child
-
end
-
-
1
def merge_path_names_scope(parent, child) #:nodoc:
-
merge_options_scope(parent, child)
-
end
-
-
1
def merge_constraints_scope(parent, child) #:nodoc:
-
16
merge_options_scope(parent, child)
-
end
-
-
1
def merge_defaults_scope(parent, child) #:nodoc:
-
16
merge_options_scope(parent, child)
-
end
-
-
1
def merge_blocks_scope(parent, child) #:nodoc:
-
merged = parent ? parent.dup : []
-
merged << child if child
-
merged
-
end
-
-
1
def merge_options_scope(parent, child) #:nodoc:
-
48
(parent || {}).except(*override_keys(child)).merge!(child)
-
end
-
-
1
def merge_shallow_scope(parent, child) #:nodoc:
-
child ? true : false
-
end
-
-
1
def override_keys(child) #:nodoc:
-
48
child.key?(:only) || child.key?(:except) ? [:only, :except] : []
-
end
-
end
-
-
# Resource routing allows you to quickly declare all of the common routes
-
# for a given resourceful controller. Instead of declaring separate routes
-
# for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
-
# actions, a resourceful route declares them in a single line of code:
-
#
-
# resources :photos
-
#
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the profile of
-
# the currently logged in user. In this case, you can use a singular resource
-
# to map /profile (rather than /profile/:id) to the show action.
-
#
-
# resource :profile
-
#
-
# It's common to have resources that are logically children of other
-
# resources:
-
#
-
# resources :magazines do
-
# resources :ads
-
# end
-
#
-
# You may wish to organize groups of controllers under a namespace. Most
-
# commonly, you might group a number of administrative controllers under
-
# an +admin+ namespace. You would place these controllers under the
-
# <tt>app/controllers/admin</tt> directory, and you can group them together
-
# in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# By default the +:id+ parameter doesn't accept dots. If you need to
-
# use dots as part of the +:id+ parameter add a constraint which
-
# overrides this restriction, e.g:
-
#
-
# resources :articles, id: /[^\/]+/
-
#
-
# This allows any character other than a slash as part of your +:id+.
-
#
-
1
module Resources
-
# CANONICAL_ACTIONS holds all actions that does not need a prefix or
-
# a path appended since they fit properly in their scope level.
-
1
VALID_ON_OPTIONS = [:new, :collection, :member]
-
1
RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param, :concerns]
-
1
CANONICAL_ACTIONS = %w(index create new show update destroy)
-
-
1
class Resource #:nodoc:
-
1
attr_reader :controller, :path, :options, :param
-
-
1
def initialize(entities, options = {})
-
4
@name = entities.to_s
-
4
@path = (options[:path] || @name).to_s
-
4
@controller = (options[:controller] || @name).to_s
-
4
@as = options[:as]
-
4
@param = (options[:param] || :id).to_sym
-
4
@options = options
-
4
@shallow = false
-
end
-
-
1
def default_actions
-
28
[:index, :create, :new, :show, :update, :destroy, :edit]
-
end
-
-
1
def actions
-
28
if only = @options[:only]
-
Array(only).map(&:to_sym)
-
28
elsif except = @options[:except]
-
default_actions - Array(except).map(&:to_sym)
-
else
-
28
default_actions
-
end
-
end
-
-
1
def name
-
8
@as || @name
-
end
-
-
1
def plural
-
64
@plural ||= name.to_s
-
end
-
-
1
def singular
-
64
@singular ||= name.to_s.singularize
-
end
-
-
1
alias :member_name :singular
-
-
# Checks for uncountable plurals, and appends "_index" if the plural
-
# and singular form are the same.
-
1
def collection_name
-
32
singular == plural ? "#{plural}_index" : plural
-
end
-
-
1
def resource_scope
-
4
{ :controller => controller }
-
end
-
-
1
alias :collection_scope :path
-
-
1
def member_scope
-
4
"#{path}/:#{param}"
-
end
-
-
1
alias :shallow_scope :member_scope
-
-
1
def new_scope(new_path)
-
4
"#{path}/#{new_path}"
-
end
-
-
1
def nested_param
-
:"#{singular}_#{param}"
-
end
-
-
1
def nested_scope
-
"#{path}/:#{nested_param}"
-
end
-
-
1
def shallow=(value)
-
4
@shallow = value
-
end
-
-
1
def shallow?
-
@shallow
-
end
-
end
-
-
1
class SingletonResource < Resource #:nodoc:
-
1
def initialize(entities, options)
-
super
-
@as = nil
-
@controller = (options[:controller] || plural).to_s
-
@as = options[:as]
-
end
-
-
1
def default_actions
-
[:show, :create, :update, :destroy, :new, :edit]
-
end
-
-
1
def plural
-
@plural ||= name.to_s.pluralize
-
end
-
-
1
def singular
-
@singular ||= name.to_s
-
end
-
-
1
alias :member_name :singular
-
1
alias :collection_name :singular
-
-
1
alias :member_scope :path
-
1
alias :nested_scope :path
-
end
-
-
1
def resources_path_names(options)
-
@scope[:path_names].merge!(options)
-
end
-
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the
-
# profile of the currently logged in user. In this case, you can use
-
# a singular resource to map /profile (rather than /profile/:id) to
-
# the show action:
-
#
-
# resource :profile
-
#
-
# creates six different routes in your application, all mapping to
-
# the +Profiles+ controller (note that the controller is named after
-
# the plural):
-
#
-
# GET /profile/new
-
# POST /profile
-
# GET /profile
-
# GET /profile/edit
-
# PATCH/PUT /profile
-
# DELETE /profile
-
#
-
# === Options
-
# Takes same options as +resources+.
-
1
def resource(*resources, &block)
-
options = resources.extract_options!.dup
-
-
if apply_common_behavior_for(:resource, resources, options, &block)
-
return self
-
end
-
-
resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
-
yield if block_given?
-
-
concerns(options[:concerns]) if options[:concerns]
-
-
collection do
-
post :create
-
end if parent_resource.actions.include?(:create)
-
-
new do
-
get :new
-
end if parent_resource.actions.include?(:new)
-
-
set_member_mappings_for_resource
-
end
-
-
self
-
end
-
-
# In Rails, a resourceful route provides a mapping between HTTP verbs
-
# and URLs and controller actions. By convention, each action also maps
-
# to particular CRUD operations in a database. A single entry in the
-
# routing file, such as
-
#
-
# resources :photos
-
#
-
# creates seven different routes in your application, all mapping to
-
# the +Photos+ controller:
-
#
-
# GET /photos
-
# GET /photos/new
-
# POST /photos
-
# GET /photos/:id
-
# GET /photos/:id/edit
-
# PATCH/PUT /photos/:id
-
# DELETE /photos/:id
-
#
-
# Resources can also be nested infinitely by using this block syntax:
-
#
-
# resources :photos do
-
# resources :comments
-
# end
-
#
-
# This generates the following comments routes:
-
#
-
# GET /photos/:photo_id/comments
-
# GET /photos/:photo_id/comments/new
-
# POST /photos/:photo_id/comments
-
# GET /photos/:photo_id/comments/:id
-
# GET /photos/:photo_id/comments/:id/edit
-
# PATCH/PUT /photos/:photo_id/comments/:id
-
# DELETE /photos/:photo_id/comments/:id
-
#
-
# === Options
-
# Takes same options as <tt>Base#match</tt> as well as:
-
#
-
# [:path_names]
-
# Allows you to change the segment component of the +edit+ and +new+ actions.
-
# Actions not specified are not changed.
-
#
-
# resources :posts, path_names: { new: "brand_new" }
-
#
-
# The above example will now change /posts/new to /posts/brand_new
-
#
-
# [:path]
-
# Allows you to change the path prefix for the resource.
-
#
-
# resources :posts, path: 'postings'
-
#
-
# The resource and all segments will now route to /postings instead of /posts
-
#
-
# [:only]
-
# Only generate routes for the given actions.
-
#
-
# resources :cows, only: :show
-
# resources :cows, only: [:show, :index]
-
#
-
# [:except]
-
# Generate all routes except for the given actions.
-
#
-
# resources :cows, except: :show
-
# resources :cows, except: [:show, :index]
-
#
-
# [:shallow]
-
# Generates shallow routes for nested resource(s). When placed on a parent resource,
-
# generates shallow routes for all nested resources.
-
#
-
# resources :posts, shallow: true do
-
# resources :comments
-
# end
-
#
-
# Is the same as:
-
#
-
# resources :posts do
-
# resources :comments, except: [:show, :edit, :update, :destroy]
-
# end
-
# resources :comments, only: [:show, :edit, :update, :destroy]
-
#
-
# This allows URLs for resources that otherwise would be deeply nested such
-
# as a comment on a blog post like <tt>/posts/a-long-permalink/comments/1234</tt>
-
# to be shortened to just <tt>/comments/1234</tt>.
-
#
-
# [:shallow_path]
-
# Prefixes nested shallow routes with the specified path.
-
#
-
# scope shallow_path: "sekret" do
-
# resources :posts do
-
# resources :comments, shallow: true
-
# end
-
# end
-
#
-
# The +comments+ resource here will have the following routes generated for it:
-
#
-
# post_comments GET /posts/:post_id/comments(.:format)
-
# post_comments POST /posts/:post_id/comments(.:format)
-
# new_post_comment GET /posts/:post_id/comments/new(.:format)
-
# edit_comment GET /sekret/comments/:id/edit(.:format)
-
# comment GET /sekret/comments/:id(.:format)
-
# comment PATCH/PUT /sekret/comments/:id(.:format)
-
# comment DELETE /sekret/comments/:id(.:format)
-
#
-
# [:shallow_prefix]
-
# Prefixes nested shallow route names with specified prefix.
-
#
-
# scope shallow_prefix: "sekret" do
-
# resources :posts do
-
# resources :comments, shallow: true
-
# end
-
# end
-
#
-
# The +comments+ resource here will have the following routes generated for it:
-
#
-
# post_comments GET /posts/:post_id/comments(.:format)
-
# post_comments POST /posts/:post_id/comments(.:format)
-
# new_post_comment GET /posts/:post_id/comments/new(.:format)
-
# edit_sekret_comment GET /comments/:id/edit(.:format)
-
# sekret_comment GET /comments/:id(.:format)
-
# sekret_comment PATCH/PUT /comments/:id(.:format)
-
# sekret_comment DELETE /comments/:id(.:format)
-
#
-
# [:format]
-
# Allows you to specify the default value for optional +format+
-
# segment or disable it by supplying +false+.
-
#
-
# === Examples
-
#
-
# # routes call <tt>Admin::PostsController</tt>
-
# resources :posts, module: "admin"
-
#
-
# # resource actions are at /admin/posts.
-
# resources :posts, path: "admin/posts"
-
1
def resources(*resources, &block)
-
4
options = resources.extract_options!.dup
-
-
4
if apply_common_behavior_for(:resources, resources, options, &block)
-
return self
-
end
-
-
4
resource_scope(:resources, Resource.new(resources.pop, options)) do
-
4
yield if block_given?
-
-
4
concerns(options[:concerns]) if options[:concerns]
-
-
4
collection do
-
4
get :index if parent_resource.actions.include?(:index)
-
4
post :create if parent_resource.actions.include?(:create)
-
end
-
-
new do
-
4
get :new
-
4
end if parent_resource.actions.include?(:new)
-
-
4
set_member_mappings_for_resource
-
end
-
-
4
self
-
end
-
-
# To add a route to the collection:
-
#
-
# resources :photos do
-
# collection do
-
# get 'search'
-
# end
-
# end
-
#
-
# This will enable Rails to recognize paths such as <tt>/photos/search</tt>
-
# with GET, and route to the search action of +PhotosController+. It will also
-
# create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
-
# route helpers.
-
1
def collection
-
4
unless resource_scope?
-
raise ArgumentError, "can't use collection outside resource(s) scope"
-
end
-
-
4
with_scope_level(:collection) do
-
4
scope(parent_resource.collection_scope) do
-
4
yield
-
end
-
end
-
end
-
-
# To add a member route, add a member block into the resource block:
-
#
-
# resources :photos do
-
# member do
-
# get 'preview'
-
# end
-
# end
-
#
-
# This will recognize <tt>/photos/1/preview</tt> with GET, and route to the
-
# preview action of +PhotosController+. It will also create the
-
# <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
-
1
def member
-
4
unless resource_scope?
-
raise ArgumentError, "can't use member outside resource(s) scope"
-
end
-
-
4
with_scope_level(:member) do
-
4
if shallow?
-
shallow_scope(parent_resource.member_scope) { yield }
-
else
-
8
scope(parent_resource.member_scope) { yield }
-
end
-
end
-
end
-
-
1
def new
-
4
unless resource_scope?
-
raise ArgumentError, "can't use new outside resource(s) scope"
-
end
-
-
4
with_scope_level(:new) do
-
4
scope(parent_resource.new_scope(action_path(:new))) do
-
4
yield
-
end
-
end
-
end
-
-
1
def nested
-
unless resource_scope?
-
raise ArgumentError, "can't use nested outside resource(s) scope"
-
end
-
-
with_scope_level(:nested) do
-
if shallow? && shallow_nesting_depth >= 1
-
shallow_scope(parent_resource.nested_scope, nested_options) { yield }
-
else
-
scope(parent_resource.nested_scope, nested_options) { yield }
-
end
-
end
-
end
-
-
# See ActionDispatch::Routing::Mapper::Scoping#namespace
-
1
def namespace(path, options = {})
-
if resource_scope?
-
nested { super }
-
else
-
super
-
end
-
end
-
-
1
def shallow
-
scope(:shallow => true) do
-
yield
-
end
-
end
-
-
1
def shallow?
-
4
parent_resource.instance_of?(Resource) && @scope[:shallow]
-
end
-
-
# match 'path' => 'controller#action'
-
# match 'path', to: 'controller#action'
-
# match 'path', 'otherpath', on: :member, via: :get
-
1
def match(path, *rest)
-
35
if rest.empty? && Hash === path
-
options = path
-
path, to = options.find { |name, _value| name.is_a?(String) }
-
-
case to
-
when Symbol
-
options[:action] = to
-
when String
-
if to =~ /#/
-
options[:to] = to
-
else
-
options[:controller] = to
-
end
-
else
-
options[:to] = to
-
end
-
-
options.delete(path)
-
paths = [path]
-
else
-
35
options = rest.pop || {}
-
35
paths = [path] + rest
-
end
-
-
35
options[:anchor] = true unless options.key?(:anchor)
-
-
35
if options[:on] && !VALID_ON_OPTIONS.include?(options[:on])
-
raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
-
end
-
-
35
if @scope[:controller] && @scope[:action]
-
options[:to] ||= "#{@scope[:controller]}##{@scope[:action]}"
-
end
-
-
35
paths.each do |_path|
-
35
route_options = options.dup
-
35
route_options[:path] ||= _path if _path.is_a?(String)
-
-
35
path_without_format = _path.to_s.sub(/\(\.:format\)$/, '')
-
35
if using_match_shorthand?(path_without_format, route_options)
-
1
route_options[:to] ||= path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1')
-
1
route_options[:to].tr!("-", "_")
-
end
-
-
35
decomposed_match(_path, route_options)
-
end
-
35
self
-
end
-
-
1
def using_match_shorthand?(path, options)
-
35
path && (options[:to] || options[:action]).nil? && path =~ %r{^/?[-\w]+/[-\w/]+$}
-
end
-
-
1
def decomposed_match(path, options) # :nodoc:
-
35
if on = options.delete(:on)
-
send(on) { decomposed_match(path, options) }
-
else
-
35
case @scope.scope_level
-
when :resources
-
nested { decomposed_match(path, options) }
-
when :resource
-
member { decomposed_match(path, options) }
-
else
-
35
add_route(path, options)
-
end
-
end
-
end
-
-
1
def add_route(action, options) # :nodoc:
-
35
path = path_for_action(action, options.delete(:path))
-
35
raise ArgumentError, "path is required" if path.blank?
-
-
35
action = action.to_s.dup
-
-
35
if action =~ /^[\w\-\/]+$/
-
35
options[:action] ||= action.tr('-', '_') unless action.include?("/")
-
else
-
action = nil
-
end
-
-
35
as = if !options.fetch(:as, true) # if it's set to nil or false
-
1
options.delete(:as)
-
else
-
34
name_for_action(options.delete(:as), action)
-
end
-
-
35
mapping = Mapping.build(@scope, @set, URI.parser.escape(path), as, options)
-
35
app, conditions, requirements, defaults, as, anchor = mapping.to_route
-
35
@set.add_route(app, conditions, requirements, defaults, as, anchor)
-
end
-
-
1
def root(path, options={})
-
1
if path.is_a?(String)
-
1
options[:to] = path
-
elsif path.is_a?(Hash) and options.empty?
-
options = path
-
else
-
raise ArgumentError, "must be called with a path and/or options"
-
end
-
-
1
if @scope.resources?
-
with_scope_level(:root) do
-
scope(parent_resource.path) do
-
super(options)
-
end
-
end
-
else
-
1
super(options)
-
end
-
end
-
-
1
protected
-
-
1
def parent_resource #:nodoc:
-
147
@scope[:scope_level_resource]
-
end
-
-
1
def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
-
4
if resources.length > 1
-
resources.each { |r| send(method, r, options, &block) }
-
return true
-
end
-
-
4
if options.delete(:shallow)
-
shallow do
-
send(method, resources.pop, options, &block)
-
end
-
return true
-
end
-
-
4
if resource_scope?
-
nested { send(method, resources.pop, options, &block) }
-
return true
-
end
-
-
4
options.keys.each do |k|
-
(options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
-
end
-
-
4
scope_options = options.slice!(*RESOURCE_OPTIONS)
-
4
unless scope_options.empty?
-
scope(scope_options) do
-
send(method, resources.pop, options, &block)
-
end
-
return true
-
end
-
-
4
unless action_options?(options)
-
4
options.merge!(scope_action_options) if scope_action_options?
-
end
-
-
4
false
-
end
-
-
1
def action_options?(options) #:nodoc:
-
4
options[:only] || options[:except]
-
end
-
-
1
def scope_action_options? #:nodoc:
-
4
@scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
-
end
-
-
1
def scope_action_options #:nodoc:
-
@scope[:options].slice(:only, :except)
-
end
-
-
1
def resource_scope? #:nodoc:
-
16
@scope.resource_scope?
-
end
-
-
1
def resource_method_scope? #:nodoc:
-
66
@scope.resource_method_scope?
-
end
-
-
1
def nested_scope? #:nodoc:
-
16
@scope.nested?
-
end
-
-
1
def with_exclusive_scope
-
begin
-
@scope = @scope.new(:as => nil, :path => nil)
-
-
with_scope_level(:exclusive) do
-
yield
-
end
-
ensure
-
@scope = @scope.parent
-
end
-
end
-
-
1
def with_scope_level(kind)
-
16
@scope = @scope.new_level(kind)
-
16
yield
-
ensure
-
16
@scope = @scope.parent
-
end
-
-
1
def resource_scope(kind, resource) #:nodoc:
-
4
resource.shallow = @scope[:shallow]
-
4
@scope = @scope.new(:scope_level_resource => resource)
-
4
@nesting.push(resource)
-
-
4
with_scope_level(kind) do
-
8
scope(parent_resource.resource_scope) { yield }
-
end
-
ensure
-
4
@nesting.pop
-
4
@scope = @scope.parent
-
end
-
-
1
def nested_options #:nodoc:
-
options = { :as => parent_resource.member_name }
-
options[:constraints] = {
-
parent_resource.nested_param => param_constraint
-
} if param_constraint?
-
-
options
-
end
-
-
1
def nesting_depth #:nodoc:
-
@nesting.size
-
end
-
-
1
def shallow_nesting_depth #:nodoc:
-
@nesting.select(&:shallow?).size
-
end
-
-
1
def param_constraint? #:nodoc:
-
@scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp)
-
end
-
-
1
def param_constraint #:nodoc:
-
@scope[:constraints][parent_resource.param]
-
end
-
-
1
def canonical_action?(action) #:nodoc:
-
66
resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
-
end
-
-
1
def shallow_scope(path, options = {}) #:nodoc:
-
scope = { :as => @scope[:shallow_prefix],
-
:path => @scope[:shallow_path] }
-
@scope = @scope.new scope
-
-
scope(path, options) { yield }
-
ensure
-
@scope = @scope.parent
-
end
-
-
1
def path_for_action(action, path) #:nodoc:
-
35
if path.blank? && canonical_action?(action)
-
28
@scope[:path].to_s
-
else
-
7
"#{@scope[:path]}/#{action_path(action, path)}"
-
end
-
end
-
-
1
def action_path(name, path = nil) #:nodoc:
-
11
name = name.to_sym if name.is_a?(String)
-
11
path || @scope[:path_names][name] || name.to_s
-
end
-
-
1
def prefix_name_for_action(as, action) #:nodoc:
-
35
if as
-
1
prefix = as
-
elsif !canonical_action?(action)
-
6
prefix = action
-
end
-
-
35
if prefix && prefix != '/' && !prefix.empty?
-
7
Mapper.normalize_name prefix.to_s.tr('-', '_')
-
end
-
end
-
-
1
def name_for_action(as, action) #:nodoc:
-
35
prefix = prefix_name_for_action(as, action)
-
35
name_prefix = @scope[:as]
-
-
35
if parent_resource
-
32
return nil unless as || action
-
-
32
collection_name = parent_resource.collection_name
-
32
member_name = parent_resource.member_name
-
end
-
-
35
name = @scope.action_name(name_prefix, prefix, collection_name, member_name)
-
-
35
if candidate = name.compact.join("_").presence
-
# If a name was not explicitly given, we check if it is valid
-
# and return nil in case it isn't. Otherwise, we pass the invalid name
-
# forward so the underlying router engine treats it and raises an exception.
-
35
if as.nil?
-
34
candidate unless candidate !~ /\A[_a-z]/i || @set.named_routes.key?(candidate)
-
else
-
1
candidate
-
end
-
end
-
end
-
-
1
def set_member_mappings_for_resource
-
4
member do
-
4
get :edit if parent_resource.actions.include?(:edit)
-
4
get :show if parent_resource.actions.include?(:show)
-
4
if parent_resource.actions.include?(:update)
-
4
patch :update
-
4
put :update
-
end
-
4
delete :destroy if parent_resource.actions.include?(:destroy)
-
end
-
end
-
end
-
-
# Routing Concerns allow you to declare common routes that can be reused
-
# inside others resources and routes.
-
#
-
# concern :commentable do
-
# resources :comments
-
# end
-
#
-
# concern :image_attachable do
-
# resources :images, only: :index
-
# end
-
#
-
# These concerns are used in Resources routing:
-
#
-
# resources :messages, concerns: [:commentable, :image_attachable]
-
#
-
# or in a scope or namespace:
-
#
-
# namespace :posts do
-
# concerns :commentable
-
# end
-
1
module Concerns
-
# Define a routing concern using a name.
-
#
-
# Concerns may be defined inline, using a block, or handled by
-
# another object, by passing that object as the second parameter.
-
#
-
# The concern object, if supplied, should respond to <tt>call</tt>,
-
# which will receive two parameters:
-
#
-
# * The current mapper
-
# * A hash of options which the concern object may use
-
#
-
# Options may also be used by concerns defined in a block by accepting
-
# a block parameter. So, using a block, you might do something as
-
# simple as limit the actions available on certain resources, passing
-
# standard resource options through the concern:
-
#
-
# concern :commentable do |options|
-
# resources :comments, options
-
# end
-
#
-
# resources :posts, concerns: :commentable
-
# resources :archived_posts do
-
# # Don't allow comments on archived posts
-
# concerns :commentable, only: [:index, :show]
-
# end
-
#
-
# Or, using a callable object, you might implement something more
-
# specific to your application, which would be out of place in your
-
# routes file.
-
#
-
# # purchasable.rb
-
# class Purchasable
-
# def initialize(defaults = {})
-
# @defaults = defaults
-
# end
-
#
-
# def call(mapper, options = {})
-
# options = @defaults.merge(options)
-
# mapper.resources :purchases
-
# mapper.resources :receipts
-
# mapper.resources :returns if options[:returnable]
-
# end
-
# end
-
#
-
# # routes.rb
-
# concern :purchasable, Purchasable.new(returnable: true)
-
#
-
# resources :toys, concerns: :purchasable
-
# resources :electronics, concerns: :purchasable
-
# resources :pets do
-
# concerns :purchasable, returnable: false
-
# end
-
#
-
# Any routing helpers can be used inside a concern. If using a
-
# callable, they're accessible from the Mapper that's passed to
-
# <tt>call</tt>.
-
1
def concern(name, callable = nil, &block)
-
callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) }
-
@concerns[name] = callable
-
end
-
-
# Use the named concerns
-
#
-
# resources :posts do
-
# concerns :commentable
-
# end
-
#
-
# concerns also work in any routes helper that you want to use:
-
#
-
# namespace :posts do
-
# concerns :commentable
-
# end
-
1
def concerns(*args)
-
options = args.extract_options!
-
args.flatten.each do |name|
-
if concern = @concerns[name]
-
concern.call(self, options)
-
else
-
raise ArgumentError, "No concern named #{name} was found!"
-
end
-
end
-
end
-
end
-
-
1
class Scope # :nodoc:
-
1
OPTIONS = [:path, :shallow_path, :as, :shallow_prefix, :module,
-
:controller, :action, :path_names, :constraints,
-
:shallow, :blocks, :defaults, :options]
-
-
1
RESOURCE_SCOPES = [:resource, :resources]
-
1
RESOURCE_METHOD_SCOPES = [:collection, :member, :new]
-
-
1
attr_reader :parent, :scope_level
-
-
1
def initialize(hash, parent = {}, scope_level = nil)
-
38
@hash = hash
-
38
@parent = parent
-
38
@scope_level = scope_level
-
end
-
-
1
def nested?
-
16
scope_level == :nested
-
end
-
-
1
def resources?
-
1
scope_level == :resources
-
end
-
-
1
def resource_method_scope?
-
66
RESOURCE_METHOD_SCOPES.include? scope_level
-
end
-
-
1
def action_name(name_prefix, prefix, collection_name, member_name)
-
35
case scope_level
-
when :nested
-
[name_prefix, prefix]
-
when :collection
-
8
[prefix, name_prefix, collection_name]
-
when :new
-
4
[prefix, :new, name_prefix, member_name]
-
when :member
-
20
[prefix, name_prefix, member_name]
-
when :root
-
[name_prefix, collection_name, prefix]
-
else
-
3
[name_prefix, member_name, prefix]
-
end
-
end
-
-
1
def resource_scope?
-
16
RESOURCE_SCOPES.include? scope_level
-
end
-
-
1
def options
-
16
OPTIONS
-
end
-
-
1
def new(hash)
-
20
self.class.new hash, self, scope_level
-
end
-
-
1
def new_level(level)
-
16
self.class.new(self, self, level)
-
end
-
-
1
def fetch(key, &block)
-
724
@hash.fetch(key, &block)
-
end
-
-
1
def [](key)
-
3430
@hash.fetch(key) { @parent[key] }
-
end
-
-
1
def []=(k,v)
-
@hash[k] = v
-
end
-
end
-
-
1
def initialize(set) #:nodoc:
-
2
@set = set
-
2
@scope = Scope.new({ :path_names => @set.resources_path_names })
-
2
@concerns = {}
-
2
@nesting = []
-
end
-
-
1
include Base
-
1
include HttpHelpers
-
1
include Redirection
-
1
include Scoping
-
1
include Concerns
-
1
include Resources
-
end
-
end
-
end
-
1
require 'action_controller/model_naming'
-
-
1
module ActionDispatch
-
1
module Routing
-
# Polymorphic URL helpers are methods for smart resolution to a named route call when
-
# given an Active Record model instance. They are to be used in combination with
-
# ActionController::Resources.
-
#
-
# These methods are useful when you want to generate correct URL or path to a RESTful
-
# resource without having to know the exact type of the record in question.
-
#
-
# Nested resources and/or namespaces are also supported, as illustrated in the example:
-
#
-
# polymorphic_url([:admin, @article, @comment])
-
#
-
# results in:
-
#
-
# admin_article_comment_url(@article, @comment)
-
#
-
# == Usage within the framework
-
#
-
# Polymorphic URL helpers are used in a number of places throughout the \Rails framework:
-
#
-
# * <tt>url_for</tt>, so you can use it with a record as the argument, e.g.
-
# <tt>url_for(@article)</tt>;
-
# * ActionView::Helpers::FormHelper uses <tt>polymorphic_path</tt>, so you can write
-
# <tt>form_for(@article)</tt> without having to specify <tt>:url</tt> parameter for the form
-
# action;
-
# * <tt>redirect_to</tt> (which, in fact, uses <tt>url_for</tt>) so you can write
-
# <tt>redirect_to(post)</tt> in your controllers;
-
# * ActionView::Helpers::AtomFeedHelper, so you don't have to explicitly specify URLs
-
# for feed entries.
-
#
-
# == Prefixed polymorphic helpers
-
#
-
# In addition to <tt>polymorphic_url</tt> and <tt>polymorphic_path</tt> methods, a
-
# number of prefixed helpers are available as a shorthand to <tt>action: "..."</tt>
-
# in options. Those are:
-
#
-
# * <tt>edit_polymorphic_url</tt>, <tt>edit_polymorphic_path</tt>
-
# * <tt>new_polymorphic_url</tt>, <tt>new_polymorphic_path</tt>
-
#
-
# Example usage:
-
#
-
# edit_polymorphic_path(@post) # => "/posts/1/edit"
-
# polymorphic_path(@post, format: :pdf) # => "/posts/1.pdf"
-
#
-
# == Usage with mounted engines
-
#
-
# If you are using a mounted engine and you need to use a polymorphic_url
-
# pointing at the engine's routes, pass in the engine's route proxy as the first
-
# argument to the method. For example:
-
#
-
# polymorphic_url([blog, @post]) # calls blog.post_path(@post)
-
# form_for([blog, @post]) # => "/blog/posts/1"
-
#
-
1
module PolymorphicRoutes
-
1
include ActionController::ModelNaming
-
-
# Constructs a call to a named RESTful route for the given record and returns the
-
# resulting URL string. For example:
-
#
-
# # calls post_url(post)
-
# polymorphic_url(post) # => "http://example.com/posts/1"
-
# polymorphic_url([blog, post]) # => "http://example.com/blogs/1/posts/1"
-
# polymorphic_url([:admin, blog, post]) # => "http://example.com/admin/blogs/1/posts/1"
-
# polymorphic_url([user, :blog, post]) # => "http://example.com/users/1/blog/posts/1"
-
# polymorphic_url(Comment) # => "http://example.com/comments"
-
#
-
# ==== Options
-
#
-
# * <tt>:action</tt> - Specifies the action prefix for the named route:
-
# <tt>:new</tt> or <tt>:edit</tt>. Default is no prefix.
-
# * <tt>:routing_type</tt> - Allowed values are <tt>:path</tt> or <tt>:url</tt>.
-
# Default is <tt>:url</tt>.
-
#
-
# Also includes all the options from <tt>url_for</tt>. These include such
-
# things as <tt>:anchor</tt> or <tt>:trailing_slash</tt>. Example usage
-
# is given below:
-
#
-
# polymorphic_url([blog, post], anchor: 'my_anchor')
-
# # => "http://example.com/blogs/1/posts/1#my_anchor"
-
# polymorphic_url([blog, post], anchor: 'my_anchor', script_name: "/my_app")
-
# # => "http://example.com/my_app/blogs/1/posts/1#my_anchor"
-
#
-
# For all of these options, see the documentation for <tt>url_for</tt>.
-
#
-
# ==== Functionality
-
#
-
# # an Article record
-
# polymorphic_url(record) # same as article_url(record)
-
#
-
# # a Comment record
-
# polymorphic_url(record) # same as comment_url(record)
-
#
-
# # it recognizes new records and maps to the collection
-
# record = Comment.new
-
# polymorphic_url(record) # same as comments_url()
-
#
-
# # the class of a record will also map to the collection
-
# polymorphic_url(Comment) # same as comments_url()
-
#
-
1
def polymorphic_url(record_or_hash_or_array, options = {})
-
if Hash === record_or_hash_or_array
-
options = record_or_hash_or_array.merge(options)
-
record = options.delete :id
-
return polymorphic_url record, options
-
end
-
-
opts = options.dup
-
action = opts.delete :action
-
type = opts.delete(:routing_type) || :url
-
-
HelperMethodBuilder.polymorphic_method self,
-
record_or_hash_or_array,
-
action,
-
type,
-
opts
-
end
-
-
# Returns the path component of a URL for the given record. It uses
-
# <tt>polymorphic_url</tt> with <tt>routing_type: :path</tt>.
-
1
def polymorphic_path(record_or_hash_or_array, options = {})
-
8
if Hash === record_or_hash_or_array
-
options = record_or_hash_or_array.merge(options)
-
record = options.delete :id
-
return polymorphic_path record, options
-
end
-
-
8
opts = options.dup
-
8
action = opts.delete :action
-
8
type = :path
-
-
8
HelperMethodBuilder.polymorphic_method self,
-
record_or_hash_or_array,
-
action,
-
type,
-
opts
-
end
-
-
-
1
%w(edit new).each do |action|
-
2
module_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{action}_polymorphic_url(record_or_hash, options = {})
-
polymorphic_url_for_action("#{action}", record_or_hash, options)
-
end
-
-
def #{action}_polymorphic_path(record_or_hash, options = {})
-
polymorphic_path_for_action("#{action}", record_or_hash, options)
-
end
-
EOT
-
end
-
-
1
private
-
-
1
def polymorphic_url_for_action(action, record_or_hash, options)
-
polymorphic_url(record_or_hash, options.merge(:action => action))
-
end
-
-
1
def polymorphic_path_for_action(action, record_or_hash, options)
-
polymorphic_path(record_or_hash, options.merge(:action => action))
-
end
-
-
1
class HelperMethodBuilder # :nodoc:
-
1
CACHE = { 'path' => {}, 'url' => {} }
-
-
1
def self.get(action, type)
-
8
type = type.to_s
-
8
CACHE[type].fetch(action) { build action, type }
-
end
-
-
8
def self.url; CACHE['url'.freeze][nil]; end
-
12
def self.path; CACHE['path'.freeze][nil]; end
-
-
1
def self.build(action, type)
-
6
prefix = action ? "#{action}_" : ""
-
6
suffix = type
-
6
if action.to_s == 'new'
-
2
HelperMethodBuilder.singular prefix, suffix
-
else
-
4
HelperMethodBuilder.plural prefix, suffix
-
end
-
end
-
-
1
def self.singular(prefix, suffix)
-
2
new(->(name) { name.singular_route_key }, prefix, suffix)
-
end
-
-
1
def self.plural(prefix, suffix)
-
9
new(->(name) { name.route_key }, prefix, suffix)
-
end
-
-
1
def self.polymorphic_method(recipient, record_or_hash_or_array, action, type, options)
-
8
builder = get action, type
-
-
8
case record_or_hash_or_array
-
when Array
-
record_or_hash_or_array = record_or_hash_or_array.compact
-
if record_or_hash_or_array.empty?
-
raise ArgumentError, "Nil location provided. Can't build URI."
-
end
-
if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy)
-
recipient = record_or_hash_or_array.shift
-
end
-
-
method, args = builder.handle_list record_or_hash_or_array
-
when String, Symbol
-
method, args = builder.handle_string record_or_hash_or_array
-
when Class
-
method, args = builder.handle_class record_or_hash_or_array
-
-
when nil
-
raise ArgumentError, "Nil location provided. Can't build URI."
-
else
-
8
method, args = builder.handle_model record_or_hash_or_array
-
end
-
-
-
8
if options.empty?
-
8
recipient.send(method, *args)
-
else
-
recipient.send(method, *args, options)
-
end
-
end
-
-
1
attr_reader :suffix, :prefix
-
-
1
def initialize(key_strategy, prefix, suffix)
-
6
@key_strategy = key_strategy
-
6
@prefix = prefix
-
6
@suffix = suffix
-
end
-
-
1
def handle_string(record)
-
[get_method_for_string(record), []]
-
end
-
-
1
def handle_string_call(target, str)
-
target.send get_method_for_string str
-
end
-
-
1
def handle_class(klass)
-
[get_method_for_class(klass), []]
-
end
-
-
1
def handle_class_call(target, klass)
-
target.send get_method_for_class klass
-
end
-
-
1
def handle_model(record)
-
26
args = []
-
-
26
model = record.to_model
-
26
name = if model.persisted?
-
21
args << model
-
21
model.model_name.singular_route_key
-
else
-
5
@key_strategy.call model.model_name
-
end
-
-
26
named_route = prefix + "#{name}_#{suffix}"
-
-
26
[named_route, args]
-
end
-
-
1
def handle_model_call(target, model)
-
18
method, args = handle_model model
-
18
target.send(method, *args)
-
end
-
-
1
def handle_list(list)
-
record_list = list.dup
-
record = record_list.pop
-
-
args = []
-
-
route = record_list.map { |parent|
-
case parent
-
when Symbol, String
-
parent.to_s
-
when Class
-
args << parent
-
parent.model_name.singular_route_key
-
else
-
args << parent.to_model
-
parent.to_model.model_name.singular_route_key
-
end
-
}
-
-
route <<
-
case record
-
when Symbol, String
-
record.to_s
-
when Class
-
@key_strategy.call record.model_name
-
else
-
model = record.to_model
-
if model.persisted?
-
args << model
-
model.model_name.singular_route_key
-
else
-
@key_strategy.call model.model_name
-
end
-
end
-
-
route << suffix
-
-
named_route = prefix + route.join("_")
-
[named_route, args]
-
end
-
-
1
private
-
-
1
def get_method_for_class(klass)
-
name = @key_strategy.call klass.model_name
-
prefix + "#{name}_#{suffix}"
-
end
-
-
1
def get_method_for_string(str)
-
prefix + "#{str}_#{suffix}"
-
end
-
-
1
[nil, 'new', 'edit'].each do |action|
-
3
CACHE['url'][action] = build action, 'url'
-
3
CACHE['path'][action] = build action, 'path'
-
end
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/http/request'
-
1
require 'active_support/core_ext/uri'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'rack/utils'
-
1
require 'action_controller/metal/exceptions'
-
1
require 'action_dispatch/routing/endpoint'
-
-
1
module ActionDispatch
-
1
module Routing
-
1
class Redirect < Endpoint # :nodoc:
-
1
attr_reader :status, :block
-
-
1
def initialize(status, block)
-
@status = status
-
@block = block
-
end
-
-
1
def redirect?; true; end
-
-
1
def call(env)
-
serve Request.new env
-
end
-
-
1
def serve(req)
-
req.check_path_parameters!
-
uri = URI.parse(path(req.path_parameters, req))
-
-
unless uri.host
-
if relative_path?(uri.path)
-
uri.path = "#{req.script_name}/#{uri.path}"
-
elsif uri.path.empty?
-
uri.path = req.script_name.empty? ? "/" : req.script_name
-
end
-
end
-
-
uri.scheme ||= req.scheme
-
uri.host ||= req.host
-
uri.port ||= req.port unless req.standard_port?
-
-
body = %(<html><body>You are being <a href="#{ERB::Util.unwrapped_html_escape(uri.to_s)}">redirected</a>.</body></html>)
-
-
headers = {
-
'Location' => uri.to_s,
-
'Content-Type' => 'text/html',
-
'Content-Length' => body.length.to_s
-
}
-
-
[ status, headers, [body] ]
-
end
-
-
1
def path(params, request)
-
block.call params, request
-
end
-
-
1
def inspect
-
"redirect(#{status})"
-
end
-
-
1
private
-
1
def relative_path?(path)
-
path && !path.empty? && path[0] != '/'
-
end
-
-
1
def escape(params)
-
Hash[params.map{ |k,v| [k, Rack::Utils.escape(v)] }]
-
end
-
-
1
def escape_fragment(params)
-
Hash[params.map{ |k,v| [k, Journey::Router::Utils.escape_fragment(v)] }]
-
end
-
-
1
def escape_path(params)
-
Hash[params.map{ |k,v| [k, Journey::Router::Utils.escape_path(v)] }]
-
end
-
end
-
-
1
class PathRedirect < Redirect
-
1
URL_PARTS = /\A([^?]+)?(\?[^#]+)?(#.+)?\z/
-
-
1
def path(params, request)
-
if block.match(URL_PARTS)
-
path = interpolation_required?($1, params) ? $1 % escape_path(params) : $1
-
query = interpolation_required?($2, params) ? $2 % escape(params) : $2
-
fragment = interpolation_required?($3, params) ? $3 % escape_fragment(params) : $3
-
-
"#{path}#{query}#{fragment}"
-
else
-
interpolation_required?(block, params) ? block % escape(params) : block
-
end
-
end
-
-
1
def inspect
-
"redirect(#{status}, #{block})"
-
end
-
-
1
private
-
1
def interpolation_required?(string, params)
-
!params.empty? && string && string.match(/%\{\w*\}/)
-
end
-
end
-
-
1
class OptionRedirect < Redirect # :nodoc:
-
1
alias :options :block
-
-
1
def path(params, request)
-
url_options = {
-
:protocol => request.protocol,
-
:host => request.host,
-
:port => request.optional_port,
-
:path => request.path,
-
:params => request.query_parameters
-
}.merge! options
-
-
if !params.empty? && url_options[:path].match(/%\{\w*\}/)
-
url_options[:path] = (url_options[:path] % escape_path(params))
-
end
-
-
unless options[:host] || options[:domain]
-
if relative_path?(url_options[:path])
-
url_options[:path] = "/#{url_options[:path]}"
-
url_options[:script_name] = request.script_name
-
elsif url_options[:path].empty?
-
url_options[:path] = request.script_name.empty? ? "/" : ""
-
url_options[:script_name] = request.script_name
-
end
-
end
-
-
ActionDispatch::Http::URL.url_for url_options
-
end
-
-
1
def inspect
-
"redirect(#{status}, #{options.map{ |k,v| "#{k}: #{v}" }.join(', ')})"
-
end
-
end
-
-
1
module Redirection
-
-
# Redirect any path to another path:
-
#
-
# get "/stories" => redirect("/posts")
-
#
-
# You can also use interpolation in the supplied redirect argument:
-
#
-
# get 'docs/:article', to: redirect('/wiki/%{article}')
-
#
-
# Note that if you return a path without a leading slash then the url is prefixed with the
-
# current SCRIPT_NAME environment variable. This is typically '/' but may be different in
-
# a mounted engine or where the application is deployed to a subdirectory of a website.
-
#
-
# Alternatively you can use one of the other syntaxes:
-
#
-
# The block version of redirect allows for the easy encapsulation of any logic associated with
-
# the redirect in question. Either the params and request are supplied as arguments, or just
-
# params, depending of how many arguments your block accepts. A string is required as a
-
# return value.
-
#
-
# get 'jokes/:number', to: redirect { |params, request|
-
# path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp")
-
# "http://#{request.host_with_port}/#{path}"
-
# }
-
#
-
# Note that the +do end+ syntax for the redirect block wouldn't work, as Ruby would pass
-
# the block to +get+ instead of +redirect+. Use <tt>{ ... }</tt> instead.
-
#
-
# The options version of redirect allows you to supply only the parts of the url which need
-
# to change, it also supports interpolation of the path similar to the first example.
-
#
-
# get 'stores/:name', to: redirect(subdomain: 'stores', path: '/%{name}')
-
# get 'stores/:name(*all)', to: redirect(subdomain: 'stores', path: '/%{name}%{all}')
-
#
-
# Finally, an object which responds to call can be supplied to redirect, allowing you to reuse
-
# common redirect routes. The call method must accept two arguments, params and request, and return
-
# a string.
-
#
-
# get 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
-
#
-
1
def redirect(*args, &block)
-
options = args.extract_options!
-
status = options.delete(:status) || 301
-
path = args.shift
-
-
return OptionRedirect.new(status, options) if options.any?
-
return PathRedirect.new(status, path) if String === path
-
-
block = path if path.respond_to? :call
-
raise ArgumentError, "redirection argument not supported" unless block
-
Redirect.new status, block
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey'
-
1
require 'forwardable'
-
1
require 'thread_safe'
-
1
require 'active_support/concern'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'action_controller/metal/exceptions'
-
1
require 'action_dispatch/http/request'
-
1
require 'action_dispatch/routing/endpoint'
-
-
1
module ActionDispatch
-
1
module Routing
-
# :stopdoc:
-
1
class RouteSet
-
# Since the router holds references to many parts of the system
-
# like engines, controllers and the application itself, inspecting
-
# the route set can actually be really slow, therefore we default
-
# alias inspect to to_s.
-
1
alias inspect to_s
-
-
1
mattr_accessor :relative_url_root
-
-
1
class Dispatcher < Routing::Endpoint
-
1
def initialize(defaults)
-
34
@defaults = defaults
-
34
@controller_class_names = ThreadSafe::Cache.new
-
end
-
-
148
def dispatcher?; true; end
-
-
1
def serve(req)
-
66
req.check_path_parameters!
-
66
params = req.path_parameters
-
-
66
prepare_params!(params)
-
-
# Just raise undefined constant errors if a controller was specified as default.
-
66
unless controller = controller(params, @defaults.key?(:controller))
-
return [404, {'X-Cascade' => 'pass'}, []]
-
end
-
-
66
dispatch(controller, params[:action], req.env)
-
end
-
-
1
def prepare_params!(params)
-
66
normalize_controller!(params)
-
66
merge_default_action!(params)
-
end
-
-
# If this is a default_controller (i.e. a controller specified by the user)
-
# we should raise an error in case it's not found, because it usually means
-
# a user error. However, if the controller was retrieved through a dynamic
-
# segment, as in :controller(/:action), we should simply return nil and
-
# delegate the control back to Rack cascade. Besides, if this is not a default
-
# controller, it means we should respect the @scope[:module] parameter.
-
1
def controller(params, default_controller=true)
-
66
if params && params.key?(:controller)
-
66
controller_param = params[:controller]
-
66
controller_reference(controller_param)
-
end
-
rescue NameError => e
-
raise ActionController::RoutingError, e.message, e.backtrace if default_controller
-
end
-
-
1
private
-
-
1
def controller_reference(controller_param)
-
66
const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"
-
66
ActiveSupport::Dependencies.constantize(const_name)
-
end
-
-
1
def dispatch(controller, action, env)
-
66
controller.action(action).call(env)
-
end
-
-
1
def normalize_controller!(params)
-
66
params[:controller] = params[:controller].underscore if params.key?(:controller)
-
end
-
-
1
def merge_default_action!(params)
-
66
params[:action] ||= 'index'
-
end
-
end
-
-
# A NamedRouteCollection instance is a collection of named routes, and also
-
# maintains an anonymous module that can be used to install helpers for the
-
# named routes.
-
1
class NamedRouteCollection
-
1
include Enumerable
-
1
attr_reader :routes, :url_helpers_module
-
-
1
def initialize
-
1
@routes = {}
-
1
@path_helpers = Set.new
-
1
@url_helpers = Set.new
-
1
@url_helpers_module = Module.new
-
1
@path_helpers_module = Module.new
-
end
-
-
1
def route_defined?(name)
-
key = name.to_sym
-
@path_helpers.include?(key) || @url_helpers.include?(key)
-
end
-
-
1
def helpers
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
`named_routes.helpers` is deprecated, please use `route_defined?(route_name)`
-
to see if a named route was defined.
-
MSG
-
@path_helpers + @url_helpers
-
end
-
-
1
def helper_names
-
5
@path_helpers.map(&:to_s) + @url_helpers.map(&:to_s)
-
end
-
-
1
def clear!
-
1
@path_helpers.each do |helper|
-
@path_helpers_module.send :undef_method, helper
-
end
-
-
1
@url_helpers.each do |helper|
-
@url_helpers_module.send :undef_method, helper
-
end
-
-
1
@routes.clear
-
1
@path_helpers.clear
-
1
@url_helpers.clear
-
end
-
-
1
def add(name, route)
-
18
key = name.to_sym
-
18
path_name = :"#{name}_path"
-
18
url_name = :"#{name}_url"
-
-
18
if routes.key? key
-
@path_helpers_module.send :undef_method, path_name
-
@url_helpers_module.send :undef_method, url_name
-
end
-
18
routes[key] = route
-
18
define_url_helper @path_helpers_module, route, path_name, route.defaults, name, LEGACY
-
18
define_url_helper @url_helpers_module, route, url_name, route.defaults, name, UNKNOWN
-
-
18
@path_helpers << path_name
-
18
@url_helpers << url_name
-
end
-
-
1
def get(name)
-
20
routes[name.to_sym]
-
end
-
-
1
def key?(name)
-
34
routes.key? name.to_sym
-
end
-
-
1
alias []= add
-
1
alias [] get
-
1
alias clear clear!
-
-
1
def each
-
routes.each { |name, route| yield name, route }
-
self
-
end
-
-
1
def names
-
routes.keys
-
end
-
-
1
def length
-
routes.length
-
end
-
-
1
def path_helpers_module(warn = false)
-
12
if warn
-
mod = @path_helpers_module
-
helpers = @path_helpers
-
Module.new do
-
include mod
-
-
helpers.each do |meth|
-
define_method(meth) do |*args, &block|
-
ActiveSupport::Deprecation.warn("The method `#{meth}` cannot be used here as a full URL is required. Use `#{meth.to_s.sub(/_path$/, '_url')}` instead")
-
super(*args, &block)
-
end
-
end
-
end
-
else
-
12
@path_helpers_module
-
end
-
end
-
-
1
class UrlHelper
-
1
def self.create(route, options, route_name, url_strategy)
-
36
if optimize_helper?(route)
-
36
OptimizedUrlHelper.new(route, options, route_name, url_strategy)
-
else
-
new route, options, route_name, url_strategy
-
end
-
end
-
-
1
def self.optimize_helper?(route)
-
36
!route.glob? && route.path.requirements.empty?
-
end
-
-
1
attr_reader :url_strategy, :route_name
-
-
1
class OptimizedUrlHelper < UrlHelper
-
1
attr_reader :arg_size
-
-
1
def initialize(route, options, route_name, url_strategy)
-
36
super
-
36
@required_parts = @route.required_parts
-
36
@arg_size = @required_parts.size
-
end
-
-
1
def call(t, args, inner_options)
-
130
if args.size == arg_size && !inner_options && optimize_routes_generation?(t)
-
129
options = t.url_options.merge @options
-
129
options[:path] = optimized_helper(args)
-
129
url_strategy.call options
-
else
-
1
super
-
end
-
end
-
-
1
private
-
-
1
def optimized_helper(args)
-
129
params = parameterize_args(args)
-
129
missing_keys = missing_keys(params)
-
-
129
unless missing_keys.empty?
-
raise_generation_error(params, missing_keys)
-
end
-
-
129
@route.format params
-
end
-
-
1
def optimize_routes_generation?(t)
-
129
t.send(:optimize_routes_generation?)
-
end
-
-
1
def parameterize_args(args)
-
129
params = {}
-
207
@required_parts.zip(args.map(&:to_param)) { |k,v| params[k] = v }
-
129
params
-
end
-
-
1
def missing_keys(args)
-
207
args.select{ |part, arg| arg.nil? || arg.empty? }.keys
-
end
-
-
1
def raise_generation_error(args, missing_keys)
-
constraints = Hash[@route.requirements.merge(args).sort_by{|k,v| k.to_s}]
-
message = "No route matches #{constraints.inspect}"
-
message << " missing required keys: #{missing_keys.sort.inspect}"
-
-
raise ActionController::UrlGenerationError, message
-
end
-
end
-
-
1
def initialize(route, options, route_name, url_strategy)
-
36
@options = options
-
36
@segment_keys = route.segment_keys.uniq
-
36
@route = route
-
36
@url_strategy = url_strategy
-
36
@route_name = route_name
-
end
-
-
1
def call(t, args, inner_options)
-
1
controller_options = t.url_options
-
1
options = controller_options.merge @options
-
1
hash = handle_positional_args(controller_options,
-
deprecate_string_options(inner_options) || {},
-
args,
-
options,
-
@segment_keys)
-
-
1
t._routes.url_for(hash, route_name, url_strategy)
-
end
-
-
1
def handle_positional_args(controller_options, inner_options, args, result, path_params)
-
1
if args.size > 0
-
# take format into account
-
if path_params.include?(:format)
-
path_params_size = path_params.size - 1
-
else
-
path_params_size = path_params.size
-
end
-
-
if args.size < path_params_size
-
path_params -= controller_options.keys
-
path_params -= result.keys
-
end
-
path_params.each { |param|
-
value = inner_options.fetch(param) { args.shift }
-
-
unless param == :format && value.nil?
-
result[param] = value
-
end
-
}
-
end
-
-
1
result.merge!(inner_options)
-
end
-
-
1
DEPRECATED_STRING_OPTIONS = %w[controller action]
-
-
1
def deprecate_string_options(options)
-
1
options ||= {}
-
1
deprecated_string_options = options.keys & DEPRECATED_STRING_OPTIONS
-
1
if deprecated_string_options.any?
-
msg = "Calling URL helpers with string keys #{deprecated_string_options.join(", ")} is deprecated. Use symbols instead."
-
ActiveSupport::Deprecation.warn(msg)
-
deprecated_string_options.each do |option|
-
value = options.delete(option)
-
options[option.to_sym] = value
-
end
-
end
-
1
options
-
end
-
end
-
-
1
private
-
# Create a url helper allowing ordered parameters to be associated
-
# with corresponding dynamic segments, so you can do:
-
#
-
# foo_url(bar, baz, bang)
-
#
-
# Instead of:
-
#
-
# foo_url(bar: bar, baz: baz, bang: bang)
-
#
-
# Also allow options hash, so you can do:
-
#
-
# foo_url(bar, baz, bang, sort_by: 'baz')
-
#
-
1
def define_url_helper(mod, route, name, opts, route_key, url_strategy)
-
36
helper = UrlHelper.create(route, opts, route_key, url_strategy)
-
36
mod.module_eval do
-
36
define_method(name) do |*args|
-
130
options = nil
-
130
options = args.pop if args.last.is_a? Hash
-
130
helper.call self, args, options
-
end
-
end
-
end
-
end
-
-
# strategy for building urls to send to the client
-
123
PATH = ->(options) { ActionDispatch::Http::URL.path_for(options) }
-
1
FULL = ->(options) { ActionDispatch::Http::URL.full_url_for(options) }
-
156
UNKNOWN = ->(options) { ActionDispatch::Http::URL.url_for(options) }
-
1
LEGACY = ->(options) {
-
122
if options.key?(:only_path)
-
if options[:only_path]
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
You are calling a `*_path` helper with the `only_path` option
-
explicitly set to `true`. This option will stop working on
-
path helpers in Rails 5. Simply remove the `only_path: true`
-
argument from your call as it is redundant when applied to a
-
path helper.
-
MSG
-
-
PATH.call(options)
-
else
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
You are calling a `*_path` helper with the `only_path` option
-
explicitly set to `false`. This option will stop working on
-
path helpers in Rails 5. Use the corresponding `*_url` helper
-
instead.
-
MSG
-
-
FULL.call(options)
-
end
-
else
-
122
PATH.call(options)
-
end
-
}
-
-
1
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
-
1
attr_accessor :disable_clear_and_finalize, :resources_path_names
-
1
attr_accessor :default_url_options, :request_class
-
-
1
alias :routes :set
-
-
1
def self.default_resources_path_names
-
1
{ :new => 'new', :edit => 'edit' }
-
end
-
-
1
def initialize(request_class = ActionDispatch::Request)
-
1
self.named_routes = NamedRouteCollection.new
-
1
self.resources_path_names = self.class.default_resources_path_names
-
1
self.default_url_options = {}
-
1
self.request_class = request_class
-
-
1
@append = []
-
1
@prepend = []
-
1
@disable_clear_and_finalize = false
-
1
@finalized = false
-
-
1
@set = Journey::Routes.new
-
1
@router = Journey::Router.new @set
-
1
@formatter = Journey::Formatter.new @set
-
end
-
-
1
def draw(&block)
-
1
clear! unless @disable_clear_and_finalize
-
1
eval_block(block)
-
1
finalize! unless @disable_clear_and_finalize
-
nil
-
end
-
-
1
def append(&block)
-
@append << block
-
end
-
-
1
def prepend(&block)
-
1
@prepend << block
-
end
-
-
1
def eval_block(block)
-
2
if block.arity == 1
-
raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
-
"Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
-
end
-
2
mapper = Mapper.new(self)
-
2
if default_scope
-
mapper.with_default_scope(default_scope, &block)
-
else
-
2
mapper.instance_exec(&block)
-
end
-
end
-
1
private :eval_block
-
-
1
def finalize!
-
1
return if @finalized
-
1
@append.each { |blk| eval_block(blk) }
-
1
@finalized = true
-
end
-
-
1
def clear!
-
1
@finalized = false
-
1
named_routes.clear
-
1
set.clear
-
1
formatter.clear
-
2
@prepend.each { |blk| eval_block(blk) }
-
end
-
-
1
def dispatcher(defaults)
-
34
Routing::RouteSet::Dispatcher.new(defaults)
-
end
-
-
1
module MountedHelpers
-
1
extend ActiveSupport::Concern
-
1
include UrlFor
-
end
-
-
# Contains all the mounted helpers across different
-
# engines and the `main_app` helper for the application.
-
# You can include this in your classes if you want to
-
# access routes for other engines.
-
1
def mounted_helpers
-
8
MountedHelpers
-
end
-
-
1
def define_mounted_helper(name)
-
1
return if MountedHelpers.method_defined?(name)
-
-
1
routes = self
-
1
MountedHelpers.class_eval do
-
1
define_method "_#{name}" do
-
RoutesProxy.new(routes, _routes_context)
-
end
-
end
-
-
1
MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
-
def #{name}
-
@_#{name} ||= _#{name}
-
end
-
RUBY
-
end
-
-
1
def url_helpers(supports_path = true)
-
12
routes = self
-
-
12
Module.new do
-
12
extend ActiveSupport::Concern
-
12
include UrlFor
-
-
# Define url_for in the singleton level so one can do:
-
# Rails.application.routes.url_helpers.url_for(args)
-
12
@_routes = routes
-
12
class << self
-
12
delegate :url_for, :optimize_routes_generation?, to: '@_routes'
-
12
attr_reader :_routes
-
12
def url_options; {}; end
-
end
-
-
12
url_helpers = routes.named_routes.url_helpers_module
-
-
# Make named_routes available in the module singleton
-
# as well, so one can do:
-
# Rails.application.routes.url_helpers.posts_path
-
12
extend url_helpers
-
-
# Any class that includes this module will get all
-
# named routes...
-
12
include url_helpers
-
-
12
if supports_path
-
12
path_helpers = routes.named_routes.path_helpers_module
-
else
-
path_helpers = routes.named_routes.path_helpers_module(true)
-
end
-
-
12
include path_helpers
-
12
extend path_helpers
-
-
# plus a singleton class method called _routes ...
-
12
included do
-
27
singleton_class.send(:redefine_method, :_routes) { routes }
-
end
-
-
# And an instance method _routes. Note that
-
# UrlFor (included in this module) add extra
-
# conveniences for working with @_routes.
-
565
define_method(:_routes) { @_routes || routes }
-
-
12
define_method(:_generate_paths_by_default) do
-
158
supports_path
-
end
-
-
12
private :_generate_paths_by_default
-
end
-
end
-
-
1
def empty?
-
routes.empty?
-
end
-
-
1
def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
-
35
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
-
-
35
if name && named_routes[name]
-
raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
-
"You may have defined two routes with the same name using the `:as` option, or " \
-
"you may be overriding a route already defined by a resource with the same naming. " \
-
"For the latter, you can restrict the routes created with `resources` as explained here: \n" \
-
"http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
-
end
-
-
35
path = conditions.delete :path_info
-
35
ast = conditions.delete :parsed_path_info
-
35
path = build_path(path, ast, requirements, anchor)
-
88
conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
-
-
35
route = @set.add_route(app, path, conditions, defaults, name)
-
35
named_routes[name] = route if name
-
35
route
-
end
-
-
1
def build_path(path, ast, requirements, anchor)
-
35
strexp = Journey::Router::Strexp.new(
-
ast,
-
path,
-
requirements,
-
SEPARATORS,
-
anchor)
-
-
35
pattern = Journey::Path::Pattern.new(strexp)
-
-
35
builder = Journey::GTG::Builder.new pattern.spec
-
-
# Get all the symbol nodes followed by literals that are not the
-
# dummy node.
-
35
symbols = pattern.spec.grep(Journey::Nodes::Symbol).find_all { |n|
-
53
builder.followpos(n).first.literal?
-
}
-
-
# Get all the symbol nodes preceded by literals.
-
35
symbols.concat pattern.spec.find_all(&:literal?).map { |n|
-
43
builder.followpos(n).first
-
}.find_all(&:symbol?)
-
-
35
symbols.each { |x|
-
x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
-
}
-
-
35
pattern
-
end
-
1
private :build_path
-
-
1
def build_conditions(current_conditions, path_values)
-
35
conditions = current_conditions.dup
-
-
# Rack-Mount requires that :request_method be a regular expression.
-
# :request_method represents the HTTP verb that matches this route.
-
#
-
# Here we munge values before they get sent on to rack-mount.
-
35
verbs = conditions[:request_method] || []
-
35
unless verbs.empty?
-
34
conditions[:request_method] = %r[^#{verbs.join('|')}$]
-
end
-
-
35
conditions.keep_if do |k, _|
-
69
k == :action || k == :controller || k == :required_defaults ||
-
@request_class.public_method_defined?(k) || path_values.include?(k)
-
end
-
end
-
1
private :build_conditions
-
-
1
class Generator
-
1
PARAMETERIZE = lambda do |name, value|
-
1
if name == :controller
-
value
-
elsif value.is_a?(Array)
-
value.map { |v| v.to_param }.join('/')
-
elsif param = value.to_param
-
1
param
-
end
-
end
-
-
1
attr_reader :options, :recall, :set, :named_route
-
-
1
def initialize(named_route, options, recall, set)
-
148
@named_route = named_route
-
148
@options = options.dup
-
148
@recall = recall.dup
-
148
@set = set
-
-
148
normalize_recall!
-
148
normalize_options!
-
148
normalize_controller_action_id!
-
148
use_relative_controller!
-
148
normalize_controller!
-
148
normalize_action!
-
end
-
-
1
def controller
-
672
@options[:controller]
-
end
-
-
1
def current_controller
-
335
@recall[:controller]
-
end
-
-
1
def use_recall_for(key)
-
254
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
-
107
if !named_route_exists? || segment_keys.include?(key)
-
106
@options[key] = @recall.delete(key)
-
end
-
end
-
end
-
-
# Set 'index' as default action for recall
-
1
def normalize_recall!
-
148
@recall[:action] ||= 'index'
-
end
-
-
1
def normalize_options!
-
# If an explicit :controller was given, always make :action explicit
-
# too, so that action expiry works as expected for things like
-
#
-
# generate({controller: 'content'}, {controller: 'content', action: 'show'})
-
#
-
# (the above is from the unit tests). In the above case, because the
-
# controller was explicitly given, but no action, the action is implied to
-
# be "index", not the recalled action of "show".
-
-
148
if options[:controller]
-
108
options[:action] ||= 'index'
-
108
options[:controller] = options[:controller].to_s
-
end
-
-
148
if options.key?(:action)
-
108
options[:action] = (options[:action] || 'index').to_s
-
end
-
end
-
-
# This pulls :controller, :action, and :id out of the recall.
-
# The recall key is only used if there is no key in the options
-
# or if the key in the options is identical. If any of
-
# :controller, :action or :id is not found, don't pull any
-
# more keys from the recall.
-
1
def normalize_controller_action_id!
-
148
use_recall_for(:controller) or return
-
53
use_recall_for(:action) or return
-
53
use_recall_for(:id)
-
end
-
-
# if the current controller is "foo/bar/baz" and controller: "baz/bat"
-
# is specified, the controller becomes "foo/baz/bat"
-
1
def use_relative_controller!
-
148
if !named_route && different_controller? && !controller.start_with?("/")
-
94
old_parts = current_controller.split('/')
-
94
size = controller.count("/") + 1
-
94
parts = old_parts[0...-size] << controller
-
94
@options[:controller] = parts.join("/")
-
end
-
end
-
-
# Remove leading slashes from controllers
-
1
def normalize_controller!
-
148
@options[:controller] = controller.sub(%r{^/}, '') if controller
-
end
-
-
# Move 'index' action from options to recall
-
1
def normalize_action!
-
148
if @options[:action] == 'index'
-
147
@recall[:action] = @options.delete(:action)
-
end
-
end
-
-
# Generates a path from routes, returns [path, params].
-
# If no route is generated the formatter will raise ActionController::UrlGenerationError
-
1
def generate
-
148
@set.formatter.generate(named_route, options, recall, PARAMETERIZE)
-
end
-
-
1
def different_controller?
-
147
return false unless current_controller
-
94
controller.to_param != current_controller.to_param
-
end
-
-
1
private
-
1
def named_route_exists?
-
107
named_route && set.named_routes[named_route]
-
end
-
-
1
def segment_keys
-
1
set.named_routes[named_route].segment_keys
-
end
-
end
-
-
# Generate the path indicated by the arguments, and return an array of
-
# the keys that were not used to generate it.
-
1
def extra_keys(options, recall={})
-
generate_extras(options, recall).last
-
end
-
-
1
def generate_extras(options, recall={})
-
route_key = options.delete :use_route
-
path, params = generate(route_key, options, recall)
-
return path, params.keys
-
end
-
-
1
def generate(route_key, options, recall = {})
-
148
Generator.new(route_key, options, recall, self).generate
-
end
-
1
private :generate
-
-
1
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
-
:trailing_slash, :anchor, :params, :only_path, :script_name,
-
:original_script_name, :relative_url_root]
-
-
1
def optimize_routes_generation?
-
129
default_url_options.empty?
-
end
-
-
1
def find_script_name(options)
-
148
options.delete(:script_name) || find_relative_url_root(options) || ''
-
end
-
-
1
def find_relative_url_root(options)
-
options.delete(:relative_url_root) || relative_url_root
-
end
-
-
1
def path_for(options, route_name = nil)
-
url_for(options, route_name, PATH)
-
end
-
-
# The +options+ argument must be a hash whose keys are *symbols*.
-
1
def url_for(options, route_name = nil, url_strategy = UNKNOWN)
-
148
options = default_url_options.merge options
-
-
148
user = password = nil
-
-
148
if options[:user] && options[:password]
-
user = options.delete :user
-
password = options.delete :password
-
end
-
-
148
recall = options.delete(:_recall) { {} }
-
-
148
original_script_name = options.delete(:original_script_name)
-
148
script_name = find_script_name options
-
-
148
if original_script_name
-
script_name = original_script_name + script_name
-
end
-
-
148
path_options = options.dup
-
2072
RESERVED_OPTIONS.each { |ro| path_options.delete ro }
-
-
148
path, params = generate(route_name, path_options, recall)
-
-
148
if options.key? :params
-
params.merge! options[:params]
-
end
-
-
148
options[:path] = path
-
148
options[:script_name] = script_name
-
148
options[:params] = params
-
148
options[:user] = user
-
148
options[:password] = password
-
-
148
url_strategy.call options
-
end
-
-
1
def call(env)
-
66
req = request_class.new(env)
-
66
req.path_info = Journey::Router::Utils.normalize_path(req.path_info)
-
66
@router.serve(req)
-
end
-
-
1
def recognize_path(path, environment = {})
-
method = (environment[:method] || "GET").to_s.upcase
-
path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
-
extras = environment[:extras] || {}
-
-
begin
-
env = Rack::MockRequest.env_for(path, {:method => method})
-
rescue URI::InvalidURIError => e
-
raise ActionController::RoutingError, e.message
-
end
-
-
req = request_class.new(env)
-
@router.recognize(req) do |route, params|
-
params.merge!(extras)
-
params.each do |key, value|
-
if value.is_a?(String)
-
value = value.dup.force_encoding(Encoding::BINARY)
-
params[key] = URI.parser.unescape(value)
-
end
-
end
-
old_params = req.path_parameters
-
req.path_parameters = old_params.merge params
-
app = route.app
-
if app.matches?(req) && app.dispatcher?
-
dispatcher = app.app
-
-
if dispatcher.controller(params, false)
-
dispatcher.prepare_params!(params)
-
return params
-
else
-
raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller"
-
end
-
end
-
end
-
-
raise ActionController::RoutingError, "No route matches #{path.inspect}"
-
end
-
end
-
# :startdoc:
-
end
-
end
-
1
module ActionDispatch
-
1
module Routing
-
# In <tt>config/routes.rb</tt> you define URL-to-controller mappings, but the reverse
-
# is also possible: an URL can be generated from one of your routing definitions.
-
# URL generation functionality is centralized in this module.
-
#
-
# See ActionDispatch::Routing for general information about routing and routes.rb.
-
#
-
# <b>Tip:</b> If you need to generate URLs from your models or some other place,
-
# then ActionController::UrlFor is what you're looking for. Read on for
-
# an introduction. In general, this module should not be included on its own,
-
# as it is usually included by url_helpers (as in Rails.application.routes.url_helpers).
-
#
-
# == URL generation from parameters
-
#
-
# As you may know, some functions, such as ActionController::Base#url_for
-
# and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set
-
# of parameters. For example, you've probably had the chance to write code
-
# like this in one of your views:
-
#
-
# <%= link_to('Click here', controller: 'users',
-
# action: 'new', message: 'Welcome!') %>
-
# # => <a href="/users/new?message=Welcome%21">Click here</a>
-
#
-
# link_to, and all other functions that require URL generation functionality,
-
# actually use ActionController::UrlFor under the hood. And in particular,
-
# they use the ActionController::UrlFor#url_for method. One can generate
-
# the same path as the above example by using the following code:
-
#
-
# include UrlFor
-
# url_for(controller: 'users',
-
# action: 'new',
-
# message: 'Welcome!',
-
# only_path: true)
-
# # => "/users/new?message=Welcome%21"
-
#
-
# Notice the <tt>only_path: true</tt> part. This is because UrlFor has no
-
# information about the website hostname that your Rails app is serving. So if you
-
# want to include the hostname as well, then you must also pass the <tt>:host</tt>
-
# argument:
-
#
-
# include UrlFor
-
# url_for(controller: 'users',
-
# action: 'new',
-
# message: 'Welcome!',
-
# host: 'www.example.com')
-
# # => "http://www.example.com/users/new?message=Welcome%21"
-
#
-
# By default, all controllers and views have access to a special version of url_for,
-
# that already knows what the current hostname is. So if you use url_for in your
-
# controllers or your views, then you don't need to explicitly pass the <tt>:host</tt>
-
# argument.
-
#
-
# For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for.
-
# So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for'
-
# in full. However, mailers don't have hostname information, and that's why you'll still
-
# have to specify the <tt>:host</tt> argument when generating URLs in mailers.
-
#
-
#
-
# == URL generation for named routes
-
#
-
# UrlFor also allows one to access methods that have been auto-generated from
-
# named routes. For example, suppose that you have a 'users' resource in your
-
# <tt>config/routes.rb</tt>:
-
#
-
# resources :users
-
#
-
# This generates, among other things, the method <tt>users_path</tt>. By default,
-
# this method is accessible from your controllers, views and mailers. If you need
-
# to access this auto-generated method from other places (such as a model), then
-
# you can do that by including Rails.application.routes.url_helpers in your class:
-
#
-
# class User < ActiveRecord::Base
-
# include Rails.application.routes.url_helpers
-
#
-
# def base_uri
-
# user_path(self)
-
# end
-
# end
-
#
-
# User.find(1).base_uri # => "/users/1"
-
#
-
1
module UrlFor
-
1
extend ActiveSupport::Concern
-
1
include PolymorphicRoutes
-
-
1
included do
-
10
unless method_defined?(:default_url_options)
-
# Including in a class uses an inheritable hash. Modules get a plain hash.
-
9
if respond_to?(:class_attribute)
-
8
class_attribute :default_url_options
-
else
-
1
mattr_writer :default_url_options
-
end
-
-
9
self.default_url_options = {}
-
end
-
-
10
include(*_url_for_modules) if respond_to?(:_url_for_modules)
-
end
-
-
1
def initialize(*)
-
122
@_routes = nil
-
122
super
-
end
-
-
# Hook overridden in controller to add request information
-
# with `default_url_options`. Application logic should not
-
# go into url_options.
-
1
def url_options
-
66
default_url_options
-
end
-
-
# Generate a url based on the options provided, default_url_options and the
-
# routes defined in routes.rb. The following options are supported:
-
#
-
# * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+.
-
# * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'.
-
# * <tt>:host</tt> - Specifies the host the link should be targeted at.
-
# If <tt>:only_path</tt> is false, this option must be
-
# provided either explicitly, or via +default_url_options+.
-
# * <tt>:subdomain</tt> - Specifies the subdomain of the link, using the +tld_length+
-
# to split the subdomain from the host.
-
# If false, removes all subdomains from the host part of the link.
-
# * <tt>:domain</tt> - Specifies the domain of the link, using the +tld_length+
-
# to split the domain from the host.
-
# * <tt>:tld_length</tt> - Number of labels the TLD id composed of, only used if
-
# <tt>:subdomain</tt> or <tt>:domain</tt> are supplied. Defaults to
-
# <tt>ActionDispatch::Http::URL.tld_length</tt>, which in turn defaults to 1.
-
# * <tt>:port</tt> - Optionally specify the port to connect to.
-
# * <tt>:anchor</tt> - An anchor name to be appended to the path.
-
# * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2009/"
-
# * <tt>:script_name</tt> - Specifies application path relative to domain root. If provided, prepends application path.
-
#
-
# Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to
-
# +url_for+ is forwarded to the Routes module.
-
#
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', port: '8080'
-
# # => 'http://somehost.org:8080/tasks/testing'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', anchor: 'ok', only_path: true
-
# # => '/tasks/testing#ok'
-
# url_for controller: 'tasks', action: 'testing', trailing_slash: true
-
# # => 'http://somehost.org/tasks/testing/'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', number: '33'
-
# # => 'http://somehost.org/tasks/testing?number=33'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp"
-
# # => 'http://somehost.org/myapp/tasks/testing'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp", only_path: true
-
# # => '/myapp/tasks/testing'
-
1
def url_for(options = nil)
-
154
case options
-
when nil
-
_routes.url_for(url_options.symbolize_keys)
-
when Hash
-
147
route_name = options.delete :use_route
-
147
_routes.url_for(options.symbolize_keys.reverse_merge!(url_options),
-
route_name)
-
when String
-
options
-
when Symbol
-
HelperMethodBuilder.url.handle_string_call self, options
-
when Array
-
components = options.dup
-
polymorphic_url(components, components.extract_options!)
-
when Class
-
HelperMethodBuilder.url.handle_class_call self, options
-
else
-
7
HelperMethodBuilder.url.handle_model_call self, options
-
end
-
end
-
-
1
protected
-
-
1
def optimize_routes_generation?
-
129
_routes.optimize_routes_generation? && default_url_options.empty?
-
end
-
-
1
def _with_routes(routes)
-
old_routes, @_routes = @_routes, routes
-
yield
-
ensure
-
@_routes = old_routes
-
end
-
-
1
def _routes_context
-
self
-
end
-
-
1
private
-
-
1
def _generate_paths_by_default
-
true
-
end
-
end
-
end
-
end
-
1
require 'rails-dom-testing'
-
-
1
module ActionDispatch
-
1
module Assertions
-
1
autoload :ResponseAssertions, 'action_dispatch/testing/assertions/response'
-
1
autoload :RoutingAssertions, 'action_dispatch/testing/assertions/routing'
-
-
1
extend ActiveSupport::Concern
-
-
1
include ResponseAssertions
-
1
include RoutingAssertions
-
1
include Rails::Dom::Testing::Assertions
-
-
1
def html_document
-
@html_document ||= if @response.content_type.to_s =~ /xml$/
-
Nokogiri::XML::Document.parse(@response.body)
-
else
-
Nokogiri::HTML::Document.parse(@response.body)
-
end
-
end
-
end
-
end
-
-
1
module ActionDispatch
-
1
module Assertions
-
# A small suite of assertions that test responses from \Rails applications.
-
1
module ResponseAssertions
-
# Asserts that the response is one of the following types:
-
#
-
# * <tt>:success</tt> - Status code was in the 200-299 range
-
# * <tt>:redirect</tt> - Status code was in the 300-399 range
-
# * <tt>:missing</tt> - Status code was 404
-
# * <tt>:error</tt> - Status code was in the 500-599 range
-
#
-
# You can also pass an explicit status number like <tt>assert_response(501)</tt>
-
# or its symbolic equivalent <tt>assert_response(:not_implemented)</tt>.
-
# See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list.
-
#
-
# # assert that the response was a redirection
-
# assert_response :redirect
-
#
-
# # assert that the response code was status code 401 (unauthorized)
-
# assert_response 401
-
1
def assert_response(type, message = nil)
-
message ||= "Expected response to be a <#{type}>, but was <#{@response.response_code}>"
-
-
if Symbol === type
-
if [:success, :missing, :redirect, :error].include?(type)
-
assert @response.send("#{type}?"), message
-
else
-
code = Rack::Utils::SYMBOL_TO_STATUS_CODE[type]
-
if code.nil?
-
raise ArgumentError, "Invalid response type :#{type}"
-
end
-
assert_equal code, @response.response_code, message
-
end
-
else
-
assert_equal type, @response.response_code, message
-
end
-
end
-
-
# Assert that the redirection options passed in match those of the redirect called in the latest action.
-
# This match can be partial, such that <tt>assert_redirected_to(controller: "weblog")</tt> will also
-
# match the redirection of <tt>redirect_to(controller: "weblog", action: "show")</tt> and so on.
-
#
-
# # assert that the redirection was to the "index" action on the WeblogController
-
# assert_redirected_to controller: "weblog", action: "index"
-
#
-
# # assert that the redirection was to the named route login_url
-
# assert_redirected_to login_url
-
#
-
# # assert that the redirection was to the url for @customer
-
# assert_redirected_to @customer
-
#
-
# # asserts that the redirection matches the regular expression
-
# assert_redirected_to %r(\Ahttp://example.org)
-
1
def assert_redirected_to(options = {}, message=nil)
-
assert_response(:redirect, message)
-
return true if options === @response.location
-
-
redirect_is = normalize_argument_to_redirection(@response.location)
-
redirect_expected = normalize_argument_to_redirection(options)
-
-
message ||= "Expected response to be a redirect to <#{redirect_expected}> but was a redirect to <#{redirect_is}>"
-
assert_operator redirect_expected, :===, redirect_is, message
-
end
-
-
1
private
-
# Proxy to to_param if the object will respond to it.
-
1
def parameterize(value)
-
value.respond_to?(:to_param) ? value.to_param : value
-
end
-
-
1
def normalize_argument_to_redirection(fragment)
-
if Regexp === fragment
-
fragment
-
else
-
handle = @controller || ActionController::Redirecting
-
handle._compute_redirect_to_location(@request, fragment)
-
end
-
end
-
end
-
end
-
end
-
1
require 'uri'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/core_ext/string/access'
-
1
require 'action_controller/metal/exceptions'
-
-
1
module ActionDispatch
-
1
module Assertions
-
# Suite of assertions to test routes generated by \Rails and the handling of requests made to them.
-
1
module RoutingAssertions
-
# Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
-
# match +path+. Basically, it asserts that \Rails recognizes the route given by +expected_options+.
-
#
-
# Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes
-
# requiring a specific HTTP method. The hash should contain a :path with the incoming request path
-
# and a :method containing the required HTTP verb.
-
#
-
# # assert that POSTing to /items will call the create action on ItemsController
-
# assert_recognizes({controller: 'items', action: 'create'}, {path: 'items', method: :post})
-
#
-
# You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
-
# to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
-
# extras argument, appending the query string on the path directly will not work. For example:
-
#
-
# # assert that a path of '/items/list/1?view=print' returns the correct options
-
# assert_recognizes({controller: 'items', action: 'list', id: '1', view: 'print'}, 'items/list/1', { view: "print" })
-
#
-
# The +message+ parameter allows you to pass in an error message that is displayed upon failure.
-
#
-
# # Check the default route (i.e., the index action)
-
# assert_recognizes({controller: 'items', action: 'index'}, 'items')
-
#
-
# # Test a specific action
-
# assert_recognizes({controller: 'items', action: 'list'}, 'items/list')
-
#
-
# # Test an action with a parameter
-
# assert_recognizes({controller: 'items', action: 'destroy', id: '1'}, 'items/destroy/1')
-
#
-
# # Test a custom route
-
# assert_recognizes({controller: 'items', action: 'show', id: '1'}, 'view/item1')
-
1
def assert_recognizes(expected_options, path, extras={}, msg=nil)
-
if path.is_a?(Hash) && path[:method].to_s == "all"
-
[:get, :post, :put, :delete].each do |method|
-
assert_recognizes(expected_options, path.merge(method: method), extras, msg)
-
end
-
else
-
request = recognized_request_for(path, extras, msg)
-
-
expected_options = expected_options.clone
-
-
expected_options.stringify_keys!
-
-
msg = message(msg, "") {
-
sprintf("The recognized options <%s> did not match <%s>, difference:",
-
request.path_parameters, expected_options)
-
}
-
-
assert_equal(expected_options, request.path_parameters, msg)
-
end
-
end
-
-
# Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+.
-
# The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in
-
# a query string. The +message+ parameter allows you to specify a custom error message for assertion failures.
-
#
-
# The +defaults+ parameter is unused.
-
#
-
# # Asserts that the default action is generated for a route with no action
-
# assert_generates "/items", controller: "items", action: "index"
-
#
-
# # Tests that the list action is properly routed
-
# assert_generates "/items/list", controller: "items", action: "list"
-
#
-
# # Tests the generation of a route with a parameter
-
# assert_generates "/items/list/1", { controller: "items", action: "list", id: "1" }
-
#
-
# # Asserts that the generated route gives us our custom route
-
# assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" }
-
1
def assert_generates(expected_path, options, defaults={}, extras={}, message=nil)
-
if expected_path =~ %r{://}
-
fail_on(URI::InvalidURIError, message) do
-
uri = URI.parse(expected_path)
-
expected_path = uri.path.to_s.empty? ? "/" : uri.path
-
end
-
else
-
expected_path = "/#{expected_path}" unless expected_path.first == '/'
-
end
-
# Load routes.rb if it hasn't been loaded.
-
-
generated_path, extra_keys = @routes.generate_extras(options, defaults)
-
found_extras = options.reject { |k, _| ! extra_keys.include? k }
-
-
msg = message || sprintf("found extras <%s>, not <%s>", found_extras, extras)
-
assert_equal(extras, found_extras, msg)
-
-
msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path,
-
expected_path)
-
assert_equal(expected_path, generated_path, msg)
-
end
-
-
# Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates
-
# <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines +assert_recognizes+
-
# and +assert_generates+ into one step.
-
#
-
# The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
-
# +message+ parameter allows you to specify a custom error message to display upon failure.
-
#
-
# # Assert a basic route: a controller with the default action (index)
-
# assert_routing '/home', controller: 'home', action: 'index'
-
#
-
# # Test a route generated with a specific controller, action, and parameter (id)
-
# assert_routing '/entries/show/23', controller: 'entries', action: 'show', id: 23
-
#
-
# # Assert a basic route (controller + default action), with an error message if it fails
-
# assert_routing '/store', { controller: 'store', action: 'index' }, {}, {}, 'Route for store index not generated properly'
-
#
-
# # Tests a route, providing a defaults hash
-
# assert_routing 'controller/action/9', {id: "9", item: "square"}, {controller: "controller", action: "action"}, {}, {item: "square"}
-
#
-
# # Tests a route with a HTTP method
-
# assert_routing({ method: 'put', path: '/product/321' }, { controller: "product", action: "update", id: "321" })
-
1
def assert_routing(path, options, defaults={}, extras={}, message=nil)
-
assert_recognizes(options, path, extras, message)
-
-
controller, default_controller = options[:controller], defaults[:controller]
-
if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
-
options[:controller] = "/#{controller}"
-
end
-
-
generate_options = options.dup.delete_if{ |k, _| defaults.key?(k) }
-
assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
-
end
-
-
# A helper to make it easier to test different route configurations.
-
# This method temporarily replaces @routes
-
# with a new RouteSet instance.
-
#
-
# The new instance is yielded to the passed block. Typically the block
-
# will create some routes using <tt>set.draw { match ... }</tt>:
-
#
-
# with_routing do |set|
-
# set.draw do
-
# resources :users
-
# end
-
# assert_equal "/users", users_path
-
# end
-
#
-
1
def with_routing
-
old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new
-
if defined?(@controller) && @controller
-
old_controller, @controller = @controller, @controller.clone
-
_routes = @routes
-
-
@controller.singleton_class.send(:include, _routes.url_helpers)
-
@controller.view_context_class = Class.new(@controller.view_context_class) do
-
include _routes.url_helpers
-
end
-
end
-
yield @routes
-
ensure
-
@routes = old_routes
-
if defined?(@controller) && @controller
-
@controller = old_controller
-
end
-
end
-
-
# ROUTES TODO: These assertions should really work in an integration context
-
1
def method_missing(selector, *args, &block)
-
if defined?(@controller) && @controller && defined?(@routes) && @routes && @routes.named_routes.route_defined?(selector)
-
@controller.send(selector, *args, &block)
-
else
-
super
-
end
-
end
-
-
1
private
-
# Recognizes the route for a given path.
-
1
def recognized_request_for(path, extras = {}, msg)
-
if path.is_a?(Hash)
-
method = path[:method]
-
path = path[:path]
-
else
-
method = :get
-
end
-
-
# Assume given controller
-
request = ActionController::TestRequest.new
-
-
if path =~ %r{://}
-
fail_on(URI::InvalidURIError, msg) do
-
uri = URI.parse(path)
-
request.env["rack.url_scheme"] = uri.scheme || "http"
-
request.host = uri.host if uri.host
-
request.port = uri.port if uri.port
-
request.path = uri.path.to_s.empty? ? "/" : uri.path
-
end
-
else
-
path = "/#{path}" unless path.first == "/"
-
request.path = path
-
end
-
-
request.request_method = method if method
-
-
params = fail_on(ActionController::RoutingError, msg) do
-
@routes.recognize_path(path, { :method => method, :extras => extras })
-
end
-
request.path_parameters = params.with_indifferent_access
-
-
request
-
end
-
-
1
def fail_on(exception_class, message)
-
yield
-
rescue exception_class => e
-
raise Minitest::Assertion, message || e.message
-
end
-
end
-
end
-
end
-
1
require 'stringio'
-
1
require 'uri'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/object/try'
-
1
require 'rack/test'
-
1
require 'minitest'
-
-
1
module ActionDispatch
-
1
module Integration #:nodoc:
-
1
module RequestHelpers
-
# Performs a GET request with the given parameters.
-
#
-
# - +path+: The URI (as a String) on which you want to perform a GET
-
# request.
-
# - +parameters+: The HTTP parameters that you want to pass. This may
-
# be +nil+,
-
# a Hash, or a String that is appropriately encoded
-
# (<tt>application/x-www-form-urlencoded</tt> or
-
# <tt>multipart/form-data</tt>).
-
# - +headers_or_env+: Additional headers to pass, as a Hash. The headers will be
-
# merged into the Rack env hash.
-
#
-
# This method returns a Response object, which one can use to
-
# inspect the details of the response. Furthermore, if this method was
-
# called from an ActionDispatch::IntegrationTest object, then that
-
# object's <tt>@response</tt> instance variable will point to the same
-
# response object.
-
#
-
# You can also perform POST, PATCH, PUT, DELETE, and HEAD requests with
-
# +#post+, +#patch+, +#put+, +#delete+, and +#head+.
-
1
def get(path, parameters = nil, headers_or_env = nil)
-
process :get, path, parameters, headers_or_env
-
end
-
-
# Performs a POST request with the given parameters. See +#get+ for more
-
# details.
-
1
def post(path, parameters = nil, headers_or_env = nil)
-
process :post, path, parameters, headers_or_env
-
end
-
-
# Performs a PATCH request with the given parameters. See +#get+ for more
-
# details.
-
1
def patch(path, parameters = nil, headers_or_env = nil)
-
process :patch, path, parameters, headers_or_env
-
end
-
-
# Performs a PUT request with the given parameters. See +#get+ for more
-
# details.
-
1
def put(path, parameters = nil, headers_or_env = nil)
-
process :put, path, parameters, headers_or_env
-
end
-
-
# Performs a DELETE request with the given parameters. See +#get+ for
-
# more details.
-
1
def delete(path, parameters = nil, headers_or_env = nil)
-
process :delete, path, parameters, headers_or_env
-
end
-
-
# Performs a HEAD request with the given parameters. See +#get+ for more
-
# details.
-
1
def head(path, parameters = nil, headers_or_env = nil)
-
process :head, path, parameters, headers_or_env
-
end
-
-
# Performs an XMLHttpRequest request with the given parameters, mirroring
-
# a request from the Prototype library.
-
#
-
# The request_method is +:get+, +:post+, +:patch+, +:put+, +:delete+ or
-
# +:head+; the parameters are +nil+, a hash, or a url-encoded or multipart
-
# string; the headers are a hash.
-
1
def xml_http_request(request_method, path, parameters = nil, headers_or_env = nil)
-
headers_or_env ||= {}
-
headers_or_env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
-
headers_or_env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
-
process(request_method, path, parameters, headers_or_env)
-
end
-
1
alias xhr :xml_http_request
-
-
# Follow a single redirect response. If the last response was not a
-
# redirect, an exception will be raised. Otherwise, the redirect is
-
# performed on the location header.
-
1
def follow_redirect!
-
raise "not a redirect! #{status} #{status_message}" unless redirect?
-
get(response.location)
-
status
-
end
-
-
# Performs a request using the specified method, following any subsequent
-
# redirect. Note that the redirects are followed until the response is
-
# not a redirect--this means you may run into an infinite loop if your
-
# redirect loops back to itself.
-
1
def request_via_redirect(http_method, path, parameters = nil, headers_or_env = nil)
-
process(http_method, path, parameters, headers_or_env)
-
follow_redirect! while redirect?
-
status
-
end
-
-
# Performs a GET request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
1
def get_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:get, path, parameters, headers_or_env)
-
end
-
-
# Performs a POST request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
1
def post_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:post, path, parameters, headers_or_env)
-
end
-
-
# Performs a PATCH request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
1
def patch_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:patch, path, parameters, headers_or_env)
-
end
-
-
# Performs a PUT request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
1
def put_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:put, path, parameters, headers_or_env)
-
end
-
-
# Performs a DELETE request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
1
def delete_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:delete, path, parameters, headers_or_env)
-
end
-
end
-
-
# An instance of this class represents a set of requests and responses
-
# performed sequentially by a test process. Because you can instantiate
-
# multiple sessions and run them side-by-side, you can also mimic (to some
-
# limited extent) multiple simultaneous users interacting with your system.
-
#
-
# Typically, you will instantiate a new session using
-
# IntegrationTest#open_session, rather than instantiating
-
# Integration::Session directly.
-
1
class Session
-
1
DEFAULT_HOST = "www.example.com"
-
-
1
include Minitest::Assertions
-
1
include TestProcess, RequestHelpers, Assertions
-
-
1
%w( status status_message headers body redirect? ).each do |method|
-
5
delegate method, :to => :response, :allow_nil => true
-
end
-
-
1
%w( path ).each do |method|
-
1
delegate method, :to => :request, :allow_nil => true
-
end
-
-
# The hostname used in the last request.
-
1
def host
-
1
@host || DEFAULT_HOST
-
end
-
1
attr_writer :host
-
-
# The remote_addr used in the last request.
-
1
attr_accessor :remote_addr
-
-
# The Accept header to send.
-
1
attr_accessor :accept
-
-
# A map of the cookies returned by the last response, and which will be
-
# sent with the next request.
-
1
def cookies
-
_mock_session.cookie_jar
-
end
-
-
# A reference to the controller instance used by the last request.
-
1
attr_reader :controller
-
-
# A reference to the request instance used by the last request.
-
1
attr_reader :request
-
-
# A reference to the response instance used by the last request.
-
1
attr_reader :response
-
-
# A running counter of the number of requests processed.
-
1
attr_accessor :request_count
-
-
1
include ActionDispatch::Routing::UrlFor
-
-
# Create and initialize a new Session instance.
-
1
def initialize(app)
-
1
super()
-
1
@app = app
-
-
# If the app is a Rails app, make url_helpers available on the session
-
# This makes app.url_for and app.foo_path available in the console
-
1
if app.respond_to?(:routes)
-
1
singleton_class.class_eval do
-
1
include app.routes.url_helpers
-
1
include app.routes.mounted_helpers
-
end
-
end
-
-
1
reset!
-
end
-
-
1
def url_options
-
@url_options ||= default_url_options.dup.tap do |url_options|
-
1
url_options.reverse_merge!(controller.url_options) if controller
-
-
1
if @app.respond_to?(:routes)
-
1
url_options.reverse_merge!(@app.routes.default_url_options)
-
end
-
-
1
url_options.reverse_merge!(:host => host, :protocol => https? ? "https" : "http")
-
1
end
-
end
-
-
# Resets the instance. This can be used to reset the state information
-
# in an existing session instance, so it can be used from a clean-slate
-
# condition.
-
#
-
# session.reset!
-
1
def reset!
-
1
@https = false
-
1
@controller = @request = @response = nil
-
1
@_mock_session = nil
-
1
@request_count = 0
-
1
@url_options = nil
-
-
1
self.host = DEFAULT_HOST
-
1
self.remote_addr = "127.0.0.1"
-
1
self.accept = "text/xml,application/xml,application/xhtml+xml," +
-
"text/html;q=0.9,text/plain;q=0.8,image/png," +
-
"*/*;q=0.5"
-
-
1
unless defined? @named_routes_configured
-
# the helpers are made protected by default--we make them public for
-
# easier access during testing and troubleshooting.
-
1
@named_routes_configured = true
-
end
-
end
-
-
# Specify whether or not the session should mimic a secure HTTPS request.
-
#
-
# session.https!
-
# session.https!(false)
-
1
def https!(flag = true)
-
@https = flag
-
end
-
-
# Returns +true+ if the session is mimicking a secure HTTPS request.
-
#
-
# if session.https?
-
# ...
-
# end
-
1
def https?
-
1
@https
-
end
-
-
# Set the host name to use in the next request.
-
#
-
# session.host! "www.example.com"
-
1
alias :host! :host=
-
-
1
private
-
1
def _mock_session
-
@_mock_session ||= Rack::MockSession.new(@app, host)
-
end
-
-
# Performs the actual request.
-
1
def process(method, path, parameters = nil, headers_or_env = nil)
-
if path =~ %r{://}
-
location = URI.parse(path)
-
https! URI::HTTPS === location if location.scheme
-
host! "#{location.host}:#{location.port}" if location.host
-
path = location.query ? "#{location.path}?#{location.query}" : location.path
-
end
-
-
hostname, port = host.split(':')
-
-
env = {
-
:method => method,
-
:params => parameters,
-
-
"SERVER_NAME" => hostname,
-
"SERVER_PORT" => port || (https? ? "443" : "80"),
-
"HTTPS" => https? ? "on" : "off",
-
"rack.url_scheme" => https? ? "https" : "http",
-
-
"REQUEST_URI" => path,
-
"HTTP_HOST" => host,
-
"REMOTE_ADDR" => remote_addr,
-
"CONTENT_TYPE" => "application/x-www-form-urlencoded",
-
"HTTP_ACCEPT" => accept
-
}
-
# this modifies the passed env directly
-
Http::Headers.new(env).merge!(headers_or_env || {})
-
-
session = Rack::Test::Session.new(_mock_session)
-
-
# NOTE: rack-test v0.5 doesn't build a default uri correctly
-
# Make sure requested path is always a full uri
-
session.request(build_full_uri(path, env), env)
-
-
@request_count += 1
-
@request = ActionDispatch::Request.new(session.last_request.env)
-
response = _mock_session.last_response
-
@response = ActionDispatch::TestResponse.from_response(response)
-
@html_document = nil
-
@html_scanner_document = nil
-
@url_options = nil
-
-
@controller = session.last_request.env['action_controller.instance']
-
-
return response.status
-
end
-
-
1
def build_full_uri(path, env)
-
"#{env['rack.url_scheme']}://#{env['SERVER_NAME']}:#{env['SERVER_PORT']}#{path}"
-
end
-
end
-
-
1
module Runner
-
1
include ActionDispatch::Assertions
-
-
1
def app
-
1
@app ||= nil
-
end
-
-
# Reset the current session. This is useful for testing multiple sessions
-
# in a single test case.
-
1
def reset!
-
1
@integration_session = Integration::Session.new(app)
-
end
-
-
1
def remove! # :nodoc:
-
@integration_session = nil
-
end
-
-
%w(get post patch put head delete cookies assigns
-
1
xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
-
12
define_method(method) do |*args|
-
reset! unless integration_session
-
-
# reset the html_document variable, except for cookies/assigns calls
-
unless method == 'cookies' || method == 'assigns'
-
@html_document = nil
-
@html_scanner_document = nil
-
reset_template_assertion
-
end
-
-
integration_session.__send__(method, *args).tap do
-
copy_session_variables!
-
end
-
end
-
end
-
-
# Open a new session instance. If a block is given, the new session is
-
# yielded to the block before being returned.
-
#
-
# session = open_session do |sess|
-
# sess.extend(CustomAssertions)
-
# end
-
#
-
# By default, a single session is automatically created for you, but you
-
# can use this method to open multiple sessions that ought to be tested
-
# simultaneously.
-
1
def open_session
-
dup.tap do |session|
-
yield session if block_given?
-
end
-
end
-
-
# Copy the instance variables from the current session instance into the
-
# test instance.
-
1
def copy_session_variables! #:nodoc:
-
1
return unless integration_session
-
1
%w(controller response request).each do |var|
-
3
instance_variable_set("@#{var}", @integration_session.__send__(var))
-
end
-
end
-
-
1
def default_url_options
-
reset! unless integration_session
-
integration_session.default_url_options
-
end
-
-
1
def default_url_options=(options)
-
reset! unless integration_session
-
integration_session.default_url_options = options
-
end
-
-
1
def respond_to?(method, include_private = false)
-
integration_session.respond_to?(method, include_private) || super
-
end
-
-
# Delegate unhandled messages to the current session instance.
-
1
def method_missing(sym, *args, &block)
-
1
reset! unless integration_session
-
1
if integration_session.respond_to?(sym)
-
1
integration_session.__send__(sym, *args, &block).tap do
-
1
copy_session_variables!
-
end
-
else
-
super
-
end
-
end
-
-
1
private
-
1
def integration_session
-
4
@integration_session ||= nil
-
end
-
end
-
end
-
-
# An integration test spans multiple controllers and actions,
-
# tying them all together to ensure they work together as expected. It tests
-
# more completely than either unit or functional tests do, exercising the
-
# entire stack, from the dispatcher to the database.
-
#
-
# At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests
-
# using the get/post methods:
-
#
-
# require "test_helper"
-
#
-
# class ExampleTest < ActionDispatch::IntegrationTest
-
# fixtures :people
-
#
-
# def test_login
-
# # get the login page
-
# get "/login"
-
# assert_equal 200, status
-
#
-
# # post the login and follow through to the home page
-
# post "/login", username: people(:jamis).username,
-
# password: people(:jamis).password
-
# follow_redirect!
-
# assert_equal 200, status
-
# assert_equal "/home", path
-
# end
-
# end
-
#
-
# However, you can also have multiple session instances open per test, and
-
# even extend those instances with assertions and methods to create a very
-
# powerful testing DSL that is specific for your application. You can even
-
# reference any named routes you happen to have defined.
-
#
-
# require "test_helper"
-
#
-
# class AdvancedTest < ActionDispatch::IntegrationTest
-
# fixtures :people, :rooms
-
#
-
# def test_login_and_speak
-
# jamis, david = login(:jamis), login(:david)
-
# room = rooms(:office)
-
#
-
# jamis.enter(room)
-
# jamis.speak(room, "anybody home?")
-
#
-
# david.enter(room)
-
# david.speak(room, "hello!")
-
# end
-
#
-
# private
-
#
-
# module CustomAssertions
-
# def enter(room)
-
# # reference a named route, for maximum internal consistency!
-
# get(room_url(id: room.id))
-
# assert(...)
-
# ...
-
# end
-
#
-
# def speak(room, message)
-
# xml_http_request "/say/#{room.id}", message: message
-
# assert(...)
-
# ...
-
# end
-
# end
-
#
-
# def login(who)
-
# open_session do |sess|
-
# sess.extend(CustomAssertions)
-
# who = people(who)
-
# sess.post "/login", username: who.username,
-
# password: who.password
-
# assert(...)
-
# end
-
# end
-
# end
-
1
class IntegrationTest < ActiveSupport::TestCase
-
1
include Integration::Runner
-
1
include ActionController::TemplateAssertions
-
1
include ActionDispatch::Routing::UrlFor
-
-
1
@@app = nil
-
-
1
def self.app
-
1
@@app || ActionDispatch.test_app
-
end
-
-
1
def self.app=(app)
-
@@app = app
-
end
-
-
1
def app
-
1
super || self.class.app
-
end
-
-
1
def url_options
-
reset! unless integration_session
-
integration_session.url_options
-
end
-
-
1
def document_root_element
-
html_document.root
-
end
-
end
-
end
-
1
require 'action_dispatch/middleware/cookies'
-
1
require 'action_dispatch/middleware/flash'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActionDispatch
-
1
module TestProcess
-
1
def assigns(key = nil)
-
assigns = {}.with_indifferent_access
-
@controller.view_assigns.each { |k, v| assigns.regular_writer(k, v) }
-
key.nil? ? assigns : assigns[key]
-
end
-
-
1
def session
-
@request.session
-
end
-
-
1
def flash
-
@request.flash
-
end
-
-
1
def cookies
-
@request.cookie_jar
-
end
-
-
1
def redirect_to_url
-
@response.redirect_url
-
end
-
-
# Shortcut for <tt>Rack::Test::UploadedFile.new(File.join(ActionController::TestCase.fixture_path, path), type)</tt>:
-
#
-
# post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png')
-
#
-
# To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter.
-
# This will not affect other platforms:
-
#
-
# post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png', :binary)
-
1
def fixture_file_upload(path, mime_type = nil, binary = false)
-
if self.class.respond_to?(:fixture_path) && self.class.fixture_path
-
path = File.join(self.class.fixture_path, path)
-
end
-
Rack::Test::UploadedFile.new(path, mime_type, binary)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'rack/utils'
-
-
1
module ActionDispatch
-
1
class TestRequest < Request
-
1
DEFAULT_ENV = Rack::MockRequest.env_for('/',
-
'HTTP_HOST' => 'test.host',
-
'REMOTE_ADDR' => '0.0.0.0',
-
'HTTP_USER_AGENT' => 'Rails Testing'
-
)
-
-
1
def self.new(env = {})
-
super
-
end
-
-
1
def initialize(env = {})
-
env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
-
super(default_env.merge(env))
-
end
-
-
1
def request_method=(method)
-
@env['REQUEST_METHOD'] = method.to_s.upcase
-
end
-
-
1
def host=(host)
-
@env['HTTP_HOST'] = host
-
end
-
-
1
def port=(number)
-
@env['SERVER_PORT'] = number.to_i
-
end
-
-
1
def request_uri=(uri)
-
@env['REQUEST_URI'] = uri
-
end
-
-
1
def path=(path)
-
@env['PATH_INFO'] = path
-
end
-
-
1
def action=(action_name)
-
path_parameters[:action] = action_name.to_s
-
end
-
-
1
def if_modified_since=(last_modified)
-
@env['HTTP_IF_MODIFIED_SINCE'] = last_modified
-
end
-
-
1
def if_none_match=(etag)
-
@env['HTTP_IF_NONE_MATCH'] = etag
-
end
-
-
1
def remote_addr=(addr)
-
@env['REMOTE_ADDR'] = addr
-
end
-
-
1
def user_agent=(user_agent)
-
@env['HTTP_USER_AGENT'] = user_agent
-
end
-
-
1
def accept=(mime_types)
-
@env.delete('action_dispatch.request.accepts')
-
@env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",")
-
end
-
-
1
alias :rack_cookies :cookies
-
-
1
def cookies
-
@cookies ||= {}.with_indifferent_access
-
end
-
-
1
private
-
-
1
def default_env
-
DEFAULT_ENV
-
end
-
end
-
end
-
1
module ActionDispatch
-
# Integration test methods such as ActionDispatch::Integration::Session#get
-
# and ActionDispatch::Integration::Session#post return objects of class
-
# TestResponse, which represent the HTTP response results of the requested
-
# controller actions.
-
#
-
# See Response for more information on controller response objects.
-
1
class TestResponse < Response
-
1
def self.from_response(response)
-
new response.status, response.headers, response.body, default_headers: nil
-
end
-
-
# Was the response successful?
-
1
alias_method :success?, :successful?
-
-
# Was the URL not found?
-
1
alias_method :missing?, :not_found?
-
-
# Were we redirected?
-
1
alias_method :redirect?, :redirection?
-
-
# Was there a server-side error?
-
1
alias_method :error?, :server_error?
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'action_pack/version'
-
1
module ActionPack
-
# Returns the version of the currently loaded Action Pack as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 2
-
1
TINY = 5
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActionPack
-
# Returns the version of the currently loaded ActionPack as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'action_view/version'
-
-
1
module ActionView
-
1
extend ActiveSupport::Autoload
-
-
1
ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*'
-
-
1
eager_autoload do
-
1
autoload :Base
-
1
autoload :Context
-
1
autoload :CompiledTemplates, "action_view/context"
-
1
autoload :Digestor
-
1
autoload :Helpers
-
1
autoload :LookupContext
-
1
autoload :Layouts
-
1
autoload :PathSet
-
1
autoload :RecordIdentifier
-
1
autoload :Rendering
-
1
autoload :RoutingUrlFor
-
1
autoload :Template
-
1
autoload :ViewPaths
-
-
1
autoload_under "renderer" do
-
1
autoload :Renderer
-
1
autoload :AbstractRenderer
-
1
autoload :PartialRenderer
-
1
autoload :TemplateRenderer
-
1
autoload :StreamingTemplateRenderer
-
end
-
-
1
autoload_at "action_view/template/resolver" do
-
1
autoload :Resolver
-
1
autoload :PathResolver
-
1
autoload :OptimizedFileSystemResolver
-
1
autoload :FallbackFileSystemResolver
-
end
-
-
1
autoload_at "action_view/buffers" do
-
1
autoload :OutputBuffer
-
1
autoload :StreamingBuffer
-
end
-
-
1
autoload_at "action_view/flows" do
-
1
autoload :OutputFlow
-
1
autoload :StreamingFlow
-
end
-
-
1
autoload_at "action_view/template/error" do
-
1
autoload :MissingTemplate
-
1
autoload :ActionViewError
-
1
autoload :EncodingError
-
1
autoload :MissingRequestError
-
1
autoload :TemplateError
-
1
autoload :WrongEncodingError
-
end
-
end
-
-
1
autoload :TestCase
-
-
1
def self.eager_load!
-
super
-
ActionView::Helpers.eager_load!
-
ActionView::Template.eager_load!
-
end
-
end
-
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
ActiveSupport.on_load(:i18n) do
-
1
I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml"
-
end
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/ordered_options'
-
1
require 'action_view/log_subscriber'
-
1
require 'action_view/helpers'
-
1
require 'action_view/context'
-
1
require 'action_view/template'
-
1
require 'action_view/lookup_context'
-
-
1
module ActionView #:nodoc:
-
# = Action View Base
-
#
-
# Action View templates can be written in several ways.
-
# If the template file has a <tt>.erb</tt> extension, then it uses the erubis[https://rubygems.org/gems/erubis]
-
# template system which can embed Ruby into an HTML document.
-
# If the template file has a <tt>.builder</tt> extension, then Jim Weirich's Builder::XmlMarkup library is used.
-
#
-
# == ERB
-
#
-
# You trigger ERB by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the
-
# following loop for names:
-
#
-
# <b>Names of all the people</b>
-
# <% @people.each do |person| %>
-
# Name: <%= person.name %><br/>
-
# <% end %>
-
#
-
# The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this
-
# is not just a usage suggestion. Regular output functions like print or puts won't work with ERB templates. So this would be wrong:
-
#
-
# <%# WRONG %>
-
# Hi, Mr. <% puts "Frodo" %>
-
#
-
# If you absolutely must write from within a function use +concat+.
-
#
-
# When on a line that only contains whitespaces except for the tag, <% %> suppress leading and trailing whitespace,
-
# including the trailing newline. <% %> and <%- -%> are the same.
-
# Note however that <%= %> and <%= -%> are different: only the latter removes trailing whitespaces.
-
#
-
# === Using sub templates
-
#
-
# Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The
-
# classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts):
-
#
-
# <%= render "shared/header" %>
-
# Something really specific and terrific
-
# <%= render "shared/footer" %>
-
#
-
# As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the
-
# result of the rendering. The output embedding writes it to the current template.
-
#
-
# But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance
-
# variables defined using the regular embedding tags. Like this:
-
#
-
# <% @page_title = "A Wonderful Hello" %>
-
# <%= render "shared/header" %>
-
#
-
# Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag:
-
#
-
# <title><%= @page_title %></title>
-
#
-
# === Passing local variables to sub templates
-
#
-
# You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
-
#
-
# <%= render "shared/header", { headline: "Welcome", person: person } %>
-
#
-
# These can now be accessed in <tt>shared/header</tt> with:
-
#
-
# Headline: <%= headline %>
-
# First name: <%= person.first_name %>
-
#
-
# === Template caching
-
#
-
# By default, Rails will compile each template to a method in order to render it. When you alter a template,
-
# Rails will check the file's modification time and recompile it in development mode.
-
#
-
# == Builder
-
#
-
# Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object
-
# named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
-
#
-
# Here are some basic examples:
-
#
-
# xml.em("emphasized") # => <em>emphasized</em>
-
# xml.em { xml.b("emph & bold") } # => <em><b>emph & bold</b></em>
-
# xml.a("A Link", "href" => "http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
-
# xml.target("name" => "compile", "option" => "fast") # => <target option="fast" name="compile"\>
-
# # NOTE: order of attributes is not specified.
-
#
-
# Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
-
#
-
# xml.div do
-
# xml.h1(@person.name)
-
# xml.p(@person.bio)
-
# end
-
#
-
# would produce something like:
-
#
-
# <div>
-
# <h1>David Heinemeier Hansson</h1>
-
# <p>A product of Danish Design during the Winter of '79...</p>
-
# </div>
-
#
-
# A full-length RSS example actually used on Basecamp:
-
#
-
# xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
-
# xml.channel do
-
# xml.title(@feed_title)
-
# xml.link(@url)
-
# xml.description "Basecamp: Recent items"
-
# xml.language "en-us"
-
# xml.ttl "40"
-
#
-
# @recent_items.each do |item|
-
# xml.item do
-
# xml.title(item_title(item))
-
# xml.description(item_description(item)) if item_description(item)
-
# xml.pubDate(item_pubDate(item))
-
# xml.guid(@person.firm.account.url + @recent_items.url(item))
-
# xml.link(@person.firm.account.url + @recent_items.url(item))
-
#
-
# xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
-
# end
-
# end
-
# end
-
# end
-
#
-
# For more information on Builder please consult the [source
-
# code](https://github.com/jimweirich/builder).
-
1
class Base
-
1
include Helpers, ::ERB::Util, Context
-
-
# Specify the proc used to decorate input tags that refer to attributes with errors.
-
1
cattr_accessor :field_error_proc
-
1
@@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
-
-
# How to complete the streaming when an exception occurs.
-
# This is our best guess: first try to close the attribute, then the tag.
-
1
cattr_accessor :streaming_completion_on_exception
-
1
@@streaming_completion_on_exception = %("><script>window.location = "/500.html"</script></html>)
-
-
# Specify whether rendering within namespaced controllers should prefix
-
# the partial paths for ActiveModel objects with the namespace.
-
# (e.g., an Admin::PostsController would render @post using /admin/posts/_post.erb)
-
1
cattr_accessor :prefix_partial_path_with_controller_namespace
-
1
@@prefix_partial_path_with_controller_namespace = true
-
-
# Specify default_formats that can be rendered.
-
1
cattr_accessor :default_formats
-
-
# Specify whether an error should be raised for missing translations
-
1
cattr_accessor :raise_on_missing_translations
-
1
@@raise_on_missing_translations = false
-
-
1
class_attribute :_routes
-
1
class_attribute :logger
-
-
1
class << self
-
1
delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB'
-
-
1
def cache_template_loading
-
ActionView::Resolver.caching?
-
end
-
-
1
def cache_template_loading=(value)
-
ActionView::Resolver.caching = value
-
end
-
-
1
def xss_safe? #:nodoc:
-
true
-
end
-
end
-
-
1
attr_accessor :view_renderer
-
1
attr_internal :config, :assigns
-
-
1
delegate :lookup_context, :to => :view_renderer
-
1
delegate :formats, :formats=, :locale, :locale=, :view_paths, :view_paths=, :to => :lookup_context
-
-
1
def assign(new_assigns) # :nodoc:
-
152
@_assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
-
end
-
-
1
def initialize(context = nil, assigns = {}, controller = nil, formats = nil) #:nodoc:
-
55
@_config = ActiveSupport::InheritableOptions.new
-
-
55
if context.is_a?(ActionView::Renderer)
-
55
@view_renderer = context
-
else
-
lookup_context = context.is_a?(ActionView::LookupContext) ?
-
context : ActionView::LookupContext.new(context)
-
lookup_context.formats = formats if formats
-
lookup_context.prefixes = controller._prefixes if controller
-
@view_renderer = ActionView::Renderer.new(lookup_context)
-
end
-
-
55
assign(assigns)
-
55
assign_controller(controller)
-
55
_prepare_context
-
end
-
-
1
ActiveSupport.run_load_hooks(:action_view, self)
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView
-
1
class OutputBuffer < ActiveSupport::SafeBuffer #:nodoc:
-
1
def initialize(*)
-
118
super
-
118
encode!
-
end
-
-
1
def <<(value)
-
return self if value.nil?
-
super(value.to_s)
-
end
-
1
alias :append= :<<
-
-
1
def safe_expr_append=(val)
-
return self if val.nil?
-
safe_concat val.to_s
-
end
-
-
1
alias :safe_append= :safe_concat
-
end
-
-
1
class StreamingBuffer #:nodoc:
-
1
def initialize(block)
-
@block = block
-
end
-
-
1
def <<(value)
-
value = value.to_s
-
value = ERB::Util.h(value) unless value.html_safe?
-
@block.call(value)
-
end
-
1
alias :concat :<<
-
1
alias :append= :<<
-
-
1
def safe_concat(value)
-
@block.call(value.to_s)
-
end
-
1
alias :safe_append= :safe_concat
-
-
1
def html_safe?
-
true
-
end
-
-
1
def html_safe
-
self
-
end
-
end
-
end
-
1
module ActionView
-
1
module CompiledTemplates #:nodoc:
-
# holds compiled template code
-
end
-
-
# = Action View Context
-
#
-
# Action View contexts are supplied to Action Controller to render a template.
-
# The default Action View context is ActionView::Base.
-
#
-
# In order to work with ActionController, a Context must just include this module.
-
# The initialization of the variables used by the context (@output_buffer, @view_flow,
-
# and @virtual_path) is responsibility of the object that includes this module
-
# (although you can call _prepare_context defined below).
-
1
module Context
-
1
include CompiledTemplates
-
1
attr_accessor :output_buffer, :view_flow
-
-
# Prepares the context by setting the appropriate instance variables.
-
# :api: plugin
-
1
def _prepare_context
-
55
@view_flow = OutputFlow.new
-
55
@output_buffer = nil
-
55
@virtual_path = nil
-
end
-
-
# Encapsulates the interaction with the view flow so it
-
# returns the correct buffer on +yield+. This is usually
-
# overwritten by helpers to add more behavior.
-
# :api: plugin
-
1
def _layout_for(name=nil)
-
55
name ||= :layout
-
55
view_flow.get(name).html_safe
-
end
-
end
-
end
-
1
require 'thread_safe'
-
-
1
module ActionView
-
1
class DependencyTracker # :nodoc:
-
1
@trackers = ThreadSafe::Cache.new
-
-
1
def self.find_dependencies(name, template)
-
tracker = @trackers[template.handler]
-
-
if tracker.present?
-
tracker.call(name, template)
-
else
-
[]
-
end
-
end
-
-
1
def self.register_tracker(extension, tracker)
-
2
handler = Template.handler_for_extension(extension)
-
2
@trackers[handler] = tracker
-
end
-
-
1
def self.remove_tracker(handler)
-
@trackers.delete(handler)
-
end
-
-
1
class ERBTracker # :nodoc:
-
1
EXPLICIT_DEPENDENCY = /# Template Dependency: (\S+)/
-
-
# A valid ruby identifier - suitable for class, method and specially variable names
-
1
IDENTIFIER = /
-
[[:alpha:]_] # at least one uppercase letter, lowercase letter or underscore
-
[[:word:]]* # followed by optional letters, numbers or underscores
-
/x
-
-
# Any kind of variable name. e.g. @instance, @@class, $global or local.
-
# Possibly following a method call chain
-
1
VARIABLE_OR_METHOD_CHAIN = /
-
(?:\$|@{1,2})? # optional global, instance or class variable indicator
-
(?:#{IDENTIFIER}\.)* # followed by an optional chain of zero-argument method calls
-
(?<dynamic>#{IDENTIFIER}) # and a final valid identifier, captured as DYNAMIC
-
/x
-
-
# A simple string literal. e.g. "School's out!"
-
1
STRING = /
-
(?<quote>['"]) # an opening quote
-
(?<static>.*?) # with anything inside, captured as STATIC
-
\k<quote> # and a matching closing quote
-
/x
-
-
# Part of any hash containing the :partial key
-
1
PARTIAL_HASH_KEY = /
-
(?:\bpartial:|:partial\s*=>) # partial key in either old or new style hash syntax
-
\s* # followed by optional spaces
-
/x
-
-
# Part of any hash containing the :layout key
-
1
LAYOUT_HASH_KEY = /
-
(?:\blayout:|:layout\s*=>) # layout key in either old or new style hash syntax
-
\s* # followed by optional spaces
-
/x
-
-
# Matches:
-
# partial: "comments/comment", collection: @all_comments => "comments/comment"
-
# (object: @single_comment, partial: "comments/comment") => "comments/comment"
-
#
-
# "comments/comments"
-
# 'comments/comments'
-
# ('comments/comments')
-
#
-
# (@topic) => "topics/topic"
-
# topics => "topics/topic"
-
# (message.topics) => "topics/topic"
-
1
RENDER_ARGUMENTS = /\A
-
(?:\s*\(?\s*) # optional opening paren surrounded by spaces
-
(?:.*?#{PARTIAL_HASH_KEY}|#{LAYOUT_HASH_KEY})? # optional hash, up to the partial or layout key declaration
-
(?:#{STRING}|#{VARIABLE_OR_METHOD_CHAIN}) # finally, the dependency name of interest
-
/xm
-
-
1
def self.call(name, template)
-
new(name, template).dependencies
-
end
-
-
1
def initialize(name, template)
-
@name, @template = name, template
-
end
-
-
1
def dependencies
-
render_dependencies + explicit_dependencies
-
end
-
-
1
attr_reader :name, :template
-
1
private :name, :template
-
-
-
1
private
-
1
def source
-
template.source
-
end
-
-
1
def directory
-
name.split("/")[0..-2].join("/")
-
end
-
-
1
def render_dependencies
-
render_dependencies = []
-
render_calls = source.split(/\brender\b/).drop(1)
-
-
render_calls.each do |arguments|
-
arguments.scan(RENDER_ARGUMENTS) do
-
add_dynamic_dependency(render_dependencies, Regexp.last_match[:dynamic])
-
add_static_dependency(render_dependencies, Regexp.last_match[:static])
-
end
-
end
-
-
render_dependencies.uniq
-
end
-
-
1
def add_dynamic_dependency(dependencies, dependency)
-
if dependency
-
dependencies << "#{dependency.pluralize}/#{dependency.singularize}"
-
end
-
end
-
-
1
def add_static_dependency(dependencies, dependency)
-
if dependency
-
if dependency.include?('/')
-
dependencies << dependency
-
else
-
dependencies << "#{directory}/#{dependency}"
-
end
-
end
-
end
-
-
1
def explicit_dependencies
-
source.scan(EXPLICIT_DEPENDENCY).flatten.uniq
-
end
-
end
-
-
1
register_tracker :erb, ERBTracker
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView
-
1
class OutputFlow #:nodoc:
-
1
attr_reader :content
-
-
1
def initialize
-
110
@content = Hash.new { |h,k| h[k] = ActiveSupport::SafeBuffer.new }
-
end
-
-
# Called by _layout_for to read stored values.
-
1
def get(key)
-
110
@content[key]
-
end
-
-
# Called by each renderer object to set the layout contents.
-
1
def set(key, value)
-
55
@content[key] = value
-
end
-
-
# Called by content_for
-
1
def append(key, value)
-
@content[key] << value
-
end
-
1
alias_method :append!, :append
-
-
end
-
-
1
class StreamingFlow < OutputFlow #:nodoc:
-
1
def initialize(view, fiber)
-
@view = view
-
@parent = nil
-
@child = view.output_buffer
-
@content = view.view_flow.content
-
@fiber = fiber
-
@root = Fiber.current.object_id
-
end
-
-
# Try to get stored content. If the content
-
# is not available and we are inside the layout
-
# fiber, we set that we are waiting for the given
-
# key and yield.
-
1
def get(key)
-
return super if @content.key?(key)
-
-
if inside_fiber?
-
view = @view
-
-
begin
-
@waiting_for = key
-
view.output_buffer, @parent = @child, view.output_buffer
-
Fiber.yield
-
ensure
-
@waiting_for = nil
-
view.output_buffer, @child = @parent, view.output_buffer
-
end
-
end
-
-
super
-
end
-
-
# Appends the contents for the given key. This is called
-
# by provides and resumes back to the fiber if it is
-
# the key it is waiting for.
-
1
def append!(key, value)
-
super
-
@fiber.resume if @waiting_for == key
-
end
-
-
1
private
-
-
1
def inside_fiber?
-
Fiber.current.object_id != @root
-
end
-
end
-
end
-
1
module ActionView
-
# Returns the version of the currently loaded Action View as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 2
-
1
TINY = 5
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'active_support/benchmarkable'
-
-
1
module ActionView #:nodoc:
-
1
module Helpers #:nodoc:
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :ActiveModelHelper
-
1
autoload :AssetTagHelper
-
1
autoload :AssetUrlHelper
-
1
autoload :AtomFeedHelper
-
1
autoload :CacheHelper
-
1
autoload :CaptureHelper
-
1
autoload :ControllerHelper
-
1
autoload :CsrfHelper
-
1
autoload :DateHelper
-
1
autoload :DebugHelper
-
1
autoload :FormHelper
-
1
autoload :FormOptionsHelper
-
1
autoload :FormTagHelper
-
1
autoload :JavaScriptHelper, "action_view/helpers/javascript_helper"
-
1
autoload :NumberHelper
-
1
autoload :OutputSafetyHelper
-
1
autoload :RecordTagHelper
-
1
autoload :RenderingHelper
-
1
autoload :SanitizeHelper
-
1
autoload :TagHelper
-
1
autoload :TextHelper
-
1
autoload :TranslationHelper
-
1
autoload :UrlHelper
-
1
autoload :Tags
-
-
1
def self.eager_load!
-
super
-
Tags.eager_load!
-
end
-
-
1
extend ActiveSupport::Concern
-
-
1
include ActiveSupport::Benchmarkable
-
1
include ActiveModelHelper
-
1
include AssetTagHelper
-
1
include AssetUrlHelper
-
1
include AtomFeedHelper
-
1
include CacheHelper
-
1
include CaptureHelper
-
1
include ControllerHelper
-
1
include CsrfHelper
-
1
include DateHelper
-
1
include DebugHelper
-
1
include FormHelper
-
1
include FormOptionsHelper
-
1
include FormTagHelper
-
1
include JavaScriptHelper
-
1
include NumberHelper
-
1
include OutputSafetyHelper
-
1
include RecordTagHelper
-
1
include RenderingHelper
-
1
include SanitizeHelper
-
1
include TagHelper
-
1
include TextHelper
-
1
include TranslationHelper
-
1
include UrlHelper
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/enumerable'
-
-
1
module ActionView
-
# = Active Model Helpers
-
1
module Helpers
-
1
module ActiveModelHelper
-
end
-
-
1
module ActiveModelInstanceTag
-
1
def object
-
@active_model_object ||= begin
-
object = super
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
end
-
-
1
def content_tag(*)
-
30
error_wrapping(super)
-
end
-
-
1
def tag(type, options, *)
-
20
tag_generate_errors?(options) ? error_wrapping(super) : super
-
end
-
-
1
def error_wrapping(html_tag)
-
52
if object_has_errors?
-
Base.field_error_proc.call(html_tag, self)
-
else
-
52
html_tag
-
end
-
end
-
-
1
def error_message
-
52
object.errors[@method_name]
-
end
-
-
1
private
-
-
1
def object_has_errors?
-
52
object.respond_to?(:errors) && object.errors.respond_to?(:[]) && error_message.present?
-
end
-
-
1
def tag_generate_errors?(options)
-
20
options['type'] != 'hidden'
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'action_view/helpers/asset_url_helper'
-
1
require 'action_view/helpers/tag_helper'
-
-
1
module ActionView
-
# = Action View Asset Tag Helpers
-
1
module Helpers #:nodoc:
-
# This module provides methods for generating HTML that links views to assets such
-
# as images, JavaScripts, stylesheets, and feeds. These methods do not verify
-
# the assets exist before linking to them:
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="/assets/application.css?body=1" media="screen" rel="stylesheet" />
-
1
module AssetTagHelper
-
1
extend ActiveSupport::Concern
-
-
1
include AssetUrlHelper
-
1
include TagHelper
-
-
# Returns an HTML script tag for each of the +sources+ provided.
-
#
-
# Sources may be paths to JavaScript files. Relative paths are assumed to be relative
-
# to <tt>assets/javascripts</tt>, full paths are assumed to be relative to the document
-
# root. Relative paths are idiomatic, use absolute paths only when needed.
-
#
-
# When passing paths, the ".js" extension is optional. If you do not want ".js"
-
# appended to the path <tt>extname: false</tt> can be set on the options.
-
#
-
# You can modify the HTML attributes of the script tag by passing a hash as the
-
# last argument.
-
#
-
# When the Asset Pipeline is enabled, you can pass the name of your manifest as
-
# source, and include other JavaScript or CoffeeScript files inside the manifest.
-
#
-
# javascript_include_tag "xmlhr"
-
# # => <script src="/assets/xmlhr.js?1284139606"></script>
-
#
-
# javascript_include_tag "template.jst", extname: false
-
# # => <script src="/assets/template.jst?1284139606"></script>
-
#
-
# javascript_include_tag "xmlhr.js"
-
# # => <script src="/assets/xmlhr.js?1284139606"></script>
-
#
-
# javascript_include_tag "common.javascript", "/elsewhere/cools"
-
# # => <script src="/assets/common.javascript?1284139606"></script>
-
# # <script src="/elsewhere/cools.js?1423139606"></script>
-
#
-
# javascript_include_tag "http://www.example.com/xmlhr"
-
# # => <script src="http://www.example.com/xmlhr"></script>
-
#
-
# javascript_include_tag "http://www.example.com/xmlhr.js"
-
# # => <script src="http://www.example.com/xmlhr.js"></script>
-
1
def javascript_include_tag(*sources)
-
55
options = sources.extract_options!.stringify_keys
-
55
path_options = options.extract!('protocol', 'extname').symbolize_keys
-
sources.uniq.map { |source|
-
55
tag_options = {
-
"src" => path_to_javascript(source, path_options)
-
}.merge!(options)
-
55
content_tag(:script, "", tag_options)
-
55
}.join("\n").html_safe
-
end
-
-
# Returns a stylesheet link tag for the sources specified as arguments. If
-
# you don't specify an extension, <tt>.css</tt> will be appended automatically.
-
# You can modify the link attributes by passing a hash as the last argument.
-
# For historical reasons, the 'media' attribute will always be present and defaults
-
# to "screen", so you must explicitly set it to "all" for the stylesheet(s) to
-
# apply to all media types.
-
#
-
# stylesheet_link_tag "style"
-
# # => <link href="/assets/style.css" media="screen" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "style.css"
-
# # => <link href="/assets/style.css" media="screen" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "http://www.example.com/style.css"
-
# # => <link href="http://www.example.com/style.css" media="screen" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "style", media: "all"
-
# # => <link href="/assets/style.css" media="all" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "style", media: "print"
-
# # => <link href="/assets/style.css" media="print" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "random.styles", "/css/stylish"
-
# # => <link href="/assets/random.styles" media="screen" rel="stylesheet" />
-
# # <link href="/css/stylish.css" media="screen" rel="stylesheet" />
-
1
def stylesheet_link_tag(*sources)
-
55
options = sources.extract_options!.stringify_keys
-
55
path_options = options.extract!('protocol').symbolize_keys
-
-
sources.uniq.map { |source|
-
55
tag_options = {
-
"rel" => "stylesheet",
-
"media" => "screen",
-
"href" => path_to_stylesheet(source, path_options)
-
}.merge!(options)
-
55
tag(:link, tag_options)
-
55
}.join("\n").html_safe
-
end
-
-
# Returns a link tag that browsers and feed readers can use to auto-detect
-
# an RSS or Atom feed. The +type+ can either be <tt>:rss</tt> (default) or
-
# <tt>:atom</tt>. Control the link options in url_for format using the
-
# +url_options+. You can modify the LINK tag itself in +tag_options+.
-
#
-
# ==== Options
-
#
-
# * <tt>:rel</tt> - Specify the relation of this link, defaults to "alternate"
-
# * <tt>:type</tt> - Override the auto-generated mime type
-
# * <tt>:title</tt> - Specify the title of the link, defaults to the +type+
-
#
-
# ==== Examples
-
#
-
# auto_discovery_link_tag
-
# # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
-
# auto_discovery_link_tag(:atom)
-
# # => <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
-
# auto_discovery_link_tag(:rss, {action: "feed"})
-
# # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
-
# auto_discovery_link_tag(:rss, {action: "feed"}, {title: "My RSS"})
-
# # => <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
-
# auto_discovery_link_tag(:rss, {controller: "news", action: "feed"})
-
# # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
-
# auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {title: "Example RSS"})
-
# # => <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed.rss" />
-
1
def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
-
if !(type == :rss || type == :atom) && tag_options[:type].blank?
-
raise ArgumentError.new("You should pass :type tag_option key explicitly, because you have passed #{type} type other than :rss or :atom.")
-
end
-
-
tag(
-
"link",
-
"rel" => tag_options[:rel] || "alternate",
-
"type" => tag_options[:type] || Mime::Type.lookup_by_extension(type.to_s).to_s,
-
"title" => tag_options[:title] || type.to_s.upcase,
-
"href" => url_options.is_a?(Hash) ? url_for(url_options.merge(:only_path => false)) : url_options
-
)
-
end
-
-
# Returns a link tag for a favicon managed by the asset pipeline.
-
#
-
# If a page has no link like the one generated by this helper, browsers
-
# ask for <tt>/favicon.ico</tt> automatically, and cache the file if the
-
# request succeeds. If the favicon changes it is hard to get it updated.
-
#
-
# To have better control applications may let the asset pipeline manage
-
# their favicon storing the file under <tt>app/assets/images</tt>, and
-
# using this helper to generate its corresponding link tag.
-
#
-
# The helper gets the name of the favicon file as first argument, which
-
# defaults to "favicon.ico", and also supports +:rel+ and +:type+ options
-
# to override their defaults, "shortcut icon" and "image/x-icon"
-
# respectively:
-
#
-
# favicon_link_tag
-
# # => <link href="/assets/favicon.ico" rel="shortcut icon" type="image/x-icon" />
-
#
-
# favicon_link_tag 'myicon.ico'
-
# # => <link href="/assets/myicon.ico" rel="shortcut icon" type="image/x-icon" />
-
#
-
# Mobile Safari looks for a different link tag, pointing to an image that
-
# will be used if you add the page to the home screen of an iOS device.
-
# The following call would generate such a tag:
-
#
-
# favicon_link_tag 'mb-icon.png', rel: 'apple-touch-icon', type: 'image/png'
-
# # => <link href="/assets/mb-icon.png" rel="apple-touch-icon" type="image/png" />
-
1
def favicon_link_tag(source='favicon.ico', options={})
-
tag('link', {
-
:rel => 'shortcut icon',
-
:type => 'image/x-icon',
-
:href => path_to_image(source)
-
}.merge!(options.symbolize_keys))
-
end
-
-
# Returns an HTML image tag for the +source+. The +source+ can be a full
-
# path or a file.
-
#
-
# ==== Options
-
#
-
# You can add HTML attributes using the +options+. The +options+ supports
-
# two additional keys for convenience and conformance:
-
#
-
# * <tt>:alt</tt> - If no alt text is given, the file name part of the
-
# +source+ is used (capitalized and without the extension)
-
# * <tt>:size</tt> - Supplied as "{Width}x{Height}" or "{Number}", so "30x45" becomes
-
# width="30" and height="45", and "50" becomes width="50" and height="50".
-
# <tt>:size</tt> will be ignored if the value is not in the correct format.
-
#
-
# ==== Examples
-
#
-
# image_tag("icon")
-
# # => <img alt="Icon" src="/assets/icon" />
-
# image_tag("icon.png")
-
# # => <img alt="Icon" src="/assets/icon.png" />
-
# image_tag("icon.png", size: "16x10", alt: "Edit Entry")
-
# # => <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
-
# image_tag("/icons/icon.gif", size: "16")
-
# # => <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
-
# image_tag("/icons/icon.gif", height: '32', width: '32')
-
# # => <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
-
# image_tag("/icons/icon.gif", class: "menu_icon")
-
# # => <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
-
1
def image_tag(source, options={})
-
options = options.symbolize_keys
-
-
src = options[:src] = path_to_image(source)
-
-
unless src =~ /^(?:cid|data):/ || src.blank?
-
options[:alt] = options.fetch(:alt){ image_alt(src) }
-
end
-
-
options[:width], options[:height] = extract_dimensions(options.delete(:size)) if options[:size]
-
tag("img", options)
-
end
-
-
# Returns a string suitable for an HTML image tag alt attribute.
-
# The +src+ argument is meant to be an image file path.
-
# The method removes the basename of the file path and the digest,
-
# if any. It also removes hyphens and underscores from file names and
-
# replaces them with spaces, returning a space-separated, titleized
-
# string.
-
#
-
# ==== Examples
-
#
-
# image_alt('rails.png')
-
# # => Rails
-
#
-
# image_alt('hyphenated-file-name.png')
-
# # => Hyphenated file name
-
#
-
# image_alt('underscored_file_name.png')
-
# # => Underscored file name
-
1
def image_alt(src)
-
File.basename(src, '.*').sub(/-[[:xdigit:]]{32}\z/, '').tr('-_', ' ').capitalize
-
end
-
-
# Returns an HTML video tag for the +sources+. If +sources+ is a string,
-
# a single video tag will be returned. If +sources+ is an array, a video
-
# tag with nested source tags for each source will be returned. The
-
# +sources+ can be full paths or files that exists in your public videos
-
# directory.
-
#
-
# ==== Options
-
# You can add HTML attributes using the +options+. The +options+ supports
-
# two additional keys for convenience and conformance:
-
#
-
# * <tt>:poster</tt> - Set an image (like a screenshot) to be shown
-
# before the video loads. The path is calculated like the +src+ of +image_tag+.
-
# * <tt>:size</tt> - Supplied as "{Width}x{Height}" or "{Number}", so "30x45" becomes
-
# width="30" and height="45", and "50" becomes width="50" and height="50".
-
# <tt>:size</tt> will be ignored if the value is not in the correct format.
-
#
-
# ==== Examples
-
#
-
# video_tag("trailer")
-
# # => <video src="/videos/trailer"></video>
-
# video_tag("trailer.ogg")
-
# # => <video src="/videos/trailer.ogg"></video>
-
# video_tag("trailer.ogg", controls: true, autobuffer: true)
-
# # => <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" ></video>
-
# video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png")
-
# # => <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png"></video>
-
# video_tag("/trailers/hd.avi", size: "16x16")
-
# # => <video src="/trailers/hd.avi" width="16" height="16"></video>
-
# video_tag("/trailers/hd.avi", size: "16")
-
# # => <video height="16" src="/trailers/hd.avi" width="16"></video>
-
# video_tag("/trailers/hd.avi", height: '32', width: '32')
-
# # => <video height="32" src="/trailers/hd.avi" width="32"></video>
-
# video_tag("trailer.ogg", "trailer.flv")
-
# # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
-
# video_tag(["trailer.ogg", "trailer.flv"])
-
# # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
-
# video_tag(["trailer.ogg", "trailer.flv"], size: "160x120")
-
# # => <video height="120" width="160"><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
-
1
def video_tag(*sources)
-
multiple_sources_tag('video', sources) do |options|
-
options[:poster] = path_to_image(options[:poster]) if options[:poster]
-
options[:width], options[:height] = extract_dimensions(options.delete(:size)) if options[:size]
-
end
-
end
-
-
# Returns an HTML audio tag for the +source+.
-
# The +source+ can be full path or file that exists in
-
# your public audios directory.
-
#
-
# audio_tag("sound")
-
# # => <audio src="/audios/sound"></audio>
-
# audio_tag("sound.wav")
-
# # => <audio src="/audios/sound.wav"></audio>
-
# audio_tag("sound.wav", autoplay: true, controls: true)
-
# # => <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav"></audio>
-
# audio_tag("sound.wav", "sound.mid")
-
# # => <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio>
-
1
def audio_tag(*sources)
-
multiple_sources_tag('audio', sources)
-
end
-
-
1
private
-
1
def multiple_sources_tag(type, sources)
-
options = sources.extract_options!.symbolize_keys
-
sources.flatten!
-
-
yield options if block_given?
-
-
if sources.size > 1
-
content_tag(type, options) do
-
safe_join sources.map { |source| tag("source", :src => send("path_to_#{type}", source)) }
-
end
-
else
-
options[:src] = send("path_to_#{type}", sources.first)
-
content_tag(type, nil, options)
-
end
-
end
-
-
1
def extract_dimensions(size)
-
if size =~ %r{\A\d+x\d+\z}
-
size.split('x')
-
elsif size =~ %r{\A\d+\z}
-
[size, size]
-
end
-
end
-
end
-
end
-
end
-
1
require 'zlib'
-
-
1
module ActionView
-
# = Action View Asset URL Helpers
-
1
module Helpers
-
# This module provides methods for generating asset paths and
-
# urls.
-
#
-
# image_path("rails.png")
-
# # => "/assets/rails.png"
-
#
-
# image_url("rails.png")
-
# # => "http://www.example.com/assets/rails.png"
-
#
-
# === Using asset hosts
-
#
-
# By default, Rails links to these assets on the current host in the public
-
# folder, but you can direct Rails to link to assets from a dedicated asset
-
# server by setting <tt>ActionController::Base.asset_host</tt> in the application
-
# configuration, typically in <tt>config/environments/production.rb</tt>.
-
# For example, you'd define <tt>assets.example.com</tt> to be your asset
-
# host this way, inside the <tt>configure</tt> block of your environment-specific
-
# configuration files or <tt>config/application.rb</tt>:
-
#
-
# config.action_controller.asset_host = "assets.example.com"
-
#
-
# Helpers take that into account:
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# Browsers typically open at most two simultaneous connections to a single
-
# host, which means your assets often have to wait for other assets to finish
-
# downloading. You can alleviate this by using a <tt>%d</tt> wildcard in the
-
# +asset_host+. For example, "assets%d.example.com". If that wildcard is
-
# present Rails distributes asset requests among the corresponding four hosts
-
# "assets0.example.com", ..., "assets3.example.com". With this trick browsers
-
# will open eight simultaneous connections rather than two.
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets0.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# To do this, you can either setup four actual hosts, or you can use wildcard
-
# DNS to CNAME the wildcard to a single asset host. You can read more about
-
# setting up your DNS CNAME records from your ISP.
-
#
-
# Note: This is purely a browser performance optimization and is not meant
-
# for server load balancing. See http://www.die.net/musings/page_load_time/
-
# for background.
-
#
-
# Alternatively, you can exert more control over the asset host by setting
-
# +asset_host+ to a proc like this:
-
#
-
# ActionController::Base.asset_host = Proc.new { |source|
-
# "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"
-
# }
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets1.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# The example above generates "http://assets1.example.com" and
-
# "http://assets2.example.com". This option is useful for example if
-
# you need fewer/more than four hosts, custom host names, etc.
-
#
-
# As you see the proc takes a +source+ parameter. That's a string with the
-
# absolute path of the asset, for example "/assets/rails.png".
-
#
-
# ActionController::Base.asset_host = Proc.new { |source|
-
# if source.ends_with?('.css')
-
# "http://stylesheets.example.com"
-
# else
-
# "http://assets.example.com"
-
# end
-
# }
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://stylesheets.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# Alternatively you may ask for a second parameter +request+. That one is
-
# particularly useful for serving assets from an SSL-protected page. The
-
# example proc below disables asset hosting for HTTPS connections, while
-
# still sending assets for plain HTTP requests from asset hosts. If you don't
-
# have SSL certificates for each of the asset hosts this technique allows you
-
# to avoid warnings in the client about mixed media.
-
# Note that the request parameter might not be supplied, e.g. when the assets
-
# are precompiled via a Rake task. Make sure to use a Proc instead of a lambda,
-
# since a Proc allows missing parameters and sets them to nil.
-
#
-
# config.action_controller.asset_host = Proc.new { |source, request|
-
# if request && request.ssl?
-
# "#{request.protocol}#{request.host_with_port}"
-
# else
-
# "#{request.protocol}assets.example.com"
-
# end
-
# }
-
#
-
# You can also implement a custom asset host object that responds to +call+
-
# and takes either one or two parameters just like the proc.
-
#
-
# config.action_controller.asset_host = AssetHostingWithMinimumSsl.new(
-
# "http://asset%d.example.com", "https://asset1.example.com"
-
# )
-
#
-
1
module AssetUrlHelper
-
1
URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//}i
-
-
# Computes the path to asset in public directory. If :type
-
# options is set, a file extension will be appended and scoped
-
# to the corresponding public directory.
-
#
-
# All other asset *_path helpers delegate through this method.
-
#
-
# asset_path "application.js" # => /assets/application.js
-
# asset_path "application", type: :javascript # => /assets/application.js
-
# asset_path "application", type: :stylesheet # => /assets/application.css
-
# asset_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
-
1
def asset_path(source, options = {})
-
110
source = source.to_s
-
110
return "" unless source.present?
-
110
return source if source =~ URI_REGEXP
-
-
110
tail, source = source[/([\?#].+)$/], source.sub(/([\?#].+)$/, '')
-
-
110
if extname = compute_asset_extname(source, options)
-
110
source = "#{source}#{extname}"
-
end
-
-
110
if source[0] != ?/
-
110
source = compute_asset_path(source, options)
-
end
-
-
110
relative_url_root = defined?(config.relative_url_root) && config.relative_url_root
-
110
if relative_url_root
-
source = File.join(relative_url_root, source) unless source.starts_with?("#{relative_url_root}/")
-
end
-
-
110
if host = compute_asset_host(source, options)
-
source = File.join(host, source)
-
end
-
-
110
"#{source}#{tail}"
-
end
-
1
alias_method :path_to_asset, :asset_path # aliased to avoid conflicts with an asset_path named route
-
-
# Computes the full URL to an asset in the public directory. This
-
# will use +asset_path+ internally, so most of their behaviors
-
# will be the same. If :host options is set, it overwrites global
-
# +config.action_controller.asset_host+ setting.
-
#
-
# All other options provided are forwarded to +asset_path+ call.
-
#
-
# asset_url "application.js" # => http://example.com/assets/application.js
-
# asset_url "application.js", host: "http://cdn.example.com" # => http://cdn.example.com/assets/application.js
-
#
-
1
def asset_url(source, options = {})
-
path_to_asset(source, options.merge(:protocol => :request))
-
end
-
1
alias_method :url_to_asset, :asset_url # aliased to avoid conflicts with an asset_url named route
-
-
1
ASSET_EXTENSIONS = {
-
javascript: '.js',
-
stylesheet: '.css'
-
}
-
-
# Compute extname to append to asset path. Returns nil if
-
# nothing should be added.
-
1
def compute_asset_extname(source, options = {})
-
110
return if options[:extname] == false
-
110
extname = options[:extname] || ASSET_EXTENSIONS[options[:type]]
-
110
extname if extname && File.extname(source) != extname
-
end
-
-
# Maps asset types to public directory.
-
1
ASSET_PUBLIC_DIRECTORIES = {
-
audio: '/audios',
-
font: '/fonts',
-
image: '/images',
-
javascript: '/javascripts',
-
stylesheet: '/stylesheets',
-
video: '/videos'
-
}
-
-
# Computes asset path to public directory. Plugins and
-
# extensions can override this method to point to custom assets
-
# or generate digested paths or query strings.
-
1
def compute_asset_path(source, options = {})
-
dir = ASSET_PUBLIC_DIRECTORIES[options[:type]] || ""
-
File.join(dir, source)
-
end
-
-
# Pick an asset host for this source. Returns +nil+ if no host is set,
-
# the host if no wildcard is set, the host interpolated with the
-
# numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4),
-
# or the value returned from invoking call on an object responding to call
-
# (proc or otherwise).
-
1
def compute_asset_host(source = "", options = {})
-
110
request = self.request if respond_to?(:request)
-
110
host = options[:host]
-
110
host ||= config.asset_host if defined? config.asset_host
-
-
110
if host.respond_to?(:call)
-
arity = host.respond_to?(:arity) ? host.arity : host.method(:call).arity
-
args = [source]
-
args << request if request && (arity > 1 || arity < 0)
-
host = host.call(*args)
-
elsif host =~ /%d/
-
host = host % (Zlib.crc32(source) % 4)
-
end
-
-
110
host ||= request.base_url if request && options[:protocol] == :request
-
110
return unless host
-
-
if host =~ URI_REGEXP
-
host
-
else
-
protocol = options[:protocol] || config.default_asset_host_protocol || (request ? :request : :relative)
-
case protocol
-
when :relative
-
"//#{host}"
-
when :request
-
"#{request.protocol}#{host}"
-
else
-
"#{protocol}://#{host}"
-
end
-
end
-
end
-
-
# Computes the path to a JavaScript asset in the public javascripts directory.
-
# If the +source+ filename has no extension, .js will be appended (except for explicit URIs)
-
# Full paths from the document root will be passed through.
-
# Used internally by +javascript_include_tag+ to build the script path.
-
#
-
# javascript_path "xmlhr" # => /assets/xmlhr.js
-
# javascript_path "dir/xmlhr.js" # => /assets/dir/xmlhr.js
-
# javascript_path "/dir/xmlhr" # => /dir/xmlhr.js
-
# javascript_path "http://www.example.com/js/xmlhr" # => http://www.example.com/js/xmlhr
-
# javascript_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
-
1
def javascript_path(source, options = {})
-
55
path_to_asset(source, {type: :javascript}.merge!(options))
-
end
-
1
alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
-
-
# Computes the full URL to a JavaScript asset in the public javascripts directory.
-
# This will use +javascript_path+ internally, so most of their behaviors will be the same.
-
1
def javascript_url(source, options = {})
-
url_to_asset(source, {type: :javascript}.merge!(options))
-
end
-
1
alias_method :url_to_javascript, :javascript_url # aliased to avoid conflicts with a javascript_url named route
-
-
# Computes the path to a stylesheet asset in the public stylesheets directory.
-
# If the +source+ filename has no extension, .css will be appended (except for explicit URIs).
-
# Full paths from the document root will be passed through.
-
# Used internally by +stylesheet_link_tag+ to build the stylesheet path.
-
#
-
# stylesheet_path "style" # => /assets/style.css
-
# stylesheet_path "dir/style.css" # => /assets/dir/style.css
-
# stylesheet_path "/dir/style.css" # => /dir/style.css
-
# stylesheet_path "http://www.example.com/css/style" # => http://www.example.com/css/style
-
# stylesheet_path "http://www.example.com/css/style.css" # => http://www.example.com/css/style.css
-
1
def stylesheet_path(source, options = {})
-
55
path_to_asset(source, {type: :stylesheet}.merge!(options))
-
end
-
1
alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
-
-
# Computes the full URL to a stylesheet asset in the public stylesheets directory.
-
# This will use +stylesheet_path+ internally, so most of their behaviors will be the same.
-
1
def stylesheet_url(source, options = {})
-
url_to_asset(source, {type: :stylesheet}.merge!(options))
-
end
-
1
alias_method :url_to_stylesheet, :stylesheet_url # aliased to avoid conflicts with a stylesheet_url named route
-
-
# Computes the path to an image asset.
-
# Full paths from the document root will be passed through.
-
# Used internally by +image_tag+ to build the image path:
-
#
-
# image_path("edit") # => "/assets/edit"
-
# image_path("edit.png") # => "/assets/edit.png"
-
# image_path("icons/edit.png") # => "/assets/icons/edit.png"
-
# image_path("/icons/edit.png") # => "/icons/edit.png"
-
# image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png"
-
#
-
# If you have images as application resources this method may conflict with their named routes.
-
# The alias +path_to_image+ is provided to avoid that. Rails uses the alias internally, and
-
# plugin authors are encouraged to do so.
-
1
def image_path(source, options = {})
-
path_to_asset(source, {type: :image}.merge!(options))
-
end
-
1
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
-
-
# Computes the full URL to an image asset.
-
# This will use +image_path+ internally, so most of their behaviors will be the same.
-
1
def image_url(source, options = {})
-
url_to_asset(source, {type: :image}.merge!(options))
-
end
-
1
alias_method :url_to_image, :image_url # aliased to avoid conflicts with an image_url named route
-
-
# Computes the path to a video asset in the public videos directory.
-
# Full paths from the document root will be passed through.
-
# Used internally by +video_tag+ to build the video path.
-
#
-
# video_path("hd") # => /videos/hd
-
# video_path("hd.avi") # => /videos/hd.avi
-
# video_path("trailers/hd.avi") # => /videos/trailers/hd.avi
-
# video_path("/trailers/hd.avi") # => /trailers/hd.avi
-
# video_path("http://www.example.com/vid/hd.avi") # => http://www.example.com/vid/hd.avi
-
1
def video_path(source, options = {})
-
path_to_asset(source, {type: :video}.merge!(options))
-
end
-
1
alias_method :path_to_video, :video_path # aliased to avoid conflicts with a video_path named route
-
-
# Computes the full URL to a video asset in the public videos directory.
-
# This will use +video_path+ internally, so most of their behaviors will be the same.
-
1
def video_url(source, options = {})
-
url_to_asset(source, {type: :video}.merge!(options))
-
end
-
1
alias_method :url_to_video, :video_url # aliased to avoid conflicts with an video_url named route
-
-
# Computes the path to an audio asset in the public audios directory.
-
# Full paths from the document root will be passed through.
-
# Used internally by +audio_tag+ to build the audio path.
-
#
-
# audio_path("horse") # => /audios/horse
-
# audio_path("horse.wav") # => /audios/horse.wav
-
# audio_path("sounds/horse.wav") # => /audios/sounds/horse.wav
-
# audio_path("/sounds/horse.wav") # => /sounds/horse.wav
-
# audio_path("http://www.example.com/sounds/horse.wav") # => http://www.example.com/sounds/horse.wav
-
1
def audio_path(source, options = {})
-
path_to_asset(source, {type: :audio}.merge!(options))
-
end
-
1
alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route
-
-
# Computes the full URL to an audio asset in the public audios directory.
-
# This will use +audio_path+ internally, so most of their behaviors will be the same.
-
1
def audio_url(source, options = {})
-
url_to_asset(source, {type: :audio}.merge!(options))
-
end
-
1
alias_method :url_to_audio, :audio_url # aliased to avoid conflicts with an audio_url named route
-
-
# Computes the path to a font asset.
-
# Full paths from the document root will be passed through.
-
#
-
# font_path("font") # => /fonts/font
-
# font_path("font.ttf") # => /fonts/font.ttf
-
# font_path("dir/font.ttf") # => /fonts/dir/font.ttf
-
# font_path("/dir/font.ttf") # => /dir/font.ttf
-
# font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf
-
1
def font_path(source, options = {})
-
path_to_asset(source, {type: :font}.merge!(options))
-
end
-
1
alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route
-
-
# Computes the full URL to a font asset.
-
# This will use +font_path+ internally, so most of their behaviors will be the same.
-
1
def font_url(source, options = {})
-
url_to_asset(source, {type: :font}.merge!(options))
-
end
-
1
alias_method :url_to_font, :font_url # aliased to avoid conflicts with an font_url named route
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module ActionView
-
# = Action View Atom Feed Helpers
-
1
module Helpers
-
1
module AtomFeedHelper
-
# Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERB or any other
-
# template languages).
-
#
-
# Full usage example:
-
#
-
# config/routes.rb:
-
# Rails.application.routes.draw do
-
# resources :posts
-
# root to: "posts#index"
-
# end
-
#
-
# app/controllers/posts_controller.rb:
-
# class PostsController < ApplicationController::Base
-
# # GET /posts.html
-
# # GET /posts.atom
-
# def index
-
# @posts = Post.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.atom
-
# end
-
# end
-
# end
-
#
-
# app/views/posts/index.atom.builder:
-
# atom_feed do |feed|
-
# feed.title("My great blog!")
-
# feed.updated(@posts[0].created_at) if @posts.length > 0
-
#
-
# @posts.each do |post|
-
# feed.entry(post) do |entry|
-
# entry.title(post.title)
-
# entry.content(post.body, type: 'html')
-
#
-
# entry.author do |author|
-
# author.name("DHH")
-
# end
-
# end
-
# end
-
# end
-
#
-
# The options for atom_feed are:
-
#
-
# * <tt>:language</tt>: Defaults to "en-US".
-
# * <tt>:root_url</tt>: The HTML alternative that this feed is doubling for. Defaults to / on the current host.
-
# * <tt>:url</tt>: The URL for this feed. Defaults to the current URL.
-
# * <tt>:id</tt>: The id for this feed. Defaults to "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}"
-
# * <tt>:schema_date</tt>: The date at which the tag scheme for the feed was first used. A good default is the year you
-
# created the feed. See http://feedvalidator.org/docs/error/InvalidTAG.html for more information. If not specified,
-
# 2005 is used (as an "I don't care" value).
-
# * <tt>:instruct</tt>: Hash of XML processing instructions in the form {target => {attribute => value, }} or {target => [{attribute => value, }, ]}
-
#
-
# Other namespaces can be added to the root element:
-
#
-
# app/views/posts/index.atom.builder:
-
# atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app',
-
# 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed|
-
# feed.title("My great blog!")
-
# feed.updated((@posts.first.created_at))
-
# feed.tag!('openSearch:totalResults', 10)
-
#
-
# @posts.each do |post|
-
# feed.entry(post) do |entry|
-
# entry.title(post.title)
-
# entry.content(post.body, type: 'html')
-
# entry.tag!('app:edited', Time.now)
-
#
-
# entry.author do |author|
-
# author.name("DHH")
-
# end
-
# end
-
# end
-
# end
-
#
-
# The Atom spec defines five elements (content rights title subtitle
-
# summary) which may directly contain xhtml content if type: 'xhtml'
-
# is specified as an attribute. If so, this helper will take care of
-
# the enclosing div and xhtml namespace declaration. Example usage:
-
#
-
# entry.summary type: 'xhtml' do |xhtml|
-
# xhtml.p pluralize(order.line_items.count, "line item")
-
# xhtml.p "Shipped to #{order.address}"
-
# xhtml.p "Paid by #{order.pay_type}"
-
# end
-
#
-
#
-
# <tt>atom_feed</tt> yields an +AtomFeedBuilder+ instance. Nested elements yield
-
# an +AtomBuilder+ instance.
-
1
def atom_feed(options = {}, &block)
-
if options[:schema_date]
-
options[:schema_date] = options[:schema_date].strftime("%Y-%m-%d") if options[:schema_date].respond_to?(:strftime)
-
else
-
options[:schema_date] = "2005" # The Atom spec copyright date
-
end
-
-
xml = options.delete(:xml) || eval("xml", block.binding)
-
xml.instruct!
-
if options[:instruct]
-
options[:instruct].each do |target,attrs|
-
if attrs.respond_to?(:keys)
-
xml.instruct!(target, attrs)
-
elsif attrs.respond_to?(:each)
-
attrs.each { |attr_group| xml.instruct!(target, attr_group) }
-
end
-
end
-
end
-
-
feed_opts = {"xml:lang" => options[:language] || "en-US", "xmlns" => 'http://www.w3.org/2005/Atom'}
-
feed_opts.merge!(options).reject!{|k,v| !k.to_s.match(/^xml/)}
-
-
xml.feed(feed_opts) do
-
xml.id(options[:id] || "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}")
-
xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:root_url] || (request.protocol + request.host_with_port))
-
xml.link(:rel => 'self', :type => 'application/atom+xml', :href => options[:url] || request.url)
-
-
yield AtomFeedBuilder.new(xml, self, options)
-
end
-
end
-
-
1
class AtomBuilder #:nodoc:
-
1
XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set
-
-
1
def initialize(xml)
-
@xml = xml
-
end
-
-
1
private
-
# Delegate to xml builder, first wrapping the element in a xhtml
-
# namespaced div element if the method and arguments indicate
-
# that an xhtml_block? is desired.
-
1
def method_missing(method, *arguments, &block)
-
if xhtml_block?(method, arguments)
-
@xml.__send__(method, *arguments) do
-
@xml.div(:xmlns => 'http://www.w3.org/1999/xhtml') do |xhtml|
-
block.call(xhtml)
-
end
-
end
-
else
-
@xml.__send__(method, *arguments, &block)
-
end
-
end
-
-
# True if the method name matches one of the five elements defined
-
# in the Atom spec as potentially containing XHTML content and
-
# if type: 'xhtml' is, in fact, specified.
-
1
def xhtml_block?(method, arguments)
-
if XHTML_TAG_NAMES.include?(method.to_s)
-
last = arguments.last
-
last.is_a?(Hash) && last[:type].to_s == 'xhtml'
-
end
-
end
-
end
-
-
1
class AtomFeedBuilder < AtomBuilder #:nodoc:
-
1
def initialize(xml, view, feed_options = {})
-
@xml, @view, @feed_options = xml, view, feed_options
-
end
-
-
# Accepts a Date or Time object and inserts it in the proper format. If nil is passed, current time in UTC is used.
-
1
def updated(date_or_time = nil)
-
@xml.updated((date_or_time || Time.now.utc).xmlschema)
-
end
-
-
# Creates an entry tag for a specific record and prefills the id using class and id.
-
#
-
# Options:
-
#
-
# * <tt>:published</tt>: Time first published. Defaults to the created_at attribute on the record if one such exists.
-
# * <tt>:updated</tt>: Time of update. Defaults to the updated_at attribute on the record if one such exists.
-
# * <tt>:url</tt>: The URL for this entry. Defaults to the polymorphic_url for the record.
-
# * <tt>:id</tt>: The ID for this entry. Defaults to "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}"
-
# * <tt>:type</tt>: The TYPE for this entry. Defaults to "text/html".
-
1
def entry(record, options = {})
-
@xml.entry do
-
@xml.id(options[:id] || "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}")
-
-
if options[:published] || (record.respond_to?(:created_at) && record.created_at)
-
@xml.published((options[:published] || record.created_at).xmlschema)
-
end
-
-
if options[:updated] || (record.respond_to?(:updated_at) && record.updated_at)
-
@xml.updated((options[:updated] || record.updated_at).xmlschema)
-
end
-
-
type = options.fetch(:type, 'text/html')
-
-
@xml.link(:rel => 'alternate', :type => type, :href => options[:url] || @view.polymorphic_url(record))
-
-
yield AtomBuilder.new(@xml)
-
end
-
end
-
end
-
-
end
-
end
-
end
-
1
module ActionView
-
# = Action View Cache Helper
-
1
module Helpers
-
1
module CacheHelper
-
# This helper exposes a method for caching fragments of a view
-
# rather than an entire action or page. This technique is useful
-
# caching pieces like menus, lists of new topics, static HTML
-
# fragments, and so on. This method takes a block that contains
-
# the content you wish to cache.
-
#
-
# The best way to use this is by doing key-based cache expiration
-
# on top of a cache store like Memcached that'll automatically
-
# kick out old entries. For more on key-based expiration, see:
-
# http://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works
-
#
-
# When using this method, you list the cache dependency as the name of the cache, like so:
-
#
-
# <% cache project do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
#
-
# This approach will assume that when a new topic is added, you'll touch
-
# the project. The cache key generated from this call will be something like:
-
#
-
# views/projects/123-20120806214154/7a1156131a6928cb0026877f8b749ac9
-
# ^class ^id ^updated_at ^template tree digest
-
#
-
# The cache is thus automatically bumped whenever the project updated_at is touched.
-
#
-
# If your template cache depends on multiple sources (try to avoid this to keep things simple),
-
# you can name all these dependencies as part of an array:
-
#
-
# <% cache [ project, current_user ] do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
#
-
# This will include both records as part of the cache key and updating either of them will
-
# expire the cache.
-
#
-
# ==== Template digest
-
#
-
# The template digest that's added to the cache key is computed by taking an md5 of the
-
# contents of the entire template file. This ensures that your caches will automatically
-
# expire when you change the template file.
-
#
-
# Note that the md5 is taken of the entire template file, not just what's within the
-
# cache do/end call. So it's possible that changing something outside of that call will
-
# still expire the cache.
-
#
-
# Additionally, the digestor will automatically look through your template file for
-
# explicit and implicit dependencies, and include those as part of the digest.
-
#
-
# The digestor can be bypassed by passing skip_digest: true as an option to the cache call:
-
#
-
# <% cache project, skip_digest: true do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
#
-
# ==== Implicit dependencies
-
#
-
# Most template dependencies can be derived from calls to render in the template itself.
-
# Here are some examples of render calls that Cache Digests knows how to decode:
-
#
-
# render partial: "comments/comment", collection: commentable.comments
-
# render "comments/comments"
-
# render 'comments/comments'
-
# render('comments/comments')
-
#
-
# render "header" => render("comments/header")
-
#
-
# render(@topic) => render("topics/topic")
-
# render(topics) => render("topics/topic")
-
# render(message.topics) => render("topics/topic")
-
#
-
# It's not possible to derive all render calls like that, though. Here are a few examples of things that can't be derived:
-
#
-
# render group_of_attachments
-
# render @project.documents.where(published: true).order('created_at')
-
#
-
# You will have to rewrite those to the explicit form:
-
#
-
# render partial: 'attachments/attachment', collection: group_of_attachments
-
# render partial: 'documents/document', collection: @project.documents.where(published: true).order('created_at')
-
#
-
# === Explicit dependencies
-
#
-
# Some times you'll have template dependencies that can't be derived at all. This is typically
-
# the case when you have template rendering that happens in helpers. Here's an example:
-
#
-
# <%= render_sortable_todolists @project.todolists %>
-
#
-
# You'll need to use a special comment format to call those out:
-
#
-
# <%# Template Dependency: todolists/todolist %>
-
# <%= render_sortable_todolists @project.todolists %>
-
#
-
# The pattern used to match these is /# Template Dependency: ([^ ]+)/, so it's important that you type it out just so.
-
# You can only declare one template dependency per line.
-
#
-
# === External dependencies
-
#
-
# If you use a helper method, for example, inside of a cached block and you then update that helper,
-
# you'll have to bump the cache as well. It doesn't really matter how you do it, but the md5 of the template file
-
# must change. One recommendation is to simply be explicit in a comment, like:
-
#
-
# <%# Helper Dependency Updated: May 6, 2012 at 6pm %>
-
# <%= some_helper_method(person) %>
-
#
-
# Now all you'll have to do is change that timestamp when the helper method changes.
-
1
def cache(name = {}, options = nil, &block)
-
if controller.respond_to?(:perform_caching) && controller.perform_caching
-
safe_concat(fragment_for(cache_fragment_name(name, options), options, &block))
-
else
-
yield
-
end
-
-
nil
-
end
-
-
# Cache fragments of a view if +condition+ is true
-
#
-
# <% cache_if admin?, project do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
1
def cache_if(condition, name = {}, options = nil, &block)
-
if condition
-
cache(name, options, &block)
-
else
-
yield
-
end
-
-
nil
-
end
-
-
# Cache fragments of a view unless +condition+ is true
-
#
-
# <% cache_unless admin?, project do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
1
def cache_unless(condition, name = {}, options = nil, &block)
-
cache_if !condition, name, options, &block
-
end
-
-
# This helper returns the name of a cache key for a given fragment cache
-
# call. By supplying skip_digest: true to cache, the digestion of cache
-
# fragments can be manually bypassed. This is useful when cache fragments
-
# cannot be manually expired unless you know the exact key which is the
-
# case when using memcached.
-
1
def cache_fragment_name(name = {}, options = nil)
-
skip_digest = options && options[:skip_digest]
-
-
if skip_digest
-
name
-
else
-
fragment_name_with_digest(name)
-
end
-
end
-
-
1
private
-
-
1
def fragment_name_with_digest(name) #:nodoc:
-
if @virtual_path
-
names = Array(name.is_a?(Hash) ? controller.url_for(name).split("://").last : name)
-
digest = Digestor.digest name: @virtual_path, finder: lookup_context, dependencies: view_cache_dependencies
-
-
[ *names, digest ]
-
else
-
name
-
end
-
end
-
-
# TODO: Create an object that has caching read/write on it
-
1
def fragment_for(name = {}, options = nil, &block) #:nodoc:
-
read_fragment_for(name, options) || write_fragment_for(name, options, &block)
-
end
-
-
1
def read_fragment_for(name, options) #:nodoc:
-
controller.read_fragment(name, options)
-
end
-
-
1
def write_fragment_for(name, options) #:nodoc:
-
# VIEW TODO: Make #capture usable outside of ERB
-
# This dance is needed because Builder can't use capture
-
pos = output_buffer.length
-
yield
-
output_safe = output_buffer.html_safe?
-
fragment = output_buffer.slice!(pos..-1)
-
if output_safe
-
self.output_buffer = output_buffer.class.new(output_buffer)
-
end
-
controller.write_fragment(name, fragment, options)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView
-
# = Action View Capture Helper
-
1
module Helpers
-
# CaptureHelper exposes methods to let you extract generated markup which
-
# can be used in other parts of a template or layout file.
-
#
-
# It provides a method to capture blocks into variables through capture and
-
# a way to capture a block of markup for use in a layout through content_for.
-
1
module CaptureHelper
-
# The capture method allows you to extract part of a template into a
-
# variable. You can then use this variable anywhere in your templates or layout.
-
#
-
# The capture method can be used in ERB templates...
-
#
-
# <% @greeting = capture do %>
-
# Welcome to my shiny new web page! The date and time is
-
# <%= Time.now %>
-
# <% end %>
-
#
-
# ...and Builder (RXML) templates.
-
#
-
# @timestamp = capture do
-
# "The current timestamp is #{Time.now}."
-
# end
-
#
-
# You can then use that variable anywhere else. For example:
-
#
-
# <html>
-
# <head><title><%= @greeting %></title></head>
-
# <body>
-
# <b><%= @greeting %></b>
-
# </body></html>
-
#
-
1
def capture(*args)
-
value = nil
-
buffer = with_output_buffer { value = yield(*args) }
-
if string = buffer.presence || value and string.is_a?(String)
-
ERB::Util.html_escape string
-
end
-
end
-
-
# Calling content_for stores a block of markup in an identifier for later use.
-
# In order to access this stored content in other templates, helper modules
-
# or the layout, you would pass the identifier as an argument to <tt>content_for</tt>.
-
#
-
# Note: <tt>yield</tt> can still be used to retrieve the stored content, but calling
-
# <tt>yield</tt> doesn't work in helper modules, while <tt>content_for</tt> does.
-
#
-
# <% content_for :not_authorized do %>
-
# alert('You are not authorized to do that!')
-
# <% end %>
-
#
-
# You can then use <tt>content_for :not_authorized</tt> anywhere in your templates.
-
#
-
# <%= content_for :not_authorized if current_user.nil? %>
-
#
-
# This is equivalent to:
-
#
-
# <%= yield :not_authorized if current_user.nil? %>
-
#
-
# <tt>content_for</tt>, however, can also be used in helper modules.
-
#
-
# module StorageHelper
-
# def stored_content
-
# content_for(:storage) || "Your storage is empty"
-
# end
-
# end
-
#
-
# This helper works just like normal helpers.
-
#
-
# <%= stored_content %>
-
#
-
# You can also use the <tt>yield</tt> syntax alongside an existing call to
-
# <tt>yield</tt> in a layout. For example:
-
#
-
# <%# This is the layout %>
-
# <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
# <head>
-
# <title>My Website</title>
-
# <%= yield :script %>
-
# </head>
-
# <body>
-
# <%= yield %>
-
# </body>
-
# </html>
-
#
-
# And now, we'll create a view that has a <tt>content_for</tt> call that
-
# creates the <tt>script</tt> identifier.
-
#
-
# <%# This is our view %>
-
# Please login!
-
#
-
# <% content_for :script do %>
-
# <script>alert('You are not authorized to view this page!')</script>
-
# <% end %>
-
#
-
# Then, in another view, you could to do something like this:
-
#
-
# <%= link_to 'Logout', action: 'logout', remote: true %>
-
#
-
# <% content_for :script do %>
-
# <%= javascript_include_tag :defaults %>
-
# <% end %>
-
#
-
# That will place +script+ tags for your default set of JavaScript files on the page;
-
# this technique is useful if you'll only be using these scripts in a few views.
-
#
-
# Note that content_for concatenates (default) the blocks it is given for a particular
-
# identifier in order. For example:
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Home', action: 'index' %></li>
-
# <% end %>
-
#
-
# And in other place:
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Login', action: 'login' %></li>
-
# <% end %>
-
#
-
# Then, in another template or layout, this code would render both links in order:
-
#
-
# <ul><%= content_for :navigation %></ul>
-
#
-
# If the flush parameter is true content_for replaces the blocks it is given. For example:
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Home', action: 'index' %></li>
-
# <% end %>
-
#
-
# <%# Add some other content, or use a different template: %>
-
#
-
# <% content_for :navigation, flush: true do %>
-
# <li><%= link_to 'Login', action: 'login' %></li>
-
# <% end %>
-
#
-
# Then, in another template or layout, this code would render only the last link:
-
#
-
# <ul><%= content_for :navigation %></ul>
-
#
-
# Lastly, simple content can be passed as a parameter:
-
#
-
# <% content_for :script, javascript_include_tag(:defaults) %>
-
#
-
# WARNING: content_for is ignored in caches. So you shouldn't use it for elements that will be fragment cached.
-
1
def content_for(name, content = nil, options = {}, &block)
-
if content || block_given?
-
if block_given?
-
options = content if content
-
content = capture(&block)
-
end
-
if content
-
options[:flush] ? @view_flow.set(name, content) : @view_flow.append(name, content)
-
end
-
nil
-
else
-
@view_flow.get(name).presence
-
end
-
end
-
-
# The same as +content_for+ but when used with streaming flushes
-
# straight back to the layout. In other words, if you want to
-
# concatenate several times to the same buffer when rendering a given
-
# template, you should use +content_for+, if not, use +provide+ to tell
-
# the layout to stop looking for more contents.
-
1
def provide(name, content = nil, &block)
-
content = capture(&block) if block_given?
-
result = @view_flow.append!(name, content) if content
-
result unless content
-
end
-
-
# content_for? checks whether any content has been captured yet using `content_for`.
-
# Useful to render parts of your layout differently based on what is in your views.
-
#
-
# <%# This is the layout %>
-
# <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
# <head>
-
# <title>My Website</title>
-
# <%= yield :script %>
-
# </head>
-
# <body class="<%= content_for?(:right_col) ? 'two-column' : 'one-column' %>">
-
# <%= yield %>
-
# <%= yield :right_col %>
-
# </body>
-
# </html>
-
1
def content_for?(name)
-
55
@view_flow.get(name).present?
-
end
-
-
# Use an alternate output buffer for the duration of the block.
-
# Defaults to a new empty string.
-
1
def with_output_buffer(buf = nil) #:nodoc:
-
unless buf
-
buf = ActionView::OutputBuffer.new
-
if output_buffer && output_buffer.respond_to?(:encoding)
-
buf.force_encoding(output_buffer.encoding)
-
end
-
end
-
self.output_buffer, old_buffer = buf, output_buffer
-
yield
-
output_buffer
-
ensure
-
self.output_buffer = old_buffer
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attr_internal'
-
-
1
module ActionView
-
1
module Helpers
-
# This module keeps all methods and behavior in ActionView
-
# that simply delegates to the controller.
-
1
module ControllerHelper #:nodoc:
-
1
attr_internal :controller, :request
-
-
1
delegate :request_forgery_protection_token, :params, :session, :cookies, :response, :headers,
-
:flash, :action_name, :controller_name, :controller_path, :to => :controller
-
-
1
def assign_controller(controller)
-
55
if @_controller = controller
-
55
@_request = controller.request if controller.respond_to?(:request)
-
55
@_config = controller.config.inheritable_copy if controller.respond_to?(:config)
-
end
-
end
-
-
1
def logger
-
controller.logger if controller.respond_to?(:logger)
-
end
-
end
-
end
-
end
-
1
module ActionView
-
# = Action View CSRF Helper
-
1
module Helpers
-
1
module CsrfHelper
-
# Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site
-
# request forgery protection parameter and token, respectively.
-
#
-
# <head>
-
# <%= csrf_meta_tags %>
-
# </head>
-
#
-
# These are used to generate the dynamic forms that implement non-remote links with
-
# <tt>:method</tt>.
-
#
-
# You don't need to use these tags for regular forms as they generate their own hidden fields.
-
#
-
# For AJAX requests other than GETs, extract the "csrf-token" from the meta-tag and send as the
-
# "X-CSRF-Token" HTTP header. If you are using jQuery with jquery-rails this happens automatically.
-
#
-
1
def csrf_meta_tags
-
55
if protect_against_forgery?
-
[
-
tag('meta', :name => 'csrf-param', :content => request_forgery_protection_token),
-
tag('meta', :name => 'csrf-token', :content => form_authenticity_token)
-
].join("\n").html_safe
-
end
-
end
-
-
# For backwards compatibility.
-
1
alias csrf_meta_tag csrf_meta_tags
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'action_view/helpers/tag_helper'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/date/conversions'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/object/with_options'
-
-
1
module ActionView
-
1
module Helpers
-
# = Action View Date Helpers
-
#
-
# The Date Helper primarily creates select/option tags for different kinds of dates and times or date and time
-
# elements. All of the select-type methods share a number of common options that are as follows:
-
#
-
# * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday"
-
# would give \birthday[month] instead of \date[month] if passed to the <tt>select_month</tt> method.
-
# * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
-
# * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true,
-
# the <tt>select_month</tt> method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead
-
# of \date[month].
-
1
module DateHelper
-
1
MINUTES_IN_YEAR = 525600
-
1
MINUTES_IN_QUARTER_YEAR = 131400
-
1
MINUTES_IN_THREE_QUARTERS_YEAR = 394200
-
-
# Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds.
-
# Pass <tt>include_seconds: true</tt> if you want more detailed approximations when distance < 1 min, 29 secs.
-
# Distances are reported based on the following table:
-
#
-
# 0 <-> 29 secs # => less than a minute
-
# 30 secs <-> 1 min, 29 secs # => 1 minute
-
# 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
-
# 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
-
# 89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
-
# 23 hrs, 59 mins, 30 secs <-> 41 hrs, 59 mins, 29 secs # => 1 day
-
# 41 hrs, 59 mins, 30 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
-
# 29 days, 23 hrs, 59 mins, 30 secs <-> 44 days, 23 hrs, 59 mins, 29 secs # => about 1 month
-
# 44 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 2 months
-
# 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months
-
# 1 yr <-> 1 yr, 3 months # => about 1 year
-
# 1 yr, 3 months <-> 1 yr, 9 months # => over 1 year
-
# 1 yr, 9 months <-> 2 yr minus 1 sec # => almost 2 years
-
# 2 yrs <-> max time or date # => (same rules as 1 yr)
-
#
-
# With <tt>include_seconds: true</tt> and the difference < 1 minute 29 seconds:
-
# 0-4 secs # => less than 5 seconds
-
# 5-9 secs # => less than 10 seconds
-
# 10-19 secs # => less than 20 seconds
-
# 20-39 secs # => half a minute
-
# 40-59 secs # => less than a minute
-
# 60-89 secs # => 1 minute
-
#
-
# from_time = Time.now
-
# distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
-
# distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
-
# distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
-
# distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) # => less than 20 seconds
-
# distance_of_time_in_words(from_time, 3.years.from_now) # => about 3 years
-
# distance_of_time_in_words(from_time, from_time + 60.hours) # => 3 days
-
# distance_of_time_in_words(from_time, from_time + 45.seconds, include_seconds: true) # => less than a minute
-
# distance_of_time_in_words(from_time, from_time - 45.seconds, include_seconds: true) # => less than a minute
-
# distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute
-
# distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year
-
# distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years
-
# distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => about 4 years
-
#
-
# to_time = Time.now + 6.years + 19.days
-
# distance_of_time_in_words(from_time, to_time, include_seconds: true) # => about 6 years
-
# distance_of_time_in_words(to_time, from_time, include_seconds: true) # => about 6 years
-
# distance_of_time_in_words(Time.now, Time.now) # => less than a minute
-
1
def distance_of_time_in_words(from_time, to_time = 0, options = {})
-
options = {
-
scope: :'datetime.distance_in_words'
-
}.merge!(options)
-
-
from_time = from_time.to_time if from_time.respond_to?(:to_time)
-
to_time = to_time.to_time if to_time.respond_to?(:to_time)
-
from_time, to_time = to_time, from_time if from_time > to_time
-
distance_in_minutes = ((to_time - from_time)/60.0).round
-
distance_in_seconds = (to_time - from_time).round
-
-
I18n.with_options :locale => options[:locale], :scope => options[:scope] do |locale|
-
case distance_in_minutes
-
when 0..1
-
return distance_in_minutes == 0 ?
-
locale.t(:less_than_x_minutes, :count => 1) :
-
locale.t(:x_minutes, :count => distance_in_minutes) unless options[:include_seconds]
-
-
case distance_in_seconds
-
when 0..4 then locale.t :less_than_x_seconds, :count => 5
-
when 5..9 then locale.t :less_than_x_seconds, :count => 10
-
when 10..19 then locale.t :less_than_x_seconds, :count => 20
-
when 20..39 then locale.t :half_a_minute
-
when 40..59 then locale.t :less_than_x_minutes, :count => 1
-
else locale.t :x_minutes, :count => 1
-
end
-
-
when 2...45 then locale.t :x_minutes, :count => distance_in_minutes
-
when 45...90 then locale.t :about_x_hours, :count => 1
-
# 90 mins up to 24 hours
-
when 90...1440 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round
-
# 24 hours up to 42 hours
-
when 1440...2520 then locale.t :x_days, :count => 1
-
# 42 hours up to 30 days
-
when 2520...43200 then locale.t :x_days, :count => (distance_in_minutes.to_f / 1440.0).round
-
# 30 days up to 60 days
-
when 43200...86400 then locale.t :about_x_months, :count => (distance_in_minutes.to_f / 43200.0).round
-
# 60 days up to 365 days
-
when 86400...525600 then locale.t :x_months, :count => (distance_in_minutes.to_f / 43200.0).round
-
else
-
if from_time.acts_like?(:time) && to_time.acts_like?(:time)
-
fyear = from_time.year
-
fyear += 1 if from_time.month >= 3
-
tyear = to_time.year
-
tyear -= 1 if to_time.month < 3
-
leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count{|x| Date.leap?(x)}
-
minute_offset_for_leap_year = leap_years * 1440
-
# Discount the leap year days when calculating year distance.
-
# e.g. if there are 20 leap year days between 2 dates having the same day
-
# and month then the based on 365 days calculation
-
# the distance in years will come out to over 80 years when in written
-
# English it would read better as about 80 years.
-
minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
-
else
-
minutes_with_offset = distance_in_minutes
-
end
-
remainder = (minutes_with_offset % MINUTES_IN_YEAR)
-
distance_in_years = (minutes_with_offset.div MINUTES_IN_YEAR)
-
if remainder < MINUTES_IN_QUARTER_YEAR
-
locale.t(:about_x_years, :count => distance_in_years)
-
elsif remainder < MINUTES_IN_THREE_QUARTERS_YEAR
-
locale.t(:over_x_years, :count => distance_in_years)
-
else
-
locale.t(:almost_x_years, :count => distance_in_years + 1)
-
end
-
end
-
end
-
end
-
-
# Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
-
#
-
# time_ago_in_words(3.minutes.from_now) # => 3 minutes
-
# time_ago_in_words(3.minutes.ago) # => 3 minutes
-
# time_ago_in_words(Time.now - 15.hours) # => about 15 hours
-
# time_ago_in_words(Time.now) # => less than a minute
-
# time_ago_in_words(Time.now, include_seconds: true) # => less than 5 seconds
-
#
-
# from_time = Time.now - 3.days - 14.minutes - 25.seconds
-
# time_ago_in_words(from_time) # => 3 days
-
#
-
# from_time = (3.days + 14.minutes + 25.seconds).ago
-
# time_ago_in_words(from_time) # => 3 days
-
#
-
# Note that you cannot pass a <tt>Numeric</tt> value to <tt>time_ago_in_words</tt>.
-
#
-
1
def time_ago_in_words(from_time, options = {})
-
distance_of_time_in_words(from_time, Time.now, options)
-
end
-
-
1
alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
-
-
# Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based
-
# attribute (identified by +method+) on an object assigned to the template (identified by +object+).
-
#
-
# ==== Options
-
# * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g.
-
# "2" instead of "February").
-
# * <tt>:use_two_digit_numbers</tt> - Set to true if you want to display two digit month and day numbers (e.g.
-
# "02" instead of "February" and "08" instead of "8").
-
# * <tt>:use_short_month</tt> - Set to true if you want to use abbreviated month names instead of full
-
# month names (e.g. "Feb" instead of "February").
-
# * <tt>:add_month_numbers</tt> - Set to true if you want to use both month numbers and month names (e.g.
-
# "2 - February" instead of "February").
-
# * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names.
-
# Note: You can also use Rails' i18n functionality for this.
-
# * <tt>:month_format_string</tt> - Set to a format string. The string gets passed keys +:number+ (integer)
-
# and +:name+ (string). A format string would be something like "%{name} (%<number>02d)" for example.
-
# See <tt>Kernel.sprintf</tt> for documentation on format sequences.
-
# * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
-
# * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Date.today.year - 5</tt> if
-
# you are creating new record. While editing existing record, <tt>:start_year</tt> defaults to
-
# the current selected year minus 5.
-
# * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Date.today.year + 5</tt> if
-
# you are creating new record. While editing existing record, <tt>:end_year</tt> defaults to
-
# the current selected year plus 5.
-
# * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day
-
# as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the
-
# first of the given month in order to not create invalid dates like 31 February.
-
# * <tt>:discard_month</tt> - Set to true if you don't want to show a month select. This includes the month
-
# as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true.
-
# * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year
-
# as a hidden field instead of showing a select field.
-
# * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> to
-
# customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
-
# select will not be shown (like when you set <tt>discard_xxx: true</tt>. Defaults to the order defined in
-
# the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
-
# * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty
-
# dates.
-
# * <tt>:default</tt> - Set a default date if the affected date isn't set or is nil.
-
# * <tt>:selected</tt> - Set a date that overrides the actual value.
-
# * <tt>:disabled</tt> - Set to true if you want show the select fields as disabled.
-
# * <tt>:prompt</tt> - Set to true (for a generic prompt), a prompt string or a hash of prompt strings
-
# for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt> and <tt>:second</tt>.
-
# Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds)
-
# or the given prompt string.
-
# * <tt>:with_css_classes</tt> - Set to true if you want assign different styles for 'select' tags. This option
-
# automatically set classes 'year', 'month', 'day', 'hour', 'minute' and 'second' for your 'select' tags.
-
#
-
# If anything is passed in the +html_options+ hash it will be applied to every select tag in the set.
-
#
-
# NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute.
-
# date_select("article", "written_on")
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with the year in the year drop down box starting at 1995.
-
# date_select("article", "written_on", start_year: 1995)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with the year in the year drop down box starting at 1995, numbers used for months instead of words,
-
# # and without a day select box.
-
# date_select("article", "written_on", start_year: 1995, use_month_numbers: true,
-
# discard_day: true, include_blank: true)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with two digit numbers used for months and days.
-
# date_select("article", "written_on", use_two_digit_numbers: true)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # with the fields ordered as day, month, year rather than month, day, year.
-
# date_select("article", "written_on", order: [:day, :month, :year])
-
#
-
# # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
-
# # lacking a year field.
-
# date_select("user", "birthday", order: [:month, :day])
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # which is initially set to the date 3 days from the current date
-
# date_select("article", "written_on", default: 3.days.from_now)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # which is set in the form with todays date, regardless of the value in the Active Record object.
-
# date_select("article", "written_on", selected: Date.today)
-
#
-
# # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute
-
# # that will have a default day of 20.
-
# date_select("credit_card", "bill_due", default: { day: 20 })
-
#
-
# # Generates a date select with custom prompts.
-
# date_select("article", "written_on", prompt: { day: 'Select day', month: 'Select month', year: 'Select year' })
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
#
-
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
-
# all month choices are valid.
-
1
def date_select(object_name, method, options = {}, html_options = {})
-
2
Tags::DateSelect.new(object_name, method, self, options, html_options).render
-
end
-
-
# Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a
-
# specified time-based attribute (identified by +method+) on an object assigned to the template (identified by
-
# +object+). You can include the seconds with <tt>:include_seconds</tt>. You can get hours in the AM/PM format
-
# with <tt>:ampm</tt> option.
-
#
-
# This method will also generate 3 input hidden tags, for the actual year, month and day unless the option
-
# <tt>:ignore_date</tt> is set to +true+. If you set the <tt>:ignore_date</tt> to +true+, you must have a
-
# +date_select+ on the same method within the form otherwise an exception will be raised.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# # Creates a time select tag that, when POSTed, will be stored in the article variable in the sunrise attribute.
-
# time_select("article", "sunrise")
-
#
-
# # Creates a time select tag with a seconds field that, when POSTed, will be stored in the article variables in
-
# # the sunrise attribute.
-
# time_select("article", "start_time", include_seconds: true)
-
#
-
# # You can set the <tt>:minute_step</tt> to 15 which will give you: 00, 15, 30 and 45.
-
# time_select 'game', 'game_time', {minute_step: 15}
-
#
-
# # Creates a time select tag with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# time_select("article", "written_on", prompt: {hour: 'Choose hour', minute: 'Choose minute', second: 'Choose seconds'})
-
# time_select("article", "written_on", prompt: {hour: true}) # generic prompt for hours
-
# time_select("article", "written_on", prompt: true) # generic prompts for all
-
#
-
# # You can set :ampm option to true which will show the hours as: 12 PM, 01 AM .. 11 PM.
-
# time_select 'game', 'game_time', {ampm: true}
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
#
-
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
-
# all month choices are valid.
-
1
def time_select(object_name, method, options = {}, html_options = {})
-
Tags::TimeSelect.new(object_name, method, self, options, html_options).render
-
end
-
-
# Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a
-
# specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified
-
# by +object+).
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# # Generates a datetime select that, when POSTed, will be stored in the article variable in the written_on
-
# # attribute.
-
# datetime_select("article", "written_on")
-
#
-
# # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the
-
# # article variable in the written_on attribute.
-
# datetime_select("article", "written_on", start_year: 1995)
-
#
-
# # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will
-
# # be stored in the trip variable in the departing attribute.
-
# datetime_select("trip", "departing", default: 3.days.from_now)
-
#
-
# # Generate a datetime select with hours in the AM/PM format
-
# datetime_select("article", "written_on", ampm: true)
-
#
-
# # Generates a datetime select that discards the type that, when POSTed, will be stored in the article variable
-
# # as the written_on attribute.
-
# datetime_select("article", "written_on", discard_type: true)
-
#
-
# # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# datetime_select("article", "written_on", prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# datetime_select("article", "written_on", prompt: {hour: true}) # generic prompt for hours
-
# datetime_select("article", "written_on", prompt: true) # generic prompts for all
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
1
def datetime_select(object_name, method, options = {}, html_options = {})
-
Tags::DatetimeSelect.new(object_name, method, self, options, html_options).render
-
end
-
-
# Returns a set of HTML select-tags (one for year, month, day, hour, minute, and second) pre-selected with the
-
# +datetime+. It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with
-
# an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not
-
# supply a Symbol, it will be appended onto the <tt>:order</tt> passed in. You can also add
-
# <tt>:date_separator</tt>, <tt>:datetime_separator</tt> and <tt>:time_separator</tt> keys to the +options+ to
-
# control visual display of the elements.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# my_date_time = Time.now + 4.days
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today).
-
# select_datetime(my_date_time)
-
#
-
# # Generates a datetime select that defaults to today (no specified datetime)
-
# select_datetime()
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with the fields ordered year, month, day rather than month, day, year.
-
# select_datetime(my_date_time, order: [:year, :month, :day])
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with a '/' between each date field.
-
# select_datetime(my_date_time, date_separator: '/')
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with a date fields separated by '/', time fields separated by '' and the date and time fields
-
# # separated by a comma (',').
-
# select_datetime(my_date_time, date_separator: '/', time_separator: '', datetime_separator: ',')
-
#
-
# # Generates a datetime select that discards the type of the field and defaults to the datetime in
-
# # my_date_time (four days after today)
-
# select_datetime(my_date_time, discard_type: true)
-
#
-
# # Generate a datetime field with hours in the AM/PM format
-
# select_datetime(my_date_time, ampm: true)
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # prefixed with 'payday' rather than 'date'
-
# select_datetime(my_date_time, prefix: 'payday')
-
#
-
# # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# select_datetime(my_date_time, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# select_datetime(my_date_time, prompt: {hour: true}) # generic prompt for hours
-
# select_datetime(my_date_time, prompt: true) # generic prompts for all
-
1
def select_datetime(datetime = Time.current, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_datetime
-
end
-
-
# Returns a set of HTML select-tags (one for year, month, and day) pre-selected with the +date+.
-
# It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
-
# symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order.
-
# If the array passed to the <tt>:order</tt> option does not contain all the three symbols, all tags will be hidden.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# my_date = Time.now + 6.days
-
#
-
# # Generates a date select that defaults to the date in my_date (six days after today).
-
# select_date(my_date)
-
#
-
# # Generates a date select that defaults to today (no specified date).
-
# select_date()
-
#
-
# # Generates a date select that defaults to the date in my_date (six days after today)
-
# # with the fields ordered year, month, day rather than month, day, year.
-
# select_date(my_date, order: [:year, :month, :day])
-
#
-
# # Generates a date select that discards the type of the field and defaults to the date in
-
# # my_date (six days after today).
-
# select_date(my_date, discard_type: true)
-
#
-
# # Generates a date select that defaults to the date in my_date,
-
# # which has fields separated by '/'.
-
# select_date(my_date, date_separator: '/')
-
#
-
# # Generates a date select that defaults to the datetime in my_date (six days after today)
-
# # prefixed with 'payday' rather than 'date'.
-
# select_date(my_date, prefix: 'payday')
-
#
-
# # Generates a date select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# select_date(my_date, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# select_date(my_date, prompt: {hour: true}) # generic prompt for hours
-
# select_date(my_date, prompt: true) # generic prompts for all
-
1
def select_date(date = Date.current, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_date
-
end
-
-
# Returns a set of HTML select-tags (one for hour and minute).
-
# You can set <tt>:time_separator</tt> key to format the output, and
-
# the <tt>:include_seconds</tt> option to include an input for seconds.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds
-
#
-
# # Generates a time select that defaults to the time in my_time.
-
# select_time(my_time)
-
#
-
# # Generates a time select that defaults to the current time (no specified time).
-
# select_time()
-
#
-
# # Generates a time select that defaults to the time in my_time,
-
# # which has fields separated by ':'.
-
# select_time(my_time, time_separator: ':')
-
#
-
# # Generates a time select that defaults to the time in my_time,
-
# # that also includes an input for seconds.
-
# select_time(my_time, include_seconds: true)
-
#
-
# # Generates a time select that defaults to the time in my_time, that has fields
-
# # separated by ':' and includes an input for seconds.
-
# select_time(my_time, time_separator: ':', include_seconds: true)
-
#
-
# # Generate a time select field with hours in the AM/PM format
-
# select_time(my_time, ampm: true)
-
#
-
# # Generates a time select field with hours that range from 2 to 14
-
# select_time(my_time, start_hour: 2, end_hour: 14)
-
#
-
# # Generates a time select with a custom prompt. Use <tt>:prompt</tt> to true for generic prompts.
-
# select_time(my_time, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# select_time(my_time, prompt: {hour: true}) # generic prompt for hours
-
# select_time(my_time, prompt: true) # generic prompts for all
-
1
def select_time(datetime = Time.current, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_time
-
end
-
-
# Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
-
# The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'second' by default.
-
#
-
# my_time = Time.now + 16.minutes
-
#
-
# # Generates a select field for seconds that defaults to the seconds for the time in my_time.
-
# select_second(my_time)
-
#
-
# # Generates a select field for seconds that defaults to the number given.
-
# select_second(33)
-
#
-
# # Generates a select field for seconds that defaults to the seconds for the time in my_time
-
# # that is named 'interval' rather than 'second'.
-
# select_second(my_time, field_name: 'interval')
-
#
-
# # Generates a select field for seconds with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_second(14, prompt: 'Choose seconds')
-
1
def select_second(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_second
-
end
-
-
# Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
-
# Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute
-
# selected. The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'minute' by default.
-
#
-
# my_time = Time.now + 6.hours
-
#
-
# # Generates a select field for minutes that defaults to the minutes for the time in my_time.
-
# select_minute(my_time)
-
#
-
# # Generates a select field for minutes that defaults to the number given.
-
# select_minute(14)
-
#
-
# # Generates a select field for minutes that defaults to the minutes for the time in my_time
-
# # that is named 'moment' rather than 'minute'.
-
# select_minute(my_time, field_name: 'moment')
-
#
-
# # Generates a select field for minutes with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_minute(14, prompt: 'Choose minutes')
-
1
def select_minute(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_minute
-
end
-
-
# Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
-
# The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'hour' by default.
-
#
-
# my_time = Time.now + 6.hours
-
#
-
# # Generates a select field for hours that defaults to the hour for the time in my_time.
-
# select_hour(my_time)
-
#
-
# # Generates a select field for hours that defaults to the number given.
-
# select_hour(13)
-
#
-
# # Generates a select field for hours that defaults to the hour for the time in my_time
-
# # that is named 'stride' rather than 'hour'.
-
# select_hour(my_time, field_name: 'stride')
-
#
-
# # Generates a select field for hours with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_hour(13, prompt: 'Choose hour')
-
#
-
# # Generate a select field for hours in the AM/PM format
-
# select_hour(my_time, ampm: true)
-
#
-
# # Generates a select field that includes options for hours from 2 to 14.
-
# select_hour(my_time, start_hour: 2, end_hour: 14)
-
1
def select_hour(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_hour
-
end
-
-
# Returns a select tag with options for each of the days 1 through 31 with the current day selected.
-
# The <tt>date</tt> can also be substituted for a day number.
-
# If you want to display days with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true.
-
# Override the field name using the <tt>:field_name</tt> option, 'day' by default.
-
#
-
# my_date = Time.now + 2.days
-
#
-
# # Generates a select field for days that defaults to the day for the date in my_date.
-
# select_day(my_date)
-
#
-
# # Generates a select field for days that defaults to the number given.
-
# select_day(5)
-
#
-
# # Generates a select field for days that defaults to the number given, but displays it with two digits.
-
# select_day(5, use_two_digit_numbers: true)
-
#
-
# # Generates a select field for days that defaults to the day for the date in my_date
-
# # that is named 'due' rather than 'day'.
-
# select_day(my_date, field_name: 'due')
-
#
-
# # Generates a select field for days with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_day(5, prompt: 'Choose day')
-
1
def select_day(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_day
-
end
-
-
# Returns a select tag with options for each of the months January through December with the current month
-
# selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are
-
# used as values (what's submitted to the server). It's also possible to use month numbers for the presentation
-
# instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you
-
# want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer
-
# to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want
-
# to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names.
-
# If you want to display months with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true.
-
# Override the field name using the <tt>:field_name</tt> option, 'month' by default.
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "January", "March".
-
# select_month(Date.today)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # is named "start" rather than "month".
-
# select_month(Date.today, field_name: 'start')
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "1", "3".
-
# select_month(Date.today, use_month_numbers: true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "1 - January", "3 - March".
-
# select_month(Date.today, add_month_numbers: true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "Jan", "Mar".
-
# select_month(Date.today, use_short_month: true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "Januar", "Marts."
-
# select_month(Date.today, use_month_names: %w(Januar Februar Marts ...))
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys with two digit numbers like "01", "03".
-
# select_month(Date.today, use_two_digit_numbers: true)
-
#
-
# # Generates a select field for months with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_month(14, prompt: 'Choose month')
-
1
def select_month(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_month
-
end
-
-
# Returns a select tag with options for each of the five years on each side of the current, which is selected.
-
# The five year radius can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the
-
# +options+. Both ascending and descending year lists are supported by making <tt>:start_year</tt> less than or
-
# greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number.
-
# Override the field name using the <tt>:field_name</tt> option, 'year' by default.
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # has ascending year values.
-
# select_year(Date.today, start_year: 1992, end_year: 2007)
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # is named 'birth' rather than 'year'.
-
# select_year(Date.today, field_name: 'birth')
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # has descending year values.
-
# select_year(Date.today, start_year: 2005, end_year: 1900)
-
#
-
# # Generates a select field for years that defaults to the year 2006 that
-
# # has ascending year values.
-
# select_year(2006, start_year: 2000, end_year: 2010)
-
#
-
# # Generates a select field for years with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_year(14, prompt: 'Choose year')
-
1
def select_year(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_year
-
end
-
-
# Returns an HTML time tag for the given date or time.
-
#
-
# time_tag Date.today # =>
-
# <time datetime="2010-11-04">November 04, 2010</time>
-
# time_tag Time.now # =>
-
# <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time>
-
# time_tag Date.yesterday, 'Yesterday' # =>
-
# <time datetime="2010-11-03">Yesterday</time>
-
# time_tag Date.today, pubdate: true # =>
-
# <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time>
-
# time_tag Date.today, datetime: Date.today.strftime('%G-W%V') # =>
-
# <time datetime="2010-W44">November 04, 2010</time>
-
#
-
# <%= time_tag Time.now do %>
-
# <span>Right now</span>
-
# <% end %>
-
# # => <time datetime="2010-11-04T17:55:45+01:00"><span>Right now</span></time>
-
1
def time_tag(date_or_time, *args, &block)
-
options = args.extract_options!
-
format = options.delete(:format) || :long
-
content = args.first || I18n.l(date_or_time, :format => format)
-
datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.iso8601
-
-
content_tag(:time, content, options.reverse_merge(:datetime => datetime), &block)
-
end
-
end
-
-
1
class DateTimeSelector #:nodoc:
-
1
include ActionView::Helpers::TagHelper
-
-
1
DEFAULT_PREFIX = 'date'.freeze
-
1
POSITION = {
-
:year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6
-
}.freeze
-
-
1
AMPM_TRANSLATION = Hash[
-
[[0, "12 AM"], [1, "01 AM"], [2, "02 AM"], [3, "03 AM"],
-
[4, "04 AM"], [5, "05 AM"], [6, "06 AM"], [7, "07 AM"],
-
[8, "08 AM"], [9, "09 AM"], [10, "10 AM"], [11, "11 AM"],
-
[12, "12 PM"], [13, "01 PM"], [14, "02 PM"], [15, "03 PM"],
-
[16, "04 PM"], [17, "05 PM"], [18, "06 PM"], [19, "07 PM"],
-
[20, "08 PM"], [21, "09 PM"], [22, "10 PM"], [23, "11 PM"]]
-
].freeze
-
-
1
def initialize(datetime, options = {}, html_options = {})
-
2
@options = options.dup
-
2
@html_options = html_options.dup
-
2
@datetime = datetime
-
2
@options[:datetime_separator] ||= ' — '
-
2
@options[:time_separator] ||= ' : '
-
end
-
-
1
def select_datetime
-
order = date_order.dup
-
order -= [:hour, :minute, :second]
-
@options[:discard_year] ||= true unless order.include?(:year)
-
@options[:discard_month] ||= true unless order.include?(:month)
-
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
-
@options[:discard_minute] ||= true if @options[:discard_hour]
-
@options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute]
-
-
set_day_if_discarded
-
-
if @options[:tag] && @options[:ignore_date]
-
select_time
-
else
-
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
-
order += [:hour, :minute, :second] unless @options[:discard_hour]
-
-
build_selects_from_types(order)
-
end
-
end
-
-
1
def select_date
-
2
order = date_order.dup
-
-
2
@options[:discard_hour] = true
-
2
@options[:discard_minute] = true
-
2
@options[:discard_second] = true
-
-
2
@options[:discard_year] ||= true unless order.include?(:year)
-
2
@options[:discard_month] ||= true unless order.include?(:month)
-
2
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
-
-
2
set_day_if_discarded
-
-
8
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
-
-
2
build_selects_from_types(order)
-
end
-
-
1
def select_time
-
order = []
-
-
@options[:discard_month] = true
-
@options[:discard_year] = true
-
@options[:discard_day] = true
-
@options[:discard_second] ||= true unless @options[:include_seconds]
-
-
order += [:year, :month, :day] unless @options[:ignore_date]
-
-
order += [:hour, :minute]
-
order << :second if @options[:include_seconds]
-
-
build_selects_from_types(order)
-
end
-
-
1
def select_second
-
if @options[:use_hidden] || @options[:discard_second]
-
build_hidden(:second, sec) if @options[:include_seconds]
-
else
-
build_options_and_select(:second, sec)
-
end
-
end
-
-
1
def select_minute
-
if @options[:use_hidden] || @options[:discard_minute]
-
build_hidden(:minute, min)
-
else
-
build_options_and_select(:minute, min, :step => @options[:minute_step])
-
end
-
end
-
-
1
def select_hour
-
if @options[:use_hidden] || @options[:discard_hour]
-
build_hidden(:hour, hour)
-
else
-
options = {}
-
options[:ampm] = @options[:ampm] || false
-
options[:start] = @options[:start_hour] || 0
-
options[:end] = @options[:end_hour] || 23
-
build_options_and_select(:hour, hour, options)
-
end
-
end
-
-
1
def select_day
-
2
if @options[:use_hidden] || @options[:discard_day]
-
build_hidden(:day, day || 1)
-
else
-
2
build_options_and_select(:day, day, :start => 1, :end => 31, :leading_zeros => false, :use_two_digit_numbers => @options[:use_two_digit_numbers])
-
end
-
end
-
-
1
def select_month
-
2
if @options[:use_hidden] || @options[:discard_month]
-
build_hidden(:month, month || 1)
-
else
-
2
month_options = []
-
2
1.upto(12) do |month_number|
-
24
options = { :value => month_number }
-
24
options[:selected] = "selected" if month == month_number
-
24
month_options << content_tag(:option, month_name(month_number), options) + "\n"
-
end
-
2
build_select(:month, month_options.join)
-
end
-
end
-
-
1
def select_year
-
2
if !@datetime || @datetime == 0
-
val = '1'
-
middle_year = Date.today.year
-
else
-
2
val = middle_year = year
-
end
-
-
2
if @options[:use_hidden] || @options[:discard_year]
-
build_hidden(:year, val)
-
else
-
2
options = {}
-
2
options[:start] = @options[:start_year] || middle_year - 5
-
2
options[:end] = @options[:end_year] || middle_year + 5
-
2
options[:step] = options[:start] < options[:end] ? 1 : -1
-
2
options[:leading_zeros] = false
-
2
options[:max_years_allowed] = @options[:max_years_allowed] || 1000
-
-
2
if (options[:end] - options[:start]).abs > options[:max_years_allowed]
-
raise ArgumentError, "There are too many years options to be built. Are you sure you haven't mistyped something? You can provide the :max_years_allowed parameter."
-
end
-
-
2
build_options_and_select(:year, val, options)
-
end
-
end
-
-
1
private
-
1
%w( sec min hour day month year ).each do |method|
-
6
define_method(method) do
-
28
@datetime.kind_of?(Numeric) ? @datetime : @datetime.send(method) if @datetime
-
end
-
end
-
-
# If the day is hidden, the day should be set to the 1st so all month and year choices are
-
# valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid.
-
1
def set_day_if_discarded
-
2
if @datetime && @options[:discard_day]
-
@datetime = @datetime.change(:day => 1)
-
end
-
end
-
-
# Returns translated month names, but also ensures that a custom month
-
# name array has a leading nil element.
-
1
def month_names
-
@month_names ||= begin
-
2
month_names = @options[:use_month_names] || translated_month_names
-
2
month_names.unshift(nil) if month_names.size < 13
-
2
month_names
-
24
end
-
end
-
-
# Returns translated month names.
-
# => [nil, "January", "February", "March",
-
# "April", "May", "June", "July",
-
# "August", "September", "October",
-
# "November", "December"]
-
#
-
# If <tt>:use_short_month</tt> option is set
-
# => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
-
# "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
-
1
def translated_month_names
-
2
key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
-
2
I18n.translate(key, :locale => @options[:locale])
-
end
-
-
# Looks up month names by number (1-based):
-
#
-
# month_name(1) # => "January"
-
#
-
# If the <tt>:use_month_numbers</tt> option is passed:
-
#
-
# month_name(1) # => 1
-
#
-
# If the <tt>:use_two_month_numbers</tt> option is passed:
-
#
-
# month_name(1) # => '01'
-
#
-
# If the <tt>:add_month_numbers</tt> option is passed:
-
#
-
# month_name(1) # => "1 - January"
-
#
-
# If the <tt>:month_format_string</tt> option is passed:
-
#
-
# month_name(1) # => "January (01)"
-
#
-
# depending on the format string.
-
1
def month_name(number)
-
24
if @options[:use_month_numbers]
-
number
-
24
elsif @options[:use_two_digit_numbers]
-
'%02d' % number
-
24
elsif @options[:add_month_numbers]
-
"#{number} - #{month_names[number]}"
-
24
elsif format_string = @options[:month_format_string]
-
format_string % {number: number, name: month_names[number]}
-
else
-
24
month_names[number]
-
end
-
end
-
-
1
def date_order
-
2
@date_order ||= @options[:order] || translated_date_order
-
end
-
-
1
def translated_date_order
-
2
date_order = I18n.translate(:'date.order', :locale => @options[:locale], :default => [])
-
8
date_order = date_order.map { |element| element.to_sym }
-
-
2
forbidden_elements = date_order - [:year, :month, :day]
-
2
if forbidden_elements.any?
-
raise StandardError,
-
"#{@options[:locale]}.date.order only accepts :year, :month and :day"
-
end
-
-
2
date_order
-
end
-
-
# Build full select tag from date type and options.
-
1
def build_options_and_select(type, selected, options = {})
-
4
build_select(type, build_options(selected, options))
-
end
-
-
# Build select option HTML from date value and options.
-
# build_options(15, start: 1, end: 31)
-
# => "<option value="1">1</option>
-
# <option value="2">2</option>
-
# <option value="3">3</option>..."
-
#
-
# If <tt>use_two_digit_numbers: true</tt> option is passed
-
# build_options(15, start: 1, end: 31, use_two_digit_numbers: true)
-
# => "<option value="1">01</option>
-
# <option value="2">02</option>
-
# <option value="3">03</option>..."
-
#
-
# If <tt>:step</tt> options is passed
-
# build_options(15, start: 1, end: 31, step: 2)
-
# => "<option value="1">1</option>
-
# <option value="3">3</option>
-
# <option value="5">5</option>..."
-
1
def build_options(selected, options = {})
-
4
options = {
-
leading_zeros: true, ampm: false, use_two_digit_numbers: false
-
}.merge!(options)
-
-
4
start = options.delete(:start) || 0
-
4
stop = options.delete(:end) || 59
-
4
step = options.delete(:step) || 1
-
4
leading_zeros = options.delete(:leading_zeros)
-
-
4
select_options = []
-
4
start.step(stop, step) do |i|
-
84
value = leading_zeros ? sprintf("%02d", i) : i
-
84
tag_options = { :value => value }
-
84
tag_options[:selected] = "selected" if selected == i
-
84
text = options[:use_two_digit_numbers] ? sprintf("%02d", i) : value
-
84
text = options[:ampm] ? AMPM_TRANSLATION[i] : text
-
84
select_options << content_tag(:option, text, tag_options)
-
end
-
-
4
(select_options.join("\n") + "\n").html_safe
-
end
-
-
# Builds select tag from date type and HTML select options.
-
# build_select(:month, "<option value="1">January</option>...")
-
# => "<select id="post_written_on_2i" name="post[written_on(2i)]">
-
# <option value="1">January</option>...
-
# </select>"
-
1
def build_select(type, select_options_as_html)
-
6
select_options = {
-
:id => input_id_from_type(type),
-
:name => input_name_from_type(type)
-
}.merge!(@html_options)
-
6
select_options[:disabled] = 'disabled' if @options[:disabled]
-
6
select_options[:class] = [select_options[:class], type].compact.join(' ') if @options[:with_css_classes]
-
-
6
select_html = "\n"
-
6
select_html << content_tag(:option, '', :value => '') + "\n" if @options[:include_blank]
-
6
select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt]
-
6
select_html << select_options_as_html
-
-
6
(content_tag(:select, select_html.html_safe, select_options) + "\n").html_safe
-
end
-
-
# Builds a prompt option tag with supplied options or from default options.
-
# prompt_option_tag(:month, prompt: 'Select month')
-
# => "<option value="">Select month</option>"
-
1
def prompt_option_tag(type, options)
-
prompt = case options
-
when Hash
-
default_options = {:year => false, :month => false, :day => false, :hour => false, :minute => false, :second => false}
-
default_options.merge!(options)[type.to_sym]
-
when String
-
options
-
else
-
I18n.translate(:"datetime.prompts.#{type}", :locale => @options[:locale])
-
end
-
-
prompt ? content_tag(:option, prompt, :value => '') : ''
-
end
-
-
# Builds hidden input tag for date part and value.
-
# build_hidden(:year, 2008)
-
# => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />"
-
1
def build_hidden(type, value)
-
select_options = {
-
:type => "hidden",
-
:id => input_id_from_type(type),
-
:name => input_name_from_type(type),
-
:value => value
-
}.merge!(@html_options.slice(:disabled))
-
select_options[:disabled] = 'disabled' if @options[:disabled]
-
-
tag(:input, select_options) + "\n".html_safe
-
end
-
-
# Returns the name attribute for the input tag.
-
# => post[written_on(1i)]
-
1
def input_name_from_type(type)
-
12
prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX
-
12
prefix += "[#{@options[:index]}]" if @options.has_key?(:index)
-
-
12
field_name = @options[:field_name] || type
-
12
if @options[:include_position]
-
12
field_name += "(#{ActionView::Helpers::DateTimeSelector::POSITION[type]}i)"
-
end
-
-
12
@options[:discard_type] ? prefix : "#{prefix}[#{field_name}]"
-
end
-
-
# Returns the id attribute for the input tag.
-
# => "post_written_on_1i"
-
1
def input_id_from_type(type)
-
6
id = input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
-
6
id = @options[:namespace] + '_' + id if @options[:namespace]
-
-
6
id
-
end
-
-
# Given an ordering of datetime components, create the selection HTML
-
# and join them with their appropriate separators.
-
1
def build_selects_from_types(order)
-
2
select = ''
-
4
first_visible = order.find { |type| !@options[:"discard_#{type}"] }
-
2
order.reverse_each do |type|
-
6
separator = separator(type) unless type == first_visible # don't add before first visible field
-
6
select.insert(0, separator.to_s + send("select_#{type}").to_s)
-
end
-
2
select.html_safe
-
end
-
-
# Returns the separator for a given datetime component.
-
1
def separator(type)
-
4
return "" if @options[:use_hidden]
-
-
4
case type
-
when :year, :month, :day
-
4
@options[:"discard_#{type}"] ? "" : @options[:date_separator]
-
when :hour
-
(@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator]
-
when :minute, :second
-
@options[:"discard_#{type}"] ? "" : @options[:time_separator]
-
end
-
end
-
end
-
-
1
class FormBuilder
-
# Wraps ActionView::Helpers::DateHelper#date_select for form builders:
-
#
-
# <%= form_for @person do |f| %>
-
# <%= f.date_select :birth_date %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def date_select(method, options = {}, html_options = {})
-
2
@template.date_select(@object_name, method, objectify_options(options), html_options)
-
end
-
-
# Wraps ActionView::Helpers::DateHelper#time_select for form builders:
-
#
-
# <%= form_for @race do |f| %>
-
# <%= f.time_select :average_lap %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def time_select(method, options = {}, html_options = {})
-
@template.time_select(@object_name, method, objectify_options(options), html_options)
-
end
-
-
# Wraps ActionView::Helpers::DateHelper#datetime_select for form builders:
-
#
-
# <%= form_for @person do |f| %>
-
# <%= f.datetime_select :last_request_at %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def datetime_select(method, options = {}, html_options = {})
-
@template.datetime_select(@object_name, method, objectify_options(options), html_options)
-
end
-
end
-
end
-
end
-
1
module ActionView
-
# = Action View Debug Helper
-
#
-
# Provides a set of methods for making it easier to debug Rails objects.
-
1
module Helpers
-
1
module DebugHelper
-
-
1
include TagHelper
-
-
# Returns a YAML representation of +object+ wrapped with <pre> and </pre>.
-
# If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead.
-
# Useful for inspecting an object at the time of rendering.
-
#
-
# @user = User.new({ username: 'testing', password: 'xyz', age: 42})
-
# debug(@user)
-
# # =>
-
# <pre class='debug_dump'>--- !ruby/object:User
-
# attributes:
-
# updated_at:
-
# username: testing
-
# age: 42
-
# password: xyz
-
# created_at:
-
# </pre>
-
1
def debug(object)
-
Marshal::dump(object)
-
object = ERB::Util.html_escape(object.to_yaml)
-
content_tag(:pre, object, :class => "debug_dump")
-
rescue Exception # errors from Marshal or YAML
-
# Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
-
content_tag(:code, object.inspect, :class => "debug_dump")
-
end
-
end
-
end
-
end
-
1
require 'cgi'
-
1
require 'action_view/helpers/date_helper'
-
1
require 'action_view/helpers/tag_helper'
-
1
require 'action_view/helpers/form_tag_helper'
-
1
require 'action_view/helpers/active_model_helper'
-
1
require 'action_view/model_naming'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module ActionView
-
# = Action View Form Helpers
-
1
module Helpers
-
# Form helpers are designed to make working with resources much easier
-
# compared to using vanilla HTML.
-
#
-
# Typically, a form designed to create or update a resource reflects the
-
# identity of the resource in several ways: (i) the url that the form is
-
# sent to (the form element's +action+ attribute) should result in a request
-
# being routed to the appropriate controller action (with the appropriate <tt>:id</tt>
-
# parameter in the case of an existing resource), (ii) input fields should
-
# be named in such a way that in the controller their values appear in the
-
# appropriate places within the +params+ hash, and (iii) for an existing record,
-
# when the form is initially displayed, input fields corresponding to attributes
-
# of the resource should show the current values of those attributes.
-
#
-
# In Rails, this is usually achieved by creating the form using +form_for+ and
-
# a number of related helper methods. +form_for+ generates an appropriate <tt>form</tt>
-
# tag and yields a form builder object that knows the model the form is about.
-
# Input fields are created by calling methods defined on the form builder, which
-
# means they are able to generate the appropriate names and default values
-
# corresponding to the model attributes, as well as convenient IDs, etc.
-
# Conventions in the generated field names allow controllers to receive form data
-
# nicely structured in +params+ with no effort on your side.
-
#
-
# For example, to create a new person you typically set up a new instance of
-
# +Person+ in the <tt>PeopleController#new</tt> action, <tt>@person</tt>, and
-
# in the view template pass that object to +form_for+:
-
#
-
# <%= form_for @person do |f| %>
-
# <%= f.label :first_name %>:
-
# <%= f.text_field :first_name %><br />
-
#
-
# <%= f.label :last_name %>:
-
# <%= f.text_field :last_name %><br />
-
#
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# The HTML generated for this would be (modulus formatting):
-
#
-
# <form action="/people" class="new_person" id="new_person" method="post">
-
# <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
-
# <label for="person_first_name">First name</label>:
-
# <input id="person_first_name" name="person[first_name]" type="text" /><br />
-
#
-
# <label for="person_last_name">Last name</label>:
-
# <input id="person_last_name" name="person[last_name]" type="text" /><br />
-
#
-
# <input name="commit" type="submit" value="Create Person" />
-
# </form>
-
#
-
# As you see, the HTML reflects knowledge about the resource in several spots,
-
# like the path the form should be submitted to, or the names of the input fields.
-
#
-
# In particular, thanks to the conventions followed in the generated field names, the
-
# controller gets a nested hash <tt>params[:person]</tt> with the person attributes
-
# set in the form. That hash is ready to be passed to <tt>Person.create</tt>:
-
#
-
# if @person = Person.create(params[:person])
-
# # success
-
# else
-
# # error handling
-
# end
-
#
-
# Interestingly, the exact same view code in the previous example can be used to edit
-
# a person. If <tt>@person</tt> is an existing record with name "John Smith" and ID 256,
-
# the code above as is would yield instead:
-
#
-
# <form action="/people/256" class="edit_person" id="edit_person_256" method="post">
-
# <input name="_method" type="hidden" value="patch" />
-
# <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
-
# <label for="person_first_name">First name</label>:
-
# <input id="person_first_name" name="person[first_name]" type="text" value="John" /><br />
-
#
-
# <label for="person_last_name">Last name</label>:
-
# <input id="person_last_name" name="person[last_name]" type="text" value="Smith" /><br />
-
#
-
# <input name="commit" type="submit" value="Update Person" />
-
# </form>
-
#
-
# Note that the endpoint, default values, and submit button label are tailored for <tt>@person</tt>.
-
# That works that way because the involved helpers know whether the resource is a new record or not,
-
# and generate HTML accordingly.
-
#
-
# The controller would receive the form data again in <tt>params[:person]</tt>, ready to be
-
# passed to <tt>Person#update</tt>:
-
#
-
# if @person.update(params[:person])
-
# # success
-
# else
-
# # error handling
-
# end
-
#
-
# That's how you typically work with resources.
-
1
module FormHelper
-
1
extend ActiveSupport::Concern
-
-
1
include FormTagHelper
-
1
include UrlHelper
-
1
include ModelNaming
-
-
# Creates a form that allows the user to create or update the attributes
-
# of a specific model object.
-
#
-
# The method can be used in several slightly different ways, depending on
-
# how much you wish to rely on Rails to infer automatically from the model
-
# how the form should be constructed. For a generic model object, a form
-
# can be created by passing +form_for+ a string or symbol representing
-
# the object we are concerned with:
-
#
-
# <%= form_for :person do |f| %>
-
# First name: <%= f.text_field :first_name %><br />
-
# Last name : <%= f.text_field :last_name %><br />
-
# Biography : <%= f.text_area :biography %><br />
-
# Admin? : <%= f.check_box :admin %><br />
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# The variable +f+ yielded to the block is a FormBuilder object that
-
# incorporates the knowledge about the model object represented by
-
# <tt>:person</tt> passed to +form_for+. Methods defined on the FormBuilder
-
# are used to generate fields bound to this model. Thus, for example,
-
#
-
# <%= f.text_field :first_name %>
-
#
-
# will get expanded to
-
#
-
# <%= text_field :person, :first_name %>
-
# which results in an HTML <tt><input></tt> tag whose +name+ attribute is
-
# <tt>person[first_name]</tt>. This means that when the form is submitted,
-
# the value entered by the user will be available in the controller as
-
# <tt>params[:person][:first_name]</tt>.
-
#
-
# For fields generated in this way using the FormBuilder,
-
# if <tt>:person</tt> also happens to be the name of an instance variable
-
# <tt>@person</tt>, the default value of the field shown when the form is
-
# initially displayed (e.g. in the situation where you are editing an
-
# existing record) will be the value of the corresponding attribute of
-
# <tt>@person</tt>.
-
#
-
# The rightmost argument to +form_for+ is an
-
# optional hash of options -
-
#
-
# * <tt>:url</tt> - The URL the form is to be submitted to. This may be
-
# represented in the same way as values passed to +url_for+ or +link_to+.
-
# So for example you may use a named route directly. When the model is
-
# represented by a string or symbol, as in the example above, if the
-
# <tt>:url</tt> option is not specified, by default the form will be
-
# sent back to the current url (We will describe below an alternative
-
# resource-oriented usage of +form_for+ in which the URL does not need
-
# to be specified explicitly).
-
# * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of
-
# id attributes on form elements. The namespace attribute will be prefixed
-
# with underscore on the generated HTML id.
-
# * <tt>:method</tt> - The method to use when submitting the form, usually
-
# either "get" or "post". If "patch", "put", "delete", or another verb
-
# is used, a hidden input with name <tt>_method</tt> is added to
-
# simulate the verb over post.
-
# * <tt>:authenticity_token</tt> - Authenticity token to use in the form.
-
# Use only if you need to pass custom authenticity token string, or to
-
# not add authenticity_token field at all (by passing <tt>false</tt>).
-
# Remote forms may omit the embedded authenticity token by setting
-
# <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>.
-
# This is helpful when you're fragment-caching the form. Remote forms
-
# get the authenticity token from the <tt>meta</tt> tag, so embedding is
-
# unnecessary unless you support browsers without JavaScript.
-
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive
-
# JavaScript drivers to control the submit behavior. By default this
-
# behavior is an ajax submit.
-
# * <tt>:enforce_utf8</tt> - If set to false, a hidden input with name
-
# utf8 is not output.
-
# * <tt>:html</tt> - Optional HTML attributes for the form tag.
-
#
-
# Also note that +form_for+ doesn't create an exclusive scope. It's still
-
# possible to use both the stand-alone FormHelper methods and methods
-
# from FormTagHelper. For example:
-
#
-
# <%= form_for :person do |f| %>
-
# First name: <%= f.text_field :first_name %>
-
# Last name : <%= f.text_field :last_name %>
-
# Biography : <%= text_area :person, :biography %>
-
# Admin? : <%= check_box_tag "person[admin]", "1", @person.company.admin? %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# This also works for the methods in FormOptionHelper and DateHelper that
-
# are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === #form_for with a model object
-
#
-
# In the examples above, the object to be created or edited was
-
# represented by a symbol passed to +form_for+, and we noted that
-
# a string can also be used equivalently. It is also possible, however,
-
# to pass a model object itself to +form_for+. For example, if <tt>@post</tt>
-
# is an existing record you wish to edit, you can create the form using
-
#
-
# <%= form_for @post do |f| %>
-
# ...
-
# <% end %>
-
#
-
# This behaves in almost the same way as outlined previously, with a
-
# couple of small exceptions. First, the prefix used to name the input
-
# elements within the form (hence the key that denotes them in the +params+
-
# hash) is actually derived from the object's _class_, e.g. <tt>params[:post]</tt>
-
# if the object's class is +Post+. However, this can be overwritten using
-
# the <tt>:as</tt> option, e.g. -
-
#
-
# <%= form_for(@person, as: :client) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# would result in <tt>params[:client]</tt>.
-
#
-
# Secondly, the field values shown when the form is initially displayed
-
# are taken from the attributes of the object passed to +form_for+,
-
# regardless of whether the object is an instance
-
# variable. So, for example, if we had a _local_ variable +post+
-
# representing an existing record,
-
#
-
# <%= form_for post do |f| %>
-
# ...
-
# <% end %>
-
#
-
# would produce a form with fields whose initial state reflect the current
-
# values of the attributes of +post+.
-
#
-
# === Resource-oriented style
-
#
-
# In the examples just shown, although not indicated explicitly, we still
-
# need to use the <tt>:url</tt> option in order to specify where the
-
# form is going to be sent. However, further simplification is possible
-
# if the record passed to +form_for+ is a _resource_, i.e. it corresponds
-
# to a set of RESTful routes, e.g. defined using the +resources+ method
-
# in <tt>config/routes.rb</tt>. In this case Rails will simply infer the
-
# appropriate URL from the record itself. For example,
-
#
-
# <%= form_for @post do |f| %>
-
# ...
-
# <% end %>
-
#
-
# is then equivalent to something like:
-
#
-
# <%= form_for @post, as: :post, url: post_path(@post), method: :patch, html: { class: "edit_post", id: "edit_post_45" } do |f| %>
-
# ...
-
# <% end %>
-
#
-
# And for a new record
-
#
-
# <%= form_for(Post.new) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# is equivalent to something like:
-
#
-
# <%= form_for @post, as: :post, url: posts_path, html: { class: "new_post", id: "new_post" } do |f| %>
-
# ...
-
# <% end %>
-
#
-
# However you can still overwrite individual conventions, such as:
-
#
-
# <%= form_for(@post, url: super_posts_path) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# You can also set the answer format, like this:
-
#
-
# <%= form_for(@post, format: :json) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# For namespaced routes, like +admin_post_url+:
-
#
-
# <%= form_for([:admin, @post]) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# If your resource has associations defined, for example, you want to add comments
-
# to the document given that the routes are set correctly:
-
#
-
# <%= form_for([@document, @comment]) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# Where <tt>@document = Document.find(params[:id])</tt> and
-
# <tt>@comment = Comment.new</tt>.
-
#
-
# === Setting the method
-
#
-
# You can force the form to use the full array of HTTP verbs by setting
-
#
-
# method: (:get|:post|:patch|:put|:delete)
-
#
-
# in the options hash. If the verb is not GET or POST, which are natively
-
# supported by HTML forms, the form will be set to POST and a hidden input
-
# called _method will carry the intended verb for the server to interpret.
-
#
-
# === Unobtrusive JavaScript
-
#
-
# Specifying:
-
#
-
# remote: true
-
#
-
# in the options hash creates a form that will allow the unobtrusive JavaScript drivers to modify its
-
# behavior. The expected default behavior is an XMLHttpRequest in the background instead of the regular
-
# POST arrangement, but ultimately the behavior is the choice of the JavaScript driver implementor.
-
# Even though it's using JavaScript to serialize the form elements, the form submission will work just like
-
# a regular submission as viewed by the receiving side (all elements available in <tt>params</tt>).
-
#
-
# Example:
-
#
-
# <%= form_for(@post, remote: true) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# The HTML generated for this would be:
-
#
-
# <form action='http://www.example.com' method='post' data-remote='true'>
-
# <input name='_method' type='hidden' value='patch' />
-
# ...
-
# </form>
-
#
-
# === Setting HTML options
-
#
-
# You can set data attributes directly by passing in a data hash, but all other HTML options must be wrapped in
-
# the HTML key. Example:
-
#
-
# <%= form_for(@post, data: { behavior: "autosave" }, html: { name: "go" }) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# The HTML generated for this would be:
-
#
-
# <form action='http://www.example.com' method='post' data-behavior='autosave' name='go'>
-
# <input name='_method' type='hidden' value='patch' />
-
# ...
-
# </form>
-
#
-
# === Removing hidden model id's
-
#
-
# The form_for method automatically includes the model id as a hidden field in the form.
-
# This is used to maintain the correlation between the form data and its associated model.
-
# Some ORM systems do not use IDs on nested models so in this case you want to be able
-
# to disable the hidden id.
-
#
-
# In the following example the Post model has many Comments stored within it in a NoSQL database,
-
# thus there is no primary key for comments.
-
#
-
# Example:
-
#
-
# <%= form_for(@post) do |f| %>
-
# <%= f.fields_for(:comments, include_id: false) do |cf| %>
-
# ...
-
# <% end %>
-
# <% end %>
-
#
-
# === Customized form builders
-
#
-
# You can also build forms using a customized FormBuilder class. Subclass
-
# FormBuilder and override or define some more helpers, then use your
-
# custom builder. For example, let's say you made a helper to
-
# automatically add labels to form inputs.
-
#
-
# <%= form_for @person, url: { action: "create" }, builder: LabellingFormBuilder do |f| %>
-
# <%= f.text_field :first_name %>
-
# <%= f.text_field :last_name %>
-
# <%= f.text_area :biography %>
-
# <%= f.check_box :admin %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# In this case, if you use this:
-
#
-
# <%= render f %>
-
#
-
# The rendered template is <tt>people/_labelling_form</tt> and the local
-
# variable referencing the form builder is called
-
# <tt>labelling_form</tt>.
-
#
-
# The custom FormBuilder class is automatically merged with the options
-
# of a nested fields_for call, unless it's explicitly set.
-
#
-
# In many cases you will want to wrap the above in another helper, so you
-
# could do something like the following:
-
#
-
# def labelled_form_for(record_or_name_or_array, *args, &block)
-
# options = args.extract_options!
-
# form_for(record_or_name_or_array, *(args << options.merge(builder: LabellingFormBuilder)), &block)
-
# end
-
#
-
# If you don't need to attach a form to a model instance, then check out
-
# FormTagHelper#form_tag.
-
#
-
# === Form to external resources
-
#
-
# When you build forms to external resources sometimes you need to set an authenticity token or just render a form
-
# without it, for example when you submit data to a payment gateway number and types of fields could be limited.
-
#
-
# To set an authenticity token you need to pass an <tt>:authenticity_token</tt> parameter
-
#
-
# <%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f|
-
# ...
-
# <% end %>
-
#
-
# If you don't want to an authenticity token field be rendered at all just pass <tt>false</tt>:
-
#
-
# <%= form_for @invoice, url: external_url, authenticity_token: false do |f|
-
# ...
-
# <% end %>
-
1
def form_for(record, options = {}, &block)
-
8
raise ArgumentError, "Missing block" unless block_given?
-
8
html_options = options[:html] ||= {}
-
-
8
case record
-
when String, Symbol
-
object_name = record
-
object = nil
-
else
-
8
object = record.is_a?(Array) ? record.last : record
-
8
raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object
-
8
object_name = options[:as] || model_name_from_record_or_class(object).param_key
-
8
apply_form_for_options!(record, object, options)
-
end
-
-
8
html_options[:data] = options.delete(:data) if options.has_key?(:data)
-
8
html_options[:remote] = options.delete(:remote) if options.has_key?(:remote)
-
8
html_options[:method] = options.delete(:method) if options.has_key?(:method)
-
8
html_options[:enforce_utf8] = options.delete(:enforce_utf8) if options.has_key?(:enforce_utf8)
-
8
html_options[:authenticity_token] = options.delete(:authenticity_token)
-
-
8
builder = instantiate_builder(object_name, object, options)
-
8
output = capture(builder, &block)
-
8
html_options[:multipart] ||= builder.multipart?
-
-
8
html_options = html_options_for_form(options[:url] || {}, html_options)
-
8
form_tag_with_body(html_options, output)
-
end
-
-
1
def apply_form_for_options!(record, object, options) #:nodoc:
-
8
object = convert_to_model(object)
-
-
8
as = options[:as]
-
8
namespace = options[:namespace]
-
8
action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :patch] : [:new, :post]
-
8
options[:html].reverse_merge!(
-
class: as ? "#{action}_#{as}" : dom_class(object, action),
-
8
id: (as ? [namespace, action, as] : [namespace, dom_id(object, action)]).compact.join("_").presence,
-
method: method
-
)
-
-
8
options[:url] ||= if options.key?(:format)
-
polymorphic_path(record, format: options.delete(:format))
-
else
-
8
polymorphic_path(record, {})
-
end
-
end
-
1
private :apply_form_for_options!
-
-
# Creates a scope around a specific model object like form_for, but
-
# doesn't create the form tags themselves. This makes fields_for suitable
-
# for specifying additional model objects in the same form.
-
#
-
# Although the usage and purpose of +fields_for+ is similar to +form_for+'s,
-
# its method signature is slightly different. Like +form_for+, it yields
-
# a FormBuilder object associated with a particular model object to a block,
-
# and within the block allows methods to be called on the builder to
-
# generate fields associated with the model object. Fields may reflect
-
# a model object in two ways - how they are named (hence how submitted
-
# values appear within the +params+ hash in the controller) and what
-
# default values are shown when the form the fields appear in is first
-
# displayed. In order for both of these features to be specified independently,
-
# both an object name (represented by either a symbol or string) and the
-
# object itself can be passed to the method separately -
-
#
-
# <%= form_for @person do |person_form| %>
-
# First name: <%= person_form.text_field :first_name %>
-
# Last name : <%= person_form.text_field :last_name %>
-
#
-
# <%= fields_for :permission, @person.permission do |permission_fields| %>
-
# Admin? : <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# <%= person_form.submit %>
-
# <% end %>
-
#
-
# In this case, the checkbox field will be represented by an HTML +input+
-
# tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted
-
# value will appear in the controller as <tt>params[:permission][:admin]</tt>.
-
# If <tt>@person.permission</tt> is an existing record with an attribute
-
# +admin+, the initial state of the checkbox when first displayed will
-
# reflect the value of <tt>@person.permission.admin</tt>.
-
#
-
# Often this can be simplified by passing just the name of the model
-
# object to +fields_for+ -
-
#
-
# <%= fields_for :permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# ...in which case, if <tt>:permission</tt> also happens to be the name of an
-
# instance variable <tt>@permission</tt>, the initial state of the input
-
# field will reflect the value of that variable's attribute <tt>@permission.admin</tt>.
-
#
-
# Alternatively, you can pass just the model object itself (if the first
-
# argument isn't a string or symbol +fields_for+ will realize that the
-
# name has been omitted) -
-
#
-
# <%= fields_for @person.permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# and +fields_for+ will derive the required name of the field from the
-
# _class_ of the model object, e.g. if <tt>@person.permission</tt>, is
-
# of class +Permission+, the field will still be named <tt>permission[admin]</tt>.
-
#
-
# Note: This also works for the methods in FormOptionHelper and
-
# DateHelper that are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === Nested Attributes Examples
-
#
-
# When the object belonging to the current scope has a nested attribute
-
# writer for a certain attribute, fields_for will yield a new scope
-
# for that attribute. This allows you to create forms that set or change
-
# the attributes of a parent object and its associations in one go.
-
#
-
# Nested attribute writers are normal setter methods named after an
-
# association. The most common way of defining these writers is either
-
# with +accepts_nested_attributes_for+ in a model definition or by
-
# defining a method with the proper name. For example: the attribute
-
# writer for the association <tt>:address</tt> is called
-
# <tt>address_attributes=</tt>.
-
#
-
# Whether a one-to-one or one-to-many style form builder will be yielded
-
# depends on whether the normal reader method returns a _single_ object
-
# or an _array_ of objects.
-
#
-
# ==== One-to-one
-
#
-
# Consider a Person class which returns a _single_ Address from the
-
# <tt>address</tt> reader method and responds to the
-
# <tt>address_attributes=</tt> writer method:
-
#
-
# class Person
-
# def address
-
# @address
-
# end
-
#
-
# def address_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# This model can now be used with a nested fields_for, like so:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# Street : <%= address_fields.text_field :street %>
-
# Zip code: <%= address_fields.text_field :zip_code %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When address is already an association on a Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address
-
# end
-
#
-
# If you want to destroy the associated model through the form, you have
-
# to enable it first using the <tt>:allow_destroy</tt> option for
-
# +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address, allow_destroy: true
-
# end
-
#
-
# Now, when you use a form element with the <tt>_destroy</tt> parameter,
-
# with a value that evaluates to +true+, you will destroy the associated
-
# model (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# ...
-
# Delete: <%= address_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# ==== One-to-many
-
#
-
# Consider a Person class which returns an _array_ of Project instances
-
# from the <tt>projects</tt> reader method and responds to the
-
# <tt>projects_attributes=</tt> writer method:
-
#
-
# class Person
-
# def projects
-
# [@project1, @project2]
-
# end
-
#
-
# def projects_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# Note that the <tt>projects_attributes=</tt> writer method is in fact
-
# required for fields_for to correctly identify <tt>:projects</tt> as a
-
# collection, and the correct indices to be set in the form markup.
-
#
-
# When projects is already an association on Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects
-
# end
-
#
-
# This model can now be used with a nested fields_for. The block given to
-
# the nested fields_for call will be repeated for each instance in the
-
# collection:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# <% if project_fields.object.active? %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# It's also possible to specify the instance to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <% @person.projects.each do |project| %>
-
# <% if project.active? %>
-
# <%= person_form.fields_for :projects, project do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Or a collection to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# If you want to destroy any of the associated models through the
-
# form, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option for +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects, allow_destroy: true
-
# end
-
#
-
# This will allow you to specify which models to destroy in the
-
# attributes hash by adding a form element for the <tt>_destroy</tt>
-
# parameter with a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Delete: <%= project_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When a collection is used you might want to know the index of each
-
# object into the array. For this purpose, the <tt>index</tt> method
-
# is available in the FormBuilder object.
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Project #<%= project_fields.index %>
-
# ...
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Note that fields_for will automatically generate a hidden field
-
# to store the ID of the record. There are circumstances where this
-
# hidden field is not needed and you can pass <tt>include_id: false</tt>
-
# to prevent fields_for from rendering it automatically.
-
1
def fields_for(record_name, record_object = nil, options = {}, &block)
-
builder = instantiate_builder(record_name, record_object, options)
-
capture(builder, &block)
-
end
-
-
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
-
# is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
-
# Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
-
# onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
-
# target labels for radio_button tags (where the value is used in the ID of the input tag).
-
#
-
# ==== Examples
-
# label(:post, :title)
-
# # => <label for="post_title">Title</label>
-
#
-
# You can localize your labels based on model and attribute names.
-
# For example you can define the following in your locale (e.g. en.yml)
-
#
-
# helpers:
-
# label:
-
# post:
-
# body: "Write your entire text here"
-
#
-
# Which then will result in
-
#
-
# label(:post, :body)
-
# # => <label for="post_body">Write your entire text here</label>
-
#
-
# Localization can also be based purely on the translation of the attribute-name
-
# (if you are using ActiveRecord):
-
#
-
# activerecord:
-
# attributes:
-
# post:
-
# cost: "Total cost"
-
#
-
# label(:post, :cost)
-
# # => <label for="post_cost">Total cost</label>
-
#
-
# label(:post, :title, "A short title")
-
# # => <label for="post_title">A short title</label>
-
#
-
# label(:post, :title, "A short title", class: "title_label")
-
# # => <label for="post_title" class="title_label">A short title</label>
-
#
-
# label(:post, :privacy, "Public Post", value: "public")
-
# # => <label for="post_privacy_public">Public Post</label>
-
#
-
# label(:post, :terms) do
-
# 'Accept <a href="/terms">Terms</a>.'.html_safe
-
# end
-
# # => <label for="post_terms">Accept <a href="/terms">Terms</a>.</label>
-
1
def label(object_name, method, content_or_options = nil, options = nil, &block)
-
26
Tags::Label.new(object_name, method, self, content_or_options, options).render(&block)
-
end
-
-
# Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# text_field(:post, :title, size: 20)
-
# # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />
-
#
-
# text_field(:post, :title, class: "create_input")
-
# # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" />
-
#
-
# text_field(:session, :user, onchange: "if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }")
-
# # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange="if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }"/>
-
#
-
# text_field(:snippet, :code, size: 20, class: 'code_input')
-
# # => <input type="text" id="snippet_code" name="snippet[code]" size="20" value="#{@snippet.code}" class="code_input" />
-
1
def text_field(object_name, method, options = {})
-
18
Tags::TextField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input tag of the "password" type tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown. For security reasons this field is blank by default; pass in a value via +options+ if this is not desired.
-
#
-
# ==== Examples
-
# password_field(:login, :pass, size: 20)
-
# # => <input type="password" id="login_pass" name="login[pass]" size="20" />
-
#
-
# password_field(:account, :secret, class: "form_input", value: @account.secret)
-
# # => <input type="password" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" />
-
#
-
# password_field(:user, :password, onchange: "if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }")
-
# # => <input type="password" id="user_password" name="user[password]" onchange="if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }"/>
-
#
-
# password_field(:account, :pin, size: 20, class: 'form_input')
-
# # => <input type="password" id="account_pin" name="account[pin]" size="20" class="form_input" />
-
1
def password_field(object_name, method, options = {})
-
Tags::PasswordField.new(object_name, method, self, options).render
-
end
-
-
# Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# hidden_field(:signup, :pass_confirm)
-
# # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
-
#
-
# hidden_field(:post, :tag_list)
-
# # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
-
#
-
# hidden_field(:user, :token)
-
# # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
-
1
def hidden_field(object_name, method, options = {})
-
Tags::HiddenField.new(object_name, method, self, options).render
-
end
-
-
# Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
-
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
-
#
-
# ==== Examples
-
# file_field(:user, :avatar)
-
# # => <input type="file" id="user_avatar" name="user[avatar]" />
-
#
-
# file_field(:post, :image, :multiple => true)
-
# # => <input type="file" id="post_image" name="post[image]" multiple="true" />
-
#
-
# file_field(:post, :attached, accept: 'text/html')
-
# # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
-
#
-
# file_field(:post, :image, accept: 'image/png,image/gif,image/jpeg')
-
# # => <input type="file" id="post_image" name="post[image]" accept="image/png,image/gif,image/jpeg" />
-
#
-
# file_field(:attachment, :file, class: 'file_input')
-
# # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
-
1
def file_field(object_name, method, options = {})
-
Tags::FileField.new(object_name, method, self, options).render
-
end
-
-
# Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+)
-
# on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+.
-
#
-
# ==== Examples
-
# text_area(:post, :body, cols: 20, rows: 40)
-
# # => <textarea cols="20" rows="40" id="post_body" name="post[body]">
-
# # #{@post.body}
-
# # </textarea>
-
#
-
# text_area(:comment, :text, size: "20x30")
-
# # => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
-
# # #{@comment.text}
-
# # </textarea>
-
#
-
# text_area(:application, :notes, cols: 40, rows: 15, class: 'app_input')
-
# # => <textarea cols="40" rows="15" id="application_notes" name="application[notes]" class="app_input">
-
# # #{@application.notes}
-
# # </textarea>
-
#
-
# text_area(:entry, :body, size: "20x20", disabled: 'disabled')
-
# # => <textarea cols="20" rows="20" id="entry_body" name="entry[body]" disabled="disabled">
-
# # #{@entry.body}
-
# # </textarea>
-
1
def text_area(object_name, method, options = {})
-
Tags::TextArea.new(object_name, method, self, options).render
-
end
-
-
# Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
-
# It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
-
# Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
-
# while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says unchecked check boxes are not successful, and
-
# thus web browsers do not send them. Unfortunately this introduces a gotcha:
-
# if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
-
# invoice the user unchecks its check box, no +paid+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @invoice.update(params[:invoice])
-
#
-
# wouldn't update the flag.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# the very check box. The hidden field has the same name and its
-
# attributes mimic an unchecked check box.
-
#
-
# This way, the client either sends only the hidden field (representing
-
# the check box is unchecked), or both fields. Since the HTML specification
-
# says key/value pairs have to be sent in the same order they appear in the
-
# form, and parameters extraction gets the last occurrence of any repeated
-
# key in the query string, that works for ordinary forms.
-
#
-
# Unfortunately that workaround does not work when the check box goes
-
# within an array-like parameter, as in
-
#
-
# <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
-
# <%= form.check_box :paid %>
-
# ...
-
# <% end %>
-
#
-
# because parameter name repetition is precisely what Rails seeks to distinguish
-
# the elements of the array. For each item with a checked check box you
-
# get an extra ghost item with only that attribute, assigned to "0".
-
#
-
# In that case it is preferable to either use +check_box_tag+ or to use
-
# hashes instead of arrays.
-
#
-
# # Let's say that @post.validated? is 1:
-
# check_box("post", "validated")
-
# # => <input name="post[validated]" type="hidden" value="0" />
-
# # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" />
-
#
-
# # Let's say that @puppy.gooddog is "no":
-
# check_box("puppy", "gooddog", {}, "yes", "no")
-
# # => <input name="puppy[gooddog]" type="hidden" value="no" />
-
# # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
-
#
-
# check_box("eula", "accepted", { class: 'eula_check' }, "yes", "no")
-
# # => <input name="eula[accepted]" type="hidden" value="no" />
-
# # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
-
1
def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
-
Tags::CheckBox.new(object_name, method, self, checked_value, unchecked_value, options).render
-
end
-
-
# Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
-
# radio button will be checked.
-
#
-
# To force the radio button to be checked pass <tt>checked: true</tt> in the
-
# +options+ hash. You may pass HTML options there as well.
-
#
-
# # Let's say that @post.category returns "rails":
-
# radio_button("post", "category", "rails")
-
# radio_button("post", "category", "java")
-
# # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
-
# # <input type="radio" id="post_category_java" name="post[category]" value="java" />
-
#
-
# radio_button("user", "receive_newsletter", "yes")
-
# radio_button("user", "receive_newsletter", "no")
-
# # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
-
# # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
-
1
def radio_button(object_name, method, tag_value, options = {})
-
Tags::RadioButton.new(object_name, method, self, tag_value, options).render
-
end
-
-
# Returns a text_field of type "color".
-
#
-
# color_field("car", "color")
-
# # => <input id="car_color" name="car[color]" type="color" value="#000000" />
-
1
def color_field(object_name, method, options = {})
-
Tags::ColorField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input of type "search" for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object_name+). Inputs of type "search" may be styled differently by
-
# some browsers.
-
#
-
# search_field(:user, :name)
-
# # => <input id="user_name" name="user[name]" type="search" />
-
# search_field(:user, :name, autosave: false)
-
# # => <input autosave="false" id="user_name" name="user[name]" type="search" />
-
# search_field(:user, :name, results: 3)
-
# # => <input id="user_name" name="user[name]" results="3" type="search" />
-
# # Assume request.host returns "www.example.com"
-
# search_field(:user, :name, autosave: true)
-
# # => <input autosave="com.example.www" id="user_name" name="user[name]" results="10" type="search" />
-
# search_field(:user, :name, onsearch: true)
-
# # => <input id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" />
-
# search_field(:user, :name, autosave: false, onsearch: true)
-
# # => <input autosave="false" id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" />
-
# search_field(:user, :name, autosave: true, onsearch: true)
-
# # => <input autosave="com.example.www" id="user_name" incremental="true" name="user[name]" onsearch="true" results="10" type="search" />
-
1
def search_field(object_name, method, options = {})
-
Tags::SearchField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "tel".
-
#
-
# telephone_field("user", "phone")
-
# # => <input id="user_phone" name="user[phone]" type="tel" />
-
#
-
1
def telephone_field(object_name, method, options = {})
-
Tags::TelField.new(object_name, method, self, options).render
-
end
-
# aliases telephone_field
-
1
alias phone_field telephone_field
-
-
# Returns a text_field of type "date".
-
#
-
# date_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" />
-
#
-
# The default value is generated by trying to call "to_date"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone. You can still override that
-
# by passing the "value" option explicitly, e.g.
-
#
-
# @user.born_on = Date.new(1984, 1, 27)
-
# date_field("user", "born_on", value: "1984-05-12")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-05-12" />
-
#
-
# You can create values for the "min" and "max" attributes by passing
-
# instances of Date or Time to the options hash.
-
#
-
# date_field("user", "born_on", min: Date.today)
-
# # => <input id="user_born_on" name="user[born_on]" type="date" min="2014-05-20" />
-
#
-
# Alternatively, you can pass a String formatted as an ISO8601 date as the
-
# values for "min" and "max."
-
#
-
# date_field("user", "born_on", min: "2014-05-20")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" min="2014-05-20" />
-
#
-
1
def date_field(object_name, method, options = {})
-
Tags::DateField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "time".
-
#
-
# The default value is generated by trying to call +strftime+ with "%T.%L"
-
# on the objects's value. It is still possible to override that
-
# by passing the "value" option.
-
#
-
# === Options
-
# * Accepts same options as time_field_tag
-
#
-
# === Example
-
# time_field("task", "started_at")
-
# # => <input id="task_started_at" name="task[started_at]" type="time" />
-
#
-
# You can create values for the "min" and "max" attributes by passing
-
# instances of Date or Time to the options hash.
-
#
-
# time_field("task", "started_at", min: Time.now)
-
# # => <input id="task_started_at" name="task[started_at]" type="time" min="01:00:00.000" />
-
#
-
# Alternatively, you can pass a String formatted as an ISO8601 time as the
-
# values for "min" and "max."
-
#
-
# time_field("task", "started_at", min: "01:00:00")
-
# # => <input id="task_started_at" name="task[started_at]" type="time" min="01:00:00.000" />
-
#
-
1
def time_field(object_name, method, options = {})
-
Tags::TimeField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "datetime".
-
#
-
# datetime_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T.%L%z"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 1, 12)
-
# datetime_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime" value="1984-01-12T00:00:00.000+0000" />
-
#
-
# You can create values for the "min" and "max" attributes by passing
-
# instances of Date or Time to the options hash.
-
#
-
# datetime_field("user", "born_on", min: Date.today)
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime" min="2014-05-20T00:00:00.000+0000" />
-
#
-
# Alternatively, you can pass a String formatted as an ISO8601 datetime
-
# with UTC offset as the values for "min" and "max."
-
#
-
# datetime_field("user", "born_on", min: "2014-05-20T00:00:00+0000")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime" min="2014-05-20T00:00:00.000+0000" />
-
#
-
1
def datetime_field(object_name, method, options = {})
-
Tags::DatetimeField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "datetime-local".
-
#
-
# datetime_local_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 1, 12)
-
# datetime_local_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" value="1984-01-12T00:00:00" />
-
#
-
# You can create values for the "min" and "max" attributes by passing
-
# instances of Date or Time to the options hash.
-
#
-
# datetime_local_field("user", "born_on", min: Date.today)
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />
-
#
-
# Alternatively, you can pass a String formatted as an ISO8601 datetime as
-
# the values for "min" and "max."
-
#
-
# datetime_local_field("user", "born_on", min: "2014-05-20T00:00:00")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />
-
#
-
1
def datetime_local_field(object_name, method, options = {})
-
Tags::DatetimeLocalField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "month".
-
#
-
# month_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="month" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-%m"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 1, 27)
-
# month_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-01" />
-
#
-
1
def month_field(object_name, method, options = {})
-
Tags::MonthField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "week".
-
#
-
# week_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="week" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-W%W"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 5, 12)
-
# week_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-W19" />
-
#
-
1
def week_field(object_name, method, options = {})
-
Tags::WeekField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "url".
-
#
-
# url_field("user", "homepage")
-
# # => <input id="user_homepage" name="user[homepage]" type="url" />
-
#
-
1
def url_field(object_name, method, options = {})
-
Tags::UrlField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "email".
-
#
-
# email_field("user", "address")
-
# # => <input id="user_address" name="user[address]" type="email" />
-
#
-
1
def email_field(object_name, method, options = {})
-
Tags::EmailField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input tag of type "number".
-
#
-
# ==== Options
-
# * Accepts same options as number_field_tag
-
1
def number_field(object_name, method, options = {})
-
2
Tags::NumberField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input tag of type "range".
-
#
-
# ==== Options
-
# * Accepts same options as range_field_tag
-
1
def range_field(object_name, method, options = {})
-
Tags::RangeField.new(object_name, method, self, options).render
-
end
-
-
1
private
-
-
1
def instantiate_builder(record_name, record_object, options)
-
8
case record_name
-
when String, Symbol
-
8
object = record_object
-
8
object_name = record_name
-
else
-
object = record_name
-
object_name = model_name_from_record_or_class(object).param_key
-
end
-
-
8
builder = options[:builder] || default_form_builder_class
-
8
builder.new(object_name, object, self, options)
-
end
-
-
1
def default_form_builder_class
-
8
builder = ActionView::Base.default_form_builder
-
8
builder.respond_to?(:constantize) ? builder.constantize : builder
-
end
-
end
-
-
# A +FormBuilder+ object is associated with a particular model object and
-
# allows you to generate fields associated with the model object. The
-
# +FormBuilder+ object is yielded when using +form_for+ or +fields_for+.
-
# For example:
-
#
-
# <%= form_for @person do |person_form| %>
-
# Name: <%= person_form.text_field :name %>
-
# Admin: <%= person_form.check_box :admin %>
-
# <% end %>
-
#
-
# In the above block, a +FormBuilder+ object is yielded as the
-
# +person_form+ variable. This allows you to generate the +text_field+
-
# and +check_box+ fields by specifying their eponymous methods, which
-
# modify the underlying template and associates the +@person+ model object
-
# with the form.
-
#
-
# The +FormBuilder+ object can be thought of as serving as a proxy for the
-
# methods in the +FormHelper+ module. This class, however, allows you to
-
# call methods with the model object you are building the form for.
-
#
-
# You can create your own custom FormBuilder templates by subclassing this
-
# class. For example:
-
#
-
# class MyFormBuilder < ActionView::Helpers::FormBuilder
-
# def div_radio_button(method, tag_value, options = {})
-
# @template.content_tag(:div,
-
# @template.radio_button(
-
# @object_name, method, tag_value, objectify_options(options)
-
# )
-
# )
-
# end
-
# end
-
#
-
# The above code creates a new method +div_radio_button+ which wraps a div
-
# around the new radio button. Note that when options are passed in, you
-
# must call +objectify_options+ in order for the model object to get
-
# correctly passed to the method. If +objectify_options+ is not called,
-
# then the newly created helper will not be linked back to the model.
-
#
-
# The +div_radio_button+ code from above can now be used as follows:
-
#
-
# <%= form_for @person, :builder => MyFormBuilder do |f| %>
-
# I am a child: <%= f.div_radio_button(:admin, "child") %>
-
# I am an adult: <%= f.div_radio_button(:admin, "adult") %>
-
# <% end -%>
-
#
-
# The standard set of helper methods for form building are located in the
-
# +field_helpers+ class attribute.
-
1
class FormBuilder
-
1
include ModelNaming
-
-
# The methods which wrap a form helper call.
-
1
class_attribute :field_helpers
-
1
self.field_helpers = [:fields_for, :label, :text_field, :password_field,
-
:hidden_field, :file_field, :text_area, :check_box,
-
:radio_button, :color_field, :search_field,
-
:telephone_field, :phone_field, :date_field,
-
:time_field, :datetime_field, :datetime_local_field,
-
:month_field, :week_field, :url_field, :email_field,
-
:number_field, :range_field]
-
-
1
attr_accessor :object_name, :object, :options
-
-
1
attr_reader :multipart, :index
-
1
alias :multipart? :multipart
-
-
1
def multipart=(multipart)
-
@multipart = multipart
-
-
if parent_builder = @options[:parent_builder]
-
parent_builder.multipart = multipart
-
end
-
end
-
-
1
def self._to_partial_path
-
@_to_partial_path ||= name.demodulize.underscore.sub!(/_builder$/, '')
-
end
-
-
1
def to_partial_path
-
self.class._to_partial_path
-
end
-
-
1
def to_model
-
self
-
end
-
-
1
def initialize(object_name, object, template, options)
-
8
@nested_child_index = {}
-
8
@object_name, @object, @template, @options = object_name, object, template, options
-
8
@default_options = @options ? @options.slice(:index, :namespace) : {}
-
8
if @object_name.to_s.match(/\[\]$/)
-
if object ||= @template.instance_variable_get("@#{Regexp.last_match.pre_match}") and object.respond_to?(:to_param)
-
@auto_index = object.to_param
-
else
-
raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
-
end
-
end
-
8
@multipart = nil
-
8
@index = options[:index] || options[:child_index]
-
end
-
-
1
(field_helpers - [:label, :check_box, :radio_button, :fields_for, :hidden_field, :file_field]).each do |selector|
-
17
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{selector}(method, options = {}) # def text_field(method, options = {})
-
@template.send( # @template.send(
-
#{selector.inspect}, # "text_field",
-
@object_name, # @object_name,
-
method, # method,
-
objectify_options(options)) # objectify_options(options))
-
end # end
-
RUBY_EVAL
-
end
-
-
# Creates a scope around a specific model object like form_for, but
-
# doesn't create the form tags themselves. This makes fields_for suitable
-
# for specifying additional model objects in the same form.
-
#
-
# Although the usage and purpose of +fields_for+ is similar to +form_for+'s,
-
# its method signature is slightly different. Like +form_for+, it yields
-
# a FormBuilder object associated with a particular model object to a block,
-
# and within the block allows methods to be called on the builder to
-
# generate fields associated with the model object. Fields may reflect
-
# a model object in two ways - how they are named (hence how submitted
-
# values appear within the +params+ hash in the controller) and what
-
# default values are shown when the form the fields appear in is first
-
# displayed. In order for both of these features to be specified independently,
-
# both an object name (represented by either a symbol or string) and the
-
# object itself can be passed to the method separately -
-
#
-
# <%= form_for @person do |person_form| %>
-
# First name: <%= person_form.text_field :first_name %>
-
# Last name : <%= person_form.text_field :last_name %>
-
#
-
# <%= fields_for :permission, @person.permission do |permission_fields| %>
-
# Admin? : <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# <%= person_form.submit %>
-
# <% end %>
-
#
-
# In this case, the checkbox field will be represented by an HTML +input+
-
# tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted
-
# value will appear in the controller as <tt>params[:permission][:admin]</tt>.
-
# If <tt>@person.permission</tt> is an existing record with an attribute
-
# +admin+, the initial state of the checkbox when first displayed will
-
# reflect the value of <tt>@person.permission.admin</tt>.
-
#
-
# Often this can be simplified by passing just the name of the model
-
# object to +fields_for+ -
-
#
-
# <%= fields_for :permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# ...in which case, if <tt>:permission</tt> also happens to be the name of an
-
# instance variable <tt>@permission</tt>, the initial state of the input
-
# field will reflect the value of that variable's attribute <tt>@permission.admin</tt>.
-
#
-
# Alternatively, you can pass just the model object itself (if the first
-
# argument isn't a string or symbol +fields_for+ will realize that the
-
# name has been omitted) -
-
#
-
# <%= fields_for @person.permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# and +fields_for+ will derive the required name of the field from the
-
# _class_ of the model object, e.g. if <tt>@person.permission</tt>, is
-
# of class +Permission+, the field will still be named <tt>permission[admin]</tt>.
-
#
-
# Note: This also works for the methods in FormOptionHelper and
-
# DateHelper that are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === Nested Attributes Examples
-
#
-
# When the object belonging to the current scope has a nested attribute
-
# writer for a certain attribute, fields_for will yield a new scope
-
# for that attribute. This allows you to create forms that set or change
-
# the attributes of a parent object and its associations in one go.
-
#
-
# Nested attribute writers are normal setter methods named after an
-
# association. The most common way of defining these writers is either
-
# with +accepts_nested_attributes_for+ in a model definition or by
-
# defining a method with the proper name. For example: the attribute
-
# writer for the association <tt>:address</tt> is called
-
# <tt>address_attributes=</tt>.
-
#
-
# Whether a one-to-one or one-to-many style form builder will be yielded
-
# depends on whether the normal reader method returns a _single_ object
-
# or an _array_ of objects.
-
#
-
# ==== One-to-one
-
#
-
# Consider a Person class which returns a _single_ Address from the
-
# <tt>address</tt> reader method and responds to the
-
# <tt>address_attributes=</tt> writer method:
-
#
-
# class Person
-
# def address
-
# @address
-
# end
-
#
-
# def address_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# This model can now be used with a nested fields_for, like so:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# Street : <%= address_fields.text_field :street %>
-
# Zip code: <%= address_fields.text_field :zip_code %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When address is already an association on a Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address
-
# end
-
#
-
# If you want to destroy the associated model through the form, you have
-
# to enable it first using the <tt>:allow_destroy</tt> option for
-
# +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address, allow_destroy: true
-
# end
-
#
-
# Now, when you use a form element with the <tt>_destroy</tt> parameter,
-
# with a value that evaluates to +true+, you will destroy the associated
-
# model (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# ...
-
# Delete: <%= address_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# ==== One-to-many
-
#
-
# Consider a Person class which returns an _array_ of Project instances
-
# from the <tt>projects</tt> reader method and responds to the
-
# <tt>projects_attributes=</tt> writer method:
-
#
-
# class Person
-
# def projects
-
# [@project1, @project2]
-
# end
-
#
-
# def projects_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# Note that the <tt>projects_attributes=</tt> writer method is in fact
-
# required for fields_for to correctly identify <tt>:projects</tt> as a
-
# collection, and the correct indices to be set in the form markup.
-
#
-
# When projects is already an association on Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects
-
# end
-
#
-
# This model can now be used with a nested fields_for. The block given to
-
# the nested fields_for call will be repeated for each instance in the
-
# collection:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# <% if project_fields.object.active? %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# It's also possible to specify the instance to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <% @person.projects.each do |project| %>
-
# <% if project.active? %>
-
# <%= person_form.fields_for :projects, project do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Or a collection to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# If you want to destroy any of the associated models through the
-
# form, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option for +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects, allow_destroy: true
-
# end
-
#
-
# This will allow you to specify which models to destroy in the
-
# attributes hash by adding a form element for the <tt>_destroy</tt>
-
# parameter with a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Delete: <%= project_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When a collection is used you might want to know the index of each
-
# object into the array. For this purpose, the <tt>index</tt> method
-
# is available in the FormBuilder object.
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Project #<%= project_fields.index %>
-
# ...
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Note that fields_for will automatically generate a hidden field
-
# to store the ID of the record. There are circumstances where this
-
# hidden field is not needed and you can pass <tt>include_id: false</tt>
-
# to prevent fields_for from rendering it automatically.
-
1
def fields_for(record_name, record_object = nil, fields_options = {}, &block)
-
fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
-
fields_options[:builder] ||= options[:builder]
-
fields_options[:namespace] = options[:namespace]
-
fields_options[:parent_builder] = self
-
-
case record_name
-
when String, Symbol
-
if nested_attributes_association?(record_name)
-
return fields_for_with_nested_attributes(record_name, record_object, fields_options, block)
-
end
-
else
-
record_object = record_name.is_a?(Array) ? record_name.last : record_name
-
record_name = model_name_from_record_or_class(record_object).param_key
-
end
-
-
index = if options.has_key?(:index)
-
options[:index]
-
elsif defined?(@auto_index)
-
self.object_name = @object_name.to_s.sub(/\[\]$/,"")
-
@auto_index
-
end
-
-
record_name = index ? "#{object_name}[#{index}][#{record_name}]" : "#{object_name}[#{record_name}]"
-
fields_options[:child_index] = index
-
-
@template.fields_for(record_name, record_object, fields_options, &block)
-
end
-
-
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
-
# is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
-
# Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
-
# onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
-
# target labels for radio_button tags (where the value is used in the ID of the input tag).
-
#
-
# ==== Examples
-
# label(:post, :title)
-
# # => <label for="post_title">Title</label>
-
#
-
# You can localize your labels based on model and attribute names.
-
# For example you can define the following in your locale (e.g. en.yml)
-
#
-
# helpers:
-
# label:
-
# post:
-
# body: "Write your entire text here"
-
#
-
# Which then will result in
-
#
-
# label(:post, :body)
-
# # => <label for="post_body">Write your entire text here</label>
-
#
-
# Localization can also be based purely on the translation of the attribute-name
-
# (if you are using ActiveRecord):
-
#
-
# activerecord:
-
# attributes:
-
# post:
-
# cost: "Total cost"
-
#
-
# label(:post, :cost)
-
# # => <label for="post_cost">Total cost</label>
-
#
-
# label(:post, :title, "A short title")
-
# # => <label for="post_title">A short title</label>
-
#
-
# label(:post, :title, "A short title", class: "title_label")
-
# # => <label for="post_title" class="title_label">A short title</label>
-
#
-
# label(:post, :privacy, "Public Post", value: "public")
-
# # => <label for="post_privacy_public">Public Post</label>
-
#
-
# label(:post, :terms) do
-
# 'Accept <a href="/terms">Terms</a>.'.html_safe
-
# end
-
1
def label(method, text = nil, options = {}, &block)
-
26
@template.label(@object_name, method, text, objectify_options(options), &block)
-
end
-
-
# Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
-
# It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
-
# Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
-
# while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says unchecked check boxes are not successful, and
-
# thus web browsers do not send them. Unfortunately this introduces a gotcha:
-
# if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
-
# invoice the user unchecks its check box, no +paid+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @invoice.update(params[:invoice])
-
#
-
# wouldn't update the flag.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# the very check box. The hidden field has the same name and its
-
# attributes mimic an unchecked check box.
-
#
-
# This way, the client either sends only the hidden field (representing
-
# the check box is unchecked), or both fields. Since the HTML specification
-
# says key/value pairs have to be sent in the same order they appear in the
-
# form, and parameters extraction gets the last occurrence of any repeated
-
# key in the query string, that works for ordinary forms.
-
#
-
# Unfortunately that workaround does not work when the check box goes
-
# within an array-like parameter, as in
-
#
-
# <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
-
# <%= form.check_box :paid %>
-
# ...
-
# <% end %>
-
#
-
# because parameter name repetition is precisely what Rails seeks to distinguish
-
# the elements of the array. For each item with a checked check box you
-
# get an extra ghost item with only that attribute, assigned to "0".
-
#
-
# In that case it is preferable to either use +check_box_tag+ or to use
-
# hashes instead of arrays.
-
#
-
# # Let's say that @post.validated? is 1:
-
# check_box("post", "validated")
-
# # => <input name="post[validated]" type="hidden" value="0" />
-
# # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" />
-
#
-
# # Let's say that @puppy.gooddog is "no":
-
# check_box("puppy", "gooddog", {}, "yes", "no")
-
# # => <input name="puppy[gooddog]" type="hidden" value="no" />
-
# # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
-
#
-
# check_box("eula", "accepted", { class: 'eula_check' }, "yes", "no")
-
# # => <input name="eula[accepted]" type="hidden" value="no" />
-
# # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
-
1
def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
-
@template.check_box(@object_name, method, objectify_options(options), checked_value, unchecked_value)
-
end
-
-
# Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
-
# radio button will be checked.
-
#
-
# To force the radio button to be checked pass <tt>checked: true</tt> in the
-
# +options+ hash. You may pass HTML options there as well.
-
#
-
# # Let's say that @post.category returns "rails":
-
# radio_button("post", "category", "rails")
-
# radio_button("post", "category", "java")
-
# # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
-
# # <input type="radio" id="post_category_java" name="post[category]" value="java" />
-
#
-
# radio_button("user", "receive_newsletter", "yes")
-
# radio_button("user", "receive_newsletter", "no")
-
# # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
-
# # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
-
1
def radio_button(method, tag_value, options = {})
-
@template.radio_button(@object_name, method, tag_value, objectify_options(options))
-
end
-
-
# Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# hidden_field(:signup, :pass_confirm)
-
# # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
-
#
-
# hidden_field(:post, :tag_list)
-
# # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
-
#
-
# hidden_field(:user, :token)
-
# # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
-
#
-
1
def hidden_field(method, options = {})
-
@emitted_hidden_id = true if method == :id
-
@template.hidden_field(@object_name, method, objectify_options(options))
-
end
-
-
# Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
-
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
-
#
-
# ==== Examples
-
# file_field(:user, :avatar)
-
# # => <input type="file" id="user_avatar" name="user[avatar]" />
-
#
-
# file_field(:post, :image, :multiple => true)
-
# # => <input type="file" id="post_image" name="post[image]" multiple="true" />
-
#
-
# file_field(:post, :attached, accept: 'text/html')
-
# # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
-
#
-
# file_field(:post, :image, accept: 'image/png,image/gif,image/jpeg')
-
# # => <input type="file" id="post_image" name="post[image]" accept="image/png,image/gif,image/jpeg" />
-
#
-
# file_field(:attachment, :file, class: 'file_input')
-
# # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
-
1
def file_field(method, options = {})
-
self.multipart = true
-
@template.file_field(@object_name, method, objectify_options(options))
-
end
-
-
# Add the submit button for the given form. When no value is given, it checks
-
# if the object is a new resource or not to create the proper label:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# In the example above, if @post is a new record, it will use "Create Post" as
-
# submit button label, otherwise, it uses "Update Post".
-
#
-
# Those labels can be customized using I18n, under the helpers.submit key and accept
-
# the %{model} as translation interpolation:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# create: "Create a %{model}"
-
# update: "Confirm changes to %{model}"
-
#
-
# It also searches for a key specific for the given object:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# post:
-
# create: "Add %{model}"
-
#
-
1
def submit(value=nil, options={})
-
8
value, options = nil, value if value.is_a?(Hash)
-
8
value ||= submit_default_value
-
8
@template.submit_tag(value, options)
-
end
-
-
# Add the submit button for the given form. When no value is given, it checks
-
# if the object is a new resource or not to create the proper label:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.button %>
-
# <% end %>
-
#
-
# In the example above, if @post is a new record, it will use "Create Post" as
-
# button label, otherwise, it uses "Update Post".
-
#
-
# Those labels can be customized using I18n, under the helpers.submit key
-
# (the same as submit helper) and accept the %{model} as translation interpolation:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# create: "Create a %{model}"
-
# update: "Confirm changes to %{model}"
-
#
-
# It also searches for a key specific for the given object:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# post:
-
# create: "Add %{model}"
-
#
-
# ==== Examples
-
# button("Create a post")
-
# # => <button name='button' type='submit'>Create post</button>
-
#
-
# button do
-
# content_tag(:strong, 'Ask me!')
-
# end
-
# # => <button name='button' type='submit'>
-
# # <strong>Ask me!</strong>
-
# # </button>
-
#
-
1
def button(value = nil, options = {}, &block)
-
value, options = nil, value if value.is_a?(Hash)
-
value ||= submit_default_value
-
@template.button_tag(value, options, &block)
-
end
-
-
1
def emitted_hidden_id?
-
@emitted_hidden_id ||= nil
-
end
-
-
1
private
-
1
def objectify_options(options)
-
52
@default_options.merge(options.merge(object: @object))
-
end
-
-
1
def submit_default_value
-
6
object = convert_to_model(@object)
-
6
key = object ? (object.persisted? ? :update : :create) : :submit
-
-
6
model = if object.respond_to?(:model_name)
-
6
object.model_name.human
-
else
-
@object_name.to_s.humanize
-
end
-
-
6
defaults = []
-
6
defaults << :"helpers.submit.#{object_name}.#{key}"
-
6
defaults << :"helpers.submit.#{key}"
-
6
defaults << "#{key.to_s.humanize} #{model}"
-
-
6
I18n.t(defaults.shift, model: model, default: defaults)
-
end
-
-
1
def nested_attributes_association?(association_name)
-
@object.respond_to?("#{association_name}_attributes=")
-
end
-
-
1
def fields_for_with_nested_attributes(association_name, association, options, block)
-
name = "#{object_name}[#{association_name}_attributes]"
-
association = convert_to_model(association)
-
-
if association.respond_to?(:persisted?)
-
association = [association] if @object.send(association_name).respond_to?(:to_ary)
-
elsif !association.respond_to?(:to_ary)
-
association = @object.send(association_name)
-
end
-
-
if association.respond_to?(:to_ary)
-
explicit_child_index = options[:child_index]
-
output = ActiveSupport::SafeBuffer.new
-
association.each do |child|
-
options[:child_index] = nested_child_index(name) unless explicit_child_index
-
output << fields_for_nested_model("#{name}[#{options[:child_index]}]", child, options, block)
-
end
-
output
-
elsif association
-
fields_for_nested_model(name, association, options, block)
-
end
-
end
-
-
1
def fields_for_nested_model(name, object, fields_options, block)
-
object = convert_to_model(object)
-
emit_hidden_id = object.persisted? && fields_options.fetch(:include_id) {
-
options.fetch(:include_id, true)
-
}
-
-
@template.fields_for(name, object, fields_options) do |f|
-
output = @template.capture(f, &block)
-
output.concat f.hidden_field(:id) if output && emit_hidden_id && !f.emitted_hidden_id?
-
output
-
end
-
end
-
-
1
def nested_child_index(name)
-
@nested_child_index[name] ||= -1
-
@nested_child_index[name] += 1
-
end
-
end
-
end
-
-
1
ActiveSupport.on_load(:action_view) do
-
1
cattr_accessor(:default_form_builder, instance_writer: false, instance_reader: false) do
-
2
::ActionView::Helpers::FormBuilder
-
end
-
end
-
end
-
1
require 'cgi'
-
1
require 'erb'
-
1
require 'action_view/helpers/form_helper'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/array/wrap'
-
-
1
module ActionView
-
# = Action View Form Option Helpers
-
1
module Helpers
-
# Provides a number of methods for turning different kinds of containers into a set of option tags.
-
#
-
# The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash:
-
#
-
# * <tt>:include_blank</tt> - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.
-
#
-
# select("post", "category", Post::CATEGORIES, {include_blank: true})
-
#
-
# could become:
-
#
-
# <select name="post[category]">
-
# <option></option>
-
# <option>joke</option>
-
# <option>poem</option>
-
# </select>
-
#
-
# Another common case is a select tag for a <tt>belongs_to</tt>-associated object.
-
#
-
# Example with <tt>@post.person_id => 2</tt>:
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {include_blank: 'None'})
-
#
-
# could become:
-
#
-
# <select name="post[person_id]">
-
# <option value="">None</option>
-
# <option value="1">David</option>
-
# <option value="2" selected="selected">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this prepends an option with a generic prompt -- "Please select" -- or the given prompt string.
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Person'})
-
#
-
# could become:
-
#
-
# <select name="post[person_id]">
-
# <option value="">Select Person</option>
-
# <option value="1">David</option>
-
# <option value="2">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# * <tt>:index</tt> - like the other form helpers, +select+ can accept an <tt>:index</tt> option to manually set the ID used in the resulting output. Unlike other helpers, +select+ expects this
-
# option to be in the +html_options+ parameter.
-
#
-
# select("album[]", "genre", %w[rap rock country], {}, { index: nil })
-
#
-
# becomes:
-
#
-
# <select name="album[][genre]" id="album__genre">
-
# <option value="rap">rap</option>
-
# <option value="rock">rock</option>
-
# <option value="country">country</option>
-
# </select>
-
#
-
# * <tt>:disabled</tt> - can be a single value or an array of values that will be disabled options in the final output.
-
#
-
# select("post", "category", Post::CATEGORIES, {disabled: 'restricted'})
-
#
-
# could become:
-
#
-
# <select name="post[category]">
-
# <option></option>
-
# <option>joke</option>
-
# <option>poem</option>
-
# <option disabled="disabled">restricted</option>
-
# </select>
-
#
-
# When used with the <tt>collection_select</tt> helper, <tt>:disabled</tt> can also be a Proc that identifies those options that should be disabled.
-
#
-
# collection_select(:post, :category_id, Category.all, :id, :name, {disabled: lambda{|category| category.archived? }})
-
#
-
# If the categories "2008 stuff" and "Christmas" return true when the method <tt>archived?</tt> is called, this would return:
-
# <select name="post[category_id]">
-
# <option value="1" disabled="disabled">2008 stuff</option>
-
# <option value="2" disabled="disabled">Christmas</option>
-
# <option value="3">Jokes</option>
-
# <option value="4">Poems</option>
-
# </select>
-
#
-
1
module FormOptionsHelper
-
# ERB::Util can mask some helpers like textilize. Make sure to include them.
-
1
include TextHelper
-
-
# Create a select tag and a series of contained option tags for the provided object and method.
-
# The option currently held by the object will be selected, provided that the object is available.
-
#
-
# There are two possible formats for the +choices+ parameter, corresponding to other helpers' output:
-
#
-
# * A flat collection (see +options_for_select+).
-
#
-
# * A nested collection (see +grouped_options_for_select+).
-
#
-
# For example:
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { include_blank: true })
-
#
-
# would become:
-
#
-
# <select name="post[person_id]">
-
# <option value=""></option>
-
# <option value="1" selected="selected">David</option>
-
# <option value="2">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# assuming the associated person has ID 1.
-
#
-
# This can be used to provide a default set of options in the standard way: before rendering the create form, a
-
# new model instance is assigned the default options and bound to @model_name. Usually this model is not saved
-
# to the database. Instead, a second model object is created when the create request is received.
-
# This allows the user to submit a form page more than once with the expected results of creating multiple records.
-
# In addition, this allows a single partial to be used to generate form inputs for both edit and create forms.
-
#
-
# By default, <tt>post.person_id</tt> is the selected option. Specify <tt>selected: value</tt> to use a different selection
-
# or <tt>selected: nil</tt> to leave all options unselected. Similarly, you can specify values to be disabled in the option
-
# tags by specifying the <tt>:disabled</tt> option. This can either be a single value or an array of values to be disabled.
-
#
-
# A block can be passed to +select+ to customize how the options tags will be rendered. This
-
# is useful when the options tag has complex attributes.
-
#
-
# select(report, "campaign_ids") do
-
# available_campaigns.each do |c|
-
# content_tag(:option, c.name, value: c.id, data: { tags: c.tags.to_json })
-
# end
-
# end
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says when +multiple+ parameter passed to select and all options got deselected
-
# web browsers do not send any value to server. Unfortunately this introduces a gotcha:
-
# if an +User+ model has many +roles+ and have +role_ids+ accessor, and in the form that edits roles of the user
-
# the user deselects all roles from +role_ids+ multiple select box, no +role_ids+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @user.update(params[:user])
-
#
-
# wouldn't update roles.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# every multiple select. The hidden field has the same name as multiple select and blank value.
-
#
-
# <b>Note:</b> The client either sends only the hidden field (representing
-
# the deselected multiple select box), or both fields. This means that the resulting array
-
# always contains a blank string.
-
#
-
# In case if you don't want the helper to generate this hidden field you can specify
-
# <tt>include_hidden: false</tt> option.
-
#
-
1
def select(object, method, choices = nil, options = {}, html_options = {}, &block)
-
4
Tags::Select.new(object, method, self, choices, options, html_options, &block).render
-
end
-
-
# Returns <tt><select></tt> and <tt><option></tt> tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
-
# be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
-
# or <tt>:include_blank</tt> in the +options+ hash.
-
#
-
# The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are methods to be called on each member
-
# of +collection+. The return values are used as the +value+ attribute and contents of each
-
# <tt><option></tt> tag, respectively. They can also be any object that responds to +call+, such
-
# as a +proc+, that will be called for each member of the +collection+ to
-
# retrieve the value/text.
-
#
-
# Example object structure for use with this method:
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# end
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# def name_with_initial
-
# "#{first_name.first}. #{last_name}"
-
# end
-
# end
-
#
-
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
-
#
-
# collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)
-
#
-
# If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
-
# <select name="post[author_id]">
-
# <option value="">Please select</option>
-
# <option value="1" selected="selected">D. Heinemeier Hansson</option>
-
# <option value="2">D. Thomas</option>
-
# <option value="3">M. Clark</option>
-
# </select>
-
1
def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
-
Tags::CollectionSelect.new(object, method, self, collection, value_method, text_method, options, html_options).render
-
end
-
-
# Returns <tt><select></tt>, <tt><optgroup></tt> and <tt><option></tt> tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
-
# be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
-
# or <tt>:include_blank</tt> in the +options+ hash.
-
#
-
# Parameters:
-
# * +object+ - The instance of the class to be used for the select tag
-
# * +method+ - The attribute of +object+ corresponding to the select tag
-
# * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
-
# * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
-
# array of child objects representing the <tt><option></tt> tags.
-
# * +group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
-
# string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
-
# * +option_key_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
-
# * +option_value_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
-
#
-
# Example object structure for use with this method:
-
#
-
# class Continent < ActiveRecord::Base
-
# has_many :countries
-
# # attribs: id, name
-
# end
-
#
-
# class Country < ActiveRecord::Base
-
# belongs_to :continent
-
# # attribs: id, name, continent_id
-
# end
-
#
-
# class City < ActiveRecord::Base
-
# belongs_to :country
-
# # attribs: id, name, country_id
-
# end
-
#
-
# Sample usage:
-
#
-
# grouped_collection_select(:city, :country_id, @continents, :countries, :name, :id, :name)
-
#
-
# Possible output:
-
#
-
# <select name="city[country_id]">
-
# <optgroup label="Africa">
-
# <option value="1">South Africa</option>
-
# <option value="3">Somalia</option>
-
# </optgroup>
-
# <optgroup label="Europe">
-
# <option value="7" selected="selected">Denmark</option>
-
# <option value="2">Ireland</option>
-
# </optgroup>
-
# </select>
-
#
-
1
def grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
-
Tags::GroupedCollectionSelect.new(object, method, self, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options).render
-
end
-
-
# Returns select and option tags for the given object and method, using
-
# #time_zone_options_for_select to generate the list of option tags.
-
#
-
# In addition to the <tt>:include_blank</tt> option documented above,
-
# this method also supports a <tt>:model</tt> option, which defaults
-
# to ActiveSupport::TimeZone. This may be used by users to specify a
-
# different time zone model object. (See +time_zone_options_for_select+
-
# for more information.)
-
#
-
# You can also supply an array of ActiveSupport::TimeZone objects
-
# as +priority_zones+, so that they will be listed above the rest of the
-
# (long) list. (You can use ActiveSupport::TimeZone.us_zones as a convenience
-
# for obtaining a list of the US time zones, or a Regexp to select the zones
-
# of your choice)
-
#
-
# Finally, this method supports a <tt>:default</tt> option, which selects
-
# a default ActiveSupport::TimeZone if the object's time zone is +nil+.
-
#
-
# time_zone_select( "user", "time_zone", nil, include_blank: true)
-
#
-
# time_zone_select( "user", "time_zone", nil, default: "Pacific Time (US & Canada)" )
-
#
-
# time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.us_zones, default: "Pacific Time (US & Canada)")
-
#
-
# time_zone_select( "user", 'time_zone', [ ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii'] ])
-
#
-
# time_zone_select( "user", 'time_zone', /Australia/)
-
#
-
# time_zone_select( "user", "time_zone", ActiveSupport::TimeZone.all.sort, model: ActiveSupport::TimeZone)
-
1
def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
-
Tags::TimeZoneSelect.new(object, method, self, priority_zones, options, html_options).render
-
end
-
-
# Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container
-
# where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and
-
# the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values
-
# become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +selected+
-
# may also be an array of values to be selected when using a multiple select.
-
#
-
# options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
-
# # => <option value="$">Dollar</option>
-
# # => <option value="DKK">Kroner</option>
-
#
-
# options_for_select([ "VISA", "MasterCard" ], "MasterCard")
-
# # => <option>VISA</option>
-
# # => <option selected="selected">MasterCard</option>
-
#
-
# options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
-
# # => <option value="$20">Basic</option>
-
# # => <option value="$40" selected="selected">Plus</option>
-
#
-
# options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
-
# # => <option selected="selected">VISA</option>
-
# # => <option>MasterCard</option>
-
# # => <option selected="selected">Discover</option>
-
#
-
# You can optionally provide HTML attributes as the last element of the array.
-
#
-
# options_for_select([ "Denmark", ["USA", {class: 'bold'}], "Sweden" ], ["USA", "Sweden"])
-
# # => <option value="Denmark">Denmark</option>
-
# # => <option value="USA" class="bold" selected="selected">USA</option>
-
# # => <option value="Sweden" selected="selected">Sweden</option>
-
#
-
# options_for_select([["Dollar", "$", {class: "bold"}], ["Kroner", "DKK", {onclick: "alert('HI');"}]])
-
# # => <option value="$" class="bold">Dollar</option>
-
# # => <option value="DKK" onclick="alert('HI');">Kroner</option>
-
#
-
# If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value
-
# or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags.
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: "Super Platinum")
-
# # => <option value="Free">Free</option>
-
# # => <option value="Basic">Basic</option>
-
# # => <option value="Advanced">Advanced</option>
-
# # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: ["Advanced", "Super Platinum"])
-
# # => <option value="Free">Free</option>
-
# # => <option value="Basic">Basic</option>
-
# # => <option value="Advanced" disabled="disabled">Advanced</option>
-
# # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], selected: "Free", disabled: "Super Platinum")
-
# # => <option value="Free" selected="selected">Free</option>
-
# # => <option value="Basic">Basic</option>
-
# # => <option value="Advanced">Advanced</option>
-
# # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
-
1
def options_for_select(container, selected = nil)
-
8
return container if String === container
-
-
4
selected, disabled = extract_selected_and_disabled(selected).map do |r|
-
12
Array(r).map { |item| item.to_s }
-
end
-
-
container.map do |element|
-
20
html_attributes = option_html_attributes(element)
-
60
text, value = option_text_and_value(element).map { |item| item.to_s }
-
-
20
html_attributes[:selected] ||= option_value_selected?(value, selected)
-
20
html_attributes[:disabled] ||= disabled && option_value_selected?(value, disabled)
-
20
html_attributes[:value] = value
-
-
20
content_tag_string(:option, text, html_attributes)
-
4
end.join("\n").html_safe
-
end
-
-
# Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning
-
# the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
-
#
-
# options_from_collection_for_select(@people, 'id', 'name')
-
# # => <option value="#{person.id}">#{person.name}</option>
-
#
-
# This is more often than not used inside a #select_tag like this example:
-
#
-
# select_tag 'person', options_from_collection_for_select(@people, 'id', 'name')
-
#
-
# If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+
-
# will be selected option tag(s).
-
#
-
# If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous
-
# function are the selected values.
-
#
-
# +selected+ can also be a hash, specifying both <tt>:selected</tt> and/or <tt>:disabled</tt> values as required.
-
#
-
# Be sure to specify the same class as the +value_method+ when specifying selected or disabled options.
-
# Failure to do this will produce undesired results. Example:
-
# options_from_collection_for_select(@people, 'id', 'name', '1')
-
# Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string)
-
# options_from_collection_for_select(@people, 'id', 'name', 1)
-
# should produce the desired results.
-
1
def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
-
options = collection.map do |element|
-
[value_for_collection(element, text_method), value_for_collection(element, value_method), option_html_attributes(element)]
-
end
-
selected, disabled = extract_selected_and_disabled(selected)
-
select_deselect = {
-
selected: extract_values_from_collection(collection, value_method, selected),
-
disabled: extract_values_from_collection(collection, value_method, disabled)
-
}
-
-
options_for_select(options, select_deselect)
-
end
-
-
# Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but
-
# groups them by <tt><optgroup></tt> tags based on the object relationships of the arguments.
-
#
-
# Parameters:
-
# * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
-
# * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
-
# array of child objects representing the <tt><option></tt> tags.
-
# * +group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
-
# string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
-
# * +option_key_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
-
# * +option_value_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
-
# * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
-
# which will have the +selected+ attribute set. Corresponds to the return value of one of the calls
-
# to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are
-
# to be specified.
-
#
-
# Example object structure for use with this method:
-
#
-
# class Continent < ActiveRecord::Base
-
# has_many :countries
-
# # attribs: id, name
-
# end
-
#
-
# class Country < ActiveRecord::Base
-
# belongs_to :continent
-
# # attribs: id, name, continent_id
-
# end
-
#
-
# Sample usage:
-
# option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
-
#
-
# Possible output:
-
# <optgroup label="Africa">
-
# <option value="1">Egypt</option>
-
# <option value="4">Rwanda</option>
-
# ...
-
# </optgroup>
-
# <optgroup label="Asia">
-
# <option value="3" selected="selected">China</option>
-
# <option value="12">India</option>
-
# <option value="5">Japan</option>
-
# ...
-
# </optgroup>
-
#
-
# <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
-
# wrap the output in an appropriate <tt><select></tt> tag.
-
1
def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)
-
collection.map do |group|
-
option_tags = options_from_collection_for_select(
-
group.send(group_method), option_key_method, option_value_method, selected_key)
-
-
content_tag(:optgroup, option_tags, label: group.send(group_label_method))
-
end.join.html_safe
-
end
-
-
# Returns a string of <tt><option></tt> tags, like <tt>options_for_select</tt>, but
-
# wraps them with <tt><optgroup></tt> tags:
-
#
-
# grouped_options = [
-
# ['North America',
-
# [['United States','US'],'Canada']],
-
# ['Europe',
-
# ['Denmark','Germany','France']]
-
# ]
-
# grouped_options_for_select(grouped_options)
-
#
-
# grouped_options = {
-
# 'North America' => [['United States','US'], 'Canada'],
-
# 'Europe' => ['Denmark','Germany','France']
-
# }
-
# grouped_options_for_select(grouped_options)
-
#
-
# Possible output:
-
# <optgroup label="North America">
-
# <option value="US">United States</option>
-
# <option value="Canada">Canada</option>
-
# </optgroup>
-
# <optgroup label="Europe">
-
# <option value="Denmark">Denmark</option>
-
# <option value="Germany">Germany</option>
-
# <option value="France">France</option>
-
# </optgroup>
-
#
-
# Parameters:
-
# * +grouped_options+ - Accepts a nested array or hash of strings. The first value serves as the
-
# <tt><optgroup></tt> label while the second value must be an array of options. The second value can be a
-
# nested array of text-value pairs. See <tt>options_for_select</tt> for more info.
-
# Ex. ["North America",[["United States","US"],["Canada","CA"]]]
-
# * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
-
# which will have the +selected+ attribute set. Note: It is possible for this value to match multiple options
-
# as you might have the same option in multiple groups. Each will then get <tt>selected="selected"</tt>.
-
#
-
# Options:
-
# * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this
-
# prepends an option with a generic prompt - "Please select" - or the given prompt string.
-
# * <tt>:divider</tt> - the divider for the options groups.
-
#
-
# grouped_options = [
-
# [['United States','US'], 'Canada'],
-
# ['Denmark','Germany','France']
-
# ]
-
# grouped_options_for_select(grouped_options, nil, divider: '---------')
-
#
-
# Possible output:
-
# <optgroup label="---------">
-
# <option value="US">United States</option>
-
# <option value="Canada">Canada</option>
-
# </optgroup>
-
# <optgroup label="---------">
-
# <option value="Denmark">Denmark</option>
-
# <option value="Germany">Germany</option>
-
# <option value="France">France</option>
-
# </optgroup>
-
#
-
# <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
-
# wrap the output in an appropriate <tt><select></tt> tag.
-
1
def grouped_options_for_select(grouped_options, selected_key = nil, options = {})
-
prompt = options[:prompt]
-
divider = options[:divider]
-
-
body = "".html_safe
-
-
if prompt
-
body.safe_concat content_tag(:option, prompt_text(prompt), value: "")
-
end
-
-
grouped_options.each do |container|
-
html_attributes = option_html_attributes(container)
-
-
if divider
-
label = divider
-
else
-
label, container = container
-
end
-
-
html_attributes = { label: label }.merge!(html_attributes)
-
body.safe_concat content_tag(:optgroup, options_for_select(container, selected_key), html_attributes)
-
end
-
-
body
-
end
-
-
# Returns a string of option tags for pretty much any time zone in the
-
# world. Supply a ActiveSupport::TimeZone name as +selected+ to have it
-
# marked as the selected option tag. You can also supply an array of
-
# ActiveSupport::TimeZone objects as +priority_zones+, so that they will
-
# be listed above the rest of the (long) list. (You can use
-
# ActiveSupport::TimeZone.us_zones as a convenience for obtaining a list
-
# of the US time zones, or a Regexp to select the zones of your choice)
-
#
-
# The +selected+ parameter must be either +nil+, or a string that names
-
# a ActiveSupport::TimeZone.
-
#
-
# By default, +model+ is the ActiveSupport::TimeZone constant (which can
-
# be obtained in Active Record as a value object). The only requirement
-
# is that the +model+ parameter be an object that responds to +all+, and
-
# returns an array of objects that represent time zones.
-
#
-
# NOTE: Only the option tags are returned, you have to wrap this call in
-
# a regular HTML select tag.
-
1
def time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
-
zone_options = "".html_safe
-
-
zones = model.all
-
convert_zones = lambda { |list| list.map { |z| [ z.to_s, z.name ] } }
-
-
if priority_zones
-
if priority_zones.is_a?(Regexp)
-
priority_zones = zones.select { |z| z =~ priority_zones }
-
end
-
-
zone_options.safe_concat options_for_select(convert_zones[priority_zones], selected)
-
zone_options.safe_concat content_tag(:option, '-------------', value: '', disabled: true)
-
zone_options.safe_concat "\n"
-
-
zones = zones - priority_zones
-
end
-
-
zone_options.safe_concat options_for_select(convert_zones[zones], selected)
-
end
-
-
# Returns radio button tags for the collection of existing return values
-
# of +method+ for +object+'s class. The value returned from calling
-
# +method+ on the instance +object+ will be selected. If calling +method+
-
# returns +nil+, no selection is made.
-
#
-
# The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are
-
# methods to be called on each member of +collection+. The return values
-
# are used as the +value+ attribute and contents of each radio button tag,
-
# respectively. They can also be any object that responds to +call+, such
-
# as a +proc+, that will be called for each member of the +collection+ to
-
# retrieve the value/text.
-
#
-
# Example object structure for use with this method:
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# end
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# def name_with_initial
-
# "#{first_name.first}. #{last_name}"
-
# end
-
# end
-
#
-
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial)
-
#
-
# If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
-
# <input id="post_author_id_1" name="post[author_id]" type="radio" value="1" checked="checked" />
-
# <label for="post_author_id_1">D. Heinemeier Hansson</label>
-
# <input id="post_author_id_2" name="post[author_id]" type="radio" value="2" />
-
# <label for="post_author_id_2">D. Thomas</label>
-
# <input id="post_author_id_3" name="post[author_id]" type="radio" value="3" />
-
# <label for="post_author_id_3">M. Clark</label>
-
#
-
# It is also possible to customize the way the elements will be shown by
-
# giving a block to the method:
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
-
# b.label { b.radio_button }
-
# end
-
#
-
# The argument passed to the block is a special kind of builder for this
-
# collection, which has the ability to generate the label and radio button
-
# for the current item in the collection, with proper text and value.
-
# Using it, you can change the label and radio button display order or
-
# even use the label as wrapper, as in the example above.
-
#
-
# The builder methods <tt>label</tt> and <tt>radio_button</tt> also accept
-
# extra HTML options:
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
-
# b.label(class: "radio_button") { b.radio_button(class: "radio_button") }
-
# end
-
#
-
# There are also three special methods available: <tt>object</tt>, <tt>text</tt> and
-
# <tt>value</tt>, which are the current item being rendered, its text and value methods,
-
# respectively. You can use them like this:
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
-
# b.label(:"data-value" => b.value) { b.radio_button + b.text }
-
# end
-
1
def collection_radio_buttons(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
Tags::CollectionRadioButtons.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
-
end
-
-
# Returns check box tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+
-
# on the instance +object+ will be selected. If calling +method+ returns
-
# +nil+, no selection is made.
-
#
-
# The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are
-
# methods to be called on each member of +collection+. The return values
-
# are used as the +value+ attribute and contents of each check box tag,
-
# respectively. They can also be any object that responds to +call+, such
-
# as a +proc+, that will be called for each member of the +collection+ to
-
# retrieve the value/text.
-
#
-
# Example object structure for use with this method:
-
# class Post < ActiveRecord::Base
-
# has_and_belongs_to_many :authors
-
# end
-
# class Author < ActiveRecord::Base
-
# has_and_belongs_to_many :posts
-
# def name_with_initial
-
# "#{first_name.first}. #{last_name}"
-
# end
-
# end
-
#
-
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial)
-
#
-
# If <tt>@post.author_ids</tt> is already <tt>[1]</tt>, this would return:
-
# <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
-
# <label for="post_author_ids_1">D. Heinemeier Hansson</label>
-
# <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
-
# <label for="post_author_ids_2">D. Thomas</label>
-
# <input id="post_author_ids_3" name="post[author_ids][]" type="checkbox" value="3" />
-
# <label for="post_author_ids_3">M. Clark</label>
-
# <input name="post[author_ids][]" type="hidden" value="" />
-
#
-
# It is also possible to customize the way the elements will be shown by
-
# giving a block to the method:
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
-
# b.label { b.check_box }
-
# end
-
#
-
# The argument passed to the block is a special kind of builder for this
-
# collection, which has the ability to generate the label and check box
-
# for the current item in the collection, with proper text and value.
-
# Using it, you can change the label and check box display order or even
-
# use the label as wrapper, as in the example above.
-
#
-
# The builder methods <tt>label</tt> and <tt>check_box</tt> also accept
-
# extra HTML options:
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
-
# b.label(class: "check_box") { b.check_box(class: "check_box") }
-
# end
-
#
-
# There are also three special methods available: <tt>object</tt>, <tt>text</tt> and
-
# <tt>value</tt>, which are the current item being rendered, its text and value methods,
-
# respectively. You can use them like this:
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
-
# b.label(:"data-value" => b.value) { b.check_box + b.text }
-
# end
-
1
def collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
Tags::CollectionCheckBoxes.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
-
end
-
-
1
private
-
1
def option_html_attributes(element)
-
20
if Array === element
-
element.select { |e| Hash === e }.reduce({}, :merge!)
-
else
-
20
{}
-
end
-
end
-
-
1
def option_text_and_value(option)
-
# Options are [text, value] pairs or strings used for both.
-
20
if !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
-
option = option.reject { |e| Hash === e } if Array === option
-
[option.first, option.last]
-
else
-
20
[option, option]
-
end
-
end
-
-
1
def option_value_selected?(value, selected)
-
40
Array(selected).include? value
-
end
-
-
1
def extract_selected_and_disabled(selected)
-
4
if selected.is_a?(Proc)
-
[selected, nil]
-
else
-
4
selected = Array.wrap(selected)
-
4
options = selected.extract_options!.symbolize_keys
-
4
selected_items = options.fetch(:selected, selected)
-
4
[selected_items, options[:disabled]]
-
end
-
end
-
-
1
def extract_values_from_collection(collection, value_method, selected)
-
if selected.is_a?(Proc)
-
collection.map do |element|
-
element.send(value_method) if selected.call(element)
-
end.compact
-
else
-
selected
-
end
-
end
-
-
1
def value_for_collection(item, value)
-
value.respond_to?(:call) ? value.call(item) : item.send(value)
-
end
-
-
1
def prompt_text(prompt)
-
prompt.kind_of?(String) ? prompt : I18n.translate('helpers.select.prompt', default: 'Please select')
-
end
-
end
-
-
1
class FormBuilder
-
# Wraps ActionView::Helpers::FormOptionsHelper#select for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.select :person_id, Person.all.collect { |p| [ p.name, p.id ] }, include_blank: true %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def select(method, choices = nil, options = {}, html_options = {}, &block)
-
4
@template.select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options), &block)
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#collection_select for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.collection_select :person_id, Author.all, :id, :name_with_initial, prompt: true %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
-
@template.collection_select(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#grouped_collection_select for form builders:
-
#
-
# <%= form_for @city do |f| %>
-
# <%= f.grouped_collection_select :country_id, @continents, :countries, :name, :id, :name %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
-
@template.grouped_collection_select(@object_name, method, collection, group_method, group_label_method, option_key_method, option_value_method, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#time_zone_select for form builders:
-
#
-
# <%= form_for @user do |f| %>
-
# <%= f.time_zone_select :time_zone, nil, include_blank: true %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def time_zone_select(method, priority_zones = nil, options = {}, html_options = {})
-
@template.time_zone_select(@object_name, method, priority_zones, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#collection_check_boxes for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
@template.collection_check_boxes(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block)
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#collection_radio_buttons for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.collection_radio_buttons :author_id, Author.all, :id, :name_with_initial %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
@template.collection_radio_buttons(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block)
-
end
-
end
-
end
-
end
-
1
require 'cgi'
-
1
require 'action_view/helpers/tag_helper'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
module ActionView
-
# = Action View Form Tag Helpers
-
1
module Helpers
-
# Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like
-
# FormHelper does. Instead, you provide the names and values manually.
-
#
-
# NOTE: The HTML options <tt>disabled</tt>, <tt>readonly</tt>, and <tt>multiple</tt> can all be treated as booleans. So specifying
-
# <tt>disabled: true</tt> will give <tt>disabled="disabled"</tt>.
-
1
module FormTagHelper
-
1
extend ActiveSupport::Concern
-
-
1
include UrlHelper
-
1
include TextHelper
-
-
1
mattr_accessor :embed_authenticity_token_in_remote_forms
-
1
self.embed_authenticity_token_in_remote_forms = false
-
-
# Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like
-
# ActionController::Base#url_for. The method for the form defaults to POST.
-
#
-
# ==== Options
-
# * <tt>:multipart</tt> - If set to true, the enctype is set to "multipart/form-data".
-
# * <tt>:method</tt> - The method to use when submitting the form, usually either "get" or "post".
-
# If "patch", "put", "delete", or another verb is used, a hidden input with name <tt>_method</tt>
-
# is added to simulate the verb over post.
-
# * <tt>:authenticity_token</tt> - Authenticity token to use in the form. Use only if you need to
-
# pass custom authenticity token string, or to not add authenticity_token field at all
-
# (by passing <tt>false</tt>). Remote forms may omit the embedded authenticity token
-
# by setting <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>.
-
# This is helpful when you're fragment-caching the form. Remote forms get the
-
# authenticity token from the <tt>meta</tt> tag, so embedding is unnecessary unless you
-
# support browsers without JavaScript.
-
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
-
# submit behavior. By default this behavior is an ajax submit.
-
# * <tt>:enforce_utf8</tt> - If set to false, a hidden input with name utf8 is not output.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# form_tag('/posts')
-
# # => <form action="/posts" method="post">
-
#
-
# form_tag('/posts/1', method: :put)
-
# # => <form action="/posts/1" method="post"> ... <input name="_method" type="hidden" value="put" /> ...
-
#
-
# form_tag('/upload', multipart: true)
-
# # => <form action="/upload" method="post" enctype="multipart/form-data">
-
#
-
# <%= form_tag('/posts') do -%>
-
# <div><%= submit_tag 'Save' %></div>
-
# <% end -%>
-
# # => <form action="/posts" method="post"><div><input type="submit" name="commit" value="Save" /></div></form>
-
#
-
# <%= form_tag('/posts', remote: true) %>
-
# # => <form action="/posts" method="post" data-remote="true">
-
#
-
# form_tag('http://far.away.com/form', authenticity_token: false)
-
# # form without authenticity token
-
#
-
# form_tag('http://far.away.com/form', authenticity_token: "cf50faa3fe97702ca1ae")
-
# # form with custom authenticity token
-
#
-
1
def form_tag(url_for_options = {}, options = {}, &block)
-
html_options = html_options_for_form(url_for_options, options)
-
if block_given?
-
form_tag_with_body(html_options, capture(&block))
-
else
-
form_tag_html(html_options)
-
end
-
end
-
-
# Creates a dropdown selection box, or if the <tt>:multiple</tt> option is set to true, a multiple
-
# choice selection box.
-
#
-
# Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or
-
# associated records. <tt>option_tags</tt> is a string containing the option tags for the select box.
-
#
-
# ==== Options
-
# * <tt>:multiple</tt> - If set to true the selection will allow multiple choices.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:include_blank</tt> - If set to true, an empty option will be created. If set to a string, the string will be used as the option's content and the value will be empty.
-
# * <tt>:prompt</tt> - Create a prompt option with blank value and the text asking user to select something.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name")
-
# # <select id="people" name="people"><option value="1">David</option></select>
-
#
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name", "1")
-
# # <select id="people" name="people"><option value="1" selected="selected">David</option></select>
-
#
-
# select_tag "people", "<option>David</option>".html_safe
-
# # => <select id="people" name="people"><option>David</option></select>
-
#
-
# select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>".html_safe
-
# # => <select id="count" name="count"><option>1</option><option>2</option>
-
# # <option>3</option><option>4</option></select>
-
#
-
# select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>".html_safe, multiple: true
-
# # => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
-
# # <option>Green</option><option>Blue</option></select>
-
#
-
# select_tag "locations", "<option>Home</option><option selected='selected'>Work</option><option>Out</option>".html_safe
-
# # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option>
-
# # <option>Out</option></select>
-
#
-
# select_tag "access", "<option>Read</option><option>Write</option>".html_safe, multiple: true, class: 'form_input', id: 'unique_id'
-
# # => <select class="form_input" id="unique_id" multiple="multiple" name="access[]"><option>Read</option>
-
# # <option>Write</option></select>
-
#
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name"), include_blank: true
-
# # => <select id="people" name="people"><option value=""></option><option value="1">David</option></select>
-
#
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name"), include_blank: "All"
-
# # => <select id="people" name="people"><option value="">All</option><option value="1">David</option></select>
-
#
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name"), prompt: "Select something"
-
# # => <select id="people" name="people"><option value="">Select something</option><option value="1">David</option></select>
-
#
-
# select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>".html_safe, disabled: true
-
# # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
-
# # <option>Paris</option><option>Rome</option></select>
-
#
-
# select_tag "credit_card", options_for_select([ "VISA", "MasterCard" ], "MasterCard")
-
# # => <select id="credit_card" name="credit_card"><option>VISA</option>
-
# # <option selected="selected">MasterCard</option></select>
-
1
def select_tag(name, option_tags = nil, options = {})
-
option_tags ||= ""
-
html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
-
-
if options.include?(:include_blank)
-
include_blank = options.delete(:include_blank)
-
-
if include_blank == true
-
include_blank = ''
-
end
-
-
if include_blank
-
option_tags = content_tag(:option, include_blank, value: '').safe_concat(option_tags)
-
end
-
end
-
-
if prompt = options.delete(:prompt)
-
option_tags = content_tag(:option, prompt, value: '').safe_concat(option_tags)
-
end
-
-
content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
-
end
-
-
# Creates a standard text field; use these text fields to input smaller chunks of text like a username
-
# or a search query.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:size</tt> - The number of visible characters that will fit in the input.
-
# * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
-
# * <tt>:placeholder</tt> - The text contained in the field by default which is removed when the field receives focus.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# text_field_tag 'name'
-
# # => <input id="name" name="name" type="text" />
-
#
-
# text_field_tag 'query', 'Enter your search query here'
-
# # => <input id="query" name="query" type="text" value="Enter your search query here" />
-
#
-
# text_field_tag 'search', nil, placeholder: 'Enter search term...'
-
# # => <input id="search" name="search" placeholder="Enter search term..." type="text" />
-
#
-
# text_field_tag 'request', nil, class: 'special_input'
-
# # => <input class="special_input" id="request" name="request" type="text" />
-
#
-
# text_field_tag 'address', '', size: 75
-
# # => <input id="address" name="address" size="75" type="text" value="" />
-
#
-
# text_field_tag 'zip', nil, maxlength: 5
-
# # => <input id="zip" maxlength="5" name="zip" type="text" />
-
#
-
# text_field_tag 'payment_amount', '$0.00', disabled: true
-
# # => <input disabled="disabled" id="payment_amount" name="payment_amount" type="text" value="$0.00" />
-
#
-
# text_field_tag 'ip', '0.0.0.0', maxlength: 15, size: 20, class: "ip-input"
-
# # => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" />
-
1
def text_field_tag(name, value = nil, options = {})
-
tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
-
end
-
-
# Creates a label element. Accepts a block.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# label_tag 'name'
-
# # => <label for="name">Name</label>
-
#
-
# label_tag 'name', 'Your name'
-
# # => <label for="name">Your name</label>
-
#
-
# label_tag 'name', nil, class: 'small_label'
-
# # => <label for="name" class="small_label">Name</label>
-
1
def label_tag(name = nil, content_or_options = nil, options = nil, &block)
-
26
if block_given? && content_or_options.is_a?(Hash)
-
options = content_or_options = content_or_options.stringify_keys
-
else
-
26
options ||= {}
-
26
options = options.stringify_keys
-
end
-
26
options["for"] = sanitize_to_id(name) unless name.blank? || options.has_key?("for")
-
26
content_tag :label, content_or_options || name.to_s.humanize, options, &block
-
end
-
-
# Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or
-
# data that should be hidden from the user.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# hidden_field_tag 'tags_list'
-
# # => <input id="tags_list" name="tags_list" type="hidden" />
-
#
-
# hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
-
# # => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />
-
#
-
# hidden_field_tag 'collected_input', '', onchange: "alert('Input collected!')"
-
# # => <input id="collected_input" name="collected_input" onchange="alert('Input collected!')"
-
# # type="hidden" value="" />
-
1
def hidden_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :hidden))
-
end
-
-
# Creates a file upload field. If you are using file uploads then you will also need
-
# to set the multipart option for the form tag:
-
#
-
# <%= form_tag '/upload', multipart: true do %>
-
# <label for="file">File to Upload</label> <%= file_field_tag "file" %>
-
# <%= submit_tag %>
-
# <% end %>
-
#
-
# The specified URL will then be passed a File object containing the selected file, or if the field
-
# was left blank, a StringIO object.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
-
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
-
#
-
# ==== Examples
-
# file_field_tag 'attachment'
-
# # => <input id="attachment" name="attachment" type="file" />
-
#
-
# file_field_tag 'avatar', class: 'profile_input'
-
# # => <input class="profile_input" id="avatar" name="avatar" type="file" />
-
#
-
# file_field_tag 'picture', disabled: true
-
# # => <input disabled="disabled" id="picture" name="picture" type="file" />
-
#
-
# file_field_tag 'resume', value: '~/resume.doc'
-
# # => <input id="resume" name="resume" type="file" value="~/resume.doc" />
-
#
-
# file_field_tag 'user_pic', accept: 'image/png,image/gif,image/jpeg'
-
# # => <input accept="image/png,image/gif,image/jpeg" id="user_pic" name="user_pic" type="file" />
-
#
-
# file_field_tag 'file', accept: 'text/html', class: 'upload', value: 'index.html'
-
# # => <input accept="text/html" class="upload" id="file" name="file" type="file" value="index.html" />
-
1
def file_field_tag(name, options = {})
-
text_field_tag(name, nil, options.merge(type: :file))
-
end
-
-
# Creates a password field, a masked text field that will hide the users input behind a mask character.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:size</tt> - The number of visible characters that will fit in the input.
-
# * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# password_field_tag 'pass'
-
# # => <input id="pass" name="pass" type="password" />
-
#
-
# password_field_tag 'secret', 'Your secret here'
-
# # => <input id="secret" name="secret" type="password" value="Your secret here" />
-
#
-
# password_field_tag 'masked', nil, class: 'masked_input_field'
-
# # => <input class="masked_input_field" id="masked" name="masked" type="password" />
-
#
-
# password_field_tag 'token', '', size: 15
-
# # => <input id="token" name="token" size="15" type="password" value="" />
-
#
-
# password_field_tag 'key', nil, maxlength: 16
-
# # => <input id="key" maxlength="16" name="key" type="password" />
-
#
-
# password_field_tag 'confirm_pass', nil, disabled: true
-
# # => <input disabled="disabled" id="confirm_pass" name="confirm_pass" type="password" />
-
#
-
# password_field_tag 'pin', '1234', maxlength: 4, size: 6, class: "pin_input"
-
# # => <input class="pin_input" id="pin" maxlength="4" name="pin" size="6" type="password" value="1234" />
-
1
def password_field_tag(name = "password", value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :password))
-
end
-
-
# Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions.
-
#
-
# ==== Options
-
# * <tt>:size</tt> - A string specifying the dimensions (columns by rows) of the textarea (e.g., "25x10").
-
# * <tt>:rows</tt> - Specify the number of rows in the textarea
-
# * <tt>:cols</tt> - Specify the number of columns in the textarea
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:escape</tt> - By default, the contents of the text input are HTML escaped.
-
# If you need unescaped contents, set this to false.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# text_area_tag 'post'
-
# # => <textarea id="post" name="post"></textarea>
-
#
-
# text_area_tag 'bio', @user.bio
-
# # => <textarea id="bio" name="bio">This is my biography.</textarea>
-
#
-
# text_area_tag 'body', nil, rows: 10, cols: 25
-
# # => <textarea cols="25" id="body" name="body" rows="10"></textarea>
-
#
-
# text_area_tag 'body', nil, size: "25x10"
-
# # => <textarea name="body" id="body" cols="25" rows="10"></textarea>
-
#
-
# text_area_tag 'description', "Description goes here.", disabled: true
-
# # => <textarea disabled="disabled" id="description" name="description">Description goes here.</textarea>
-
#
-
# text_area_tag 'comment', nil, class: 'comment_input'
-
# # => <textarea class="comment_input" id="comment" name="comment"></textarea>
-
1
def text_area_tag(name, content = nil, options = {})
-
options = options.stringify_keys
-
-
if size = options.delete("size")
-
options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
-
end
-
-
escape = options.delete("escape") { true }
-
content = ERB::Util.html_escape(content) if escape
-
-
content_tag :textarea, content.to_s.html_safe, { "name" => name, "id" => sanitize_to_id(name) }.update(options)
-
end
-
-
# Creates a check box form input tag.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# check_box_tag 'accept'
-
# # => <input id="accept" name="accept" type="checkbox" value="1" />
-
#
-
# check_box_tag 'rock', 'rock music'
-
# # => <input id="rock" name="rock" type="checkbox" value="rock music" />
-
#
-
# check_box_tag 'receive_email', 'yes', true
-
# # => <input checked="checked" id="receive_email" name="receive_email" type="checkbox" value="yes" />
-
#
-
# check_box_tag 'tos', 'yes', false, class: 'accept_tos'
-
# # => <input class="accept_tos" id="tos" name="tos" type="checkbox" value="yes" />
-
#
-
# check_box_tag 'eula', 'accepted', false, disabled: true
-
# # => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" />
-
1
def check_box_tag(name, value = "1", checked = false, options = {})
-
html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
-
html_options["checked"] = "checked" if checked
-
tag :input, html_options
-
end
-
-
# Creates a radio button; use groups of radio buttons named the same to allow users to
-
# select from a group of options.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# radio_button_tag 'gender', 'male'
-
# # => <input id="gender_male" name="gender" type="radio" value="male" />
-
#
-
# radio_button_tag 'receive_updates', 'no', true
-
# # => <input checked="checked" id="receive_updates_no" name="receive_updates" type="radio" value="no" />
-
#
-
# radio_button_tag 'time_slot', "3:00 p.m.", false, disabled: true
-
# # => <input disabled="disabled" id="time_slot_300_pm" name="time_slot" type="radio" value="3:00 p.m." />
-
#
-
# radio_button_tag 'color', "green", true, class: "color_input"
-
# # => <input checked="checked" class="color_input" id="color_green" name="color" type="radio" value="green" />
-
1
def radio_button_tag(name, value, checked = false, options = {})
-
html_options = { "type" => "radio", "name" => name, "id" => "#{sanitize_to_id(name)}_#{sanitize_to_id(value)}", "value" => value }.update(options.stringify_keys)
-
html_options["checked"] = "checked" if checked
-
tag :input, html_options
-
end
-
-
# Creates a submit button with the text <tt>value</tt> as the caption.
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:disabled</tt> - If true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - If present the unobtrusive JavaScript
-
# drivers will provide a prompt with the question specified. If the user accepts,
-
# the form is processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a
-
# disabled version of the submit button when the form is submitted. This feature is
-
# provided by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# submit_tag
-
# # => <input name="commit" type="submit" value="Save changes" />
-
#
-
# submit_tag "Edit this article"
-
# # => <input name="commit" type="submit" value="Edit this article" />
-
#
-
# submit_tag "Save edits", disabled: true
-
# # => <input disabled="disabled" name="commit" type="submit" value="Save edits" />
-
#
-
# submit_tag "Complete sale", data: { disable_with: "Please wait..." }
-
# # => <input name="commit" data-disable-with="Please wait..." type="submit" value="Complete sale" />
-
#
-
# submit_tag nil, class: "form_submit"
-
# # => <input class="form_submit" name="commit" type="submit" />
-
#
-
# submit_tag "Edit", class: "edit_button"
-
# # => <input class="edit_button" name="commit" type="submit" value="Edit" />
-
#
-
# submit_tag "Save", data: { confirm: "Are you sure?" }
-
# # => <input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />
-
#
-
1
def submit_tag(value = "Save changes", options = {})
-
8
options = options.stringify_keys
-
-
8
tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options)
-
end
-
-
# Creates a button element that defines a <tt>submit</tt> button,
-
# <tt>reset</tt>button or a generic button which can be used in
-
# JavaScript, for example. You can use the button tag as a regular
-
# submit tag but it isn't supported in legacy browsers. However,
-
# the button tag allows richer labels such as images and emphasis,
-
# so this helper will also accept a block.
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:disabled</tt> - If true, the user will not be able to
-
# use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - If present, the
-
# unobtrusive JavaScript drivers will provide a prompt with
-
# the question specified. If the user accepts, the form is
-
# processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be
-
# used as the value for a disabled version of the submit
-
# button when the form is submitted. This feature is provided
-
# by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# button_tag
-
# # => <button name="button" type="submit">Button</button>
-
#
-
# button_tag(type: 'button') do
-
# content_tag(:strong, 'Ask me!')
-
# end
-
# # => <button name="button" type="button">
-
# # <strong>Ask me!</strong>
-
# # </button>
-
#
-
# button_tag "Checkout", data: { disable_with: "Please wait..." }
-
# # => <button data-disable-with="Please wait..." name="button" type="submit">Checkout</button>
-
#
-
1
def button_tag(content_or_options = nil, options = nil, &block)
-
if content_or_options.is_a? Hash
-
options = content_or_options
-
else
-
options ||= {}
-
end
-
-
options = { 'name' => 'button', 'type' => 'submit' }.merge!(options.stringify_keys)
-
-
if block_given?
-
content_tag :button, options, &block
-
else
-
content_tag :button, content_or_options || 'Button', options
-
end
-
end
-
-
# Displays an image which when clicked will submit the form.
-
#
-
# <tt>source</tt> is passed to AssetTagHelper#path_to_image
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - This will add a JavaScript confirm
-
# prompt with the question specified. If the user accepts, the form is
-
# processed normally, otherwise no action is taken.
-
#
-
# ==== Examples
-
# image_submit_tag("login.png")
-
# # => <input alt="Login" src="/assets/login.png" type="image" />
-
#
-
# image_submit_tag("purchase.png", disabled: true)
-
# # => <input alt="Purchase" disabled="disabled" src="/assets/purchase.png" type="image" />
-
#
-
# image_submit_tag("search.png", class: 'search_button', alt: 'Find')
-
# # => <input alt="Find" class="search_button" src="/assets/search.png" type="image" />
-
#
-
# image_submit_tag("agree.png", disabled: true, class: "agree_disagree_button")
-
# # => <input alt="Agree" class="agree_disagree_button" disabled="disabled" src="/assets/agree.png" type="image" />
-
#
-
# image_submit_tag("save.png", data: { confirm: "Are you sure?" })
-
# # => <input alt="Save" src="/assets/save.png" data-confirm="Are you sure?" type="image" />
-
1
def image_submit_tag(source, options = {})
-
options = options.stringify_keys
-
tag :input, { "alt" => image_alt(source), "type" => "image", "src" => path_to_image(source) }.update(options)
-
end
-
-
# Creates a field set for grouping HTML form elements.
-
#
-
# <tt>legend</tt> will become the fieldset's title (optional as per W3C).
-
# <tt>options</tt> accept the same values as tag.
-
#
-
# ==== Examples
-
# <%= field_set_tag do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
-
#
-
# <%= field_set_tag 'Your details' do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset><legend>Your details</legend><p><input id="name" name="name" type="text" /></p></fieldset>
-
#
-
# <%= field_set_tag nil, class: 'format' do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset>
-
1
def field_set_tag(legend = nil, options = nil, &block)
-
output = tag(:fieldset, options, true)
-
output.safe_concat(content_tag(:legend, legend)) unless legend.blank?
-
output.concat(capture(&block)) if block_given?
-
output.safe_concat("</fieldset>")
-
end
-
-
# Creates a text field of type "color".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
#
-
# ==== Examples
-
# color_field_tag 'name'
-
# # => <input id="name" name="name" type="color" />
-
#
-
# color_field_tag 'color', '#DEF726'
-
# # => <input id="color" name="color" type="color" value="#DEF726" />
-
#
-
# color_field_tag 'color', nil, class: 'special_input'
-
# # => <input class="special_input" id="color" name="color" type="color" />
-
#
-
# color_field_tag 'color', '#DEF726', class: 'special_input', disabled: true
-
# # => <input disabled="disabled" class="special_input" id="color" name="color" type="color" value="#DEF726" />
-
1
def color_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :color))
-
end
-
-
# Creates a text field of type "search".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
#
-
# ==== Examples
-
# search_field_tag 'name'
-
# # => <input id="name" name="name" type="search" />
-
#
-
# search_field_tag 'search', 'Enter your search query here'
-
# # => <input id="search" name="search" type="search" value="Enter your search query here" />
-
#
-
# search_field_tag 'search', nil, class: 'special_input'
-
# # => <input class="special_input" id="search" name="search" type="search" />
-
#
-
# search_field_tag 'search', 'Enter your search query here', class: 'special_input', disabled: true
-
# # => <input disabled="disabled" class="special_input" id="search" name="search" type="search" value="Enter your search query here" />
-
1
def search_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :search))
-
end
-
-
# Creates a text field of type "tel".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
#
-
# ==== Examples
-
# telephone_field_tag 'name'
-
# # => <input id="name" name="name" type="tel" />
-
#
-
# telephone_field_tag 'tel', '0123456789'
-
# # => <input id="tel" name="tel" type="tel" value="0123456789" />
-
#
-
# telephone_field_tag 'tel', nil, class: 'special_input'
-
# # => <input class="special_input" id="tel" name="tel" type="tel" />
-
#
-
# telephone_field_tag 'tel', '0123456789', class: 'special_input', disabled: true
-
# # => <input disabled="disabled" class="special_input" id="tel" name="tel" type="tel" value="0123456789" />
-
1
def telephone_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :tel))
-
end
-
1
alias phone_field_tag telephone_field_tag
-
-
# Creates a text field of type "date".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
#
-
# ==== Examples
-
# date_field_tag 'name'
-
# # => <input id="name" name="name" type="date" />
-
#
-
# date_field_tag 'date', '01/01/2014'
-
# # => <input id="date" name="date" type="date" value="01/01/2014" />
-
#
-
# date_field_tag 'date', nil, class: 'special_input'
-
# # => <input class="special_input" id="date" name="date" type="date" />
-
#
-
# date_field_tag 'date', '01/01/2014', class: 'special_input', disabled: true
-
# # => <input disabled="disabled" class="special_input" id="date" name="date" type="date" value="01/01/2014" />
-
1
def date_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :date))
-
end
-
-
# Creates a text field of type "time".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
1
def time_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :time))
-
end
-
-
# Creates a text field of type "datetime".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
1
def datetime_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :datetime))
-
end
-
-
# Creates a text field of type "datetime-local".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
1
def datetime_local_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: 'datetime-local'))
-
end
-
-
# Creates a text field of type "month".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
1
def month_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :month))
-
end
-
-
# Creates a text field of type "week".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
1
def week_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :week))
-
end
-
-
# Creates a text field of type "url".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
#
-
# ==== Examples
-
# url_field_tag 'name'
-
# # => <input id="name" name="name" type="url" />
-
#
-
# url_field_tag 'url', 'http://rubyonrails.org'
-
# # => <input id="url" name="url" type="url" value="http://rubyonrails.org" />
-
#
-
# url_field_tag 'url', nil, class: 'special_input'
-
# # => <input class="special_input" id="url" name="url" type="url" />
-
#
-
# url_field_tag 'url', 'http://rubyonrails.org', class: 'special_input', disabled: true
-
# # => <input disabled="disabled" class="special_input" id="url" name="url" type="url" value="http://rubyonrails.org" />
-
1
def url_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :url))
-
end
-
-
# Creates a text field of type "email".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
#
-
# ==== Examples
-
# email_field_tag 'name'
-
# # => <input id="name" name="name" type="email" />
-
#
-
# email_field_tag 'email', 'email@example.com'
-
# # => <input id="email" name="email" type="email" value="email@example.com" />
-
#
-
# email_field_tag 'email', nil, class: 'special_input'
-
# # => <input class="special_input" id="email" name="email" type="email" />
-
#
-
# email_field_tag 'email', 'email@example.com', class: 'special_input', disabled: true
-
# # => <input disabled="disabled" class="special_input" id="email" name="email" type="email" value="email@example.com" />
-
1
def email_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.merge(type: :email))
-
end
-
-
# Creates a number field.
-
#
-
# ==== Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:in</tt> - A range specifying the <tt>:min</tt> and
-
# <tt>:max</tt> values.
-
# * <tt>:within</tt> - Same as <tt>:in</tt>.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
#
-
# ==== Examples
-
# number_field_tag 'quantity'
-
# # => <input id="quantity" name="quantity" type="number" />
-
#
-
# number_field_tag 'quantity', '1'
-
# # => <input id="quantity" name="quantity" type="number" value="1" />
-
#
-
# number_field_tag 'quantity', nil, class: 'special_input'
-
# # => <input class="special_input" id="quantity" name="quantity" type="number" />
-
#
-
# number_field_tag 'quantity', nil, min: 1
-
# # => <input id="quantity" name="quantity" min="1" type="number" />
-
#
-
# number_field_tag 'quantity', nil, max: 9
-
# # => <input id="quantity" name="quantity" max="9" type="number" />
-
#
-
# number_field_tag 'quantity', nil, in: 1...10
-
# # => <input id="quantity" name="quantity" min="1" max="9" type="number" />
-
#
-
# number_field_tag 'quantity', nil, within: 1...10
-
# # => <input id="quantity" name="quantity" min="1" max="9" type="number" />
-
#
-
# number_field_tag 'quantity', nil, min: 1, max: 10
-
# # => <input id="quantity" name="quantity" min="1" max="9" type="number" />
-
#
-
# number_field_tag 'quantity', nil, min: 1, max: 10, step: 2
-
# # => <input id="quantity" name="quantity" min="1" max="9" step="2" type="number" />
-
#
-
# number_field_tag 'quantity', '1', class: 'special_input', disabled: true
-
# # => <input disabled="disabled" class="special_input" id="quantity" name="quantity" type="number" value="1" />
-
1
def number_field_tag(name, value = nil, options = {})
-
options = options.stringify_keys
-
options["type"] ||= "number"
-
if range = options.delete("in") || options.delete("within")
-
options.update("min" => range.min, "max" => range.max)
-
end
-
text_field_tag(name, value, options)
-
end
-
-
# Creates a range form element.
-
#
-
# ==== Options
-
# * Accepts the same options as number_field_tag.
-
1
def range_field_tag(name, value = nil, options = {})
-
number_field_tag(name, value, options.merge(type: :range))
-
end
-
-
# Creates the hidden UTF8 enforcer tag. Override this method in a helper
-
# to customize the tag.
-
1
def utf8_enforcer_tag
-
# Use raw HTML to ensure the value is written as an HTML entity; it
-
# needs to be the right character regardless of which encoding the
-
# browser infers.
-
8
'<input name="utf8" type="hidden" value="✓" />'.html_safe
-
end
-
-
1
private
-
1
def html_options_for_form(url_for_options, options)
-
8
options.stringify_keys.tap do |html_options|
-
8
html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
-
# The following URL is unescaped, this is just a hash of options, and it is the
-
# responsibility of the caller to escape all the values.
-
8
html_options["action"] = url_for(url_for_options)
-
8
html_options["accept-charset"] = "UTF-8"
-
-
8
html_options["data-remote"] = true if html_options.delete("remote")
-
-
if html_options["data-remote"] &&
-
8
!embed_authenticity_token_in_remote_forms &&
-
html_options["authenticity_token"].blank?
-
# The authenticity token is taken from the meta tag in this case
-
html_options["authenticity_token"] = false
-
elsif html_options["authenticity_token"] == true
-
# Include the default authenticity_token, which is only generated when its set to nil,
-
# but we needed the true value to override the default of no authenticity_token on data-remote.
-
html_options["authenticity_token"] = nil
-
end
-
end
-
end
-
-
1
def extra_tags_for_form(html_options)
-
8
authenticity_token = html_options.delete("authenticity_token")
-
8
method = html_options.delete("method").to_s
-
-
8
method_tag = case method
-
when /^get$/i # must be case-insensitive, but can't use downcase as might be nil
-
html_options["method"] = "get"
-
''
-
when /^post$/i, "", nil
-
4
html_options["method"] = "post"
-
4
token_tag(authenticity_token)
-
else
-
4
html_options["method"] = "post"
-
4
method_tag(method) + token_tag(authenticity_token)
-
end
-
-
16
if html_options.delete("enforce_utf8") { true }
-
8
utf8_enforcer_tag + method_tag
-
else
-
method_tag
-
end
-
end
-
-
1
def form_tag_html(html_options)
-
8
extra_tags = extra_tags_for_form(html_options)
-
8
tag(:form, html_options, true) + extra_tags
-
end
-
-
1
def form_tag_with_body(html_options, content)
-
8
output = form_tag_html(html_options)
-
8
output << content
-
8
output.safe_concat("</form>")
-
end
-
-
# see http://www.w3.org/TR/html4/types.html#type-name
-
1
def sanitize_to_id(name)
-
name.to_s.delete(']').tr('^-a-zA-Z0-9:.', "_")
-
end
-
end
-
end
-
end
-
1
require 'action_view/helpers/tag_helper'
-
-
1
module ActionView
-
1
module Helpers
-
1
module JavaScriptHelper
-
1
JS_ESCAPE_MAP = {
-
'\\' => '\\\\',
-
'</' => '<\/',
-
"\r\n" => '\n',
-
"\n" => '\n',
-
"\r" => '\n',
-
'"' => '\\"',
-
"'" => "\\'"
-
}
-
-
1
JS_ESCAPE_MAP["\342\200\250".force_encoding(Encoding::UTF_8).encode!] = '
'
-
1
JS_ESCAPE_MAP["\342\200\251".force_encoding(Encoding::UTF_8).encode!] = '
'
-
-
# Escapes carriage returns and single and double quotes for JavaScript segments.
-
#
-
# Also available through the alias j(). This is particularly helpful in JavaScript
-
# responses, like:
-
#
-
# $('some_element').replaceWith('<%=j render 'some/element_template' %>');
-
1
def escape_javascript(javascript)
-
if javascript
-
result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] }
-
javascript.html_safe? ? result.html_safe : result
-
else
-
''
-
end
-
end
-
-
1
alias_method :j, :escape_javascript
-
-
# Returns a JavaScript tag with the +content+ inside. Example:
-
# javascript_tag "alert('All is good')"
-
#
-
# Returns:
-
# <script>
-
# //<![CDATA[
-
# alert('All is good')
-
# //]]>
-
# </script>
-
#
-
# +html_options+ may be a hash of attributes for the <tt>\<script></tt>
-
# tag.
-
#
-
# javascript_tag "alert('All is good')", defer: 'defer'
-
#
-
# Returns:
-
# <script defer="defer">
-
# //<![CDATA[
-
# alert('All is good')
-
# //]]>
-
# </script>
-
#
-
# Instead of passing the content as an argument, you can also use a block
-
# in which case, you pass your +html_options+ as the first parameter.
-
#
-
# <%= javascript_tag defer: 'defer' do -%>
-
# alert('All is good')
-
# <% end -%>
-
1
def javascript_tag(content_or_options_with_block = nil, html_options = {}, &block)
-
content =
-
if block_given?
-
html_options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
-
capture(&block)
-
else
-
content_or_options_with_block
-
end
-
-
content_tag(:script, javascript_cdata_section(content), html_options)
-
end
-
-
1
def javascript_cdata_section(content) #:nodoc:
-
"\n//#{cdata_section("\n#{content}\n//")}\n".html_safe
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/number_helper'
-
-
1
module ActionView
-
# = Action View Number Helpers
-
1
module Helpers #:nodoc:
-
-
# Provides methods for converting numbers into formatted strings.
-
# Methods are provided for phone numbers, currency, percentage,
-
# precision, positional notation, file size and pretty printing.
-
#
-
# Most methods expect a +number+ argument, and will return it
-
# unchanged if can't be converted into a valid number.
-
1
module NumberHelper
-
-
# Raised when argument +number+ param given to the helpers is invalid and
-
# the option :raise is set to +true+.
-
1
class InvalidNumberError < StandardError
-
1
attr_accessor :number
-
1
def initialize(number)
-
@number = number
-
end
-
end
-
-
# Formats a +number+ into a US phone number (e.g., (555)
-
# 123-9876). You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:area_code</tt> - Adds parentheses around the area code.
-
# * <tt>:delimiter</tt> - Specifies the delimiter to use
-
# (defaults to "-").
-
# * <tt>:extension</tt> - Specifies an extension to add to the
-
# end of the generated number.
-
# * <tt>:country_code</tt> - Sets the country code for the phone
-
# number.
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_phone(5551234) # => 555-1234
-
# number_to_phone("5551234") # => 555-1234
-
# number_to_phone(1235551234) # => 123-555-1234
-
# number_to_phone(1235551234, area_code: true) # => (123) 555-1234
-
# number_to_phone(1235551234, delimiter: " ") # => 123 555 1234
-
# number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
-
# number_to_phone("123a456") # => 123a456
-
# number_to_phone("1234a567", raise: true) # => InvalidNumberError
-
#
-
# number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: ".")
-
# # => +1.123.555.1234 x 1343
-
1
def number_to_phone(number, options = {})
-
return unless number
-
options = options.symbolize_keys
-
-
parse_float(number, true) if options.delete(:raise)
-
ERB::Util.html_escape(ActiveSupport::NumberHelper.number_to_phone(number, options))
-
end
-
-
# Formats a +number+ into a currency string (e.g., $13.65). You
-
# can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the level of precision (defaults
-
# to 2).
-
# * <tt>:unit</tt> - Sets the denomination of the currency
-
# (defaults to "$").
-
# * <tt>:separator</tt> - Sets the separator between the units
-
# (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:format</tt> - Sets the format for non-negative numbers
-
# (defaults to "%u%n"). Fields are <tt>%u</tt> for the
-
# currency, and <tt>%n</tt> for the number.
-
# * <tt>:negative_format</tt> - Sets the format for negative
-
# numbers (defaults to prepending an hyphen to the formatted
-
# number given by <tt>:format</tt>). Accepts the same fields
-
# than <tt>:format</tt>, except <tt>%n</tt> is here the
-
# absolute value of the number.
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_currency(1234567890.50) # => $1,234,567,890.50
-
# number_to_currency(1234567890.506) # => $1,234,567,890.51
-
# number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506
-
# number_to_currency(1234567890.506, locale: :fr) # => 1 234 567 890,51 €
-
# number_to_currency("123a456") # => $123a456
-
#
-
# number_to_currency("123a456", raise: true) # => InvalidNumberError
-
#
-
# number_to_currency(-1234567890.50, negative_format: "(%u%n)")
-
# # => ($1,234,567,890.50)
-
# number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "")
-
# # => R$1234567890,50
-
# number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "", format: "%n %u")
-
# # => 1234567890,50 R$
-
1
def number_to_currency(number, options = {})
-
delegate_number_helper_method(:number_to_currency, number, options)
-
end
-
-
# Formats a +number+ as a percentage string (e.g., 65%). You can
-
# customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:format</tt> - Specifies the format of the percentage
-
# string The number field is <tt>%n</tt> (defaults to "%n%").
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_percentage(100) # => 100.000%
-
# number_to_percentage("98") # => 98.000%
-
# number_to_percentage(100, precision: 0) # => 100%
-
# number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000%
-
# number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
-
# number_to_percentage(1000, locale: :fr) # => 1 000,000%
-
# number_to_percentage("98a") # => 98a%
-
# number_to_percentage(100, format: "%n %") # => 100 %
-
#
-
# number_to_percentage("98a", raise: true) # => InvalidNumberError
-
1
def number_to_percentage(number, options = {})
-
delegate_number_helper_method(:number_to_percentage, number, options)
-
end
-
-
# Formats a +number+ with grouped thousands using +delimiter+
-
# (e.g., 12,324). You can customize the format in the +options+
-
# hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_with_delimiter(12345678) # => 12,345,678
-
# number_with_delimiter("123456") # => 123,456
-
# number_with_delimiter(12345678.05) # => 12,345,678.05
-
# number_with_delimiter(12345678, delimiter: ".") # => 12.345.678
-
# number_with_delimiter(12345678, delimiter: ",") # => 12,345,678
-
# number_with_delimiter(12345678.05, separator: " ") # => 12,345,678 05
-
# number_with_delimiter(12345678.05, locale: :fr) # => 12 345 678,05
-
# number_with_delimiter("112a") # => 112a
-
# number_with_delimiter(98765432.98, delimiter: " ", separator: ",")
-
# # => 98 765 432,98
-
#
-
# number_with_delimiter("112a", raise: true) # => raise InvalidNumberError
-
1
def number_with_delimiter(number, options = {})
-
delegate_number_helper_method(:number_to_delimited, number, options)
-
end
-
-
# Formats a +number+ with the specified level of
-
# <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
-
# +:significant+ is +false+, and 5 if +:significant+ is +true+).
-
# You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_with_precision(111.2345) # => 111.235
-
# number_with_precision(111.2345, precision: 2) # => 111.23
-
# number_with_precision(13, precision: 5) # => 13.00000
-
# number_with_precision(389.32314, precision: 0) # => 389
-
# number_with_precision(111.2345, significant: true) # => 111
-
# number_with_precision(111.2345, precision: 1, significant: true) # => 100
-
# number_with_precision(13, precision: 5, significant: true) # => 13.000
-
# number_with_precision(111.234, locale: :fr) # => 111,234
-
#
-
# number_with_precision(13, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
#
-
# number_with_precision(389.32314, precision: 4, significant: true) # => 389.3
-
# number_with_precision(1111.2345, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
1
def number_with_precision(number, options = {})
-
delegate_number_helper_method(:number_to_rounded, number, options)
-
end
-
-
# Formats the bytes in +number+ into a more understandable
-
# representation (e.g., giving it 1500 yields 1.5 KB). This
-
# method is useful for reporting file sizes to users. You can
-
# customize the format in the +options+ hash.
-
#
-
# See <tt>number_to_human</tt> if you want to pretty-print a
-
# generic number.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:prefix</tt> - If +:si+ formats the number using the SI
-
# prefix (defaults to :binary)
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_human_size(123) # => 123 Bytes
-
# number_to_human_size(1234) # => 1.21 KB
-
# number_to_human_size(12345) # => 12.1 KB
-
# number_to_human_size(1234567) # => 1.18 MB
-
# number_to_human_size(1234567890) # => 1.15 GB
-
# number_to_human_size(1234567890123) # => 1.12 TB
-
# number_to_human_size(1234567, precision: 2) # => 1.2 MB
-
# number_to_human_size(483989, precision: 2) # => 470 KB
-
# number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB
-
# number_to_human_size(1234567890123, precision: 5) # => "1.1228 TB"
-
# number_to_human_size(524288000, precision: 5) # => "500 MB"
-
1
def number_to_human_size(number, options = {})
-
delegate_number_helper_method(:number_to_human_size, number, options)
-
end
-
-
# Pretty prints (formats and approximates) a number in a way it
-
# is more readable by humans (eg.: 1200000000 becomes "1.2
-
# Billion"). This is useful for numbers that can get very large
-
# (and too hard to read).
-
#
-
# See <tt>number_to_human_size</tt> if you want to print a file
-
# size.
-
#
-
# You can also define you own unit-quantifier names if you want
-
# to use other decimal units (eg.: 1500 becomes "1.5
-
# kilometers", 0.150 becomes "150 milliliters", etc). You may
-
# define a wide range of unit quantifiers, even fractional ones
-
# (centi, deci, mili, etc).
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:units</tt> - A Hash of unit quantifier names. Or a
-
# string containing an i18n scope where to find this hash. It
-
# might have the following keys:
-
# * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
-
# <tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
-
# <tt>:billion</tt>, <tt>:trillion</tt>,
-
# <tt>:quadrillion</tt>
-
# * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
-
# <tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
-
# <tt>:pico</tt>, <tt>:femto</tt>
-
# * <tt>:format</tt> - Sets the format of the output string
-
# (defaults to "%n %u"). The field types are:
-
# * %u - The quantifier (ex.: 'thousand')
-
# * %n - The number
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_human(123) # => "123"
-
# number_to_human(1234) # => "1.23 Thousand"
-
# number_to_human(12345) # => "12.3 Thousand"
-
# number_to_human(1234567) # => "1.23 Million"
-
# number_to_human(1234567890) # => "1.23 Billion"
-
# number_to_human(1234567890123) # => "1.23 Trillion"
-
# number_to_human(1234567890123456) # => "1.23 Quadrillion"
-
# number_to_human(1234567890123456789) # => "1230 Quadrillion"
-
# number_to_human(489939, precision: 2) # => "490 Thousand"
-
# number_to_human(489939, precision: 4) # => "489.9 Thousand"
-
# number_to_human(1234567, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# number_to_human(1234567, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
#
-
# number_to_human(500000000, precision: 5) # => "500 Million"
-
# number_to_human(12345012345, significant: false) # => "12.345 Billion"
-
#
-
# Non-significant zeros after the decimal separator are stripped
-
# out by default (set <tt>:strip_insignificant_zeros</tt> to
-
# +false+ to change that):
-
#
-
# number_to_human(12.00001) # => "12"
-
# number_to_human(12.00001, strip_insignificant_zeros: false) # => "12.0"
-
#
-
# ==== Custom Unit Quantifiers
-
#
-
# You can also use your own custom unit quantifiers:
-
# number_to_human(500000, units: {unit: "ml", thousand: "lt"}) # => "500 lt"
-
#
-
# If in your I18n locale you have:
-
# distance:
-
# centi:
-
# one: "centimeter"
-
# other: "centimeters"
-
# unit:
-
# one: "meter"
-
# other: "meters"
-
# thousand:
-
# one: "kilometer"
-
# other: "kilometers"
-
# billion: "gazillion-distance"
-
#
-
# Then you could do:
-
#
-
# number_to_human(543934, units: :distance) # => "544 kilometers"
-
# number_to_human(54393498, units: :distance) # => "54400 kilometers"
-
# number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance"
-
# number_to_human(343, units: :distance, precision: 1) # => "300 meters"
-
# number_to_human(1, units: :distance) # => "1 meter"
-
# number_to_human(0.34, units: :distance) # => "34 centimeters"
-
#
-
1
def number_to_human(number, options = {})
-
delegate_number_helper_method(:number_to_human, number, options)
-
end
-
-
1
private
-
-
1
def delegate_number_helper_method(method, number, options)
-
return unless number
-
options = escape_unsafe_options(options.symbolize_keys)
-
-
wrap_with_output_safety_handling(number, options.delete(:raise)) {
-
ActiveSupport::NumberHelper.public_send(method, number, options)
-
}
-
end
-
-
1
def escape_unsafe_options(options)
-
options[:format] = ERB::Util.html_escape(options[:format]) if options[:format]
-
options[:negative_format] = ERB::Util.html_escape(options[:negative_format]) if options[:negative_format]
-
options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator]
-
options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter]
-
options[:unit] = ERB::Util.html_escape(options[:unit]) if options[:unit] && !options[:unit].html_safe?
-
options[:units] = escape_units(options[:units]) if options[:units] && Hash === options[:units]
-
options
-
end
-
-
1
def escape_units(units)
-
Hash[units.map do |k, v|
-
[k, ERB::Util.html_escape(v)]
-
end]
-
end
-
-
1
def wrap_with_output_safety_handling(number, raise_on_invalid, &block)
-
valid_float = valid_float?(number)
-
raise InvalidNumberError, number if raise_on_invalid && !valid_float
-
-
formatted_number = yield
-
-
if valid_float || number.html_safe?
-
formatted_number.html_safe
-
else
-
formatted_number
-
end
-
end
-
-
1
def valid_float?(number)
-
!parse_float(number, false).nil?
-
end
-
-
1
def parse_float(number, raise_error)
-
Float(number)
-
rescue ArgumentError, TypeError
-
raise InvalidNumberError, number if raise_error
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView #:nodoc:
-
# = Action View Raw Output Helper
-
1
module Helpers #:nodoc:
-
1
module OutputSafetyHelper
-
# This method outputs without escaping a string. Since escaping tags is
-
# now default, this can be used when you don't want Rails to automatically
-
# escape tags. This is not recommended if the data is coming from the user's
-
# input.
-
#
-
# For example:
-
#
-
# raw @user.name
-
# # => 'Jimmy <alert>Tables</alert>'
-
1
def raw(stringish)
-
stringish.to_s.html_safe
-
end
-
-
# This method returns an HTML safe string similar to what <tt>Array#join</tt>
-
# would return. The array is flattened, and all items, including
-
# the supplied separator, are HTML escaped unless they are HTML
-
# safe, and the returned string is marked as HTML safe.
-
#
-
# safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
-
# # => "<p>foo</p><br /><p>bar</p>"
-
#
-
# safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe)
-
# # => "<p>foo</p><br /><p>bar</p>"
-
#
-
1
def safe_join(array, sep=$,)
-
sep = ERB::Util.unwrapped_html_escape(sep)
-
-
array.flatten.map! { |i| ERB::Util.unwrapped_html_escape(i) }.join(sep).html_safe
-
end
-
end
-
end
-
end
-
1
require 'action_view/record_identifier'
-
-
1
module ActionView
-
# = Action View Record Tag Helpers
-
1
module Helpers
-
1
module RecordTagHelper
-
1
include ActionView::RecordIdentifier
-
-
# Produces a wrapper DIV element with id and class parameters that
-
# relate to the specified Active Record object. Usage example:
-
#
-
# <%= div_for(@person, class: "foo") do %>
-
# <%= @person.name %>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <div id="person_123" class="person foo"> Joe Bloggs </div>
-
#
-
# You can also pass an array of Active Record objects, which will then
-
# get iterated over and yield each record as an argument for the block.
-
# For example:
-
#
-
# <%= div_for(@people, class: "foo") do |person| %>
-
# <%= person.name %>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <div id="person_123" class="person foo"> Joe Bloggs </div>
-
# <div id="person_124" class="person foo"> Jane Bloggs </div>
-
#
-
1
def div_for(record, *args, &block)
-
content_tag_for(:div, record, *args, &block)
-
end
-
-
# content_tag_for creates an HTML element with id and class parameters
-
# that relate to the specified Active Record object. For example:
-
#
-
# <%= content_tag_for(:tr, @person) do %>
-
# <td><%= @person.first_name %></td>
-
# <td><%= @person.last_name %></td>
-
# <% end %>
-
#
-
# would produce the following HTML (assuming @person is an instance of
-
# a Person object, with an id value of 123):
-
#
-
# <tr id="person_123" class="person">....</tr>
-
#
-
# If you require the HTML id attribute to have a prefix, you can specify it:
-
#
-
# <%= content_tag_for(:tr, @person, :foo) do %> ...
-
#
-
# produces:
-
#
-
# <tr id="foo_person_123" class="person">...
-
#
-
# You can also pass an array of objects which this method will loop through
-
# and yield the current object to the supplied block, reducing the need for
-
# having to iterate through the object (using <tt>each</tt>) beforehand.
-
# For example (assuming @people is an array of Person objects):
-
#
-
# <%= content_tag_for(:tr, @people) do |person| %>
-
# <td><%= person.first_name %></td>
-
# <td><%= person.last_name %></td>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <tr id="person_123" class="person">...</tr>
-
# <tr id="person_124" class="person">...</tr>
-
#
-
# content_tag_for also accepts a hash of options, which will be converted to
-
# additional HTML attributes. If you specify a <tt>:class</tt> value, it will be combined
-
# with the default class name for your object. For example:
-
#
-
# <%= content_tag_for(:li, @person, class: "bar") %>...
-
#
-
# produces:
-
#
-
# <li id="person_123" class="person bar">...
-
#
-
1
def content_tag_for(tag_name, single_or_multiple_records, prefix = nil, options = nil, &block)
-
options, prefix = prefix, nil if prefix.is_a?(Hash)
-
-
Array(single_or_multiple_records).map do |single_record|
-
content_tag_for_single_record(tag_name, single_record, prefix, options, &block)
-
end.join("\n").html_safe
-
end
-
-
1
private
-
-
# Called by <tt>content_tag_for</tt> internally to render a content tag
-
# for each record.
-
1
def content_tag_for_single_record(tag_name, record, prefix, options, &block)
-
options = options ? options.dup : {}
-
options[:class] = [ dom_class(record, prefix), options[:class] ].compact
-
options[:id] = dom_id(record, prefix)
-
-
if block_given?
-
content_tag(tag_name, capture(record, &block), options)
-
else
-
content_tag(tag_name, "", options)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
# = Action View Rendering
-
#
-
# Implements methods that allow rendering from a view context.
-
# In order to use this module, all you need is to implement
-
# view_renderer that returns an ActionView::Renderer object.
-
1
module RenderingHelper
-
# Returns the result of a render that's dictated by the options hash. The primary options are:
-
#
-
# * <tt>:partial</tt> - See <tt>ActionView::PartialRenderer</tt>.
-
# * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
-
# * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
-
# * <tt>:text</tt> - Renders the text passed in out.
-
# * <tt>:plain</tt> - Renders the text passed in out. Setting the content
-
# type as <tt>text/plain</tt>.
-
# * <tt>:html</tt> - Renders the HTML safe string passed in out, otherwise
-
# performs HTML escape on the string first. Setting the content type as
-
# <tt>text/html</tt>.
-
# * <tt>:body</tt> - Renders the text passed in, and inherits the content
-
# type of <tt>text/html</tt> from <tt>ActionDispatch::Response</tt>
-
# object.
-
#
-
# If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
-
# as the locals hash.
-
1
def render(options = {}, locals = {}, &block)
-
8
case options
-
when Hash
-
if block_given?
-
view_renderer.render_partial(self, options.merge(:partial => options[:layout]), &block)
-
else
-
view_renderer.render(self, options)
-
end
-
else
-
8
view_renderer.render_partial(self, :partial => options, :locals => locals)
-
end
-
end
-
-
# Overwrites _layout_for in the context object so it supports the case a block is
-
# passed to a partial. Returns the contents that are yielded to a layout, given a
-
# name or a block.
-
#
-
# You can think of a layout as a method that is called with a block. If the user calls
-
# <tt>yield :some_name</tt>, the block, by default, returns <tt>content_for(:some_name)</tt>.
-
# If the user calls simply +yield+, the default block returns <tt>content_for(:layout)</tt>.
-
#
-
# The user can override this default by passing a block to the layout:
-
#
-
# # The template
-
# <%= render layout: "my_layout" do %>
-
# Content
-
# <% end %>
-
#
-
# # The layout
-
# <html>
-
# <%= yield %>
-
# </html>
-
#
-
# In this case, instead of the default block, which would return <tt>content_for(:layout)</tt>,
-
# this method returns the block that was passed in to <tt>render :layout</tt>, and the response
-
# would be
-
#
-
# <html>
-
# Content
-
# </html>
-
#
-
# Finally, the block can take block arguments, which can be passed in by +yield+:
-
#
-
# # The template
-
# <%= render layout: "my_layout" do |customer| %>
-
# Hello <%= customer.name %>
-
# <% end %>
-
#
-
# # The layout
-
# <html>
-
# <%= yield Struct.new(:name).new("David") %>
-
# </html>
-
#
-
# In this case, the layout would receive the block passed into <tt>render :layout</tt>,
-
# and the struct specified would be passed into the block as an argument. The result
-
# would be
-
#
-
# <html>
-
# Hello David
-
# </html>
-
#
-
1
def _layout_for(*args, &block)
-
55
name = args.first
-
-
55
if block && !name.is_a?(Symbol)
-
capture(*args, &block)
-
else
-
55
super
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/deprecation'
-
1
require 'rails-html-sanitizer'
-
-
1
module ActionView
-
# = Action View Sanitize Helpers
-
1
module Helpers
-
# The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements.
-
# These helper methods extend Action View making them callable within your template files.
-
1
module SanitizeHelper
-
1
extend ActiveSupport::Concern
-
# Sanitizes HTML input, stripping all tags and attributes that aren't whitelisted.
-
#
-
# It also strips href/src attributes with unsafe protocols like
-
# <tt>javascript:</tt>, while also protecting against attempts to use Unicode,
-
# ASCII, and hex character references to work around these protocol filters.
-
#
-
# The default sanitizer is Rails::Html::WhiteListSanitizer. See {Rails HTML
-
# Sanitizers}[https://github.com/rails/rails-html-sanitizer] for more information.
-
#
-
# Custom sanitization rules can also be provided.
-
#
-
# Please note that sanitizing user-provided text does not guarantee that the
-
# resulting markup is valid or even well-formed. For example, the output may still
-
# contain unescaped characters like <tt><</tt>, <tt>></tt>, or <tt>&</tt>.
-
#
-
# ==== Options
-
#
-
# * <tt>:tags</tt> - An array of allowed tags.
-
# * <tt>:attributes</tt> - An array of allowed attributes.
-
# * <tt>:scrubber</tt> - A {Rails::Html scrubber}[https://github.com/rails/rails-html-sanitizer]
-
# or {Loofah::Scrubber}[https://github.com/flavorjones/loofah] object that
-
# defines custom sanitization rules. A custom scrubber takes precedence over
-
# custom tags and attributes.
-
#
-
# ==== Examples
-
#
-
# Normal use:
-
#
-
# <%= sanitize @comment.body %>
-
#
-
# Providing custom whitelisted tags and attributes:
-
#
-
# <%= sanitize @comment.body, tags: %w(strong em a), attributes: %w(href) %>
-
#
-
# Providing a custom Rails::Html scrubber:
-
#
-
# class CommentScrubber < Rails::Html::PermitScrubber
-
# def allowed_node?(node)
-
# !%w(form script comment blockquote).include?(node.name)
-
# end
-
#
-
# def skip_node?(node)
-
# node.text?
-
# end
-
#
-
# def scrub_attribute?(name)
-
# name == 'style'
-
# end
-
# end
-
#
-
# <%= sanitize @comment.body, scrubber: CommentScrubber.new %>
-
#
-
# See {Rails HTML Sanitizer}[https://github.com/rails/rails-html-sanitizer] for
-
# documentation about Rails::Html scrubbers.
-
#
-
# Providing a custom Loofah::Scrubber:
-
#
-
# scrubber = Loofah::Scrubber.new do |node|
-
# node.remove if node.name == 'script'
-
# end
-
#
-
# <%= sanitize @comment.body, scrubber: scrubber %>
-
#
-
# See {Loofah's documentation}[https://github.com/flavorjones/loofah] for more
-
# information about defining custom Loofah::Scrubber objects.
-
#
-
# To set the default allowed tags or attributes across your application:
-
#
-
# # In config/application.rb
-
# config.action_view.sanitized_allowed_tags = ['strong', 'em', 'a']
-
# config.action_view.sanitized_allowed_attributes = ['href', 'title']
-
1
def sanitize(html, options = {})
-
self.class.white_list_sanitizer.sanitize(html, options).try(:html_safe)
-
end
-
-
# Sanitizes a block of CSS code. Used by +sanitize+ when it comes across a style attribute.
-
1
def sanitize_css(style)
-
self.class.white_list_sanitizer.sanitize_css(style)
-
end
-
-
# Strips all HTML tags from +html+, including comments.
-
#
-
# strip_tags("Strip <i>these</i> tags!")
-
# # => Strip these tags!
-
#
-
# strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
-
# # => Bold no more! See more here...
-
#
-
# strip_tags("<div id='top-bar'>Welcome to my website!</div>")
-
# # => Welcome to my website!
-
1
def strip_tags(html)
-
self.class.full_sanitizer.sanitize(html, encode_special_chars: false)
-
end
-
-
# Strips all link tags from +html+ leaving just the link text.
-
#
-
# strip_links('<a href="http://www.rubyonrails.org">Ruby on Rails</a>')
-
# # => Ruby on Rails
-
#
-
# strip_links('Please e-mail me at <a href="mailto:me@email.com">me@email.com</a>.')
-
# # => Please e-mail me at me@email.com.
-
#
-
# strip_links('Blog: <a href="http://www.myblog.com/" class="nav" target=\"_blank\">Visit</a>.')
-
# # => Blog: Visit.
-
1
def strip_links(html)
-
self.class.link_sanitizer.sanitize(html)
-
end
-
-
1
module ClassMethods #:nodoc:
-
1
attr_writer :full_sanitizer, :link_sanitizer, :white_list_sanitizer
-
-
# Vendors the full, link and white list sanitizers.
-
# Provided strictly for compabitility and can be removed in Rails 5.
-
1
def sanitizer_vendor
-
Rails::Html::Sanitizer
-
end
-
-
1
def sanitized_allowed_tags
-
sanitizer_vendor.white_list_sanitizer.allowed_tags
-
end
-
-
1
def sanitized_allowed_attributes
-
sanitizer_vendor.white_list_sanitizer.allowed_attributes
-
end
-
-
# Gets the Rails::Html::FullSanitizer instance used by +strip_tags+. Replace with
-
# any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.full_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
1
def full_sanitizer
-
@full_sanitizer ||= sanitizer_vendor.full_sanitizer.new
-
end
-
-
# Gets the Rails::Html::LinkSanitizer instance used by +strip_links+.
-
# Replace with any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.link_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
1
def link_sanitizer
-
@link_sanitizer ||= sanitizer_vendor.link_sanitizer.new
-
end
-
-
# Gets the Rails::Html::WhiteListSanitizer instance used by sanitize and +sanitize_css+.
-
# Replace with any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.white_list_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
1
def white_list_sanitizer
-
@white_list_sanitizer ||= sanitizer_vendor.white_list_sanitizer.new
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'set'
-
-
1
module ActionView
-
# = Action View Tag Helpers
-
1
module Helpers #:nodoc:
-
# Provides methods to generate HTML tags programmatically when you can't use
-
# a Builder. By default, they output XHTML compliant tags.
-
1
module TagHelper
-
1
extend ActiveSupport::Concern
-
1
include CaptureHelper
-
1
include OutputSafetyHelper
-
-
1
BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer
-
autoplay controls loop selected hidden scoped async
-
defer reversed ismap seamless muted required
-
autofocus novalidate formnovalidate open pubdate
-
itemscope allowfullscreen default inert sortable
-
truespeed typemustmatch).to_set
-
-
31
BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym })
-
-
1
TAG_PREFIXES = ['aria', 'data', :aria, :data].to_set
-
-
1
PRE_CONTENT_STRINGS = {
-
:textarea => "\n"
-
}
-
-
# Returns an empty HTML tag of type +name+ which by default is XHTML
-
# compliant. Set +open+ to true to create an open tag compatible
-
# with HTML 4.0 and below. Add HTML attributes by passing an attributes
-
# hash to +options+. Set +escape+ to false to disable attribute value
-
# escaping.
-
#
-
# ==== Options
-
# You can use symbols or strings for the attribute names.
-
#
-
# Use +true+ with boolean attributes that can render with no value, like
-
# +disabled+ and +readonly+.
-
#
-
# HTML5 <tt>data-*</tt> attributes can be set with a single +data+ key
-
# pointing to a hash of sub-attributes.
-
#
-
# To play nicely with JavaScript conventions sub-attributes are dasherized.
-
# For example, a key +user_id+ would render as <tt>data-user-id</tt> and
-
# thus accessed as <tt>dataset.userId</tt>.
-
#
-
# Values are encoded to JSON, with the exception of strings, symbols and
-
# BigDecimals.
-
# This may come in handy when using jQuery's HTML5-aware <tt>.data()</tt>
-
# from 1.4.3.
-
#
-
# ==== Examples
-
# tag("br")
-
# # => <br />
-
#
-
# tag("br", nil, true)
-
# # => <br>
-
#
-
# tag("input", type: 'text', disabled: true)
-
# # => <input type="text" disabled="disabled" />
-
#
-
# tag("input", type: 'text', class: ["strong", "highlight"])
-
# # => <input class="strong highlight" type="text" />
-
#
-
# tag("img", src: "open & shut.png")
-
# # => <img src="open & shut.png" />
-
#
-
# tag("img", {src: "open & shut.png"}, false, false)
-
# # => <img src="open & shut.png" />
-
#
-
# tag("div", data: {name: 'Stephen', city_state: %w(Chicago IL)})
-
# # => <div data-name="Stephen" data-city-state="["Chicago","IL"]" />
-
1
def tag(name, options = nil, open = false, escape = true)
-
95
"<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
-
end
-
-
# Returns an HTML block tag of type +name+ surrounding the +content+. Add
-
# HTML attributes by passing an attributes hash to +options+.
-
# Instead of passing the content as an argument, you can also use a block
-
# in which case, you pass your +options+ as the second parameter.
-
# Set escape to false to disable attribute value escaping.
-
#
-
# ==== Options
-
# The +options+ hash can be used with attributes with no value like (<tt>disabled</tt> and
-
# <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use
-
# symbols or strings for the attribute names.
-
#
-
# ==== Examples
-
# content_tag(:p, "Hello world!")
-
# # => <p>Hello world!</p>
-
# content_tag(:div, content_tag(:p, "Hello world!"), class: "strong")
-
# # => <div class="strong"><p>Hello world!</p></div>
-
# content_tag(:div, "Hello world!", class: ["strong", "highlight"])
-
# # => <div class="strong highlight">Hello world!</div>
-
# content_tag("select", options, multiple: true)
-
# # => <select multiple="multiple">...options...</select>
-
#
-
# <%= content_tag :div, class: "strong" do -%>
-
# Hello world!
-
# <% end -%>
-
# # => <div class="strong">Hello world!</div>
-
1
def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
-
456
if block_given?
-
options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
-
content_tag_string(name, capture(&block), options, escape)
-
else
-
456
content_tag_string(name, content_or_options_with_block, options, escape)
-
end
-
end
-
-
# Returns a CDATA section with the given +content+. CDATA sections
-
# are used to escape blocks of text containing characters which would
-
# otherwise be recognized as markup. CDATA sections begin with the string
-
# <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>.
-
#
-
# cdata_section("<hello world>")
-
# # => <![CDATA[<hello world>]]>
-
#
-
# cdata_section(File.read("hello_world.txt"))
-
# # => <![CDATA[<hello from a text file]]>
-
#
-
# cdata_section("hello]]>world")
-
# # => <![CDATA[hello]]]]><![CDATA[>world]]>
-
1
def cdata_section(content)
-
splitted = content.to_s.gsub(/\]\]\>/, ']]]]><![CDATA[>')
-
"<![CDATA[#{splitted}]]>".html_safe
-
end
-
-
# Returns an escaped version of +html+ without affecting existing escaped entities.
-
#
-
# escape_once("1 < 2 & 3")
-
# # => "1 < 2 & 3"
-
#
-
# escape_once("<< Accept & Checkout")
-
# # => "<< Accept & Checkout"
-
1
def escape_once(html)
-
ERB::Util.html_escape_once(html)
-
end
-
-
1
private
-
-
1
def content_tag_string(name, content, options, escape = true)
-
476
tag_options = tag_options(options, escape) if options
-
476
content = ERB::Util.unwrapped_html_escape(content) if escape
-
476
"<#{name}#{tag_options}>#{PRE_CONTENT_STRINGS[name.to_sym]}#{content}</#{name}>".html_safe
-
end
-
-
1
def tag_options(options, escape = true)
-
571
return if options.blank?
-
571
attrs = []
-
571
options.each_pair do |key, value|
-
1013
if TAG_PREFIXES.include?(key) && value.is_a?(Hash)
-
15
value.each_pair do |k, v|
-
15
attrs << prefix_tag_option(key, k, v, escape)
-
end
-
elsif BOOLEAN_ATTRIBUTES.include?(key)
-
46
attrs << boolean_tag_option(key) if value
-
elsif !value.nil?
-
899
attrs << tag_option(key, value, escape)
-
end
-
end
-
571
" #{attrs * ' '}" unless attrs.empty?
-
end
-
-
1
def prefix_tag_option(prefix, key, value, escape)
-
15
key = "#{prefix}-#{key.to_s.dasherize}"
-
15
unless value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(BigDecimal)
-
value = value.to_json
-
end
-
15
tag_option(key, value, escape)
-
end
-
-
1
def boolean_tag_option(key)
-
6
%(#{key}="#{key}")
-
end
-
-
1
def tag_option(key, value, escape)
-
914
if value.is_a?(Array)
-
value = escape ? safe_join(value, " ") : value.join(" ")
-
else
-
914
value = escape ? ERB::Util.unwrapped_html_escape(value) : value
-
end
-
914
%(#{key}="#{value}")
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags #:nodoc:
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Base
-
1
autoload :Translator
-
1
autoload :CheckBox
-
1
autoload :CollectionCheckBoxes
-
1
autoload :CollectionRadioButtons
-
1
autoload :CollectionSelect
-
1
autoload :ColorField
-
1
autoload :DateField
-
1
autoload :DateSelect
-
1
autoload :DatetimeField
-
1
autoload :DatetimeLocalField
-
1
autoload :DatetimeSelect
-
1
autoload :EmailField
-
1
autoload :FileField
-
1
autoload :GroupedCollectionSelect
-
1
autoload :HiddenField
-
1
autoload :Label
-
1
autoload :MonthField
-
1
autoload :NumberField
-
1
autoload :PasswordField
-
1
autoload :RadioButton
-
1
autoload :RangeField
-
1
autoload :SearchField
-
1
autoload :Select
-
1
autoload :TelField
-
1
autoload :TextArea
-
1
autoload :TextField
-
1
autoload :TimeField
-
1
autoload :TimeSelect
-
1
autoload :TimeZoneSelect
-
1
autoload :UrlField
-
1
autoload :WeekField
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class Base # :nodoc:
-
1
include Helpers::ActiveModelInstanceTag, Helpers::TagHelper, Helpers::FormTagHelper
-
1
include FormOptionsHelper
-
-
1
attr_reader :object
-
-
1
def initialize(object_name, method_name, template_object, options = {})
-
52
@object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup
-
52
@template_object = template_object
-
-
52
@object_name.sub!(/\[\]$/,"") || @object_name.sub!(/\[\]\]$/,"]")
-
52
@object = retrieve_object(options.delete(:object))
-
52
@options = options
-
52
@auto_index = retrieve_autoindex(Regexp.last_match.pre_match) if Regexp.last_match
-
end
-
-
# This is what child classes implement.
-
1
def render
-
raise NotImplementedError, "Subclasses must implement a render method"
-
end
-
-
1
private
-
-
1
def value(object)
-
30
object.public_send @method_name if object
-
end
-
-
1
def value_before_type_cast(object)
-
20
unless object.nil?
-
20
method_before_type_cast = @method_name + "_before_type_cast"
-
-
20
if value_came_from_user?(object) && object.respond_to?(method_before_type_cast)
-
object.public_send(method_before_type_cast)
-
else
-
20
value(object)
-
end
-
end
-
end
-
-
1
def value_came_from_user?(object)
-
20
method_name = "#{@method_name}_came_from_user?"
-
20
!object.respond_to?(method_name) || object.public_send(method_name)
-
end
-
-
1
def retrieve_object(object)
-
52
if object
-
52
object
-
elsif @template_object.instance_variable_defined?("@#{@object_name}")
-
@template_object.instance_variable_get("@#{@object_name}")
-
end
-
rescue NameError
-
# As @object_name may contain the nested syntax (item[subobject]) we need to fallback to nil.
-
nil
-
end
-
-
1
def retrieve_autoindex(pre_match)
-
object = self.object || @template_object.instance_variable_get("@#{pre_match}")
-
if object && object.respond_to?(:to_param)
-
object.to_param
-
else
-
raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
-
end
-
end
-
-
1
def add_default_name_and_id_for_value(tag_value, options)
-
26
if tag_value.nil?
-
26
add_default_name_and_id(options)
-
else
-
specified_id = options["id"]
-
add_default_name_and_id(options)
-
-
if specified_id.blank? && options["id"].present?
-
options["id"] += "_#{sanitized_value(tag_value)}"
-
end
-
end
-
end
-
-
1
def add_default_name_and_id(options)
-
50
if options.has_key?("index")
-
options["name"] ||= options.fetch("name"){ tag_name_with_index(options["index"], options["multiple"]) }
-
options["id"] = options.fetch("id"){ tag_id_with_index(options["index"]) }
-
options.delete("index")
-
elsif defined?(@auto_index)
-
options["name"] ||= options.fetch("name"){ tag_name_with_index(@auto_index, options["multiple"]) }
-
options["id"] = options.fetch("id"){ tag_id_with_index(@auto_index) }
-
else
-
100
options["name"] ||= options.fetch("name"){ tag_name(options["multiple"]) }
-
100
options["id"] = options.fetch("id"){ tag_id }
-
end
-
-
50
options["id"] = [options.delete('namespace'), options["id"]].compact.join("_").presence
-
end
-
-
1
def tag_name(multiple = false)
-
50
"#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}"
-
end
-
-
1
def tag_name_with_index(index, multiple = false)
-
"#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}"
-
end
-
-
1
def tag_id
-
50
"#{sanitized_object_name}_#{sanitized_method_name}"
-
end
-
-
1
def tag_id_with_index(index)
-
"#{sanitized_object_name}_#{index}_#{sanitized_method_name}"
-
end
-
-
1
def sanitized_object_name
-
50
@sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
-
end
-
-
1
def sanitized_method_name
-
100
@sanitized_method_name ||= @method_name.sub(/\?$/,"")
-
end
-
-
1
def sanitized_value(value)
-
value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase
-
end
-
-
1
def select_content_tag(option_tags, options, html_options)
-
4
html_options = html_options.stringify_keys
-
4
add_default_name_and_id(html_options)
-
4
options[:include_blank] ||= true unless options[:prompt] || select_not_required?(html_options)
-
8
value = options.fetch(:selected) { value(object) }
-
4
select = content_tag("select", add_options(option_tags, options, value), html_options)
-
-
4
if html_options["multiple"] && options.fetch(:include_hidden, true)
-
tag("input", :disabled => html_options["disabled"], :name => html_options["name"], :type => "hidden", :value => "") + select
-
else
-
4
select
-
end
-
end
-
-
1
def select_not_required?(html_options)
-
4
!html_options["required"] || html_options["multiple"] || html_options["size"].to_i > 1
-
end
-
-
1
def add_options(option_tags, options, value = nil)
-
4
if options[:include_blank]
-
option_tags = content_tag_string('option', options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, :value => '') + "\n" + option_tags
-
end
-
4
if value.blank? && options[:prompt]
-
option_tags = content_tag_string('option', prompt_text(options[:prompt]), :value => '') + "\n" + option_tags
-
end
-
4
option_tags
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/time/calculations'
-
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class DateSelect < Base # :nodoc:
-
1
def initialize(object_name, method_name, template_object, options, html_options)
-
2
@html_options = html_options
-
-
2
super(object_name, method_name, template_object, options)
-
end
-
-
1
def render
-
2
error_wrapping(datetime_selector(@options, @html_options).send("select_#{select_type}").html_safe)
-
end
-
-
1
class << self
-
1
def select_type
-
2
@select_type ||= self.name.split("::").last.sub("Select", "").downcase
-
end
-
end
-
-
1
private
-
-
1
def select_type
-
2
self.class.select_type
-
end
-
-
1
def datetime_selector(options, html_options)
-
4
datetime = options.fetch(:selected) { value(object) || default_datetime(options) }
-
2
@auto_index ||= nil
-
-
2
options = options.dup
-
2
options[:field_name] = @method_name
-
2
options[:include_position] = true
-
2
options[:prefix] ||= @object_name
-
2
options[:index] = @auto_index if @auto_index && !options.has_key?(:index)
-
-
2
DateTimeSelector.new(datetime, options, html_options)
-
end
-
-
1
def default_datetime(options)
-
1
return if options[:include_blank] || options[:prompt]
-
-
1
case options[:default]
-
when nil
-
1
Time.current
-
when Date, Time
-
options[:default]
-
else
-
default = options[:default].dup
-
-
# Rename :minute and :second to :min and :sec
-
default[:min] ||= default[:minute]
-
default[:sec] ||= default[:second]
-
-
time = Time.current
-
-
[:year, :month, :day, :hour, :min, :sec].each do |key|
-
default[key] ||= time.send(key)
-
end
-
-
Time.utc(
-
default[:year], default[:month], default[:day],
-
default[:hour], default[:min], default[:sec]
-
)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class Label < Base # :nodoc:
-
1
class LabelBuilder # :nodoc:
-
1
attr_reader :object
-
-
1
def initialize(template_object, object_name, method_name, object, tag_value)
-
26
@template_object = template_object
-
26
@object_name = object_name
-
26
@method_name = method_name
-
26
@object = object
-
26
@tag_value = tag_value
-
end
-
-
1
def translation
-
2
method_and_value = @tag_value.present? ? "#{@method_name}.#{@tag_value}" : @method_name
-
-
content ||= Translator
-
.new(object, @object_name, method_and_value, "helpers.label")
-
2
.translate
-
2
content ||= @method_name.humanize
-
-
2
content
-
end
-
end
-
-
1
def initialize(object_name, method_name, template_object, content_or_options = nil, options = nil)
-
26
options ||= {}
-
-
26
content_is_options = content_or_options.is_a?(Hash)
-
26
if content_is_options
-
options.merge! content_or_options
-
@content = nil
-
else
-
26
@content = content_or_options
-
end
-
-
26
super(object_name, method_name, template_object, options)
-
end
-
-
1
def render(&block)
-
26
options = @options.stringify_keys
-
26
tag_value = options.delete("value")
-
26
name_and_id = options.dup
-
-
26
if name_and_id["for"]
-
name_and_id["id"] = name_and_id["for"]
-
else
-
26
name_and_id.delete("id")
-
end
-
-
26
add_default_name_and_id_for_value(tag_value, name_and_id)
-
26
options.delete("index")
-
26
options.delete("namespace")
-
26
options["for"] = name_and_id["id"] unless options.key?("for")
-
-
26
builder = LabelBuilder.new(@template_object, @object_name, @method_name, @object, tag_value)
-
-
26
content = if block_given?
-
@template_object.capture(builder, &block)
-
elsif @content.present?
-
24
@content.to_s
-
else
-
2
render_component(builder)
-
end
-
-
26
label_tag(name_and_id["id"], content, options)
-
end
-
-
1
private
-
-
1
def render_component(builder)
-
2
builder.translation
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class NumberField < TextField # :nodoc:
-
1
def render
-
2
options = @options.stringify_keys
-
-
2
if range = options.delete("in") || options.delete("within")
-
options.update("min" => range.min, "max" => range.max)
-
end
-
-
2
@options = options
-
2
super
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
module Placeholderable # :nodoc:
-
1
def initialize(*)
-
20
super
-
-
20
if tag_value = @options[:placeholder]
-
placeholder = tag_value if tag_value.is_a?(String)
-
method_and_value = tag_value.is_a?(TrueClass) ? @method_name : "#{@method_name}.#{tag_value}"
-
-
placeholder ||= Tags::Translator
-
.new(object, @object_name, method_and_value, "helpers.placeholder")
-
.translate
-
placeholder ||= @method_name.humanize
-
@options[:placeholder] = placeholder
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class Select < Base # :nodoc:
-
1
def initialize(object_name, method_name, template_object, choices, options, html_options)
-
4
@choices = block_given? ? template_object.capture { yield || "" } : choices
-
4
@choices = @choices.to_a if @choices.is_a?(Range)
-
-
4
@html_options = html_options
-
-
4
super(object_name, method_name, template_object, options)
-
end
-
-
1
def render
-
4
option_tags_options = {
-
4
:selected => @options.fetch(:selected) { value(@object) },
-
:disabled => @options[:disabled]
-
}
-
-
4
option_tags = if grouped_choices?
-
grouped_options_for_select(@choices, option_tags_options)
-
else
-
4
options_for_select(@choices, option_tags_options)
-
end
-
-
4
select_content_tag(option_tags, @options, @html_options)
-
end
-
-
1
private
-
-
# Grouped choices look like this:
-
#
-
# [nil, []]
-
# { nil => [] }
-
1
def grouped_choices?
-
4
!@choices.empty? && @choices.first.respond_to?(:last) && Array === @choices.first.last
-
end
-
end
-
end
-
end
-
end
-
1
require 'action_view/helpers/tags/placeholderable'
-
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class TextArea < Base # :nodoc:
-
1
include Placeholderable
-
-
1
def render
-
options = @options.stringify_keys
-
add_default_name_and_id(options)
-
-
if size = options.delete("size")
-
options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
-
end
-
-
content_tag("textarea", options.delete("value") { value_before_type_cast(object) }, options)
-
end
-
end
-
end
-
end
-
end
-
1
require 'action_view/helpers/tags/placeholderable'
-
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class TextField < Base # :nodoc:
-
1
include Placeholderable
-
-
1
def render
-
20
options = @options.stringify_keys
-
20
options["size"] = options["maxlength"] unless options.key?("size")
-
20
options["type"] ||= field_type
-
40
options["value"] = options.fetch("value") { value_before_type_cast(object) } unless field_type == "file"
-
20
yield options if block_given?
-
20
add_default_name_and_id(options)
-
20
tag("input", options)
-
end
-
-
1
class << self
-
1
def field_type
-
40
@field_type ||= self.name.split("::").last.sub("Field", "").downcase
-
end
-
end
-
-
1
private
-
-
1
def field_type
-
40
self.class.field_type
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class Translator # :nodoc:
-
1
def initialize(object, object_name, method_and_value, scope)
-
2
@object_name = object_name.gsub(/\[(.*)_attributes\]\[\d+\]/, '.\1')
-
2
@method_and_value = method_and_value
-
2
@scope = scope
-
2
@model = object.respond_to?(:to_model) ? object.to_model : nil
-
end
-
-
1
def translate
-
2
translated_attribute = I18n.t("#{object_name}.#{method_and_value}", default: i18n_default, scope: scope).presence
-
2
translated_attribute || human_attribute_name
-
end
-
-
1
protected
-
-
1
attr_reader :object_name, :method_and_value, :scope, :model
-
-
1
private
-
-
1
def i18n_default
-
2
if model
-
2
key = model.model_name.i18n_key
-
2
["#{key}.#{method_and_value}".to_sym, ""]
-
else
-
""
-
end
-
end
-
-
1
def human_attribute_name
-
2
if model && model.class.respond_to?(:human_attribute_name)
-
2
model.class.human_attribute_name(method_and_value)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActionView
-
# = Action View Text Helpers
-
1
module Helpers #:nodoc:
-
# The TextHelper module provides a set of methods for filtering, formatting
-
# and transforming strings, which can reduce the amount of inline Ruby code in
-
# your views. These helper methods extend Action View making them callable
-
# within your template files.
-
#
-
# ==== Sanitization
-
#
-
# Most text helpers by default sanitize the given content, but do not escape it.
-
# This means HTML tags will appear in the page but all malicious code will be removed.
-
# Let's look at some examples using the +simple_format+ method:
-
#
-
# simple_format('<a href="http://example.com/">Example</a>')
-
# # => "<p><a href=\"http://example.com/\">Example</a></p>"
-
#
-
# simple_format('<a href="javascript:alert(\'no!\')">Example</a>')
-
# # => "<p><a>Example</a></p>"
-
#
-
# If you want to escape all content, you should invoke the +h+ method before
-
# calling the text helper.
-
#
-
# simple_format h('<a href="http://example.com/">Example</a>')
-
# # => "<p><a href=\"http://example.com/\">Example</a></p>"
-
1
module TextHelper
-
1
extend ActiveSupport::Concern
-
-
1
include SanitizeHelper
-
1
include TagHelper
-
1
include OutputSafetyHelper
-
-
# The preferred method of outputting text in your views is to use the
-
# <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods
-
# do not operate as expected in an eRuby code block. If you absolutely must
-
# output text within a non-output code block (i.e., <% %>), you can use the concat method.
-
#
-
# <%
-
# concat "hello"
-
# # is the equivalent of <%= "hello" %>
-
#
-
# if logged_in
-
# concat "Logged in!"
-
# else
-
# concat link_to('login', action: :login)
-
# end
-
# # will either display "Logged in!" or a login link
-
# %>
-
1
def concat(string)
-
output_buffer << string
-
end
-
-
1
def safe_concat(string)
-
output_buffer.respond_to?(:safe_concat) ? output_buffer.safe_concat(string) : concat(string)
-
end
-
-
# Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt>
-
# (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "...")
-
# for a total length not exceeding <tt>:length</tt>.
-
#
-
# Pass a <tt>:separator</tt> to truncate +text+ at a natural break.
-
#
-
# Pass a block if you want to show extra content when the text is truncated.
-
#
-
# The result is marked as HTML-safe, but it is escaped by default, unless <tt>:escape</tt> is
-
# +false+. Care should be taken if +text+ contains HTML tags or entities, because truncation
-
# may produce invalid HTML (such as unbalanced or incomplete tags).
-
#
-
# truncate("Once upon a time in a world far far away")
-
# # => "Once upon a time in a world..."
-
#
-
# truncate("Once upon a time in a world far far away", length: 17)
-
# # => "Once upon a ti..."
-
#
-
# truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
-
# # => "Once upon a..."
-
#
-
# truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)')
-
# # => "And they f... (continued)"
-
#
-
# truncate("<p>Once upon a time in a world far far away</p>")
-
# # => "<p>Once upon a time in a wo..."
-
#
-
# truncate("<p>Once upon a time in a world far far away</p>", escape: false)
-
# # => "<p>Once upon a time in a wo..."
-
#
-
# truncate("Once upon a time in a world far far away") { link_to "Continue", "#" }
-
# # => "Once upon a time in a wo...<a href="#">Continue</a>"
-
1
def truncate(text, options = {}, &block)
-
if text
-
length = options.fetch(:length, 30)
-
-
content = text.truncate(length, options)
-
content = options[:escape] == false ? content.html_safe : ERB::Util.html_escape(content)
-
content << capture(&block) if block_given? && text.length > length
-
content
-
end
-
end
-
-
# Highlights one or more +phrases+ everywhere in +text+ by inserting it into
-
# a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt>
-
# as a single-quoted string with <tt>\1</tt> where the phrase is to be inserted (defaults to
-
# '<mark>\1</mark>') or passing a block that receives each matched term.
-
#
-
# highlight('You searched for: rails', 'rails')
-
# # => You searched for: <mark>rails</mark>
-
#
-
# highlight('You searched for: rails', /for|rails/)
-
# # => You searched <mark>for</mark>: <mark>rails</mark>
-
#
-
# highlight('You searched for: ruby, rails, dhh', 'actionpack')
-
# # => You searched for: ruby, rails, dhh
-
#
-
# highlight('You searched for: rails', ['for', 'rails'], highlighter: '<em>\1</em>')
-
# # => You searched <em>for</em>: <em>rails</em>
-
#
-
# highlight('You searched for: rails', 'rails', highlighter: '<a href="search?q=\1">\1</a>')
-
# # => You searched for: <a href="search?q=rails">rails</a>
-
#
-
# highlight('You searched for: rails', 'rails') { |match| link_to(search_path(q: match, match)) }
-
# # => You searched for: <a href="search?q=rails">rails</a>
-
1
def highlight(text, phrases, options = {})
-
text = sanitize(text) if options.fetch(:sanitize, true)
-
-
if text.blank? || phrases.blank?
-
text || ""
-
else
-
match = Array(phrases).map do |p|
-
Regexp === p ? p.to_s : Regexp.escape(p)
-
end.join('|')
-
-
if block_given?
-
text.gsub(/(#{match})(?![^<]*?>)/i) { |found| yield found }
-
else
-
highlighter = options.fetch(:highlighter, '<mark>\1</mark>')
-
text.gsub(/(#{match})(?![^<]*?>)/i, highlighter)
-
end
-
end.html_safe
-
end
-
-
# Extracts an excerpt from +text+ that matches the first instance of +phrase+.
-
# The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters
-
# defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+,
-
# then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. Use the
-
# <tt>:separator</tt> option to choose the delimitation. The resulting string will be stripped in any case. If the +phrase+
-
# isn't found, nil is returned.
-
#
-
# excerpt('This is an example', 'an', radius: 5)
-
# # => ...s is an exam...
-
#
-
# excerpt('This is an example', 'is', radius: 5)
-
# # => This is a...
-
#
-
# excerpt('This is an example', 'is')
-
# # => This is an example
-
#
-
# excerpt('This next thing is an example', 'ex', radius: 2)
-
# # => ...next...
-
#
-
# excerpt('This is also an example', 'an', radius: 8, omission: '<chop> ')
-
# # => <chop> is also an example
-
#
-
# excerpt('This is a very beautiful morning', 'very', separator: ' ', radius: 1)
-
# # => ...a very beautiful...
-
1
def excerpt(text, phrase, options = {})
-
return unless text && phrase
-
-
separator = options.fetch(:separator, nil) || ""
-
case phrase
-
when Regexp
-
regex = phrase
-
else
-
regex = /#{Regexp.escape(phrase)}/i
-
end
-
-
return unless matches = text.match(regex)
-
phrase = matches[0]
-
-
unless separator.empty?
-
text.split(separator).each do |value|
-
if value.match(regex)
-
regex = phrase = value
-
break
-
end
-
end
-
end
-
-
first_part, second_part = text.split(phrase, 2)
-
-
prefix, first_part = cut_excerpt_part(:first, first_part, separator, options)
-
postfix, second_part = cut_excerpt_part(:second, second_part, separator, options)
-
-
affix = [first_part, separator, phrase, separator, second_part].join.strip
-
[prefix, affix, postfix].join
-
end
-
-
# Attempts to pluralize the +singular+ word unless +count+ is 1. If
-
# +plural+ is supplied, it will use that when count is > 1, otherwise
-
# it will use the Inflector to determine the plural form.
-
#
-
# pluralize(1, 'person')
-
# # => 1 person
-
#
-
# pluralize(2, 'person')
-
# # => 2 people
-
#
-
# pluralize(3, 'person', 'users')
-
# # => 3 users
-
#
-
# pluralize(0, 'person')
-
# # => 0 people
-
1
def pluralize(count, singular, plural = nil)
-
word = if (count == 1 || count =~ /^1(\.0+)?$/)
-
singular
-
else
-
plural || singular.pluralize
-
end
-
-
"#{count || 0} #{word}"
-
end
-
-
# Wraps the +text+ into lines no longer than +line_width+ width. This method
-
# breaks on the first whitespace character that does not exceed +line_width+
-
# (which is 80 by default).
-
#
-
# word_wrap('Once upon a time')
-
# # => Once upon a time
-
#
-
# word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...')
-
# # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined...
-
#
-
# word_wrap('Once upon a time', line_width: 8)
-
# # => Once\nupon a\ntime
-
#
-
# word_wrap('Once upon a time', line_width: 1)
-
# # => Once\nupon\na\ntime
-
1
def word_wrap(text, options = {})
-
line_width = options.fetch(:line_width, 80)
-
-
text.split("\n").collect! do |line|
-
line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip : line
-
end * "\n"
-
end
-
-
# Returns +text+ transformed into HTML using simple formatting rules.
-
# Two or more consecutive newlines(<tt>\n\n</tt>) are considered as a
-
# paragraph and wrapped in <tt><p></tt> tags. One newline (<tt>\n</tt>) is
-
# considered as a linebreak and a <tt><br /></tt> tag is appended. This
-
# method does not remove the newlines from the +text+.
-
#
-
# You can pass any HTML attributes into <tt>html_options</tt>. These
-
# will be added to all created paragraphs.
-
#
-
# ==== Options
-
# * <tt>:sanitize</tt> - If +false+, does not sanitize +text+.
-
# * <tt>:wrapper_tag</tt> - String representing the wrapper tag, defaults to <tt>"p"</tt>
-
#
-
# ==== Examples
-
# my_text = "Here is some basic text...\n...with a line break."
-
#
-
# simple_format(my_text)
-
# # => "<p>Here is some basic text...\n<br />...with a line break.</p>"
-
#
-
# simple_format(my_text, {}, wrapper_tag: "div")
-
# # => "<div>Here is some basic text...\n<br />...with a line break.</div>"
-
#
-
# more_text = "We want to put a paragraph...\n\n...right there."
-
#
-
# simple_format(more_text)
-
# # => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"
-
#
-
# simple_format("Look ma! A class!", class: 'description')
-
# # => "<p class='description'>Look ma! A class!</p>"
-
#
-
# simple_format("<blink>Unblinkable.</blink>")
-
# # => "<p>Unblinkable.</p>"
-
#
-
# simple_format("<blink>Blinkable!</blink> It's true.", {}, sanitize: false)
-
# # => "<p><blink>Blinkable!</blink> It's true.</p>"
-
1
def simple_format(text, html_options = {}, options = {})
-
wrapper_tag = options.fetch(:wrapper_tag, :p)
-
-
text = sanitize(text) if options.fetch(:sanitize, true)
-
paragraphs = split_paragraphs(text)
-
-
if paragraphs.empty?
-
content_tag(wrapper_tag, nil, html_options)
-
else
-
paragraphs.map! { |paragraph|
-
content_tag(wrapper_tag, raw(paragraph), html_options)
-
}.join("\n\n").html_safe
-
end
-
end
-
-
# Creates a Cycle object whose _to_s_ method cycles through elements of an
-
# array every time it is called. This can be used for example, to alternate
-
# classes for table rows. You can use named cycles to allow nesting in loops.
-
# Passing a Hash as the last parameter with a <tt>:name</tt> key will create a
-
# named cycle. The default name for a cycle without a +:name+ key is
-
# <tt>"default"</tt>. You can manually reset a cycle by calling reset_cycle
-
# and passing the name of the cycle. The current cycle string can be obtained
-
# anytime using the current_cycle method.
-
#
-
# # Alternate CSS classes for even and odd numbers...
-
# @items = [1,2,3,4]
-
# <table>
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("odd", "even") -%>">
-
# <td>item</td>
-
# </tr>
-
# <% end %>
-
# </table>
-
#
-
#
-
# # Cycle CSS classes for rows, and text colors for values within each row
-
# @items = x = [{first: 'Robert', middle: 'Daniel', last: 'James'},
-
# {first: 'Emily', middle: 'Shannon', maiden: 'Pike', last: 'Hicks'},
-
# {first: 'June', middle: 'Dae', last: 'Jones'}]
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("odd", "even", name: "row_class") -%>">
-
# <td>
-
# <% item.values.each do |value| %>
-
# <%# Create a named cycle "colors" %>
-
# <span style="color:<%= cycle("red", "green", "blue", name: "colors") -%>">
-
# <%= value %>
-
# </span>
-
# <% end %>
-
# <% reset_cycle("colors") %>
-
# </td>
-
# </tr>
-
# <% end %>
-
1
def cycle(first_value, *values)
-
options = values.extract_options!
-
name = options.fetch(:name, 'default')
-
-
values.unshift(*first_value)
-
-
cycle = get_cycle(name)
-
unless cycle && cycle.values == values
-
cycle = set_cycle(name, Cycle.new(*values))
-
end
-
cycle.to_s
-
end
-
-
# Returns the current cycle string after a cycle has been started. Useful
-
# for complex table highlighting or any other design need which requires
-
# the current cycle string in more than one place.
-
#
-
# # Alternate background colors
-
# @items = [1,2,3,4]
-
# <% @items.each do |item| %>
-
# <div style="background-color:<%= cycle("red","white","blue") %>">
-
# <span style="background-color:<%= current_cycle %>"><%= item %></span>
-
# </div>
-
# <% end %>
-
1
def current_cycle(name = "default")
-
cycle = get_cycle(name)
-
cycle.current_value if cycle
-
end
-
-
# Resets a cycle so that it starts from the first element the next time
-
# it is called. Pass in +name+ to reset a named cycle.
-
#
-
# # Alternate CSS classes for even and odd numbers...
-
# @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]]
-
# <table>
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("even", "odd") -%>">
-
# <% item.each do |value| %>
-
# <span style="color:<%= cycle("#333", "#666", "#999", name: "colors") -%>">
-
# <%= value %>
-
# </span>
-
# <% end %>
-
#
-
# <% reset_cycle("colors") %>
-
# </tr>
-
# <% end %>
-
# </table>
-
1
def reset_cycle(name = "default")
-
cycle = get_cycle(name)
-
cycle.reset if cycle
-
end
-
-
1
class Cycle #:nodoc:
-
1
attr_reader :values
-
-
1
def initialize(first_value, *values)
-
@values = values.unshift(first_value)
-
reset
-
end
-
-
1
def reset
-
@index = 0
-
end
-
-
1
def current_value
-
@values[previous_index].to_s
-
end
-
-
1
def to_s
-
value = @values[@index].to_s
-
@index = next_index
-
return value
-
end
-
-
1
private
-
-
1
def next_index
-
step_index(1)
-
end
-
-
1
def previous_index
-
step_index(-1)
-
end
-
-
1
def step_index(n)
-
(@index + n) % @values.size
-
end
-
end
-
-
1
private
-
# The cycle helpers need to store the cycles in a place that is
-
# guaranteed to be reset every time a page is rendered, so it
-
# uses an instance variable of ActionView::Base.
-
1
def get_cycle(name)
-
@_cycles = Hash.new unless defined?(@_cycles)
-
return @_cycles[name]
-
end
-
-
1
def set_cycle(name, cycle_object)
-
@_cycles = Hash.new unless defined?(@_cycles)
-
@_cycles[name] = cycle_object
-
end
-
-
1
def split_paragraphs(text)
-
return [] if text.blank?
-
-
text.to_str.gsub(/\r\n?/, "\n").split(/\n\n+/).map! do |t|
-
t.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') || t
-
end
-
end
-
-
1
def cut_excerpt_part(part_position, part, separator, options)
-
return "", "" unless part
-
-
radius = options.fetch(:radius, 100)
-
omission = options.fetch(:omission, "...")
-
-
part = part.split(separator)
-
part.delete("")
-
affix = part.size > radius ? omission : ""
-
-
part = if part_position == :first
-
drop_index = [part.length - radius, 0].max
-
part.drop(drop_index)
-
else
-
part.first(radius)
-
end
-
-
return affix, part.join(separator)
-
end
-
end
-
end
-
end
-
1
require 'action_view/helpers/tag_helper'
-
1
require 'active_support/core_ext/string/access'
-
1
require 'i18n/exceptions'
-
-
1
module ActionView
-
# = Action View Translation Helpers
-
1
module Helpers
-
1
module TranslationHelper
-
1
include TagHelper
-
# Delegates to <tt>I18n#translate</tt> but also performs three additional functions.
-
#
-
# First, it will ensure that any thrown +MissingTranslation+ messages will be turned
-
# into inline spans that:
-
#
-
# * have a "translation-missing" class set,
-
# * contain the missing key as a title attribute and
-
# * a titleized version of the last key segment as a text.
-
#
-
# E.g. the value returned for a missing translation key :"blog.post.title" will be
-
# <span class="translation_missing" title="translation missing: en.blog.post.title">Title</span>.
-
# This way your views will display rather reasonable strings but it will still
-
# be easy to spot missing translations.
-
#
-
# Second, it'll scope the key by the current partial if the key starts
-
# with a period. So if you call <tt>translate(".foo")</tt> from the
-
# <tt>people/index.html.erb</tt> template, you'll actually be calling
-
# <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
-
# to translate many keys within the same partials and gives you a simple framework
-
# for scoping them consistently. If you don't prepend the key with a period,
-
# nothing is converted.
-
#
-
# Third, it'll mark the translation as safe HTML if the key has the suffix
-
# "_html" or the last element of the key is the word "html". For example,
-
# calling translate("footer_html") or translate("footer.html") will return
-
# a safe HTML string that won't be escaped by other HTML helper methods. This
-
# naming convention helps to identify translations that include HTML tags so that
-
# you know what kind of output to expect when you call translate in a template.
-
1
def translate(key, options = {})
-
options = options.dup
-
has_default = options.has_key?(:default)
-
remaining_defaults = Array(options.delete(:default)).compact
-
-
if has_default && !remaining_defaults.first.kind_of?(Symbol)
-
options[:default] = remaining_defaults
-
end
-
-
# If the user has explicitly decided to NOT raise errors, pass that option to I18n.
-
# Otherwise, tell I18n to raise an exception, which we rescue further in this method.
-
# Note: `raise_error` refers to us re-raising the error in this method. I18n is forced to raise by default.
-
if options[:raise] == false || (options.key?(:rescue_format) && options[:rescue_format].nil?)
-
raise_error = false
-
i18n_raise = false
-
else
-
raise_error = options[:raise] || options[:rescue_format] || ActionView::Base.raise_on_missing_translations
-
i18n_raise = true
-
end
-
-
if html_safe_translation_key?(key)
-
html_safe_options = options.dup
-
options.except(*I18n::RESERVED_KEYS).each do |name, value|
-
unless name == :count && value.is_a?(Numeric)
-
html_safe_options[name] = ERB::Util.html_escape(value.to_s)
-
end
-
end
-
translation = I18n.translate(scope_key_by_partial(key), html_safe_options.merge(raise: i18n_raise))
-
-
translation.respond_to?(:html_safe) ? translation.html_safe : translation
-
else
-
I18n.translate(scope_key_by_partial(key), options.merge(raise: i18n_raise))
-
end
-
rescue I18n::MissingTranslationData => e
-
if remaining_defaults.present?
-
translate remaining_defaults.shift, options.merge(default: remaining_defaults)
-
else
-
raise e if raise_error
-
-
keys = I18n.normalize_keys(e.locale, e.key, e.options[:scope])
-
content_tag('span', keys.last.to_s.titleize, :class => 'translation_missing', :title => "translation missing: #{keys.join('.')}")
-
end
-
end
-
1
alias :t :translate
-
-
# Delegates to <tt>I18n.localize</tt> with no additional functionality.
-
#
-
# See http://rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base:localize
-
# for more information.
-
1
def localize(*args)
-
I18n.localize(*args)
-
end
-
1
alias :l :localize
-
-
1
private
-
1
def scope_key_by_partial(key)
-
if key.to_s.first == "."
-
if @virtual_path
-
@virtual_path.gsub(%r{/_?}, ".") + key.to_s
-
else
-
raise "Cannot use t(#{key.inspect}) shortcut because path is not available"
-
end
-
else
-
key
-
end
-
end
-
-
1
def html_safe_translation_key?(key)
-
key.to_s =~ /(\b|_|\.)html$/
-
end
-
end
-
end
-
end
-
1
require 'action_view/helpers/javascript_helper'
-
1
require 'active_support/core_ext/array/access'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView
-
# = Action View URL Helpers
-
1
module Helpers #:nodoc:
-
# Provides a set of methods for making links and getting URLs that
-
# depend on the routing subsystem (see ActionDispatch::Routing).
-
# This allows you to use the same format for links in views
-
# and controllers.
-
1
module UrlHelper
-
# This helper may be included in any class that includes the
-
# URL helpers of a routes (routes.url_helpers). Some methods
-
# provided here will only work in the context of a request
-
# (link_to_unless_current, for instance), which must be provided
-
# as a method called #request on the context.
-
1
BUTTON_TAG_METHOD_VERBS = %w{patch put delete}
-
1
extend ActiveSupport::Concern
-
-
1
include TagHelper
-
-
1
module ClassMethods
-
1
def _url_for_modules
-
5
ActionView::RoutingUrlFor
-
end
-
end
-
-
# Basic implementation of url_for to allow use helpers without routes existence
-
1
def url_for(options = nil) # :nodoc:
-
case options
-
when String
-
options
-
when :back
-
_back_url
-
else
-
raise ArgumentError, "arguments passed to url_for can't be handled. Please require " +
-
"routes or provide your own implementation"
-
end
-
end
-
-
1
def _back_url # :nodoc:
-
referrer = controller.respond_to?(:request) && controller.request.env["HTTP_REFERER"]
-
referrer || 'javascript:history.back()'
-
end
-
1
protected :_back_url
-
-
# Creates a link tag of the given +name+ using a URL created by the set of +options+.
-
# See the valid options in the documentation for +url_for+. It's also possible to
-
# pass a String instead of an options hash, which generates a link tag that uses the
-
# value of the String as the href for the link. Using a <tt>:back</tt> Symbol instead
-
# of an options hash will generate a link to the referrer (a JavaScript back link
-
# will be used in place of a referrer if none exists). If +nil+ is passed as the name
-
# the value of the link itself will become the name.
-
#
-
# ==== Signatures
-
#
-
# link_to(body, url, html_options = {})
-
# # url is a String; you can use URL helpers like
-
# # posts_path
-
#
-
# link_to(body, url_options = {}, html_options = {})
-
# # url_options, except :method, is passed to url_for
-
#
-
# link_to(options = {}, html_options = {}) do
-
# # name
-
# end
-
#
-
# link_to(url, html_options = {}) do
-
# # name
-
# end
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>method: symbol of HTTP verb</tt> - This modifier will dynamically
-
# create an HTML form and immediately submit the form for processing using
-
# the HTTP verb specified. Useful for having links perform a POST operation
-
# in dangerous actions like deleting a record (which search bots can follow
-
# while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>.
-
# Note that if the user has JavaScript disabled, the request will fall back
-
# to using GET. If <tt>href: '#'</tt> is used and the user has JavaScript
-
# disabled clicking the link will have no effect. If you are relying on the
-
# POST behavior, you should check for it in your controller's action by using
-
# the request object's methods for <tt>post?</tt>, <tt>delete?</tt>, <tt>patch?</tt>, or <tt>put?</tt>.
-
# * <tt>remote: true</tt> - This will allow the unobtrusive JavaScript
-
# driver to make an Ajax request to the URL in question instead of following
-
# the link. The drivers each provide mechanisms for listening for the
-
# completion of the Ajax request and performing JavaScript operations once
-
# they're complete
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - This will allow the unobtrusive JavaScript
-
# driver to prompt with the question specified (in this case, the
-
# resulting text would be <tt>question?</tt>. If the user accepts, the
-
# link is processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be
-
# used as the value for a disabled version of the submit
-
# button when the form is submitted. This feature is provided
-
# by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
-
# and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base
-
# your application on resources and use
-
#
-
# link_to "Profile", profile_path(@profile)
-
# # => <a href="/profiles/1">Profile</a>
-
#
-
# or the even pithier
-
#
-
# link_to "Profile", @profile
-
# # => <a href="/profiles/1">Profile</a>
-
#
-
# in place of the older more verbose, non-resource-oriented
-
#
-
# link_to "Profile", controller: "profiles", action: "show", id: @profile
-
# # => <a href="/profiles/show/1">Profile</a>
-
#
-
# Similarly,
-
#
-
# link_to "Profiles", profiles_path
-
# # => <a href="/profiles">Profiles</a>
-
#
-
# is better than
-
#
-
# link_to "Profiles", controller: "profiles"
-
# # => <a href="/profiles">Profiles</a>
-
#
-
# You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
-
#
-
# <%= link_to(@profile) do %>
-
# <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
-
# <% end %>
-
# # => <a href="/profiles/1">
-
# <strong>David</strong> -- <span>Check it out!</span>
-
# </a>
-
#
-
# Classes and ids for CSS are easy to produce:
-
#
-
# link_to "Articles", articles_path, id: "news", class: "article"
-
# # => <a href="/articles" class="article" id="news">Articles</a>
-
#
-
# Be careful when using the older argument style, as an extra literal hash is needed:
-
#
-
# link_to "Articles", { controller: "articles" }, id: "news", class: "article"
-
# # => <a href="/articles" class="article" id="news">Articles</a>
-
#
-
# Leaving the hash off gives the wrong link:
-
#
-
# link_to "WRONG!", controller: "articles", id: "news", class: "article"
-
# # => <a href="/articles/index/news?class=article">WRONG!</a>
-
#
-
# +link_to+ can also produce links with anchors or query strings:
-
#
-
# link_to "Comment wall", profile_path(@profile, anchor: "wall")
-
# # => <a href="/profiles/1#wall">Comment wall</a>
-
#
-
# link_to "Ruby on Rails search", controller: "searches", query: "ruby on rails"
-
# # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
-
#
-
# link_to "Nonsense search", searches_path(foo: "bar", baz: "quux")
-
# # => <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
-
#
-
# The only option specific to +link_to+ (<tt>:method</tt>) is used as follows:
-
#
-
# link_to("Destroy", "http://www.example.com", method: :delete)
-
# # => <a href='http://www.example.com' rel="nofollow" data-method="delete">Destroy</a>
-
#
-
# You can also use custom data attributes using the <tt>:data</tt> option:
-
#
-
# link_to "Visit Other Site", "http://www.rubyonrails.org/", data: { confirm: "Are you sure?" }
-
# # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?">Visit Other Site</a>
-
1
def link_to(name = nil, options = nil, html_options = nil, &block)
-
257
html_options, options, name = options, name, block if block_given?
-
257
options ||= {}
-
-
257
html_options = convert_options_to_data_attributes(options, html_options)
-
-
257
url = url_for(options)
-
257
html_options['href'] ||= url
-
-
257
content_tag(:a, name || url, html_options, &block)
-
end
-
-
# Generates a form containing a single button that submits to the URL created
-
# by the set of +options+. This is the safest method to ensure links that
-
# cause changes to your data are not triggered by search bots or accelerators.
-
# If the HTML button does not work with your layout, you can also consider
-
# using the +link_to+ method with the <tt>:method</tt> modifier as described in
-
# the +link_to+ documentation.
-
#
-
# By default, the generated form element has a class name of <tt>button_to</tt>
-
# to allow styling of the form itself and its children. This can be changed
-
# using the <tt>:form_class</tt> modifier within +html_options+. You can control
-
# the form submission and input element behavior using +html_options+.
-
# This method accepts the <tt>:method</tt> modifier described in the +link_to+ documentation.
-
# If no <tt>:method</tt> modifier is given, it will default to performing a POST operation.
-
# You can also disable the button by passing <tt>disabled: true</tt> in +html_options+.
-
# If you are using RESTful routes, you can pass the <tt>:method</tt>
-
# to change the HTTP verb used to submit the form.
-
#
-
# ==== Options
-
# The +options+ hash accepts the same options as +url_for+.
-
#
-
# There are a few special +html_options+:
-
# * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>,
-
# <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>. By default it will be <tt>:post</tt>.
-
# * <tt>:disabled</tt> - If set to true, it will generate a disabled button.
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
-
# submit behavior. By default this behavior is an ajax submit.
-
# * <tt>:form</tt> - This hash will be form attributes
-
# * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
-
# be placed
-
# * <tt>:params</tt> - Hash of parameters to be rendered as hidden fields within the form.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
-
# prompt with the question specified. If the user accepts, the link is
-
# processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be
-
# used as the value for a disabled version of the submit
-
# button when the form is submitted. This feature is provided
-
# by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# <%= button_to "New", action: "new" %>
-
# # => "<form method="post" action="/controller/new" class="button_to">
-
# # <input value="New" type="submit" />
-
# # </form>"
-
#
-
# <%= button_to "New", new_articles_path %>
-
# # => "<form method="post" action="/articles/new" class="button_to">
-
# # <input value="New" type="submit" />
-
# # </form>"
-
#
-
# <%= button_to [:make_happy, @user] do %>
-
# Make happy <strong><%= @user.name %></strong>
-
# <% end %>
-
# # => "<form method="post" action="/users/1/make_happy" class="button_to">
-
# # <button type="submit">
-
# # Make happy <strong><%= @user.name %></strong>
-
# # </button>
-
# # </form>"
-
#
-
# <%= button_to "New", { action: "new" }, form_class: "new-thing" %>
-
# # => "<form method="post" action="/controller/new" class="new-thing">
-
# # <input value="New" type="submit" />
-
# # </form>"
-
#
-
#
-
# <%= button_to "Create", { action: "create" }, remote: true, form: { "data-type" => "json" } %>
-
# # => "<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json">
-
# # <input value="Create" type="submit" />
-
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
-
# # </form>"
-
#
-
#
-
# <%= button_to "Delete Image", { action: "delete", id: @image.id },
-
# method: :delete, data: { confirm: "Are you sure?" } %>
-
# # => "<form method="post" action="/images/delete/1" class="button_to">
-
# # <input type="hidden" name="_method" value="delete" />
-
# # <input data-confirm='Are you sure?' value="Delete Image" type="submit" />
-
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
-
# # </form>"
-
#
-
#
-
# <%= button_to('Destroy', 'http://www.example.com',
-
# method: "delete", remote: true, data: { confirm: 'Are you sure?', disable_with: 'loading...' }) %>
-
# # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
-
# # <input name='_method' value='delete' type='hidden' />
-
# # <input value='Destroy' type='submit' data-disable-with='loading...' data-confirm='Are you sure?' />
-
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
-
# # </form>"
-
# #
-
1
def button_to(name = nil, options = nil, html_options = nil, &block)
-
html_options, options = options, name if block_given?
-
options ||= {}
-
html_options ||= {}
-
-
html_options = html_options.stringify_keys
-
convert_boolean_attributes!(html_options, %w(disabled))
-
-
url = options.is_a?(String) ? options : url_for(options)
-
remote = html_options.delete('remote')
-
params = html_options.delete('params')
-
-
method = html_options.delete('method').to_s
-
method_tag = BUTTON_TAG_METHOD_VERBS.include?(method) ? method_tag(method) : ''.html_safe
-
-
form_method = method == 'get' ? 'get' : 'post'
-
form_options = html_options.delete('form') || {}
-
form_options[:class] ||= html_options.delete('form_class') || 'button_to'
-
form_options.merge!(method: form_method, action: url)
-
form_options.merge!("data-remote" => "true") if remote
-
-
request_token_tag = form_method == 'post' ? token_tag : ''
-
-
html_options = convert_options_to_data_attributes(options, html_options)
-
html_options['type'] = 'submit'
-
-
button = if block_given?
-
content_tag('button', html_options, &block)
-
else
-
html_options['value'] = name || url
-
tag('input', html_options)
-
end
-
-
inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
-
if params
-
params.each do |param_name, value|
-
inner_tags.safe_concat tag(:input, type: "hidden", name: param_name, value: value.to_param)
-
end
-
end
-
content_tag('form', inner_tags, form_options)
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ unless the current request URI is the same as the links, in
-
# which case only the name is returned (or the given block is yielded, if
-
# one exists). You can give +link_to_unless_current+ a block which will
-
# specialize the default behavior (e.g., show a "Start Here" link rather
-
# than the link's text).
-
#
-
# ==== Examples
-
# Let's say you have a navigation menu...
-
#
-
# <ul id="navbar">
-
# <li><%= link_to_unless_current("Home", { action: "index" }) %></li>
-
# <li><%= link_to_unless_current("About Us", { action: "about" }) %></li>
-
# </ul>
-
#
-
# If in the "about" action, it will render...
-
#
-
# <ul id="navbar">
-
# <li><a href="/controller/index">Home</a></li>
-
# <li>About Us</li>
-
# </ul>
-
#
-
# ...but if in the "index" action, it will render:
-
#
-
# <ul id="navbar">
-
# <li>Home</li>
-
# <li><a href="/controller/about">About Us</a></li>
-
# </ul>
-
#
-
# The implicit block given to +link_to_unless_current+ is evaluated if the current
-
# action is the action given. So, if we had a comments page and wanted to render a
-
# "Go Back" link instead of a link to the comments page, we could do something like this...
-
#
-
# <%=
-
# link_to_unless_current("Comment", { controller: "comments", action: "new" }) do
-
# link_to("Go back", { controller: "posts", action: "index" })
-
# end
-
# %>
-
1
def link_to_unless_current(name, options = {}, html_options = {}, &block)
-
link_to_unless current_page?(options), name, options, html_options, &block
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ unless +condition+ is true, in which case only the name is
-
# returned. To specialize the default behavior (i.e., show a login link rather
-
# than just the plaintext link text), you can pass a block that
-
# accepts the name or the full argument list for +link_to_unless+.
-
#
-
# ==== Examples
-
# <%= link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) %>
-
# # If the user is logged in...
-
# # => <a href="/controller/reply/">Reply</a>
-
#
-
# <%=
-
# link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) do |name|
-
# link_to(name, { controller: "accounts", action: "signup" })
-
# end
-
# %>
-
# # If the user is logged in...
-
# # => <a href="/controller/reply/">Reply</a>
-
# # If not...
-
# # => <a href="/accounts/signup">Reply</a>
-
1
def link_to_unless(condition, name, options = {}, html_options = {}, &block)
-
link_to_if !condition, name, options, html_options, &block
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ if +condition+ is true, otherwise only the name is
-
# returned. To specialize the default behavior, you can pass a block that
-
# accepts the name or the full argument list for +link_to_unless+ (see the examples
-
# in +link_to_unless+).
-
#
-
# ==== Examples
-
# <%= link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) %>
-
# # If the user isn't logged in...
-
# # => <a href="/sessions/new/">Login</a>
-
#
-
# <%=
-
# link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) do
-
# link_to(@current_user.login, { controller: "accounts", action: "show", id: @current_user })
-
# end
-
# %>
-
# # If the user isn't logged in...
-
# # => <a href="/sessions/new/">Login</a>
-
# # If they are logged in...
-
# # => <a href="/accounts/show/3">my_username</a>
-
1
def link_to_if(condition, name, options = {}, html_options = {}, &block)
-
if condition
-
link_to(name, options, html_options)
-
else
-
if block_given?
-
block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
-
else
-
ERB::Util.html_escape(name)
-
end
-
end
-
end
-
-
# Creates a mailto link tag to the specified +email_address+, which is
-
# also used as the name of the link unless +name+ is specified. Additional
-
# HTML attributes for the link can be passed in +html_options+.
-
#
-
# +mail_to+ has several methods for customizing the email itself by
-
# passing special keys to +html_options+.
-
#
-
# ==== Options
-
# * <tt>:subject</tt> - Preset the subject line of the email.
-
# * <tt>:body</tt> - Preset the body of the email.
-
# * <tt>:cc</tt> - Carbon Copy additional recipients on the email.
-
# * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
-
#
-
# ==== Obfuscation
-
# Prior to Rails 4.0, +mail_to+ provided options for encoding the address
-
# in order to hinder email harvesters. To take advantage of these options,
-
# install the +actionview-encoded_mail_to+ gem.
-
#
-
# ==== Examples
-
# mail_to "me@domain.com"
-
# # => <a href="mailto:me@domain.com">me@domain.com</a>
-
#
-
# mail_to "me@domain.com", "My email"
-
# # => <a href="mailto:me@domain.com">My email</a>
-
#
-
# mail_to "me@domain.com", "My email", cc: "ccaddress@domain.com",
-
# subject: "This is an example email"
-
# # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a>
-
#
-
# You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
-
#
-
# <%= mail_to "me@domain.com" do %>
-
# <strong>Email me:</strong> <span>me@domain.com</span>
-
# <% end %>
-
# # => <a href="mailto:me@domain.com">
-
# <strong>Email me:</strong> <span>me@domain.com</span>
-
# </a>
-
1
def mail_to(email_address, name = nil, html_options = {}, &block)
-
html_options, name = name, nil if block_given?
-
html_options = (html_options || {}).stringify_keys
-
-
extras = %w{ cc bcc body subject }.map! { |item|
-
option = html_options.delete(item) || next
-
"#{item}=#{Rack::Utils.escape_path(option)}"
-
}.compact
-
extras = extras.empty? ? '' : '?' + extras.join('&')
-
-
encoded_email_address = ERB::Util.url_encode(email_address ? email_address.to_str : '').gsub("%40", "@")
-
html_options["href"] = "mailto:#{encoded_email_address}#{extras}"
-
-
content_tag(:a, name || email_address, html_options, &block)
-
end
-
-
# True if the current request URI was generated by the given +options+.
-
#
-
# ==== Examples
-
# Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc</tt> action.
-
#
-
# current_page?(action: 'process')
-
# # => false
-
#
-
# current_page?(controller: 'shop', action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'asc')
-
# # => false
-
#
-
# current_page?(action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'library', action: 'checkout')
-
# # => false
-
#
-
# current_page?('http://www.example.com/shop/checkout')
-
# # => true
-
#
-
# current_page?('/shop/checkout')
-
# # => true
-
#
-
# Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc&page=1</tt> action.
-
#
-
# current_page?(action: 'process')
-
# # => false
-
#
-
# current_page?(controller: 'shop', action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '1')
-
# # => true
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '2')
-
# # => false
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'desc')
-
# # => false
-
#
-
# current_page?(action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'library', action: 'checkout')
-
# # => false
-
#
-
# Let's say we're in the <tt>http://www.example.com/products</tt> action with method POST in case of invalid product.
-
#
-
# current_page?(controller: 'product', action: 'index')
-
# # => false
-
#
-
1
def current_page?(options)
-
unless request
-
raise "You cannot use helpers that need to determine the current " \
-
"page unless your view context provides a Request object " \
-
"in a #request method"
-
end
-
-
return false unless request.get? || request.head?
-
-
url_string = URI.parser.unescape(url_for(options)).force_encoding(Encoding::BINARY)
-
-
# We ignore any extra parameters in the request_uri if the
-
# submitted url doesn't have any either. This lets the function
-
# work with things like ?order=asc
-
request_uri = url_string.index("?") ? request.fullpath : request.path
-
request_uri = URI.parser.unescape(request_uri).force_encoding(Encoding::BINARY)
-
-
if url_string =~ /^\w+:\/\//
-
url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
-
else
-
url_string == request_uri
-
end
-
end
-
-
1
private
-
1
def convert_options_to_data_attributes(options, html_options)
-
257
if html_options
-
55
html_options = html_options.stringify_keys
-
55
html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
-
-
55
method = html_options.delete('method')
-
-
55
add_method_to_attributes!(html_options, method) if method
-
-
55
html_options
-
else
-
202
link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
-
end
-
end
-
-
1
def link_to_remote_options?(options)
-
312
if options.is_a?(Hash)
-
202
options.delete('remote') || options.delete(:remote)
-
end
-
end
-
-
1
def add_method_to_attributes!(html_options, method)
-
15
if method && method.to_s.downcase != "get" && html_options["rel"] !~ /nofollow/
-
15
html_options["rel"] = "#{html_options["rel"]} nofollow".lstrip
-
end
-
15
html_options["data-method"] = method
-
end
-
-
# Processes the +html_options+ hash, converting the boolean
-
# attributes from true/false form into the form required by
-
# HTML/XHTML. (An attribute is considered to be boolean if
-
# its name is listed in the given +bool_attrs+ array.)
-
#
-
# More specifically, for each boolean attribute in +html_options+
-
# given as:
-
#
-
# "attr" => bool_value
-
#
-
# if the associated +bool_value+ evaluates to true, it is
-
# replaced with the attribute's name; otherwise the attribute is
-
# removed from the +html_options+ hash. (See the XHTML 1.0 spec,
-
# section 4.5 "Attribute Minimization" for more:
-
# http://www.w3.org/TR/xhtml1/#h-4.5)
-
#
-
# Returns the updated +html_options+ hash, which is also modified
-
# in place.
-
#
-
# Example:
-
#
-
# convert_boolean_attributes!( html_options,
-
# %w( checked disabled readonly ) )
-
1
def convert_boolean_attributes!(html_options, bool_attrs)
-
bool_attrs.each { |x| html_options[x] = x if html_options.delete(x) }
-
html_options
-
end
-
-
1
def token_tag(token=nil)
-
8
if token != false && protect_against_forgery?
-
token ||= form_authenticity_token
-
tag(:input, type: "hidden", name: request_forgery_protection_token.to_s, value: token)
-
else
-
8
''
-
end
-
end
-
-
1
def method_tag(method)
-
4
tag('input', type: 'hidden', name: '_method', value: method.to_s)
-
end
-
end
-
end
-
end
-
1
require "action_view/rendering"
-
1
require "active_support/core_ext/module/remove_method"
-
-
1
module ActionView
-
# Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in
-
# repeated setups. The inclusion pattern has pages that look like this:
-
#
-
# <%= render "shared/header" %>
-
# Hello World
-
# <%= render "shared/footer" %>
-
#
-
# This approach is a decent way of keeping common structures isolated from the changing content, but it's verbose
-
# and if you ever want to change the structure of these two includes, you'll have to change all the templates.
-
#
-
# With layouts, you can flip it around and have the common structure know where to insert changing content. This means
-
# that the header and footer are only mentioned in one place, like this:
-
#
-
# // The header part of this layout
-
# <%= yield %>
-
# // The footer part of this layout
-
#
-
# And then you have content pages that look like this:
-
#
-
# hello world
-
#
-
# At rendering time, the content page is computed and then inserted in the layout, like this:
-
#
-
# // The header part of this layout
-
# hello world
-
# // The footer part of this layout
-
#
-
# == Accessing shared variables
-
#
-
# Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with
-
# references that won't materialize before rendering time:
-
#
-
# <h1><%= @page_title %></h1>
-
# <%= yield %>
-
#
-
# ...and content pages that fulfill these references _at_ rendering time:
-
#
-
# <% @page_title = "Welcome" %>
-
# Off-world colonies offers you a chance to start a new life
-
#
-
# The result after rendering is:
-
#
-
# <h1>Welcome</h1>
-
# Off-world colonies offers you a chance to start a new life
-
#
-
# == Layout assignment
-
#
-
# You can either specify a layout declaratively (using the #layout class method) or give
-
# it the same name as your controller, and place it in <tt>app/views/layouts</tt>.
-
# If a subclass does not have a layout specified, it inherits its layout using normal Ruby inheritance.
-
#
-
# For instance, if you have PostsController and a template named <tt>app/views/layouts/posts.html.erb</tt>,
-
# that template will be used for all actions in PostsController and controllers inheriting
-
# from PostsController.
-
#
-
# If you use a module, for instance Weblog::PostsController, you will need a template named
-
# <tt>app/views/layouts/weblog/posts.html.erb</tt>.
-
#
-
# Since all your controllers inherit from ApplicationController, they will use
-
# <tt>app/views/layouts/application.html.erb</tt> if no other layout is specified
-
# or provided.
-
#
-
# == Inheritance Examples
-
#
-
# class BankController < ActionController::Base
-
# # bank.html.erb exists
-
#
-
# class ExchangeController < BankController
-
# # exchange.html.erb exists
-
#
-
# class CurrencyController < BankController
-
#
-
# class InformationController < BankController
-
# layout "information"
-
#
-
# class TellerController < InformationController
-
# # teller.html.erb exists
-
#
-
# class EmployeeController < InformationController
-
# # employee.html.erb exists
-
# layout nil
-
#
-
# class VaultController < BankController
-
# layout :access_level_layout
-
#
-
# class TillController < BankController
-
# layout false
-
#
-
# In these examples, we have three implicit lookup scenarios:
-
# * The BankController uses the "bank" layout.
-
# * The ExchangeController uses the "exchange" layout.
-
# * The CurrencyController inherits the layout from BankController.
-
#
-
# However, when a layout is explicitly set, the explicitly set layout wins:
-
# * The InformationController uses the "information" layout, explicitly set.
-
# * The TellerController also uses the "information" layout, because the parent explicitly set it.
-
# * The EmployeeController uses the "employee" layout, because it set the layout to nil, resetting the parent configuration.
-
# * The VaultController chooses a layout dynamically by calling the <tt>access_level_layout</tt> method.
-
# * The TillController does not use a layout at all.
-
#
-
# == Types of layouts
-
#
-
# Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
-
# you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
-
# be done either by specifying a method reference as a symbol or using an inline method (as a proc).
-
#
-
# The method reference is the preferred approach to variable layouts and is used like this:
-
#
-
# class WeblogController < ActionController::Base
-
# layout :writers_and_readers
-
#
-
# def index
-
# # fetching posts
-
# end
-
#
-
# private
-
# def writers_and_readers
-
# logged_in? ? "writer_layout" : "reader_layout"
-
# end
-
# end
-
#
-
# Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
-
# is logged in or not.
-
#
-
# If you want to use an inline method, such as a proc, do something like this:
-
#
-
# class WeblogController < ActionController::Base
-
# layout proc { |controller| controller.logged_in? ? "writer_layout" : "reader_layout" }
-
# end
-
#
-
# If an argument isn't given to the proc, it's evaluated in the context of
-
# the current controller anyway.
-
#
-
# class WeblogController < ActionController::Base
-
# layout proc { logged_in? ? "writer_layout" : "reader_layout" }
-
# end
-
#
-
# Of course, the most common way of specifying a layout is still just as a plain template name:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard"
-
# end
-
#
-
# The template will be looked always in <tt>app/views/layouts/</tt> folder. But you can point
-
# <tt>layouts</tt> folder direct also. <tt>layout "layouts/demo"</tt> is the same as <tt>layout "demo"</tt>.
-
#
-
# Setting the layout to nil forces it to be looked up in the filesystem and fallbacks to the parent behavior if none exists.
-
# Setting it to nil is useful to re-enable template lookup overriding a previous configuration set in the parent:
-
#
-
# class ApplicationController < ActionController::Base
-
# layout "application"
-
# end
-
#
-
# class PostsController < ApplicationController
-
# # Will use "application" layout
-
# end
-
#
-
# class CommentsController < ApplicationController
-
# # Will search for "comments" layout and fallback "application" layout
-
# layout nil
-
# end
-
#
-
# == Conditional layouts
-
#
-
# If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
-
# a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The
-
# <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard", except: :rss
-
#
-
# # ...
-
#
-
# end
-
#
-
# This will assign "weblog_standard" as the WeblogController's layout for all actions except for the +rss+ action, which will
-
# be rendered directly, without wrapping a layout around the rendered view.
-
#
-
# Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
-
# #<tt>except: [ :rss, :text_only ]</tt> is valid, as is <tt>except: :rss</tt>.
-
#
-
# == Using a different layout in the action render call
-
#
-
# If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
-
# Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller.
-
# You can do this by passing a <tt>:layout</tt> option to the <tt>render</tt> call. For example:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard"
-
#
-
# def help
-
# render action: "help", layout: "help"
-
# end
-
# end
-
#
-
# This will override the controller-wide "weblog_standard" layout, and will render the help action with the "help" layout instead.
-
1
module Layouts
-
1
extend ActiveSupport::Concern
-
-
1
include ActionView::Rendering
-
-
1
included do
-
2
class_attribute :_layout, :_layout_conditions, :instance_accessor => false
-
2
self._layout = nil
-
2
self._layout_conditions = {}
-
2
_write_layout_method
-
end
-
-
1
delegate :_layout_conditions, to: :class
-
-
1
module ClassMethods
-
1
def inherited(klass) # :nodoc:
-
6
super
-
6
klass._write_layout_method
-
end
-
-
# This module is mixed in if layout conditions are provided. This means
-
# that if no layout conditions are used, this method is not used
-
1
module LayoutConditions # :nodoc:
-
1
private
-
-
# Determines whether the current action has a layout definition by
-
# checking the action name against the :only and :except conditions
-
# set by the <tt>layout</tt> method.
-
#
-
# ==== Returns
-
# * <tt> Boolean</tt> - True if the action has a layout definition, false otherwise.
-
1
def _conditional_layout?
-
return unless super
-
-
conditions = _layout_conditions
-
-
if only = conditions[:only]
-
only.include?(action_name)
-
elsif except = conditions[:except]
-
!except.include?(action_name)
-
else
-
true
-
end
-
end
-
end
-
-
# Specify the layout to use for this class.
-
#
-
# If the specified layout is a:
-
# String:: the String is the template name
-
# Symbol:: call the method specified by the symbol, which will return the template name
-
# false:: There is no layout
-
# true:: raise an ArgumentError
-
# nil:: Force default layout behavior with inheritance
-
#
-
# ==== Parameters
-
# * <tt>layout</tt> - The layout to use.
-
#
-
# ==== Options (conditions)
-
# * :only - A list of actions to apply this layout to.
-
# * :except - Apply this layout to all actions but this one.
-
1
def layout(layout, conditions = {})
-
include LayoutConditions unless conditions.empty?
-
-
conditions.each {|k, v| conditions[k] = Array(v).map {|a| a.to_s} }
-
self._layout_conditions = conditions
-
-
self._layout = layout
-
_write_layout_method
-
end
-
-
# Creates a _layout method to be called by _default_layout .
-
#
-
# If a layout is not explicitly mentioned then look for a layout with the controller's name.
-
# if nothing is found then try same procedure to find super class's layout.
-
1
def _write_layout_method # :nodoc:
-
8
remove_possible_method(:_layout)
-
-
8
prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"]
-
8
default_behavior = "lookup_context.find_all('#{_implied_layout_name}', #{prefixes.inspect}).first || super"
-
8
name_clause = if name
-
8
default_behavior
-
else
-
<<-RUBY
-
super
-
RUBY
-
end
-
-
8
layout_definition = case _layout
-
when String
-
_layout.inspect
-
when Symbol
-
<<-RUBY
-
#{_layout}.tap do |layout|
-
return #{default_behavior} if layout.nil?
-
unless layout.is_a?(String) || !layout
-
raise ArgumentError, "Your layout method :#{_layout} returned \#{layout}. It " \
-
"should have returned a String, false, or nil"
-
end
-
end
-
RUBY
-
when Proc
-
define_method :_layout_from_proc, &_layout
-
protected :_layout_from_proc
-
<<-RUBY
-
result = _layout_from_proc(#{_layout.arity == 0 ? '' : 'self'})
-
return #{default_behavior} if result.nil?
-
result
-
RUBY
-
when false
-
nil
-
when true
-
raise ArgumentError, "Layouts must be specified as a String, Symbol, Proc, false, or nil"
-
when nil
-
8
name_clause
-
end
-
-
8
self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def _layout
-
if _conditional_layout?
-
#{layout_definition}
-
else
-
#{name_clause}
-
end
-
end
-
private :_layout
-
RUBY
-
end
-
-
1
private
-
-
# If no layout is supplied, look for a template named the return
-
# value of this method.
-
#
-
# ==== Returns
-
# * <tt>String</tt> - A template name
-
1
def _implied_layout_name # :nodoc:
-
16
controller_path
-
end
-
end
-
-
1
def _normalize_options(options) # :nodoc:
-
55
super
-
-
55
if _include_layout?(options)
-
110
layout = options.delete(:layout) { :default }
-
55
options[:layout] = _layout_for_option(layout)
-
end
-
end
-
-
1
attr_internal_writer :action_has_layout
-
-
1
def initialize(*) # :nodoc:
-
66
@_action_has_layout = true
-
66
super
-
end
-
-
# Controls whether an action should be rendered using a layout.
-
# If you want to disable any <tt>layout</tt> settings for the
-
# current action so that it is rendered without a layout then
-
# either override this method in your controller to return false
-
# for that action or set the <tt>action_has_layout</tt> attribute
-
# to false before rendering.
-
1
def action_has_layout?
-
55
@_action_has_layout
-
end
-
-
1
private
-
-
1
def _conditional_layout?
-
110
true
-
end
-
-
# This will be overwritten by _write_layout_method
-
1
def _layout; end
-
-
# Determine the layout for a given name, taking into account the name type.
-
#
-
# ==== Parameters
-
# * <tt>name</tt> - The name of the template
-
1
def _layout_for_option(name)
-
55
case name
-
when String then _normalize_layout(name)
-
when Proc then name
-
when true then Proc.new { _default_layout(true) }
-
110
when :default then Proc.new { _default_layout(false) }
-
when false, nil then nil
-
else
-
raise ArgumentError,
-
"String, Proc, :default, true, or false, expected for `layout'; you passed #{name.inspect}"
-
end
-
end
-
-
1
def _normalize_layout(value)
-
55
value.is_a?(String) && value !~ /\blayouts/ ? "layouts/#{value}" : value
-
end
-
-
# Returns the default layout for this controller.
-
# Optionally raises an exception if the layout could not be found.
-
#
-
# ==== Parameters
-
# * <tt>require_layout</tt> - If set to true and layout is not found,
-
# an ArgumentError exception is raised (defaults to false)
-
#
-
# ==== Returns
-
# * <tt>template</tt> - The template object for the default layout (or nil)
-
1
def _default_layout(require_layout = false)
-
55
begin
-
55
value = _layout if action_has_layout?
-
rescue NameError => e
-
raise e, "Could not render layout: #{e.message}"
-
end
-
-
55
if require_layout && action_has_layout? && !value
-
raise ArgumentError,
-
"There was no default layout for #{self.class} in #{view_paths.inspect}"
-
end
-
-
55
_normalize_layout(value)
-
end
-
-
1
def _include_layout?(options)
-
55
(options.keys & [:body, :text, :plain, :html, :inline, :partial]).empty? || options.key?(:layout)
-
end
-
end
-
end
-
1
require 'active_support/log_subscriber'
-
-
1
module ActionView
-
# = Action View Log Subscriber
-
#
-
# Provides functionality so that Rails can output logs from Action View.
-
1
class LogSubscriber < ActiveSupport::LogSubscriber
-
1
VIEWS_PATTERN = /^app\/views\//
-
-
1
def initialize
-
1
@root = nil
-
1
super
-
end
-
-
1
def render_template(event)
-
63
info do
-
63
message = " Rendered #{from_rails_root(event.payload[:identifier])}"
-
63
message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
-
63
message << " (#{event.duration.round(1)}ms)"
-
end
-
end
-
1
alias :render_partial :render_template
-
1
alias :render_collection :render_template
-
-
1
def logger
-
252
ActionView::Base.logger
-
end
-
-
1
protected
-
-
1
EMPTY = ''
-
1
def from_rails_root(string)
-
118
string = string.sub(rails_root, EMPTY)
-
118
string.sub!(VIEWS_PATTERN, EMPTY)
-
118
string
-
end
-
-
1
def rails_root
-
118
@root ||= "#{Rails.root}/"
-
end
-
end
-
end
-
-
1
ActionView::LogSubscriber.attach_to :action_view
-
1
require 'thread_safe'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'action_view/template/resolver'
-
-
1
module ActionView
-
# = Action View Lookup Context
-
#
-
# LookupContext is the object responsible to hold all information required to lookup
-
# templates, i.e. view paths and details. The LookupContext is also responsible to
-
# generate a key, given to view paths, used in the resolver cache lookup. Since
-
# this key is generated just once during the request, it speeds up all cache accesses.
-
1
class LookupContext #:nodoc:
-
1
attr_accessor :prefixes, :rendered_format
-
-
1
mattr_accessor :fallbacks
-
1
@@fallbacks = FallbackFileSystemResolver.instances
-
-
1
mattr_accessor :registered_details
-
1
self.registered_details = []
-
-
1
def self.register_detail(name, options = {}, &block)
-
4
self.registered_details << name
-
14
initialize = registered_details.map { |n| "@details[:#{n}] = details[:#{n}] || default_#{n}" }
-
-
4
Accessors.send :define_method, :"default_#{name}", &block
-
4
Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{name}
-
@details.fetch(:#{name}, [])
-
end
-
-
def #{name}=(value)
-
value = value.present? ? Array(value) : default_#{name}
-
_set_detail(:#{name}, value) if value != @details[:#{name}]
-
end
-
-
remove_possible_method :initialize_details
-
def initialize_details(details)
-
#{initialize.join("\n")}
-
end
-
METHOD
-
end
-
-
# Holds accessors for the registered details.
-
1
module Accessors #:nodoc:
-
end
-
-
1
register_detail(:locale) do
-
66
locales = [I18n.locale]
-
66
locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks
-
66
locales << I18n.default_locale
-
66
locales.uniq!
-
66
locales
-
end
-
67
register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css, :xml, :json] }
-
67
register_detail(:variants) { [] }
-
67
register_detail(:handlers){ Template::Handlers.extensions }
-
-
1
class DetailsKey #:nodoc:
-
1
alias :eql? :equal?
-
1
alias :object_hash :hash
-
-
1
attr_reader :hash
-
1
@details_keys = ThreadSafe::Cache.new
-
-
1
def self.get(details)
-
55
if details[:formats]
-
55
details = details.dup
-
55
details[:formats] &= Mime::SET.symbols
-
end
-
55
@details_keys[details] ||= new
-
end
-
-
1
def self.clear
-
@details_keys.clear
-
end
-
-
1
def initialize
-
1
@hash = object_hash
-
end
-
end
-
-
# Add caching behavior on top of Details.
-
1
module DetailsCache
-
1
attr_accessor :cache
-
-
# Calculate the details key. Remove the handlers from calculation to improve performance
-
# since the user cannot modify it explicitly.
-
1
def details_key #:nodoc:
-
173
@details_key ||= DetailsKey.get(@details) if @cache
-
end
-
-
# Temporary skip passing the details_key forward.
-
1
def disable_cache
-
old_value, @cache = @cache, false
-
yield
-
ensure
-
@cache = old_value
-
end
-
-
1
protected
-
-
1
def _set_detail(key, value)
-
66
@details = @details.dup if @details_key
-
66
@details_key = nil
-
66
@details[key] = value
-
end
-
end
-
-
# Helpers related to template lookup using the lookup context information.
-
1
module ViewPaths
-
1
attr_reader :view_paths, :html_fallback_for_js
-
-
# Whenever setting view paths, makes a copy so that we can manipulate them in
-
# instance objects as we wish.
-
1
def view_paths=(paths)
-
66
@view_paths = ActionView::PathSet.new(Array(paths))
-
end
-
-
1
def find(name, prefixes = [], partial = false, keys = [], options = {})
-
63
@view_paths.find(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
1
alias :find_template :find
-
-
1
def find_all(name, prefixes = [], partial = false, keys = [], options = {})
-
110
@view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
-
1
def exists?(name, prefixes = [], partial = false, keys = [], options = {})
-
@view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
1
alias :template_exists? :exists?
-
-
# Adds fallbacks to the view paths. Useful in cases when you are rendering
-
# a :file.
-
1
def with_fallbacks
-
added_resolvers = 0
-
self.class.fallbacks.each do |resolver|
-
next if view_paths.include?(resolver)
-
view_paths.push(resolver)
-
added_resolvers += 1
-
end
-
yield
-
ensure
-
added_resolvers.times { view_paths.pop }
-
end
-
-
1
protected
-
-
1
def args_for_lookup(name, prefixes, partial, keys, details_options) #:nodoc:
-
173
name, prefixes = normalize_name(name, prefixes)
-
173
details, details_key = detail_args_for(details_options)
-
173
[name, prefixes, partial || false, details, details_key, keys]
-
end
-
-
# Compute details hash and key according to user options (e.g. passed from #render).
-
1
def detail_args_for(options)
-
173
return @details, details_key if options.empty? # most common path.
-
user_details = @details.merge(options)
-
-
if @cache
-
details_key = DetailsKey.get(user_details)
-
else
-
details_key = nil
-
end
-
-
[user_details, details_key]
-
end
-
-
# Support legacy foo.erb names even though we now ignore .erb
-
# as well as incorrectly putting part of the path in the template
-
# name instead of the prefix.
-
1
def normalize_name(name, prefixes) #:nodoc:
-
173
prefixes = prefixes.presence
-
173
parts = name.to_s.split('/')
-
173
parts.shift if parts.first.empty?
-
173
name = parts.pop
-
-
173
return name, prefixes || [""] if parts.empty?
-
-
parts = parts.join('/')
-
prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts]
-
-
return name, prefixes
-
end
-
end
-
-
1
include Accessors
-
1
include DetailsCache
-
1
include ViewPaths
-
-
1
def initialize(view_paths, details = {}, prefixes = [])
-
66
@details, @details_key = {}, nil
-
66
@skip_default_locale = false
-
66
@cache = true
-
66
@prefixes = prefixes
-
66
@rendered_format = nil
-
-
66
self.view_paths = view_paths
-
66
initialize_details(details)
-
end
-
-
# Override formats= to expand ["*/*"] values and automatically
-
# add :html as fallback to :js.
-
1
def formats=(values)
-
179
if values
-
179
values.concat(default_formats) if values.delete "*/*"
-
179
if values == [:js]
-
values << :html
-
@html_fallback_for_js = true
-
end
-
end
-
179
super(values)
-
end
-
-
# Do not use the default locale on template lookup.
-
1
def skip_default_locale!
-
@skip_default_locale = true
-
self.locale = nil
-
end
-
-
# Override locale to return a symbol instead of array.
-
1
def locale
-
@details[:locale].first
-
end
-
-
# Overload locale= to also set the I18n.locale. If the current I18n.config object responds
-
# to original_config, it means that it has a copy of the original I18n configuration and it's
-
# acting as proxy, which we need to skip.
-
1
def locale=(value)
-
if value
-
config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
-
config.locale = value
-
end
-
-
super(@skip_default_locale ? I18n.locale : default_locale)
-
end
-
-
# Uses the first format in the formats array for layout lookup.
-
1
def with_layout_format
-
55
if formats.size == 1
-
55
yield
-
else
-
old_formats = formats
-
_set_detail(:formats, formats[0,1])
-
-
begin
-
yield
-
ensure
-
_set_detail(:formats, old_formats)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module ModelNaming
-
# Converts the given object to an ActiveModel compliant one.
-
1
def convert_to_model(object)
-
6
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
-
1
def model_name_from_record_or_class(record_or_class)
-
convert_to_model(record_or_class).model_name
-
end
-
end
-
end
-
1
module ActionView #:nodoc:
-
# = Action View PathSet
-
#
-
# This class is used to store and access paths in Action View. A number of
-
# operations are defined so that you can search among the paths in this
-
# set and also perform operations on other +PathSet+ objects.
-
#
-
# A +LookupContext+ will use a +PathSet+ to store the paths in its context.
-
1
class PathSet #:nodoc:
-
1
include Enumerable
-
-
1
attr_reader :paths
-
-
1
delegate :[], :include?, :pop, :size, :each, to: :paths
-
-
1
def initialize(paths = [])
-
70
@paths = typecast paths
-
end
-
-
1
def initialize_copy(other)
-
@paths = other.paths.dup
-
self
-
end
-
-
1
def to_ary
-
68
paths.dup
-
end
-
-
1
def compact
-
PathSet.new paths.compact
-
end
-
-
1
def +(array)
-
PathSet.new(paths + array)
-
end
-
-
1
%w(<< concat push insert unshift).each do |method|
-
5
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{method}(*args)
-
paths.#{method}(*typecast(args))
-
end
-
METHOD
-
end
-
-
1
def find(*args)
-
63
find_all(*args).first || raise(MissingTemplate.new(self, *args))
-
end
-
-
1
def find_all(path, prefixes = [], *args)
-
173
prefixes = [prefixes] if String === prefixes
-
173
prefixes.each do |prefix|
-
173
paths.each do |resolver|
-
173
templates = resolver.find_all(path, prefix, *args)
-
173
return templates unless templates.empty?
-
end
-
end
-
55
[]
-
end
-
-
1
def exists?(path, prefixes, *args)
-
find_all(path, prefixes, *args).any?
-
end
-
-
1
private
-
-
1
def typecast(paths)
-
70
paths.map do |path|
-
68
case path
-
when Pathname, String
-
2
OptimizedFileSystemResolver.new path.to_s
-
else
-
66
path
-
end
-
end
-
end
-
end
-
end
-
1
require "action_view"
-
1
require "rails"
-
-
1
module ActionView
-
# = Action View Railtie
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.action_view = ActiveSupport::OrderedOptions.new
-
1
config.action_view.embed_authenticity_token_in_remote_forms = false
-
-
1
config.eager_load_namespaces << ActionView
-
-
1
initializer "action_view.embed_authenticity_token_in_remote_forms" do |app|
-
1
ActiveSupport.on_load(:action_view) do
-
1
ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms =
-
app.config.action_view.delete(:embed_authenticity_token_in_remote_forms)
-
end
-
end
-
-
1
initializer "action_view.logger" do
-
2
ActiveSupport.on_load(:action_view) { self.logger ||= Rails.logger }
-
end
-
-
1
initializer "action_view.set_configs" do |app|
-
1
ActiveSupport.on_load(:action_view) do
-
1
app.config.action_view.each do |k,v|
-
send "#{k}=", v
-
end
-
end
-
end
-
-
1
initializer "action_view.caching" do |app|
-
1
ActiveSupport.on_load(:action_view) do
-
1
if app.config.action_view.cache_template_loading.nil?
-
1
ActionView::Resolver.caching = app.config.cache_classes
-
end
-
end
-
end
-
-
1
initializer "action_view.setup_action_pack" do |app|
-
1
ActiveSupport.on_load(:action_controller) do
-
1
ActionView::RoutingUrlFor.send(:include, ActionDispatch::Routing::UrlFor)
-
end
-
end
-
-
1
rake_tasks do
-
load "action_view/tasks/dependencies.rake"
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module'
-
1
require 'action_view/model_naming'
-
-
1
module ActionView
-
# The record identifier encapsulates a number of naming conventions for dealing with records, like Active Records or
-
# pretty much any other model type that has an id. These patterns are then used to try elevate the view actions to
-
# a higher logical level.
-
#
-
# # routes
-
# resources :posts
-
#
-
# # view
-
# <%= div_for(post) do %> <div id="post_45" class="post">
-
# <%= post.body %> What a wonderful world!
-
# <% end %> </div>
-
#
-
# # controller
-
# def update
-
# post = Post.find(params[:id])
-
# post.update(params[:post])
-
#
-
# redirect_to(post) # Calls polymorphic_url(post) which in turn calls post_url(post)
-
# end
-
#
-
# As the example above shows, you can stop caring to a large extent what the actual id of the post is.
-
# You just know that one is being assigned and that the subsequent calls in redirect_to expect that
-
# same naming convention and allows you to write less code if you follow it.
-
1
module RecordIdentifier
-
1
extend self
-
1
extend ModelNaming
-
-
1
include ModelNaming
-
-
1
JOIN = '_'.freeze
-
1
NEW = 'new'.freeze
-
-
# The DOM class convention is to use the singular form of an object or class.
-
#
-
# dom_class(post) # => "post"
-
# dom_class(Person) # => "person"
-
#
-
# If you need to address multiple instances of the same class in the same view, you can prefix the dom_class:
-
#
-
# dom_class(post, :edit) # => "edit_post"
-
# dom_class(Person, :edit) # => "edit_person"
-
1
def dom_class(record_or_class, prefix = nil)
-
16
singular = model_name_from_record_or_class(record_or_class).param_key
-
16
prefix ? "#{prefix}#{JOIN}#{singular}" : singular
-
end
-
-
# The DOM id convention is to use the singular form of an object or class with the id following an underscore.
-
# If no id is found, prefix with "new_" instead.
-
#
-
# dom_id(Post.find(45)) # => "post_45"
-
# dom_id(Post.new) # => "new_post"
-
#
-
# If you need to address multiple instances of the same class in the same view, you can prefix the dom_id:
-
#
-
# dom_id(Post.find(45), :edit) # => "edit_post_45"
-
# dom_id(Post.new, :custom) # => "custom_post"
-
1
def dom_id(record, prefix = nil)
-
8
if record_id = record_key_for_dom_id(record)
-
4
"#{dom_class(record, prefix)}#{JOIN}#{record_id}"
-
else
-
4
dom_class(record, prefix || NEW)
-
end
-
end
-
-
1
protected
-
-
# Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id.
-
# This can be overwritten to customize the default generated string representation if desired.
-
# If you need to read back a key from a dom_id in order to query for the underlying database record,
-
# you should write a helper like 'person_record_from_dom_id' that will extract the key either based
-
# on the default implementation (which just joins all key attributes with '_') or on your own
-
# overwritten version of the method. By default, this implementation passes the key string through a
-
# method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to
-
# make sure yourself that your dom ids are valid, in case you overwrite this method.
-
1
def record_key_for_dom_id(record)
-
8
key = convert_to_model(record).to_key
-
8
key ? key.join('_') : key
-
end
-
end
-
end
-
1
module ActionView
-
# This class defines the interface for a renderer. Each class that
-
# subclasses +AbstractRenderer+ is used by the base +Renderer+ class to
-
# render a specific type of object.
-
#
-
# The base +Renderer+ class uses its +render+ method to delegate to the
-
# renderers. These currently consist of
-
#
-
# PartialRenderer - Used for rendering partials
-
# TemplateRenderer - Used for rendering other types of templates
-
# StreamingTemplateRenderer - Used for streaming
-
#
-
# Whenever the +render+ method is called on the base +Renderer+ class, a new
-
# renderer object of the correct type is created, and the +render+ method on
-
# that new object is called in turn. This abstracts the setup and rendering
-
# into a separate classes for partials and templates.
-
1
class AbstractRenderer #:nodoc:
-
1
delegate :find_template, :template_exists?, :with_fallbacks, :with_layout_format, :formats, :to => :@lookup_context
-
-
1
def initialize(lookup_context)
-
63
@lookup_context = lookup_context
-
end
-
-
1
def render
-
raise NotImplementedError
-
end
-
-
1
protected
-
-
1
def extract_details(options)
-
63
@lookup_context.registered_details.each_with_object({}) do |key, details|
-
252
value = options[key]
-
-
252
details[key] = Array(value) if value
-
end
-
end
-
-
1
def instrument(name, options={})
-
126
ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
-
end
-
-
1
def prepend_formats(formats)
-
63
formats = Array(formats)
-
63
return if formats.empty? || @lookup_context.html_fallback_for_js
-
-
55
@lookup_context.formats = formats | @lookup_context.formats
-
end
-
end
-
end
-
1
require 'thread_safe'
-
-
1
module ActionView
-
1
class PartialIteration
-
# The number of iterations that will be done by the partial.
-
1
attr_reader :size
-
-
# The current iteration of the partial.
-
1
attr_reader :index
-
-
1
def initialize(size)
-
@size = size
-
@index = 0
-
end
-
-
# Check if this is the first iteration of the partial.
-
1
def first?
-
index == 0
-
end
-
-
# Check if this is the last iteration of the partial.
-
1
def last?
-
index == size - 1
-
end
-
-
1
def iterate! # :nodoc:
-
@index += 1
-
end
-
end
-
-
# = Action View Partials
-
#
-
# There's also a convenience method for rendering sub templates within the current controller that depends on a
-
# single object (we call this kind of sub templates for partials). It relies on the fact that partials should
-
# follow the naming convention of being prefixed with an underscore -- as to separate them from regular
-
# templates that could be rendered on their own.
-
#
-
# In a template for Advertiser#account:
-
#
-
# <%= render partial: "account" %>
-
#
-
# This would render "advertiser/_account.html.erb".
-
#
-
# In another template for Advertiser#buy, we could have:
-
#
-
# <%= render partial: "account", locals: { account: @buyer } %>
-
#
-
# <% @advertisements.each do |ad| %>
-
# <%= render partial: "ad", locals: { ad: ad } %>
-
# <% end %>
-
#
-
# This would first render "advertiser/_account.html.erb" with @buyer passed in as the local variable +account+, then
-
# render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display.
-
#
-
# == The :as and :object options
-
#
-
# By default <tt>ActionView::PartialRenderer</tt> doesn't have any local variables.
-
# The <tt>:object</tt> option can be used to pass an object to the partial. For instance:
-
#
-
# <%= render partial: "account", object: @buyer %>
-
#
-
# would provide the <tt>@buyer</tt> object to the partial, available under the local variable +account+ and is
-
# equivalent to:
-
#
-
# <%= render partial: "account", locals: { account: @buyer } %>
-
#
-
# With the <tt>:as</tt> option we can specify a different name for said local variable. For example, if we
-
# wanted it to be +user+ instead of +account+ we'd do:
-
#
-
# <%= render partial: "account", object: @buyer, as: 'user' %>
-
#
-
# This is equivalent to
-
#
-
# <%= render partial: "account", locals: { user: @buyer } %>
-
#
-
# == Rendering a collection of partials
-
#
-
# The example of partial use describes a familiar pattern where a template needs to iterate over an array and
-
# render a sub template for each of the elements. This pattern has been implemented as a single method that
-
# accepts an array and renders a partial by the same name as the elements contained within. So the three-lined
-
# example in "Using partials" can be rewritten with a single line:
-
#
-
# <%= render partial: "ad", collection: @advertisements %>
-
#
-
# This will render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. An
-
# iteration object will automatically be made available to the template with a name of the form
-
# +partial_name_iteration+. The iteration object has knowledge about which index the current object has in
-
# the collection and the total size of the collection. The iteration object also has two convenience methods,
-
# +first?+ and +last?+. In the case of the example above, the template would be fed +ad_iteration+.
-
# For backwards compatibility the +partial_name_counter+ is still present and is mapped to the iteration's
-
# +index+ method.
-
#
-
# The <tt>:as</tt> option may be used when rendering partials.
-
#
-
# You can specify a partial to be rendered between elements via the <tt>:spacer_template</tt> option.
-
# The following example will render <tt>advertiser/_ad_divider.html.erb</tt> between each ad partial:
-
#
-
# <%= render partial: "ad", collection: @advertisements, spacer_template: "ad_divider" %>
-
#
-
# If the given <tt>:collection</tt> is nil or empty, <tt>render</tt> will return nil. This will allow you
-
# to specify a text which will displayed instead by using this form:
-
#
-
# <%= render(partial: "ad", collection: @advertisements) || "There's no ad to be displayed" %>
-
#
-
# NOTE: Due to backwards compatibility concerns, the collection can't be one of hashes. Normally you'd also
-
# just keep domain objects, like Active Records, in there.
-
#
-
# == Rendering shared partials
-
#
-
# Two controllers can share a set of partials and render them like this:
-
#
-
# <%= render partial: "advertisement/ad", locals: { ad: @advertisement } %>
-
#
-
# This will render the partial "advertisement/_ad.html.erb" regardless of which controller this is being called from.
-
#
-
# == Rendering objects that respond to `to_partial_path`
-
#
-
# Instead of explicitly naming the location of a partial, you can also let PartialRenderer do the work
-
# and pick the proper path by checking `to_partial_path` method.
-
#
-
# # @account.to_partial_path returns 'accounts/account', so it can be used to replace:
-
# # <%= render partial: "accounts/account", locals: { account: @account} %>
-
# <%= render partial: @account %>
-
#
-
# # @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
-
# # that's why we can replace:
-
# # <%= render partial: "posts/post", collection: @posts %>
-
# <%= render partial: @posts %>
-
#
-
# == Rendering the default case
-
#
-
# If you're not going to be using any of the options like collections or layouts, you can also use the short-hand
-
# defaults of render to render partials. Examples:
-
#
-
# # Instead of <%= render partial: "account" %>
-
# <%= render "account" %>
-
#
-
# # Instead of <%= render partial: "account", locals: { account: @buyer } %>
-
# <%= render "account", account: @buyer %>
-
#
-
# # @account.to_partial_path returns 'accounts/account', so it can be used to replace:
-
# # <%= render partial: "accounts/account", locals: { account: @account} %>
-
# <%= render @account %>
-
#
-
# # @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
-
# # that's why we can replace:
-
# # <%= render partial: "posts/post", collection: @posts %>
-
# <%= render @posts %>
-
#
-
# == Rendering partials with layouts
-
#
-
# Partials can have their own layouts applied to them. These layouts are different than the ones that are
-
# specified globally for the entire action, but they work in a similar fashion. Imagine a list with two types
-
# of users:
-
#
-
# <%# app/views/users/index.html.erb &>
-
# Here's the administrator:
-
# <%= render partial: "user", layout: "administrator", locals: { user: administrator } %>
-
#
-
# Here's the editor:
-
# <%= render partial: "user", layout: "editor", locals: { user: editor } %>
-
#
-
# <%# app/views/users/_user.html.erb &>
-
# Name: <%= user.name %>
-
#
-
# <%# app/views/users/_administrator.html.erb &>
-
# <div id="administrator">
-
# Budget: $<%= user.budget %>
-
# <%= yield %>
-
# </div>
-
#
-
# <%# app/views/users/_editor.html.erb &>
-
# <div id="editor">
-
# Deadline: <%= user.deadline %>
-
# <%= yield %>
-
# </div>
-
#
-
# ...this will return:
-
#
-
# Here's the administrator:
-
# <div id="administrator">
-
# Budget: $<%= user.budget %>
-
# Name: <%= user.name %>
-
# </div>
-
#
-
# Here's the editor:
-
# <div id="editor">
-
# Deadline: <%= user.deadline %>
-
# Name: <%= user.name %>
-
# </div>
-
#
-
# If a collection is given, the layout will be rendered once for each item in
-
# the collection. For example, these two snippets have the same output:
-
#
-
# <%# app/views/users/_user.html.erb %>
-
# Name: <%= user.name %>
-
#
-
# <%# app/views/users/index.html.erb %>
-
# <%# This does not use layouts %>
-
# <ul>
-
# <% users.each do |user| -%>
-
# <li>
-
# <%= render partial: "user", locals: { user: user } %>
-
# </li>
-
# <% end -%>
-
# </ul>
-
#
-
# <%# app/views/users/_li_layout.html.erb %>
-
# <li>
-
# <%= yield %>
-
# </li>
-
#
-
# <%# app/views/users/index.html.erb %>
-
# <ul>
-
# <%= render partial: "user", layout: "li_layout", collection: users %>
-
# </ul>
-
#
-
# Given two users whose names are Alice and Bob, these snippets return:
-
#
-
# <ul>
-
# <li>
-
# Name: Alice
-
# </li>
-
# <li>
-
# Name: Bob
-
# </li>
-
# </ul>
-
#
-
# The current object being rendered, as well as the object_counter, will be
-
# available as local variables inside the layout template under the same names
-
# as available in the partial.
-
#
-
# You can also apply a layout to a block within any template:
-
#
-
# <%# app/views/users/_chief.html.erb &>
-
# <%= render(layout: "administrator", locals: { user: chief }) do %>
-
# Title: <%= chief.title %>
-
# <% end %>
-
#
-
# ...this will return:
-
#
-
# <div id="administrator">
-
# Budget: $<%= user.budget %>
-
# Title: <%= chief.name %>
-
# </div>
-
#
-
# As you can see, the <tt>:locals</tt> hash is shared between both the partial and its layout.
-
#
-
# If you pass arguments to "yield" then this will be passed to the block. One way to use this is to pass
-
# an array to layout and treat it as an enumerable.
-
#
-
# <%# app/views/users/_user.html.erb &>
-
# <div class="user">
-
# Budget: $<%= user.budget %>
-
# <%= yield user %>
-
# </div>
-
#
-
# <%# app/views/users/index.html.erb &>
-
# <%= render layout: @users do |user| %>
-
# Title: <%= user.title %>
-
# <% end %>
-
#
-
# This will render the layout for each user and yield to the block, passing the user, each time.
-
#
-
# You can also yield multiple times in one layout and use block arguments to differentiate the sections.
-
#
-
# <%# app/views/users/_user.html.erb &>
-
# <div class="user">
-
# <%= yield user, :header %>
-
# Budget: $<%= user.budget %>
-
# <%= yield user, :footer %>
-
# </div>
-
#
-
# <%# app/views/users/index.html.erb &>
-
# <%= render layout: @users do |user, section| %>
-
# <%- case section when :header -%>
-
# Title: <%= user.title %>
-
# <%- when :footer -%>
-
# Deadline: <%= user.deadline %>
-
# <%- end -%>
-
# <% end %>
-
1
class PartialRenderer < AbstractRenderer
-
1
PREFIXED_PARTIAL_NAMES = ThreadSafe::Cache.new do |h, k|
-
h[k] = ThreadSafe::Cache.new
-
end
-
-
1
def initialize(*)
-
8
super
-
8
@context_prefix = @lookup_context.prefixes.first
-
end
-
-
1
def render(context, options, block)
-
8
setup(context, options, block)
-
8
identifier = (@template = find_partial) ? @template.identifier : @path
-
-
8
@lookup_context.rendered_format ||= begin
-
if @template && @template.formats.present?
-
@template.formats.first
-
else
-
formats.first
-
end
-
end
-
-
8
if @collection
-
instrument(:collection, :identifier => identifier || "collection", :count => @collection.size) do
-
render_collection
-
end
-
else
-
8
instrument(:partial, :identifier => identifier) do
-
8
render_partial
-
end
-
end
-
end
-
-
1
private
-
-
1
def render_collection
-
return nil if @collection.blank?
-
-
if @options.key?(:spacer_template)
-
spacer = find_template(@options[:spacer_template], @locals.keys).render(@view, @locals)
-
end
-
-
result = @template ? collection_with_template : collection_without_template
-
result.join(spacer).html_safe
-
end
-
-
1
def render_partial
-
8
view, locals, block = @view, @locals, @block
-
8
object, as = @object, @variable
-
-
8
if !block && (layout = @options[:layout])
-
layout = find_template(layout.to_s, @template_keys)
-
end
-
-
8
object ||= locals[as]
-
8
locals[as] = object
-
-
8
content = @template.render(view, locals) do |*name|
-
view._layout_for(*name, &block)
-
end
-
-
8
content = layout.render(view, locals){ content } if layout
-
8
content
-
end
-
-
1
private
-
-
# Sets up instance variables needed for rendering a partial. This method
-
# finds the options and details and extracts them. The method also contains
-
# logic that handles the type of object passed in as the partial.
-
#
-
# If +options[:partial]+ is a string, then the +@path+ instance variable is
-
# set to that string. Otherwise, the +options[:partial]+ object must
-
# respond to +to_partial_path+ in order to setup the path.
-
1
def setup(context, options, block)
-
8
@view = context
-
8
@options = options
-
8
@block = block
-
-
8
@locals = options[:locals] || {}
-
8
@details = extract_details(options)
-
-
8
prepend_formats(options[:formats])
-
-
8
partial = options[:partial]
-
-
8
if String === partial
-
8
@has_object = options.key?(:object)
-
8
@object = options[:object]
-
8
@collection = collection_from_options
-
8
@path = partial
-
else
-
@has_object = true
-
@object = partial
-
@collection = collection_from_object || collection_from_options
-
-
if @collection
-
paths = @collection_data = @collection.map { |o| partial_path(o) }
-
@path = paths.uniq.one? ? paths.first : nil
-
else
-
@path = partial_path
-
end
-
end
-
-
8
if as = options[:as]
-
raise_invalid_option_as(as) unless as.to_s =~ /\A[a-z_]\w*\z/
-
as = as.to_sym
-
end
-
-
8
if @path
-
8
@variable, @variable_counter, @variable_iteration = retrieve_variable(@path, as)
-
8
@template_keys = retrieve_template_keys
-
else
-
paths.map! { |path| retrieve_variable(path, as).unshift(path) }
-
end
-
-
8
self
-
end
-
-
1
def collection_from_options
-
8
if @options.key?(:collection)
-
collection = @options[:collection]
-
collection.respond_to?(:to_ary) ? collection.to_ary : []
-
end
-
end
-
-
1
def collection_from_object
-
@object.to_ary if @object.respond_to?(:to_ary)
-
end
-
-
1
def find_partial
-
8
find_template(@path, @template_keys) if @path
-
end
-
-
1
def find_template(path, locals)
-
8
prefixes = path.include?(?/) ? [] : @lookup_context.prefixes
-
8
@lookup_context.find_template(path, prefixes, true, locals, @details)
-
end
-
-
1
def collection_with_template
-
view, locals, template = @view, @locals, @template
-
as, counter, iteration = @variable, @variable_counter, @variable_iteration
-
-
if layout = @options[:layout]
-
layout = find_template(layout, @template_keys)
-
end
-
-
partial_iteration = PartialIteration.new(@collection.size)
-
locals[iteration] = partial_iteration
-
-
@collection.map do |object|
-
locals[as] = object
-
locals[counter] = partial_iteration.index
-
-
content = template.render(view, locals)
-
content = layout.render(view, locals) { content } if layout
-
partial_iteration.iterate!
-
content
-
end
-
end
-
-
1
def collection_without_template
-
view, locals, collection_data = @view, @locals, @collection_data
-
cache = {}
-
keys = @locals.keys
-
-
partial_iteration = PartialIteration.new(@collection.size)
-
-
@collection.map do |object|
-
index = partial_iteration.index
-
path, as, counter, iteration = collection_data[index]
-
-
locals[as] = object
-
locals[counter] = index
-
locals[iteration] = partial_iteration
-
-
template = (cache[path] ||= find_template(path, keys + [as, counter]))
-
content = template.render(view, locals)
-
partial_iteration.iterate!
-
content
-
end
-
end
-
-
# Obtains the path to where the object's partial is located. If the object
-
# responds to +to_partial_path+, then +to_partial_path+ will be called and
-
# will provide the path. If the object does not respond to +to_partial_path+,
-
# then an +ArgumentError+ is raised.
-
#
-
# If +prefix_partial_path_with_controller_namespace+ is true, then this
-
# method will prefix the partial paths with a namespace.
-
1
def partial_path(object = @object)
-
object = object.to_model if object.respond_to?(:to_model)
-
-
path = if object.respond_to?(:to_partial_path)
-
object.to_partial_path
-
else
-
raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.")
-
end
-
-
if @view.prefix_partial_path_with_controller_namespace
-
prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup)
-
else
-
path
-
end
-
end
-
-
1
def prefixed_partial_names
-
@prefixed_partial_names ||= PREFIXED_PARTIAL_NAMES[@context_prefix]
-
end
-
-
1
def merge_prefix_into_object_path(prefix, object_path)
-
if prefix.include?(?/) && object_path.include?(?/)
-
prefixes = []
-
prefix_array = File.dirname(prefix).split('/')
-
object_path_array = object_path.split('/')[0..-3] # skip model dir & partial
-
-
prefix_array.each_with_index do |dir, index|
-
break if dir == object_path_array[index]
-
prefixes << dir
-
end
-
-
(prefixes << object_path).join("/")
-
else
-
object_path
-
end
-
end
-
-
1
def retrieve_template_keys
-
8
keys = @locals.keys
-
8
keys << @variable if @has_object || @collection
-
8
if @collection
-
keys << @variable_counter
-
keys << @variable_iteration
-
end
-
8
keys
-
end
-
-
1
def retrieve_variable(path, as)
-
8
variable = as || begin
-
8
base = path[-1] == "/" ? "" : File.basename(path)
-
8
raise_invalid_identifier(path) unless base =~ /\A_?([a-z]\w*)(\.\w+)*\z/
-
8
$1.to_sym
-
end
-
8
if @collection
-
variable_counter = :"#{variable}_counter"
-
variable_iteration = :"#{variable}_iteration"
-
end
-
8
[variable, variable_counter, variable_iteration]
-
end
-
-
1
IDENTIFIER_ERROR_MESSAGE = "The partial name (%s) is not a valid Ruby identifier; " +
-
"make sure your partial name starts with underscore, " +
-
"and is followed by any combination of letters, numbers and underscores."
-
-
1
OPTION_AS_ERROR_MESSAGE = "The value (%s) of the option `as` is not a valid Ruby identifier; " +
-
"make sure it starts with lowercase letter, " +
-
"and is followed by any combination of letters, numbers and underscores."
-
-
1
def raise_invalid_identifier(path)
-
raise ArgumentError.new(IDENTIFIER_ERROR_MESSAGE % (path))
-
end
-
-
1
def raise_invalid_option_as(as)
-
raise ArgumentError.new(OPTION_AS_ERROR_MESSAGE % (as))
-
end
-
end
-
end
-
1
module ActionView
-
# This is the main entry point for rendering. It basically delegates
-
# to other objects like TemplateRenderer and PartialRenderer which
-
# actually renders the template.
-
#
-
# The Renderer will parse the options from the +render+ or +render_body+
-
# method and render a partial or a template based on the options. The
-
# +TemplateRenderer+ and +PartialRenderer+ objects are wrappers which do all
-
# the setup and logic necessary to render a view and a new object is created
-
# each time +render+ is called.
-
1
class Renderer
-
1
attr_accessor :lookup_context
-
-
1
def initialize(lookup_context)
-
55
@lookup_context = lookup_context
-
end
-
-
# Main render entry point shared by AV and AC.
-
1
def render(context, options)
-
55
if options.key?(:partial)
-
render_partial(context, options)
-
else
-
55
render_template(context, options)
-
end
-
end
-
-
# Render but returns a valid Rack body. If fibers are defined, we return
-
# a streaming body that renders the template piece by piece.
-
#
-
# Note that partials are not supported to be rendered with streaming,
-
# so in such cases, we just wrap them in an array.
-
1
def render_body(context, options)
-
if options.key?(:partial)
-
[render_partial(context, options)]
-
else
-
StreamingTemplateRenderer.new(@lookup_context).render(context, options)
-
end
-
end
-
-
# Direct accessor to template rendering.
-
1
def render_template(context, options) #:nodoc:
-
55
TemplateRenderer.new(@lookup_context).render(context, options)
-
end
-
-
# Direct access to partial rendering.
-
1
def render_partial(context, options, &block) #:nodoc:
-
8
PartialRenderer.new(@lookup_context).render(context, options, block)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/try'
-
-
1
module ActionView
-
1
class TemplateRenderer < AbstractRenderer #:nodoc:
-
1
def render(context, options)
-
55
@view = context
-
55
@details = extract_details(options)
-
55
template = determine_template(options)
-
-
55
prepend_formats(template.formats)
-
-
55
@lookup_context.rendered_format ||= (template.formats.first || formats.first)
-
-
55
render_template(template, options[:layout], options[:locals])
-
end
-
-
1
private
-
-
# Determine the template to be rendered using the given options.
-
1
def determine_template(options)
-
55
keys = options.has_key?(:locals) ? options[:locals].keys : []
-
-
55
if options.key?(:body)
-
Template::Text.new(options[:body])
-
55
elsif options.key?(:text)
-
Template::Text.new(options[:text], formats.first)
-
55
elsif options.key?(:plain)
-
Template::Text.new(options[:plain])
-
55
elsif options.key?(:html)
-
Template::HTML.new(options[:html], formats.first)
-
55
elsif options.key?(:file)
-
with_fallbacks { find_template(options[:file], nil, false, keys, @details) }
-
55
elsif options.key?(:inline)
-
handler = Template.handler_for_extension(options[:type] || "erb")
-
Template.new(options[:inline], "inline template", handler, :locals => keys)
-
55
elsif options.key?(:template)
-
55
if options[:template].respond_to?(:render)
-
options[:template]
-
else
-
55
find_template(options[:template], options[:prefixes], false, keys, @details)
-
end
-
else
-
raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :text or :body option."
-
end
-
end
-
-
# Renders the given template. A string representing the layout can be
-
# supplied as well.
-
1
def render_template(template, layout_name = nil, locals = nil) #:nodoc:
-
55
view, locals = @view, locals || {}
-
-
55
render_with_layout(layout_name, locals) do |layout|
-
55
instrument(:template, :identifier => template.identifier, :layout => layout.try(:virtual_path)) do
-
55
template.render(view, locals) { |*name| view._layout_for(*name) }
-
end
-
end
-
end
-
-
1
def render_with_layout(path, locals) #:nodoc:
-
55
layout = path && find_layout(path, locals.keys)
-
55
content = yield(layout)
-
-
55
if layout
-
55
view = @view
-
55
view.view_flow.set(:layout, content)
-
110
layout.render(view, locals){ |*name| view._layout_for(*name) }
-
else
-
content
-
end
-
end
-
-
# This is the method which actually finds the layout using details in the lookup
-
# context object. If no layout is found, it checks if at least a layout with
-
# the given name exists across all details before raising the error.
-
1
def find_layout(layout, keys)
-
110
with_layout_format { resolve_layout(layout, keys) }
-
end
-
-
1
def resolve_layout(layout, keys)
-
110
case layout
-
when String
-
begin
-
if layout =~ /^\//
-
with_fallbacks { find_template(layout, nil, false, keys, @details) }
-
else
-
find_template(layout, nil, false, keys, @details)
-
end
-
rescue ActionView::MissingTemplate
-
all_details = @details.merge(:formats => @lookup_context.default_formats)
-
raise unless template_exists?(layout, nil, false, keys, all_details)
-
end
-
when Proc
-
55
resolve_layout(layout.call, keys)
-
when FalseClass
-
nil
-
else
-
55
layout
-
end
-
end
-
end
-
end
-
1
require "action_view/view_paths"
-
-
1
module ActionView
-
# This is a class to fix I18n global state. Whenever you provide I18n.locale during a request,
-
# it will trigger the lookup_context and consequently expire the cache.
-
1
class I18nProxy < ::I18n::Config #:nodoc:
-
1
attr_reader :original_config, :lookup_context
-
-
1
def initialize(original_config, lookup_context)
-
66
original_config = original_config.original_config if original_config.respond_to?(:original_config)
-
66
@original_config, @lookup_context = original_config, lookup_context
-
end
-
-
1
def locale
-
20
@original_config.locale
-
end
-
-
1
def locale=(value)
-
@lookup_context.locale = value
-
end
-
end
-
-
1
module Rendering
-
1
extend ActiveSupport::Concern
-
1
include ActionView::ViewPaths
-
-
# Overwrite process to setup I18n proxy.
-
1
def process(*) #:nodoc:
-
66
old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context)
-
66
super
-
ensure
-
66
I18n.config = old_config
-
end
-
-
1
module ClassMethods
-
1
def view_context_class
-
@view_context_class ||= begin
-
5
supports_path = supports_path?
-
5
routes = respond_to?(:_routes) && _routes
-
5
helpers = respond_to?(:_helpers) && _helpers
-
-
5
Class.new(ActionView::Base) do
-
5
if routes
-
5
include routes.url_helpers(supports_path)
-
5
include routes.mounted_helpers
-
end
-
-
5
if helpers
-
5
include helpers
-
end
-
end
-
55
end
-
end
-
end
-
-
1
attr_internal_writer :view_context_class
-
-
1
def view_context_class
-
55
@_view_context_class ||= self.class.view_context_class
-
end
-
-
# An instance of a view class. The default view class is ActionView::Base
-
#
-
# The view class must have the following methods:
-
# View.new[lookup_context, assigns, controller]
-
# Create a new ActionView instance for a controller and we can also pass the arguments.
-
# View#render(option)
-
# Returns String with the rendered template
-
#
-
# Override this method in a module to change the default behavior.
-
1
def view_context
-
55
view_context_class.new(view_renderer, view_assigns, self)
-
end
-
-
# Returns an object that is able to render templates.
-
# :api: private
-
1
def view_renderer
-
110
@_view_renderer ||= ActionView::Renderer.new(lookup_context)
-
end
-
-
1
def render_to_body(options = {})
-
55
_process_options(options)
-
55
_render_template(options)
-
end
-
-
1
def rendered_format
-
110
Mime[lookup_context.rendered_format]
-
end
-
-
1
private
-
-
# Find and render a template based on the options given.
-
# :api: private
-
1
def _render_template(options) #:nodoc:
-
55
variant = options[:variant]
-
-
55
lookup_context.rendered_format = nil if options[:formats]
-
55
lookup_context.variants = variant if variant
-
-
55
view_renderer.render(view_context, options)
-
end
-
-
# Assign the rendered format to lookup context.
-
1
def _process_format(format, options = {}) #:nodoc:
-
58
super
-
58
lookup_context.formats = [format.to_sym]
-
58
lookup_context.rendered_format = lookup_context.formats.first
-
end
-
-
# Normalize args by converting render "foo" to render :action => "foo" and
-
# render "foo/bar" to render :template => "foo/bar".
-
# :api: private
-
1
def _normalize_args(action=nil, options={})
-
55
options = super(action, options)
-
55
case action
-
when NilClass
-
when Hash
-
options = action
-
when String, Symbol
-
action = action.to_s
-
key = action.include?(?/) ? :template : :action
-
options[key] = action
-
else
-
options[:partial] = action
-
end
-
-
55
options
-
end
-
-
# Normalize options.
-
# :api: private
-
1
def _normalize_options(options)
-
55
options = super(options)
-
55
if options[:partial] == true
-
options[:partial] = action_name
-
end
-
-
55
if (options.keys & [:partial, :file, :template]).empty?
-
55
options[:prefixes] ||= _prefixes
-
end
-
-
55
options[:template] ||= (options[:action] || action_name).to_s
-
55
options
-
end
-
end
-
end
-
1
require 'action_dispatch/routing/polymorphic_routes'
-
-
1
module ActionView
-
1
module RoutingUrlFor
-
-
# Returns the URL for the set of +options+ provided. This takes the
-
# same options as +url_for+ in Action Controller (see the
-
# documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
-
# <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
-
# instead of the fully qualified URL like "http://example.com/controller/action".
-
#
-
# ==== Options
-
# * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path.
-
# * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified).
-
# * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this
-
# is currently not recommended since it breaks caching.
-
# * <tt>:host</tt> - Overrides the default (current) host if provided.
-
# * <tt>:protocol</tt> - Overrides the default (current) protocol if provided.
-
# * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
-
# * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
-
#
-
# ==== Relying on named routes
-
#
-
# Passing a record (like an Active Record) instead of a hash as the options parameter will
-
# trigger the named route for that record. The lookup will happen on the name of the class. So passing a
-
# Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
-
# +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
-
#
-
# ==== Implicit Controller Namespacing
-
#
-
# Controllers passed in using the +:controller+ option will retain their namespace unless it is an absolute one.
-
#
-
# ==== Examples
-
# <%= url_for(action: 'index') %>
-
# # => /blog/
-
#
-
# <%= url_for(action: 'find', controller: 'books') %>
-
# # => /books/find
-
#
-
# <%= url_for(action: 'login', controller: 'members', only_path: false, protocol: 'https') %>
-
# # => https://www.example.com/members/login/
-
#
-
# <%= url_for(action: 'play', anchor: 'player') %>
-
# # => /messages/play/#player
-
#
-
# <%= url_for(action: 'jump', anchor: 'tax&ship') %>
-
# # => /testing/jump/#tax&ship
-
#
-
# <%= url_for(Workshop.new) %>
-
# # relies on Workshop answering a persisted? call (and in this case returning false)
-
# # => /workshops
-
#
-
# <%= url_for(@workshop) %>
-
# # calls @workshop.to_param which by default returns the id
-
# # => /workshops/5
-
#
-
# # to_param can be re-defined in a model to provide different URL names:
-
# # => /workshops/1-workshop-name
-
#
-
# <%= url_for("http://www.example.com") %>
-
# # => http://www.example.com
-
#
-
# <%= url_for(:back) %>
-
# # if request.env["HTTP_REFERER"] is set to "http://www.example.com"
-
# # => http://www.example.com
-
#
-
# <%= url_for(:back) %>
-
# # if request.env["HTTP_REFERER"] is not set or is blank
-
# # => javascript:history.back()
-
#
-
# <%= url_for(action: 'index', controller: 'users') %>
-
# # Assuming an "admin" namespace
-
# # => /admin/users
-
#
-
# <%= url_for(action: 'index', controller: '/users') %>
-
# # Specify absolute path with beginning slash
-
# # => /users
-
1
def url_for(options = nil)
-
265
case options
-
when String
-
107
options
-
when nil
-
super(only_path: _generate_paths_by_default)
-
when Hash
-
147
options = options.symbolize_keys
-
147
unless options.key?(:only_path)
-
147
if options[:host].nil?
-
147
options[:only_path] = _generate_paths_by_default
-
else
-
options[:only_path] = false
-
end
-
end
-
-
147
super(options)
-
when :back
-
_back_url
-
when Array
-
components = options.dup
-
if _generate_paths_by_default
-
polymorphic_path(components, components.extract_options!)
-
else
-
polymorphic_url(components, components.extract_options!)
-
end
-
else
-
11
method = _generate_paths_by_default ? :path : :url
-
11
builder = ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.send(method)
-
-
11
case options
-
when Symbol
-
builder.handle_string_call(self, options)
-
when Class
-
builder.handle_class_call(self, options)
-
else
-
11
builder.handle_model_call(self, options)
-
end
-
end
-
end
-
-
1
def url_options #:nodoc:
-
265
return super unless controller.respond_to?(:url_options)
-
265
controller.url_options
-
end
-
-
1
def _routes_context #:nodoc:
-
controller
-
end
-
1
protected :_routes_context
-
-
1
def optimize_routes_generation? #:nodoc:
-
117
controller.respond_to?(:optimize_routes_generation?, true) ?
-
controller.optimize_routes_generation? : super
-
end
-
1
protected :optimize_routes_generation?
-
end
-
end
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'thread'
-
-
1
module ActionView
-
# = Action View Template
-
1
class Template
-
1
extend ActiveSupport::Autoload
-
-
# === Encodings in ActionView::Template
-
#
-
# ActionView::Template is one of a few sources of potential
-
# encoding issues in Rails. This is because the source for
-
# templates are usually read from disk, and Ruby (like most
-
# encoding-aware programming languages) assumes that the
-
# String retrieved through File IO is encoded in the
-
# <tt>default_external</tt> encoding. In Rails, the default
-
# <tt>default_external</tt> encoding is UTF-8.
-
#
-
# As a result, if a user saves their template as ISO-8859-1
-
# (for instance, using a non-Unicode-aware text editor),
-
# and uses characters outside of the ASCII range, their
-
# users will see diamonds with question marks in them in
-
# the browser.
-
#
-
# For the rest of this documentation, when we say "UTF-8",
-
# we mean "UTF-8 or whatever the default_internal encoding
-
# is set to". By default, it will be UTF-8.
-
#
-
# To mitigate this problem, we use a few strategies:
-
# 1. If the source is not valid UTF-8, we raise an exception
-
# when the template is compiled to alert the user
-
# to the problem.
-
# 2. The user can specify the encoding using Ruby-style
-
# encoding comments in any template engine. If such
-
# a comment is supplied, Rails will apply that encoding
-
# to the resulting compiled source returned by the
-
# template handler.
-
# 3. In all cases, we transcode the resulting String to
-
# the UTF-8.
-
#
-
# This means that other parts of Rails can always assume
-
# that templates are encoded in UTF-8, even if the original
-
# source of the template was not UTF-8.
-
#
-
# From a user's perspective, the easiest thing to do is
-
# to save your templates as UTF-8. If you do this, you
-
# do not need to do anything else for things to "just work".
-
#
-
# === Instructions for template handlers
-
#
-
# The easiest thing for you to do is to simply ignore
-
# encodings. Rails will hand you the template source
-
# as the default_internal (generally UTF-8), raising
-
# an exception for the user before sending the template
-
# to you if it could not determine the original encoding.
-
#
-
# For the greatest simplicity, you can support only
-
# UTF-8 as the <tt>default_internal</tt>. This means
-
# that from the perspective of your handler, the
-
# entire pipeline is just UTF-8.
-
#
-
# === Advanced: Handlers with alternate metadata sources
-
#
-
# If you want to provide an alternate mechanism for
-
# specifying encodings (like ERB does via <%# encoding: ... %>),
-
# you may indicate that you will handle encodings yourself
-
# by implementing <tt>self.handles_encoding?</tt>
-
# on your handler.
-
#
-
# If you do, Rails will not try to encode the String
-
# into the default_internal, passing you the unaltered
-
# bytes tagged with the assumed encoding (from
-
# default_external).
-
#
-
# In this case, make sure you return a String from
-
# your handler encoded in the default_internal. Since
-
# you are handling out-of-band metadata, you are
-
# also responsible for alerting the user to any
-
# problems with converting the user's data to
-
# the <tt>default_internal</tt>.
-
#
-
# To do so, simply raise +WrongEncodingError+ as follows:
-
#
-
# raise WrongEncodingError.new(
-
# problematic_string,
-
# expected_encoding
-
# )
-
-
1
eager_autoload do
-
1
autoload :Error
-
1
autoload :Handlers
-
1
autoload :HTML
-
1
autoload :Text
-
1
autoload :Types
-
end
-
-
1
extend Template::Handlers
-
-
1
attr_accessor :locals, :formats, :variants, :virtual_path
-
-
1
attr_reader :source, :identifier, :handler, :original_encoding, :updated_at
-
-
# This finalizer is needed (and exactly with a proc inside another proc)
-
# otherwise templates leak in development.
-
1
Finalizer = proc do |method_name, mod|
-
22
proc do
-
mod.module_eval do
-
remove_possible_method method_name
-
end
-
end
-
end
-
-
1
def initialize(source, identifier, handler, details)
-
22
format = details[:format] || (handler.default_format if handler.respond_to?(:default_format))
-
-
22
@source = source
-
22
@identifier = identifier
-
22
@handler = handler
-
22
@compiled = false
-
22
@original_encoding = nil
-
22
@locals = details[:locals] || []
-
22
@virtual_path = details[:virtual_path]
-
22
@updated_at = details[:updated_at] || Time.now
-
44
@formats = Array(format).map { |f| f.respond_to?(:ref) ? f.ref : f }
-
22
@variants = [details[:variant]]
-
22
@compile_mutex = Mutex.new
-
end
-
-
# Returns if the underlying handler supports streaming. If so,
-
# a streaming buffer *may* be passed when it start rendering.
-
1
def supports_streaming?
-
handler.respond_to?(:supports_streaming?) && handler.supports_streaming?
-
end
-
-
# Render a template. If the template was not compiled yet, it is done
-
# exactly before rendering.
-
#
-
# This method is instrumented as "!render_template.action_view". Notice that
-
# we use a bang in this instrumentation because you don't want to
-
# consume this in production. This is only slow if it's being listened to.
-
1
def render(view, locals, buffer=nil, &block)
-
118
instrument("!render_template") do
-
118
compile!(view)
-
118
view.send(method_name, locals, buffer, &block)
-
end
-
rescue => e
-
handle_render_error(view, e)
-
end
-
-
1
def type
-
22
@type ||= Types[@formats.first] if @formats.first
-
end
-
-
# Receives a view object and return a template similar to self by using @virtual_path.
-
#
-
# This method is useful if you have a template object but it does not contain its source
-
# anymore since it was already compiled. In such cases, all you need to do is to call
-
# refresh passing in the view object.
-
#
-
# Notice this method raises an error if the template to be refreshed does not have a
-
# virtual path set (true just for inline templates).
-
1
def refresh(view)
-
raise "A template needs to have a virtual path in order to be refreshed" unless @virtual_path
-
lookup = view.lookup_context
-
pieces = @virtual_path.split("/")
-
name = pieces.pop
-
partial = !!name.sub!(/^_/, "")
-
lookup.disable_cache do
-
lookup.find_template(name, [ pieces.join('/') ], partial, @locals)
-
end
-
end
-
-
1
def inspect
-
22
@inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", '') : identifier
-
end
-
-
# This method is responsible for properly setting the encoding of the
-
# source. Until this point, we assume that the source is BINARY data.
-
# If no additional information is supplied, we assume the encoding is
-
# the same as <tt>Encoding.default_external</tt>.
-
#
-
# The user can also specify the encoding via a comment on the first
-
# line of the template (# encoding: NAME-OF-ENCODING). This will work
-
# with any template engine, as we process out the encoding comment
-
# before passing the source on to the template engine, leaving a
-
# blank line in its stead.
-
1
def encode!
-
22
return unless source.encoding == Encoding::BINARY
-
-
# Look for # encoding: *. If we find one, we'll encode the
-
# String in that encoding, otherwise, we'll use the
-
# default external encoding.
-
22
if source.sub!(/\A#{ENCODING_FLAG}/, '')
-
encoding = magic_encoding = $1
-
else
-
22
encoding = Encoding.default_external
-
end
-
-
# Tag the source with the default external encoding
-
# or the encoding specified in the file
-
22
source.force_encoding(encoding)
-
-
# If the user didn't specify an encoding, and the handler
-
# handles encodings, we simply pass the String as is to
-
# the handler (with the default_external tag)
-
22
if !magic_encoding && @handler.respond_to?(:handles_encoding?) && @handler.handles_encoding?
-
source
-
# Otherwise, if the String is valid in the encoding,
-
# encode immediately to default_internal. This means
-
# that if a handler doesn't handle encodings, it will
-
# always get Strings in the default_internal
-
22
elsif source.valid_encoding?
-
22
source.encode!
-
# Otherwise, since the String is invalid in the encoding
-
# specified, raise an exception
-
else
-
raise WrongEncodingError.new(source, encoding)
-
end
-
end
-
-
1
protected
-
-
# Compile a template. This method ensures a template is compiled
-
# just once and removes the source after it is compiled.
-
1
def compile!(view) #:nodoc:
-
118
return if @compiled
-
-
# Templates can be used concurrently in threaded environments
-
# so compilation and any instance variable modification must
-
# be synchronized
-
22
@compile_mutex.synchronize do
-
# Any thread holding this lock will be compiling the template needed
-
# by the threads waiting. So re-check the @compiled flag to avoid
-
# re-compilation
-
22
return if @compiled
-
-
22
if view.is_a?(ActionView::CompiledTemplates)
-
22
mod = ActionView::CompiledTemplates
-
else
-
mod = view.singleton_class
-
end
-
-
22
instrument("!compile_template") do
-
22
compile(mod)
-
end
-
-
# Just discard the source if we have a virtual path. This
-
# means we can get the template back.
-
22
@source = nil if @virtual_path
-
22
@compiled = true
-
end
-
end
-
-
# Among other things, this method is responsible for properly setting
-
# the encoding of the compiled template.
-
#
-
# If the template engine handles encodings, we send the encoded
-
# String to the engine without further processing. This allows
-
# the template engine to support additional mechanisms for
-
# specifying the encoding. For instance, ERB supports <%# encoding: %>
-
#
-
# Otherwise, after we figure out the correct encoding, we then
-
# encode the source into <tt>Encoding.default_internal</tt>.
-
# In general, this means that templates will be UTF-8 inside of Rails,
-
# regardless of the original source encoding.
-
1
def compile(mod) #:nodoc:
-
22
encode!
-
22
method_name = self.method_name
-
22
code = @handler.call(self)
-
-
# Make sure that the resulting String to be eval'd is in the
-
# encoding of the code
-
22
source = <<-end_src
-
def #{method_name}(local_assigns, output_buffer)
-
_old_virtual_path, @virtual_path = @virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code}
-
ensure
-
@virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer
-
end
-
end_src
-
-
# Make sure the source is in the encoding of the returned code
-
22
source.force_encoding(code.encoding)
-
-
# In case we get back a String from a handler that is not in
-
# BINARY or the default_internal, encode it to the default_internal
-
22
source.encode!
-
-
# Now, validate that the source we got back from the template
-
# handler is valid in the default_internal. This is for handlers
-
# that handle encoding but screw up
-
22
unless source.valid_encoding?
-
raise WrongEncodingError.new(@source, Encoding.default_internal)
-
end
-
-
22
mod.module_eval(source, identifier, 0)
-
22
ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
-
end
-
-
1
def handle_render_error(view, e) #:nodoc:
-
if e.is_a?(Template::Error)
-
e.sub_template_of(self)
-
raise e
-
else
-
template = self
-
unless template.source
-
template = refresh(view)
-
template.encode!
-
end
-
raise Template::Error.new(template, e)
-
end
-
end
-
-
1
def locals_code #:nodoc:
-
# Double assign to suppress the dreaded 'assigned but unused variable' warning
-
22
@locals.each_with_object('') { |key, code| code << "#{key} = #{key} = local_assigns[:#{key}];" }
-
end
-
-
1
def method_name #:nodoc:
-
@method_name ||= begin
-
22
m = "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}"
-
22
m.tr!('-', '_')
-
22
m
-
140
end
-
end
-
-
1
def identifier_method_name #:nodoc:
-
22
inspect.tr('^a-z_', '_')
-
end
-
-
1
def instrument(action, &block)
-
140
payload = { virtual_path: @virtual_path, identifier: @identifier }
-
140
ActiveSupport::Notifications.instrument("#{action}.action_view", payload, &block)
-
end
-
end
-
end
-
1
module ActionView #:nodoc:
-
# = Action View Template Handlers
-
1
class Template
-
1
module Handlers #:nodoc:
-
1
autoload :ERB, 'action_view/template/handlers/erb'
-
1
autoload :Builder, 'action_view/template/handlers/builder'
-
1
autoload :Raw, 'action_view/template/handlers/raw'
-
-
1
def self.extended(base)
-
1
base.register_default_template_handler :erb, ERB.new
-
1
base.register_template_handler :builder, Builder.new
-
1
base.register_template_handler :raw, Raw.new
-
1
base.register_template_handler :ruby, :source.to_proc
-
end
-
-
1
@@template_handlers = {}
-
1
@@default_template_handlers = nil
-
-
1
def self.extensions
-
66
@@template_extensions ||= @@template_handlers.keys
-
end
-
-
# Register an object that knows how to handle template files with the given
-
# extensions. This can be used to implement new template types.
-
# The handler must respond to +:call+, which will be passed the template
-
# and should return the rendered template as a String.
-
1
def register_template_handler(*extensions, handler)
-
7
raise(ArgumentError, "Extension is required") if extensions.empty?
-
7
extensions.each do |extension|
-
7
@@template_handlers[extension.to_sym] = handler
-
end
-
7
@@template_extensions = nil
-
end
-
-
# Opposite to register_template_handler.
-
1
def unregister_template_handler(*extensions)
-
extensions.each do |extension|
-
handler = @@template_handlers.delete extension.to_sym
-
@@default_template_handlers = nil if @@default_template_handlers == handler
-
end
-
@@template_extensions = nil
-
end
-
-
1
def template_handler_extensions
-
@@template_handlers.keys.map {|key| key.to_s }.sort
-
end
-
-
1
def registered_template_handler(extension)
-
24
extension && @@template_handlers[extension.to_sym]
-
end
-
-
1
def register_default_template_handler(extension, klass)
-
1
register_template_handler(extension, klass)
-
1
@@default_template_handlers = klass
-
end
-
-
1
def handler_for_extension(extension)
-
24
registered_template_handler(extension) || @@default_template_handlers
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Template::Handlers
-
1
class Builder
-
# Default format used by Builder.
-
1
class_attribute :default_format
-
1
self.default_format = :xml
-
-
1
def call(template)
-
require_engine
-
"xml = ::Builder::XmlMarkup.new(:indent => 2);" +
-
"self.output_buffer = xml.target!;" +
-
template.source +
-
";xml.target!;"
-
end
-
-
1
protected
-
-
1
def require_engine
-
@required ||= begin
-
require "builder"
-
true
-
end
-
end
-
end
-
end
-
end
-
1
require 'erubis'
-
-
1
module ActionView
-
1
class Template
-
1
module Handlers
-
1
class Erubis < ::Erubis::Eruby
-
1
def add_preamble(src)
-
@newline_pending = 0
-
src << "@output_buffer = output_buffer || ActionView::OutputBuffer.new;"
-
end
-
-
1
def add_text(src, text)
-
return if text.empty?
-
-
if text == "\n"
-
@newline_pending += 1
-
else
-
src << "@output_buffer.safe_append='"
-
src << "\n" * @newline_pending if @newline_pending > 0
-
src << escape_text(text)
-
src << "'.freeze;"
-
-
@newline_pending = 0
-
end
-
end
-
-
# Erubis toggles <%= and <%== behavior when escaping is enabled.
-
# We override to always treat <%== as escaped.
-
1
def add_expr(src, code, indicator)
-
case indicator
-
when '=='
-
add_expr_escaped(src, code)
-
else
-
super
-
end
-
end
-
-
1
BLOCK_EXPR = /\s*((\s+|\))do|\{)(\s*\|[^|]*\|)?\s*\Z/
-
-
1
def add_expr_literal(src, code)
-
flush_newline_if_pending(src)
-
if code =~ BLOCK_EXPR
-
src << '@output_buffer.append= ' << code
-
else
-
src << '@output_buffer.append=(' << code << ');'
-
end
-
end
-
-
1
def add_expr_escaped(src, code)
-
flush_newline_if_pending(src)
-
if code =~ BLOCK_EXPR
-
src << "@output_buffer.safe_expr_append= " << code
-
else
-
src << "@output_buffer.safe_expr_append=(" << code << ");"
-
end
-
end
-
-
1
def add_stmt(src, code)
-
flush_newline_if_pending(src)
-
super
-
end
-
-
1
def add_postamble(src)
-
flush_newline_if_pending(src)
-
src << '@output_buffer.to_s'
-
end
-
-
1
def flush_newline_if_pending(src)
-
if @newline_pending > 0
-
src << "@output_buffer.safe_append='#{"\n" * @newline_pending}'.freeze;"
-
@newline_pending = 0
-
end
-
end
-
end
-
-
1
class ERB
-
# Specify trim mode for the ERB compiler. Defaults to '-'.
-
# See ERB documentation for suitable values.
-
1
class_attribute :erb_trim_mode
-
1
self.erb_trim_mode = '-'
-
-
# Default implementation used.
-
1
class_attribute :erb_implementation
-
1
self.erb_implementation = Erubis
-
-
# Do not escape templates of these mime types.
-
1
class_attribute :escape_whitelist
-
1
self.escape_whitelist = ["text/plain"]
-
-
1
ENCODING_TAG = Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*")
-
-
1
def self.call(template)
-
new.call(template)
-
end
-
-
1
def supports_streaming?
-
true
-
end
-
-
1
def handles_encoding?
-
true
-
end
-
-
1
def call(template)
-
# First, convert to BINARY, so in case the encoding is
-
# wrong, we can still find an encoding tag
-
# (<%# encoding %>) inside the String using a regular
-
# expression
-
template_source = template.source.dup.force_encoding(Encoding::ASCII_8BIT)
-
-
erb = template_source.gsub(ENCODING_TAG, '')
-
encoding = $2
-
-
erb.force_encoding valid_encoding(template.source.dup, encoding)
-
-
# Always make sure we return a String in the default_internal
-
erb.encode!
-
-
self.class.erb_implementation.new(
-
erb,
-
:escape => (self.class.escape_whitelist.include? template.type),
-
:trim => (self.class.erb_trim_mode == "-")
-
).src
-
end
-
-
1
private
-
-
1
def valid_encoding(string, encoding)
-
# If a magic encoding comment was found, tag the
-
# String with this encoding. This is for a case
-
# where the original String was assumed to be,
-
# for instance, UTF-8, but a magic comment
-
# proved otherwise
-
string.force_encoding(encoding) if encoding
-
-
# If the String is valid, return the encoding we found
-
return string.encoding if string.valid_encoding?
-
-
# Otherwise, raise an exception
-
raise WrongEncodingError.new(string, string.encoding)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Template::Handlers
-
1
class Raw
-
1
def call(template)
-
escaped = template.source.gsub(/:/, '\:')
-
-
'%q:' + escaped + ':;'
-
end
-
end
-
end
-
end
-
1
require "pathname"
-
1
require "active_support/core_ext/class"
-
1
require "active_support/core_ext/module/attribute_accessors"
-
1
require 'active_support/core_ext/string/filters'
-
1
require "action_view/template"
-
1
require "thread"
-
1
require "thread_safe"
-
-
1
module ActionView
-
# = Action View Resolver
-
1
class Resolver
-
# Keeps all information about view path and builds virtual path.
-
1
class Path
-
1
attr_reader :name, :prefix, :partial, :virtual
-
1
alias_method :partial?, :partial
-
-
1
def self.build(name, prefix, partial)
-
27
virtual = ""
-
27
virtual << "#{prefix}/" unless prefix.empty?
-
27
virtual << (partial ? "_#{name}" : name)
-
27
new name, prefix, partial, virtual
-
end
-
-
1
def initialize(name, prefix, partial, virtual)
-
27
@name = name
-
27
@prefix = prefix
-
27
@partial = partial
-
27
@virtual = virtual
-
end
-
-
1
def to_str
-
27
@virtual
-
end
-
1
alias :to_s :to_str
-
end
-
-
# Threadsafe template cache
-
1
class Cache #:nodoc:
-
1
class SmallCache < ThreadSafe::Cache
-
1
def initialize(options = {})
-
70
super(options.merge(:initial_capacity => 2))
-
end
-
end
-
-
# preallocate all the default blocks for performance/memory consumption reasons
-
28
PARTIAL_BLOCK = lambda {|cache, partial| cache[partial] = SmallCache.new}
-
28
PREFIX_BLOCK = lambda {|cache, prefix| cache[prefix] = SmallCache.new(&PARTIAL_BLOCK)}
-
12
NAME_BLOCK = lambda {|cache, name| cache[name] = SmallCache.new(&PREFIX_BLOCK)}
-
2
KEY_BLOCK = lambda {|cache, key| cache[key] = SmallCache.new(&NAME_BLOCK)}
-
-
# usually a majority of template look ups return nothing, use this canonical preallocated array to save memory
-
1
NO_TEMPLATES = [].freeze
-
-
1
def initialize
-
4
@data = SmallCache.new(&KEY_BLOCK)
-
end
-
-
# Cache the templates returned by the block
-
1
def cache(key, name, prefix, partial, locals)
-
173
if Resolver.caching?
-
173
@data[key][name][prefix][partial][locals] ||= canonical_no_templates(yield)
-
else
-
fresh_templates = yield
-
cached_templates = @data[key][name][prefix][partial][locals]
-
-
if templates_have_changed?(cached_templates, fresh_templates)
-
@data[key][name][prefix][partial][locals] = canonical_no_templates(fresh_templates)
-
else
-
cached_templates || NO_TEMPLATES
-
end
-
end
-
end
-
-
1
def clear
-
@data.clear
-
end
-
-
1
private
-
-
1
def canonical_no_templates(templates)
-
27
templates.empty? ? NO_TEMPLATES : templates
-
end
-
-
1
def templates_have_changed?(cached_templates, fresh_templates)
-
# if either the old or new template list is empty, we don't need to (and can't)
-
# compare modification times, and instead just check whether the lists are different
-
if cached_templates.blank? || fresh_templates.blank?
-
return fresh_templates.blank? != cached_templates.blank?
-
end
-
-
cached_templates_max_updated_at = cached_templates.map(&:updated_at).max
-
-
# if a template has changed, it will be now be newer than all the cached templates
-
fresh_templates.any? { |t| t.updated_at > cached_templates_max_updated_at }
-
end
-
end
-
-
1
cattr_accessor :caching
-
1
self.caching = true
-
-
1
class << self
-
1
alias :caching? :caching
-
end
-
-
1
def initialize
-
4
@cache = Cache.new
-
end
-
-
1
def clear_cache
-
@cache.clear
-
end
-
-
# Normalizes the arguments and passes it on to find_templates.
-
1
def find_all(name, prefix=nil, partial=false, details={}, key=nil, locals=[])
-
173
cached(key, [name, prefix, partial], details, locals) do
-
27
find_templates(name, prefix, partial, details)
-
end
-
end
-
-
1
private
-
-
1
delegate :caching?, to: :class
-
-
# This is what child classes implement. No defaults are needed
-
# because Resolver guarantees that the arguments are present and
-
# normalized.
-
1
def find_templates(name, prefix, partial, details)
-
raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details) method"
-
end
-
-
# Helpers that builds a path. Useful for building virtual paths.
-
1
def build_path(name, prefix, partial)
-
Path.build(name, prefix, partial)
-
end
-
-
# Handles templates caching. If a key is given and caching is on
-
# always check the cache before hitting the resolver. Otherwise,
-
# it always hits the resolver but if the key is present, check if the
-
# resolver is fresher before returning it.
-
1
def cached(key, path_info, details, locals) #:nodoc:
-
173
name, prefix, partial = path_info
-
173
locals = locals.map { |x| x.to_s }.sort!
-
-
173
if key
-
173
@cache.cache(key, name, prefix, partial, locals) do
-
27
decorate(yield, path_info, details, locals)
-
end
-
else
-
decorate(yield, path_info, details, locals)
-
end
-
end
-
-
# Ensures all the resolver information is set in the template.
-
1
def decorate(templates, path_info, details, locals) #:nodoc:
-
27
cached = nil
-
27
templates.each do |t|
-
22
t.locals = locals
-
22
t.formats = details[:formats] || [:html] if t.formats.empty?
-
22
t.variants = details[:variants] || [] if t.variants.empty?
-
22
t.virtual_path ||= (cached ||= build_path(*path_info))
-
end
-
end
-
end
-
-
# An abstract class that implements a Resolver with path semantics.
-
1
class PathResolver < Resolver #:nodoc:
-
1
EXTENSIONS = { :locale => ".", :formats => ".", :variants => "+", :handlers => "." }
-
1
DEFAULT_PATTERN = ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}"
-
-
1
def initialize(pattern=nil)
-
4
@pattern = pattern || DEFAULT_PATTERN
-
4
super()
-
end
-
-
1
private
-
-
1
def find_templates(name, prefix, partial, details)
-
27
path = Path.build(name, prefix, partial)
-
27
query(path, details, details[:formats])
-
end
-
-
1
def query(path, details, formats)
-
27
query = build_query(path, details)
-
-
27
template_paths = find_template_paths query
-
-
27
template_paths.map { |template|
-
22
handler, format, variant = extract_handler_and_format_and_variant(template, formats)
-
22
contents = File.binread(template)
-
-
22
Template.new(contents, File.expand_path(template), handler,
-
:virtual_path => path.virtual,
-
:format => format,
-
:variant => variant,
-
:updated_at => mtime(template)
-
)
-
}
-
end
-
-
1
if RUBY_VERSION >= '2.2.0'
-
1
def find_template_paths(query)
-
27
Dir[query].reject { |filename|
-
File.directory?(filename) ||
-
# deals with case-insensitive file systems.
-
22
!File.fnmatch(query, filename, File::FNM_EXTGLOB)
-
}
-
end
-
else
-
def find_template_paths(query)
-
# deals with case-insensitive file systems.
-
sanitizer = Hash.new { |h,dir| h[dir] = Dir["#{dir}/*"] }
-
-
Dir[query].reject { |filename|
-
File.directory?(filename) ||
-
!sanitizer[File.dirname(filename)].include?(filename)
-
}
-
end
-
end
-
-
# Helper for building query glob string based on resolver's pattern.
-
1
def build_query(path, details)
-
query = @pattern.dup
-
-
prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1"
-
query.gsub!(/\:prefix(\/)?/, prefix)
-
-
partial = escape_entry(path.partial? ? "_#{path.name}" : path.name)
-
query.gsub!(/\:action/, partial)
-
-
details.each do |ext, variants|
-
query.gsub!(/\:#{ext}/, "{#{variants.compact.uniq.join(',')}}")
-
end
-
-
File.expand_path(query, @path)
-
end
-
-
1
def escape_entry(entry)
-
27
entry.gsub(/[*?{}\[\]]/, '\\\\\\&')
-
end
-
-
# Returns the file mtime from the filesystem.
-
1
def mtime(p)
-
22
File.mtime(p)
-
end
-
-
# Extract handler, formats and variant from path. If a format cannot be found neither
-
# from the path, or the handler, we should return the array of formats given
-
# to the resolver.
-
1
def extract_handler_and_format_and_variant(path, default_formats)
-
22
pieces = File.basename(path).split(".")
-
22
pieces.shift
-
-
22
extension = pieces.pop
-
22
unless extension
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
The file #{path} did not specify a template handler. The default is
-
currently ERB, but will change to RAW in the future.
-
MSG
-
end
-
-
22
handler = Template.handler_for_extension(extension)
-
22
format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last
-
22
format &&= Template::Types[format]
-
-
22
[handler, format, variant]
-
end
-
end
-
-
# A resolver that loads files from the filesystem. It allows setting your own
-
# resolving pattern. Such pattern can be a glob string supported by some variables.
-
#
-
# ==== Examples
-
#
-
# Default pattern, loads views the same way as previous versions of rails, eg. when you're
-
# looking for `users/new` it will produce query glob: `users/new{.{en},}{.{html,js},}{.{erb,haml},}`
-
#
-
# FileSystemResolver.new("/path/to/views", ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}")
-
#
-
# This one allows you to keep files with different formats in separate subdirectories,
-
# eg. `users/new.html` will be loaded from `users/html/new.erb` or `users/new.html.erb`,
-
# `users/new.js` from `users/js/new.erb` or `users/new.js.erb`, etc.
-
#
-
# FileSystemResolver.new("/path/to/views", ":prefix/{:formats/,}:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}")
-
#
-
# If you don't specify a pattern then the default will be used.
-
#
-
# In order to use any of the customized resolvers above in a Rails application, you just need
-
# to configure ActionController::Base.view_paths in an initializer, for example:
-
#
-
# ActionController::Base.view_paths = FileSystemResolver.new(
-
# Rails.root.join("app/views"),
-
# ":prefix{/:locale}/:action{.:formats,}{+:variants,}{.:handlers,}"
-
# )
-
#
-
# ==== Pattern format and variables
-
#
-
# Pattern has to be a valid glob string, and it allows you to use the
-
# following variables:
-
#
-
# * <tt>:prefix</tt> - usually the controller path
-
# * <tt>:action</tt> - name of the action
-
# * <tt>:locale</tt> - possible locale versions
-
# * <tt>:formats</tt> - possible request formats (for example html, json, xml...)
-
# * <tt>:variants</tt> - possible request variants (for example phone, tablet...)
-
# * <tt>:handlers</tt> - possible handlers (for example erb, haml, builder...)
-
#
-
1
class FileSystemResolver < PathResolver
-
1
def initialize(path, pattern=nil)
-
4
raise ArgumentError, "path already is a Resolver class" if path.is_a?(Resolver)
-
4
super(pattern)
-
4
@path = File.expand_path(path)
-
end
-
-
1
def to_s
-
@path.to_s
-
end
-
1
alias :to_path :to_s
-
-
1
def eql?(resolver)
-
self.class.equal?(resolver.class) && to_path == resolver.to_path
-
end
-
1
alias :== :eql?
-
end
-
-
# An Optimized resolver for Rails' most common case.
-
1
class OptimizedFileSystemResolver < FileSystemResolver #:nodoc:
-
1
def build_query(path, details)
-
27
query = escape_entry(File.join(@path, path))
-
-
27
exts = EXTENSIONS.map do |ext, prefix|
-
351
"{#{details[ext].compact.uniq.map { |e| "#{prefix}#{e}," }.join}}"
-
end.join
-
-
27
query + exts
-
end
-
end
-
-
# The same as FileSystemResolver but does not allow templates to store
-
# a virtual path since it is invalid for such resolvers.
-
1
class FallbackFileSystemResolver < FileSystemResolver #:nodoc:
-
1
def self.instances
-
1
[new(""), new("/")]
-
end
-
-
1
def decorate(*)
-
super.each { |t| t.virtual_path = nil }
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
module ActionView
-
1
class Template
-
1
class Types
-
1
class Type
-
1
cattr_accessor :types
-
1
self.types = Set.new
-
-
1
def self.register(*t)
-
7
types.merge(t.map { |type| type.to_s })
-
end
-
-
1
register :html, :text, :js, :css, :xml, :json
-
-
1
def self.[](type)
-
return type if type.is_a?(self)
-
-
if type.is_a?(Symbol) || types.member?(type.to_s)
-
new(type)
-
end
-
end
-
-
1
attr_reader :symbol
-
-
1
def initialize(symbol)
-
@symbol = symbol.to_sym
-
end
-
-
1
delegate :to_s, :to_sym, :to => :symbol
-
1
alias to_str to_s
-
-
1
def ref
-
to_sym || to_s
-
end
-
-
1
def ==(type)
-
return false if type.blank?
-
symbol.to_sym == type.to_sym
-
end
-
end
-
-
1
cattr_accessor :type_klass
-
-
1
def self.delegate_to(klass)
-
3
self.type_klass = klass
-
end
-
-
1
delegate_to Type
-
-
1
def self.[](type)
-
44
type_klass[type]
-
end
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActionView
-
# Returns the version of the currently loaded ActionView as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
1
require 'action_view/base'
-
-
1
module ActionView
-
1
module ViewPaths
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
2
class_attribute :_view_paths
-
2
self._view_paths = ActionView::PathSet.new
-
2
self._view_paths.freeze
-
end
-
-
1
delegate :template_exists?, :view_paths, :formats, :formats=,
-
:locale, :locale=, :to => :lookup_context
-
-
1
module ClassMethods
-
1
def _prefixes # :nodoc:
-
@_prefixes ||= begin
-
10
deprecated_prefixes = handle_deprecated_parent_prefixes
-
10
if deprecated_prefixes
-
deprecated_prefixes
-
else
-
10
return local_prefixes if superclass.abstract?
-
-
5
local_prefixes + superclass._prefixes
-
end
-
126
end
-
end
-
-
1
private
-
-
# Override this method in your controller if you want to change paths prefixes for finding views.
-
# Prefixes defined here will still be added to parents' <tt>._prefixes</tt>.
-
1
def local_prefixes
-
10
[controller_path]
-
end
-
-
1
def handle_deprecated_parent_prefixes # TODO: remove in 4.3/5.0.
-
10
return unless respond_to?(:parent_prefixes)
-
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
Overriding `ActionController::Base::parent_prefixes` is deprecated,
-
override `.local_prefixes` instead.
-
MSG
-
-
local_prefixes + parent_prefixes
-
end
-
end
-
-
# The prefixes used in render "foo" shortcuts.
-
1
def _prefixes # :nodoc:
-
121
self.class._prefixes
-
end
-
-
# LookupContext is the object responsible to hold all information required to lookup
-
# templates, i.e. view paths and details. Check ActionView::LookupContext for more
-
# information.
-
1
def lookup_context
-
@_lookup_context ||=
-
581
ActionView::LookupContext.new(self.class._view_paths, details_for_lookup, _prefixes)
-
end
-
-
1
def details_for_lookup
-
66
{ }
-
end
-
-
1
def append_view_path(path)
-
lookup_context.view_paths.push(*path)
-
end
-
-
1
def prepend_view_path(path)
-
lookup_context.view_paths.unshift(*path)
-
end
-
-
1
module ClassMethods
-
# Append a path to the list of view paths for this controller.
-
#
-
# ==== Parameters
-
# * <tt>path</tt> - If a String is provided, it gets converted into
-
# the default view path. You may also provide a custom view path
-
# (see ActionView::PathSet for more information)
-
1
def append_view_path(path)
-
self._view_paths = view_paths + Array(path)
-
end
-
-
# Prepend a path to the list of view paths for this controller.
-
#
-
# ==== Parameters
-
# * <tt>path</tt> - If a String is provided, it gets converted into
-
# the default view path. You may also provide a custom view path
-
# (see ActionView::PathSet for more information)
-
1
def prepend_view_path(path)
-
2
self._view_paths = ActionView::PathSet.new(Array(path) + view_paths)
-
end
-
-
# A list of all of the default view paths for this controller.
-
1
def view_paths
-
2
_view_paths
-
end
-
-
# Set the view paths.
-
#
-
# ==== Parameters
-
# * <tt>paths</tt> - If a PathSet is provided, use that;
-
# otherwise, process the parameter into a PathSet.
-
1
def view_paths=(paths)
-
self._view_paths = ActionView::PathSet.new(Array(paths))
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'active_job/version'
-
1
require 'global_id'
-
-
1
module ActiveJob
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Base
-
1
autoload :QueueAdapters
-
1
autoload :ConfiguredJob
-
1
autoload :TestCase
-
1
autoload :TestHelper
-
end
-
1
module ActiveJob
-
# Returns the version of the currently loaded Active Job as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 2
-
1
TINY = 5
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'global_id/railtie'
-
1
require 'active_job'
-
-
1
module ActiveJob
-
# = Active Job Railtie
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.active_job = ActiveSupport::OrderedOptions.new
-
-
1
initializer 'active_job.logger' do
-
1
ActiveSupport.on_load(:active_job) { self.logger = ::Rails.logger }
-
end
-
-
1
initializer "active_job.set_configs" do |app|
-
1
options = app.config.active_job
-
1
options.queue_adapter ||= :inline
-
-
1
ActiveSupport.on_load(:active_job) do
-
options.each { |k,v| send("#{k}=", v) }
-
end
-
end
-
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActiveJob
-
# Returns the version of the currently loaded Active Job as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'active_model/version'
-
-
1
module ActiveModel
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :AttributeMethods
-
1
autoload :BlockValidator, 'active_model/validator'
-
1
autoload :Callbacks
-
1
autoload :Conversion
-
1
autoload :Dirty
-
1
autoload :EachValidator, 'active_model/validator'
-
1
autoload :ForbiddenAttributesProtection
-
1
autoload :Lint
-
1
autoload :Model
-
1
autoload :Name, 'active_model/naming'
-
1
autoload :Naming
-
1
autoload :SecurePassword
-
1
autoload :Serialization
-
1
autoload :TestCase
-
1
autoload :Translation
-
1
autoload :Validations
-
1
autoload :Validator
-
-
1
eager_autoload do
-
1
autoload :Errors
-
1
autoload :StrictValidationFailed, 'active_model/errors'
-
end
-
-
1
module Serializers
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :JSON
-
1
autoload :Xml
-
end
-
end
-
-
1
def self.eager_load!
-
super
-
ActiveModel::Serializers.eager_load!
-
end
-
end
-
-
1
ActiveSupport.on_load(:i18n) do
-
1
I18n.load_path << File.dirname(__FILE__) + '/active_model/locale/en.yml'
-
end
-
1
require 'thread_safe'
-
1
require 'mutex_m'
-
-
1
module ActiveModel
-
# Raised when an attribute is not defined.
-
#
-
# class User < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# user = User.first
-
# user.pets.select(:id).first.user_id
-
# # => ActiveModel::MissingAttributeError: missing attribute: user_id
-
1
class MissingAttributeError < NoMethodError
-
end
-
-
# == Active \Model \Attribute \Methods
-
#
-
# Provides a way to add prefixes and suffixes to your methods as
-
# well as handling the creation of <tt>ActiveRecord::Base</tt>-like
-
# class methods such as +table_name+.
-
#
-
# The requirements to implement <tt>ActiveModel::AttributeMethods</tt> are to:
-
#
-
# * <tt>include ActiveModel::AttributeMethods</tt> in your class.
-
# * Call each of its method you want to add, such as +attribute_method_suffix+
-
# or +attribute_method_prefix+.
-
# * Call +define_attribute_methods+ after the other methods are called.
-
# * Define the various generic +_attribute+ methods that you have declared.
-
# * Define an +attributes+ method which returns a hash with each
-
# attribute name in your model as hash key and the attribute value as hash value.
-
# Hash keys must be strings.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
-
# attribute_method_suffix '_contrived?'
-
# attribute_method_prefix 'clear_'
-
# define_attribute_methods :name
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# { 'name' => @name }
-
# end
-
#
-
# private
-
#
-
# def attribute_contrived?(attr)
-
# true
-
# end
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
#
-
# def reset_attribute_to_default!(attr)
-
# send("#{attr}=", 'Default Name')
-
# end
-
# end
-
1
module AttributeMethods
-
1
extend ActiveSupport::Concern
-
-
1
NAME_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/
-
1
CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/
-
-
1
included do
-
1
class_attribute :attribute_aliases, :attribute_method_matchers, instance_writer: false
-
1
self.attribute_aliases = {}
-
1
self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new]
-
end
-
-
1
module ClassMethods
-
# Declares a method available for all attributes with the given prefix.
-
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
-
#
-
# #{prefix}#{attr}(*args, &block)
-
#
-
# to
-
#
-
# #{prefix}attribute(#{attr}, *args, &block)
-
#
-
# An instance method <tt>#{prefix}attribute</tt> must exist and accept
-
# at least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_prefix 'clear_'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.clear_name
-
# person.name # => nil
-
1
def attribute_method_prefix(*prefixes)
-
self.attribute_method_matchers += prefixes.map! { |prefix| AttributeMethodMatcher.new prefix: prefix }
-
undefine_attribute_methods
-
end
-
-
# Declares a method available for all attributes with the given suffix.
-
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
-
#
-
# #{attr}#{suffix}(*args, &block)
-
#
-
# to
-
#
-
# attribute#{suffix}(#{attr}, *args, &block)
-
#
-
# An <tt>attribute#{suffix}</tt> instance method must exist and accept at
-
# least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.name_short? # => true
-
1
def attribute_method_suffix(*suffixes)
-
13
self.attribute_method_matchers += suffixes.map! { |suffix| AttributeMethodMatcher.new suffix: suffix }
-
5
undefine_attribute_methods
-
end
-
-
# Declares a method available for all attributes with the given prefix
-
# and suffix. Uses +method_missing+ and <tt>respond_to?</tt> to rewrite
-
# the method.
-
#
-
# #{prefix}#{attr}#{suffix}(*args, &block)
-
#
-
# to
-
#
-
# #{prefix}attribute#{suffix}(#{attr}, *args, &block)
-
#
-
# An <tt>#{prefix}attribute#{suffix}</tt> instance method must exist and
-
# accept at least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def reset_attribute_to_default!(attr)
-
# send("#{attr}=", 'Default Name')
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name # => 'Gem'
-
# person.reset_name_to_default!
-
# person.name # => 'Default Name'
-
1
def attribute_method_affix(*affixes)
-
4
self.attribute_method_matchers += affixes.map! { |affix| AttributeMethodMatcher.new prefix: affix[:prefix], suffix: affix[:suffix] }
-
2
undefine_attribute_methods
-
end
-
-
# Allows you to make aliases for attributes.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_methods :name
-
#
-
# alias_attribute :nickname, :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.nickname # => "Bob"
-
# person.name_short? # => true
-
# person.nickname_short? # => true
-
1
def alias_attribute(new_name, old_name)
-
self.attribute_aliases = attribute_aliases.merge(new_name.to_s => old_name.to_s)
-
attribute_method_matchers.each do |matcher|
-
matcher_new = matcher.method_name(new_name).to_s
-
matcher_old = matcher.method_name(old_name).to_s
-
define_proxy_call false, self, matcher_new, matcher_old
-
end
-
end
-
-
# Is +new_name+ an alias?
-
1
def attribute_alias?(new_name)
-
attribute_aliases.key? new_name.to_s
-
end
-
-
# Returns the original name for the alias +name+
-
1
def attribute_alias(name)
-
attribute_aliases[name.to_s]
-
end
-
-
# Declares the attributes that should be prefixed and suffixed by
-
# ActiveModel::AttributeMethods.
-
#
-
# To use, pass attribute names (as strings or symbols), be sure to declare
-
# +define_attribute_methods+ after you define any prefix, suffix or affix
-
# methods, or they will not hook in.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name, :age, :address
-
# attribute_method_prefix 'clear_'
-
#
-
# # Call to define_attribute_methods must appear after the
-
# # attribute_method_prefix, attribute_method_suffix or
-
# # attribute_method_affix declares.
-
# define_attribute_methods :name, :age, :address
-
#
-
# private
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
# end
-
1
def define_attribute_methods(*attr_names)
-
33
attr_names.flatten.each { |attr_name| define_attribute_method(attr_name) }
-
end
-
-
# Declares an attribute that should be prefixed and suffixed by
-
# ActiveModel::AttributeMethods.
-
#
-
# To use, pass an attribute name (as string or symbol), be sure to declare
-
# +define_attribute_method+ after you define any prefix, suffix or affix
-
# method, or they will not hook in.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
#
-
# # Call to define_attribute_method must appear after the
-
# # attribute_method_prefix, attribute_method_suffix or
-
# # attribute_method_affix declares.
-
# define_attribute_method :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.name_short? # => true
-
1
def define_attribute_method(attr_name)
-
28
attribute_method_matchers.each do |matcher|
-
308
method_name = matcher.method_name(attr_name)
-
-
308
unless instance_method_already_implemented?(method_name)
-
308
generate_method = "define_method_#{matcher.method_missing_target}"
-
-
308
if respond_to?(generate_method, true)
-
56
send(generate_method, attr_name)
-
else
-
252
define_proxy_call true, generated_attribute_methods, method_name, matcher.method_missing_target, attr_name.to_s
-
end
-
end
-
end
-
28
attribute_method_matchers_cache.clear
-
end
-
-
# Removes all the previously dynamically defined methods from the class.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_method :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name_short? # => true
-
#
-
# Person.undefine_attribute_methods
-
#
-
# person.name_short? # => NoMethodError
-
1
def undefine_attribute_methods
-
generated_attribute_methods.module_eval do
-
instance_methods.each { |m| undef_method(m) }
-
end
-
attribute_method_matchers_cache.clear
-
end
-
-
1
def generated_attribute_methods #:nodoc:
-
@generated_attribute_methods ||= Module.new {
-
extend Mutex_m
-
628
}.tap { |mod| include mod }
-
end
-
-
1
protected
-
1
def instance_method_already_implemented?(method_name) #:nodoc:
-
308
generated_attribute_methods.method_defined?(method_name)
-
end
-
-
1
private
-
# The methods +method_missing+ and +respond_to?+ of this module are
-
# invoked often in a typical rails, both of which invoke the method
-
# +match_attribute_method?+. The latter method iterates through an
-
# array doing regular expression matches, which results in a lot of
-
# object creations. Most of the time it returns a +nil+ match. As the
-
# match result is always the same given a +method_name+, this cache is
-
# used to alleviate the GC, which ultimately also speeds up the app
-
# significantly (in our case our test suite finishes 10% faster with
-
# this cache).
-
1
def attribute_method_matchers_cache #:nodoc:
-
35
@attribute_method_matchers_cache ||= ThreadSafe::Cache.new(initial_capacity: 4)
-
end
-
-
1
def attribute_method_matchers_matching(method_name) #:nodoc:
-
7
attribute_method_matchers_cache.compute_if_absent(method_name) do
-
# Must try to match prefixes/suffixes first, or else the matcher with no prefix/suffix
-
# will match every time.
-
3
matchers = attribute_method_matchers.partition(&:plain?).reverse.flatten(1)
-
36
matchers.map { |method| method.match(method_name) }.compact
-
end
-
end
-
-
# Define a method `name` in `mod` that dispatches to `send`
-
# using the given `extra` args. This fallbacks `define_method`
-
# and `send` if the given names cannot be compiled.
-
1
def define_proxy_call(include_private, mod, name, send, *extra) #:nodoc:
-
252
defn = if name =~ NAME_COMPILABLE_REGEXP
-
252
"def #{name}(*args)"
-
else
-
"define_method(:'#{name}') do |*args|"
-
end
-
-
252
extra = (extra.map!(&:inspect) << "*args").join(", ")
-
-
252
target = if send =~ CALL_COMPILABLE_REGEXP
-
252
"#{"self." unless include_private}#{send}(#{extra})"
-
else
-
"send(:'#{send}', #{extra})"
-
end
-
-
252
mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
#{defn}
-
#{target}
-
end
-
RUBY
-
end
-
-
1
class AttributeMethodMatcher #:nodoc:
-
1
attr_reader :prefix, :suffix, :method_missing_target
-
-
1
AttributeMethodMatch = Struct.new(:target, :attr_name, :method_name)
-
-
1
def initialize(options = {})
-
11
@prefix, @suffix = options.fetch(:prefix, ''), options.fetch(:suffix, '')
-
11
@regex = /^(?:#{Regexp.escape(@prefix)})(.*)(?:#{Regexp.escape(@suffix)})$/
-
11
@method_missing_target = "#{@prefix}attribute#{@suffix}"
-
11
@method_name = "#{prefix}%s#{suffix}"
-
end
-
-
1
def match(method_name)
-
33
if @regex =~ method_name
-
3
AttributeMethodMatch.new(method_missing_target, $1, method_name)
-
end
-
end
-
-
1
def method_name(attr_name)
-
308
@method_name % attr_name
-
end
-
-
1
def plain?
-
33
prefix.empty? && suffix.empty?
-
end
-
end
-
end
-
-
# Allows access to the object attributes, which are held in the hash
-
# returned by <tt>attributes</tt>, as though they were first-class
-
# methods. So a +Person+ class with a +name+ attribute can for example use
-
# <tt>Person#name</tt> and <tt>Person#name=</tt> and never directly use
-
# the attributes hash -- except for multiple assigns with
-
# <tt>ActiveRecord::Base#attributes=</tt>.
-
#
-
# It's also possible to instantiate related objects, so a <tt>Client</tt>
-
# class belonging to the +clients+ table with a +master_id+ foreign key
-
# can instantiate master through <tt>Client#master</tt>.
-
1
def method_missing(method, *args, &block)
-
if respond_to_without_attributes?(method, true)
-
super
-
else
-
match = match_attribute_method?(method.to_s)
-
match ? attribute_missing(match, *args, &block) : super
-
end
-
end
-
-
# +attribute_missing+ is like +method_missing+, but for attributes. When
-
# +method_missing+ is called we check to see if there is a matching
-
# attribute method. If so, we tell +attribute_missing+ to dispatch the
-
# attribute. This method can be overloaded to customize the behavior.
-
1
def attribute_missing(match, *args, &block)
-
__send__(match.target, match.attr_name, *args, &block)
-
end
-
-
# A +Person+ instance with a +name+ attribute can ask
-
# <tt>person.respond_to?(:name)</tt>, <tt>person.respond_to?(:name=)</tt>,
-
# and <tt>person.respond_to?(:name?)</tt> which will all return +true+.
-
1
alias :respond_to_without_attributes? :respond_to?
-
1
def respond_to?(method, include_private_methods = false)
-
141
if super
-
134
true
-
7
elsif !include_private_methods && super(method, true)
-
# If we're here then we haven't found among non-private methods
-
# but found among all methods. Which means that the given method is private.
-
false
-
else
-
7
!match_attribute_method?(method.to_s).nil?
-
end
-
end
-
-
1
protected
-
1
def attribute_method?(attr_name) #:nodoc:
-
respond_to_without_attributes?(:attributes) && attributes.include?(attr_name)
-
end
-
-
1
private
-
# Returns a struct representing the matching attribute method.
-
# The struct's attributes are prefix, base and suffix.
-
1
def match_attribute_method?(method_name)
-
7
matches = self.class.send(:attribute_method_matchers_matching, method_name)
-
14
matches.detect { |match| attribute_method?(match.attr_name) }
-
end
-
-
1
def missing_attribute(attr_name, stack)
-
raise ActiveModel::MissingAttributeError, "missing attribute: #{attr_name}", stack
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveModel
-
# == Active \Model \Callbacks
-
#
-
# Provides an interface for any class to have Active Record like callbacks.
-
#
-
# Like the Active Record methods, the callback chain is aborted as soon as
-
# one of the methods in the chain returns +false+.
-
#
-
# First, extend ActiveModel::Callbacks from the class you are creating:
-
#
-
# class MyModel
-
# extend ActiveModel::Callbacks
-
# end
-
#
-
# Then define a list of methods that you want callbacks attached to:
-
#
-
# define_model_callbacks :create, :update
-
#
-
# This will provide all three standard callbacks (before, around and after)
-
# for both the <tt>:create</tt> and <tt>:update</tt> methods. To implement,
-
# you need to wrap the methods you want callbacks on in a block so that the
-
# callbacks get a chance to fire:
-
#
-
# def create
-
# run_callbacks :create do
-
# # Your create action methods here
-
# end
-
# end
-
#
-
# Then in your class, you can use the +before_create+, +after_create+ and
-
# +around_create+ methods, just as you would in an Active Record model.
-
#
-
# before_create :action_before_create
-
#
-
# def action_before_create
-
# # Your code here
-
# end
-
#
-
# When defining an around callback remember to yield to the block, otherwise
-
# it won't be executed:
-
#
-
# around_create :log_status
-
#
-
# def log_status
-
# puts 'going to call the block...'
-
# yield
-
# puts 'block successfully called.'
-
# end
-
#
-
# You can choose not to have all three callbacks by passing a hash to the
-
# +define_model_callbacks+ method.
-
#
-
# define_model_callbacks :create, only: [:after, :before]
-
#
-
# Would only create the +after_create+ and +before_create+ callback methods in
-
# your class.
-
1
module Callbacks
-
1
def self.extended(base) #:nodoc:
-
1
base.class_eval do
-
1
include ActiveSupport::Callbacks
-
end
-
end
-
-
# define_model_callbacks accepts the same options +define_callbacks+ does,
-
# in case you want to overwrite a default. Besides that, it also accepts an
-
# <tt>:only</tt> option, where you can choose if you want all types (before,
-
# around or after) or just some.
-
#
-
# define_model_callbacks :initializer, only: :after
-
#
-
# Note, the <tt>only: <type></tt> hash will apply to all callbacks defined
-
# on that method call. To get around this you can call the define_model_callbacks
-
# method as many times as you need.
-
#
-
# define_model_callbacks :create, only: :after
-
# define_model_callbacks :update, only: :before
-
# define_model_callbacks :destroy, only: :around
-
#
-
# Would create +after_create+, +before_update+ and +around_destroy+ methods
-
# only.
-
#
-
# You can pass in a class to before_<type>, after_<type> and around_<type>,
-
# in which case the callback will call that class's <action>_<type> method
-
# passing the object that the callback is being called on.
-
#
-
# class MyModel
-
# extend ActiveModel::Callbacks
-
# define_model_callbacks :create
-
#
-
# before_create AnotherClass
-
# end
-
#
-
# class AnotherClass
-
# def self.before_create( obj )
-
# # obj is the MyModel instance that the callback is being called on
-
# end
-
# end
-
#
-
# NOTE: +method_name+ passed to `define_model_callbacks` must not end with
-
# `!`, `?` or `=`.
-
1
def define_model_callbacks(*callbacks)
-
2
options = callbacks.extract_options!
-
2
options = {
-
28
terminator: ->(_,result) { result == false },
-
skip_after_callbacks_if_terminated: true,
-
scope: [:kind, :name],
-
only: [:before, :around, :after]
-
}.merge!(options)
-
-
2
types = Array(options.delete(:only))
-
-
2
callbacks.each do |callback|
-
7
define_callbacks(callback, options)
-
-
7
types.each do |type|
-
15
send("_define_#{type}_model_callback", self, callback)
-
end
-
end
-
end
-
-
1
private
-
-
1
def _define_before_model_callback(klass, callback) #:nodoc:
-
4
klass.define_singleton_method("before_#{callback}") do |*args, &block|
-
4
set_callback(:"#{callback}", :before, *args, &block)
-
end
-
end
-
-
1
def _define_around_model_callback(klass, callback) #:nodoc:
-
4
klass.define_singleton_method("around_#{callback}") do |*args, &block|
-
set_callback(:"#{callback}", :around, *args, &block)
-
end
-
end
-
-
1
def _define_after_model_callback(klass, callback) #:nodoc:
-
7
klass.define_singleton_method("after_#{callback}") do |*args, &block|
-
2
options = args.extract_options!
-
2
options[:prepend] = true
-
2
conditional = ActiveSupport::Callbacks::Conditionals::Value.new { |v|
-
7
v != false
-
}
-
2
options[:if] = Array(options[:if]) << conditional
-
2
set_callback(:"#{callback}", :after, *(args << options), &block)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
# == Active \Model \Conversion
-
#
-
# Handles default conversions: to_model, to_key, to_param, and to_partial_path.
-
#
-
# Let's take for example this non-persisted object.
-
#
-
# class ContactMessage
-
# include ActiveModel::Conversion
-
#
-
# # ContactMessage are never persisted in the DB
-
# def persisted?
-
# false
-
# end
-
# end
-
#
-
# cm = ContactMessage.new
-
# cm.to_model == cm # => true
-
# cm.to_key # => nil
-
# cm.to_param # => nil
-
# cm.to_partial_path # => "contact_messages/contact_message"
-
1
module Conversion
-
1
extend ActiveSupport::Concern
-
-
# If your object is already designed to implement all of the Active Model
-
# you can use the default <tt>:to_model</tt> implementation, which simply
-
# returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Conversion
-
# end
-
#
-
# person = Person.new
-
# person.to_model == person # => true
-
#
-
# If your model does not act like an Active Model object, then you should
-
# define <tt>:to_model</tt> yourself returning a proxy object that wraps
-
# your object with Active Model compliant methods.
-
1
def to_model
-
74
self
-
end
-
-
# Returns an Array of all key attributes if any is set, regardless if
-
# the object is persisted or not. Returns +nil+ if there are no key attributes.
-
#
-
# class Person
-
# include ActiveModel::Conversion
-
# attr_accessor :id
-
# end
-
#
-
# person = Person.create(id: 1)
-
# person.to_key # => [1]
-
1
def to_key
-
key = respond_to?(:id) && id
-
key ? [key] : nil
-
end
-
-
# Returns a +string+ representing the object's key suitable for use in URLs,
-
# or +nil+ if <tt>persisted?</tt> is +false+.
-
#
-
# class Person
-
# include ActiveModel::Conversion
-
# attr_accessor :id
-
# def persisted?
-
# true
-
# end
-
# end
-
#
-
# person = Person.create(id: 1)
-
# person.to_param # => "1"
-
1
def to_param
-
(persisted? && key = to_key) ? key.join('-') : nil
-
end
-
-
# Returns a +string+ identifying the path associated with the object.
-
# ActionPack uses this to find a suitable partial to represent the object.
-
#
-
# class Person
-
# include ActiveModel::Conversion
-
# end
-
#
-
# person = Person.new
-
# person.to_partial_path # => "people/person"
-
1
def to_partial_path
-
self.class._to_partial_path
-
end
-
-
1
module ClassMethods #:nodoc:
-
# Provide a class level cache for #to_partial_path. This is an
-
# internal method and should not be accessed directly.
-
1
def _to_partial_path #:nodoc:
-
@_to_partial_path ||= begin
-
element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(name))
-
collection = ActiveSupport::Inflector.tableize(name)
-
"#{collection}/#{element}".freeze
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/hash_with_indifferent_access'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'active_support/core_ext/string/filters'
-
-
1
module ActiveModel
-
# == Active \Model \Dirty
-
#
-
# Provides a way to track changes in your object in the same way as
-
# Active Record does.
-
#
-
# The requirements for implementing ActiveModel::Dirty are:
-
#
-
# * <tt>include ActiveModel::Dirty</tt> in your object.
-
# * Call <tt>define_attribute_methods</tt> passing each method you want to
-
# track.
-
# * Call <tt>attr_name_will_change!</tt> before each change to the tracked
-
# attribute.
-
# * Call <tt>changes_applied</tt> after the changes are persisted.
-
# * Call <tt>clear_changes_information</tt> when you want to reset the changes
-
# information.
-
# * Call <tt>restore_attributes</tt> when you want to restore previous data.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Dirty
-
#
-
# define_attribute_methods :name
-
#
-
# def name
-
# @name
-
# end
-
#
-
# def name=(val)
-
# name_will_change! unless val == @name
-
# @name = val
-
# end
-
#
-
# def save
-
# # do persistence work
-
#
-
# changes_applied
-
# end
-
#
-
# def reload!
-
# # get the values from the persistence layer
-
#
-
# clear_changes_information
-
# end
-
#
-
# def rollback!
-
# restore_attributes
-
# end
-
# end
-
#
-
# A newly instantiated +Person+ object is unchanged:
-
#
-
# person = Person.new
-
# person.changed? # => false
-
#
-
# Change the name:
-
#
-
# person.name = 'Bob'
-
# person.changed? # => true
-
# person.name_changed? # => true
-
# person.name_changed?(from: "Uncle Bob", to: "Bob") # => true
-
# person.name_was # => "Uncle Bob"
-
# person.name_change # => ["Uncle Bob", "Bob"]
-
# person.name = 'Bill'
-
# person.name_change # => ["Uncle Bob", "Bill"]
-
#
-
# Save the changes:
-
#
-
# person.save
-
# person.changed? # => false
-
# person.name_changed? # => false
-
#
-
# Reset the changes:
-
#
-
# person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
-
# person.reload!
-
# person.previous_changes # => {}
-
#
-
# Rollback the changes:
-
#
-
# person.name = "Uncle Bob"
-
# person.rollback!
-
# person.name # => "Bill"
-
# person.name_changed? # => false
-
#
-
# Assigning the same value leaves the attribute unchanged:
-
#
-
# person.name = 'Bill'
-
# person.name_changed? # => false
-
# person.name_change # => nil
-
#
-
# Which attributes have changed?
-
#
-
# person.name = 'Bob'
-
# person.changed # => ["name"]
-
# person.changes # => {"name" => ["Bill", "Bob"]}
-
#
-
# If an attribute is modified in-place then make use of
-
# +[attribute_name]_will_change!+ to mark that the attribute is changing.
-
# Otherwise Active Model can't track changes to in-place attributes. Note
-
# that Active Record can detect in-place modifications automatically. You do
-
# not need to call +[attribute_name]_will_change!+ on Active Record models.
-
#
-
# person.name_will_change!
-
# person.name_change # => ["Bill", "Bill"]
-
# person.name << 'y'
-
# person.name_change # => ["Bill", "Billy"]
-
1
module Dirty
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::AttributeMethods
-
-
1
included do
-
1
attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
-
1
attribute_method_affix prefix: 'reset_', suffix: '!'
-
1
attribute_method_affix prefix: 'restore_', suffix: '!'
-
end
-
-
# Returns +true+ if any attribute have unsaved changes, +false+ otherwise.
-
#
-
# person.changed? # => false
-
# person.name = 'bob'
-
# person.changed? # => true
-
1
def changed?
-
4
changed_attributes.present?
-
end
-
-
# Returns an array with the name of the attributes with unsaved changes.
-
#
-
# person.changed # => []
-
# person.name = 'bob'
-
# person.changed # => ["name"]
-
1
def changed
-
58
changed_attributes.keys
-
end
-
-
# Returns a hash of changed attributes indicating their original
-
# and new values like <tt>attr => [original value, new value]</tt>.
-
#
-
# person.changes # => {}
-
# person.name = 'bob'
-
# person.changes # => { "name" => ["bill", "bob"] }
-
1
def changes
-
193
ActiveSupport::HashWithIndifferentAccess[changed.map { |attr| [attr, attribute_change(attr)] }]
-
end
-
-
# Returns a hash of attributes that were changed before the model was saved.
-
#
-
# person.name # => "bob"
-
# person.name = 'robert'
-
# person.save
-
# person.previous_changes # => {"name" => ["bob", "robert"]}
-
1
def previous_changes
-
@previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Returns a hash of the attributes with unsaved changes indicating their original
-
# values like <tt>attr => original value</tt>.
-
#
-
# person.name # => "bob"
-
# person.name = 'robert'
-
# person.changed_attributes # => {"name" => "bob"}
-
1
def changed_attributes
-
742
@changed_attributes ||= ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Handle <tt>*_changed?</tt> for +method_missing+.
-
1
def attribute_changed?(attr, options = {}) #:nodoc:
-
344
result = changes_include?(attr)
-
344
result &&= options[:to] == __send__(attr) if options.key?(:to)
-
344
result &&= options[:from] == changed_attributes[attr] if options.key?(:from)
-
344
result
-
end
-
-
# Handle <tt>*_was</tt> for +method_missing+.
-
1
def attribute_was(attr) # :nodoc:
-
4
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
-
end
-
-
# Restore all previous data of the provided attributes.
-
1
def restore_attributes(attributes = changed)
-
attributes.each { |attr| restore_attribute! attr }
-
end
-
-
1
private
-
-
1
def changes_include?(attr_name)
-
516
attributes_changed_by_setter.include?(attr_name)
-
end
-
1
alias attribute_changed_by_setter? changes_include?
-
-
# Removes current changes and makes them accessible through +previous_changes+.
-
1
def changes_applied # :doc:
-
29
@previously_changed = changes
-
29
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Clear all dirty data: current changes and previous changes.
-
1
def clear_changes_information # :doc:
-
@previously_changed = ActiveSupport::HashWithIndifferentAccess.new
-
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
1
def reset_changes
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
`#reset_changes` is deprecated and will be removed on Rails 5.
-
Please use `#clear_changes_information` instead.
-
MSG
-
-
clear_changes_information
-
end
-
-
# Handle <tt>*_change</tt> for +method_missing+.
-
1
def attribute_change(attr)
-
164
[changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
-
end
-
-
# Handle <tt>*_will_change!</tt> for +method_missing+.
-
1
def attribute_will_change!(attr)
-
return if attribute_changed?(attr)
-
-
begin
-
value = __send__(attr)
-
value = value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
end
-
-
set_attribute_was(attr, value)
-
end
-
-
# Handle <tt>reset_*!</tt> for +method_missing+.
-
1
def reset_attribute!(attr)
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
`#reset_#{attr}!` is deprecated and will be removed on Rails 5.
-
Please use `#restore_#{attr}!` instead.
-
MSG
-
-
restore_attribute!(attr)
-
end
-
-
# Handle <tt>restore_*!</tt> for +method_missing+.
-
1
def restore_attribute!(attr)
-
if attribute_changed?(attr)
-
__send__("#{attr}=", changed_attributes[attr])
-
clear_attribute_changes([attr])
-
end
-
end
-
-
# This is necessary because `changed_attributes` might be overridden in
-
# other implemntations (e.g. in `ActiveRecord`)
-
1
alias_method :attributes_changed_by_setter, :changed_attributes # :nodoc:
-
-
# Force an attribute to have a particular "before" value
-
1
def set_attribute_was(attr, old_value)
-
164
attributes_changed_by_setter[attr] = old_value
-
end
-
-
# Remove changes information for the provided attributes.
-
1
def clear_attribute_changes(attributes) # :doc:
-
attributes_changed_by_setter.except!(*attributes)
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module ActiveModel
-
# == Active \Model \Errors
-
#
-
# Provides a modified +Hash+ that you can include in your object
-
# for handling error messages and interacting with Action View helpers.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# # Required dependency for ActiveModel::Errors
-
# extend ActiveModel::Naming
-
#
-
# def initialize
-
# @errors = ActiveModel::Errors.new(self)
-
# end
-
#
-
# attr_accessor :name
-
# attr_reader :errors
-
#
-
# def validate!
-
# errors.add(:name, "cannot be nil") if name.nil?
-
# end
-
#
-
# # The following methods are needed to be minimally implemented
-
#
-
# def read_attribute_for_validation(attr)
-
# send(attr)
-
# end
-
#
-
# def Person.human_attribute_name(attr, options = {})
-
# attr
-
# end
-
#
-
# def Person.lookup_ancestors
-
# [self]
-
# end
-
# end
-
#
-
# The last three methods are required in your object for Errors to be
-
# able to generate error messages correctly and also handle multiple
-
# languages. Of course, if you extend your object with ActiveModel::Translation
-
# you will not need to implement the last two. Likewise, using
-
# ActiveModel::Validations will handle the validation related methods
-
# for you.
-
#
-
# The above allows you to do:
-
#
-
# person = Person.new
-
# person.validate! # => ["cannot be nil"]
-
# person.errors.full_messages # => ["name cannot be nil"]
-
# # etc..
-
1
class Errors
-
1
include Enumerable
-
-
1
CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict]
-
-
1
attr_reader :messages
-
-
# Pass in the instance of the object that is using the errors object.
-
#
-
# class Person
-
# def initialize
-
# @errors = ActiveModel::Errors.new(self)
-
# end
-
# end
-
1
def initialize(base)
-
37
@base = base
-
37
@messages = {}
-
end
-
-
1
def initialize_dup(other) # :nodoc:
-
@messages = other.messages.dup
-
super
-
end
-
-
# Clear the error messages.
-
#
-
# person.errors.full_messages # => ["name cannot be nil"]
-
# person.errors.clear
-
# person.errors.full_messages # => []
-
1
def clear
-
29
messages.clear
-
end
-
-
# Returns +true+ if the error messages include an error for the given key
-
# +attribute+, +false+ otherwise.
-
#
-
# person.errors.messages # => {:name=>["cannot be nil"]}
-
# person.errors.include?(:name) # => true
-
# person.errors.include?(:age) # => false
-
1
def include?(attribute)
-
messages[attribute].present?
-
end
-
# aliases include?
-
1
alias :has_key? :include?
-
# aliases include?
-
1
alias :key? :include?
-
-
# Get messages for +key+.
-
#
-
# person.errors.messages # => {:name=>["cannot be nil"]}
-
# person.errors.get(:name) # => ["cannot be nil"]
-
# person.errors.get(:age) # => nil
-
1
def get(key)
-
52
messages[key]
-
end
-
-
# Set messages for +key+ to +value+.
-
#
-
# person.errors.get(:name) # => ["cannot be nil"]
-
# person.errors.set(:name, ["can't be nil"])
-
# person.errors.get(:name) # => ["can't be nil"]
-
1
def set(key, value)
-
26
messages[key] = value
-
end
-
-
# Delete messages for +key+. Returns the deleted messages.
-
#
-
# person.errors.get(:name) # => ["cannot be nil"]
-
# person.errors.delete(:name) # => ["cannot be nil"]
-
# person.errors.get(:name) # => nil
-
1
def delete(key)
-
messages.delete(key)
-
end
-
-
# When passed a symbol or a name of a method, returns an array of errors
-
# for the method.
-
#
-
# person.errors[:name] # => ["cannot be nil"]
-
# person.errors['name'] # => ["cannot be nil"]
-
1
def [](attribute)
-
52
get(attribute.to_sym) || set(attribute.to_sym, [])
-
end
-
-
# Adds to the supplied attribute the supplied error message.
-
#
-
# person.errors[:name] = "must be set"
-
# person.errors[:name] # => ['must be set']
-
1
def []=(attribute, error)
-
self[attribute] << error
-
end
-
-
# Iterates through each error key, value pair in the error messages hash.
-
# Yields the attribute and the error for that attribute. If the attribute
-
# has more than one error message, yields once for each error message.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.each do |attribute, error|
-
# # Will yield :name and "can't be blank"
-
# end
-
#
-
# person.errors.add(:name, "must be specified")
-
# person.errors.each do |attribute, error|
-
# # Will yield :name and "can't be blank"
-
# # then yield :name and "must be specified"
-
# end
-
1
def each
-
66
messages.each_key do |attribute|
-
self[attribute].each { |error| yield attribute, error }
-
end
-
end
-
-
# Returns the number of error messages.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.size # => 1
-
# person.errors.add(:name, "must be specified")
-
# person.errors.size # => 2
-
1
def size
-
values.flatten.size
-
end
-
-
# Returns all message values.
-
#
-
# person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
-
# person.errors.values # => [["cannot be nil", "must be specified"]]
-
1
def values
-
messages.values
-
end
-
-
# Returns all message keys.
-
#
-
# person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
-
# person.errors.keys # => [:name]
-
1
def keys
-
messages.keys
-
end
-
-
# Returns an array of error messages, with the attribute name included.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.add(:name, "must be specified")
-
# person.errors.to_a # => ["name can't be blank", "name must be specified"]
-
1
def to_a
-
full_messages
-
end
-
-
# Returns the number of error messages.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.count # => 1
-
# person.errors.add(:name, "must be specified")
-
# person.errors.count # => 2
-
1
def count
-
to_a.size
-
end
-
-
# Returns +true+ if no errors are found, +false+ otherwise.
-
# If the error message is a string it can be empty.
-
#
-
# person.errors.full_messages # => ["name cannot be nil"]
-
# person.errors.empty? # => false
-
1
def empty?
-
58
all? { |k, v| v && v.empty? && !v.is_a?(String) }
-
end
-
# aliases empty?
-
1
alias_method :blank?, :empty?
-
-
# Returns an xml formatted representation of the Errors hash.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.add(:name, "must be specified")
-
# person.errors.to_xml
-
# # =>
-
# # <?xml version=\"1.0\" encoding=\"UTF-8\"?>
-
# # <errors>
-
# # <error>name can't be blank</error>
-
# # <error>name must be specified</error>
-
# # </errors>
-
1
def to_xml(options={})
-
to_a.to_xml({ root: "errors", skip_types: true }.merge!(options))
-
end
-
-
# Returns a Hash that can be used as the JSON representation for this
-
# object. You can pass the <tt>:full_messages</tt> option. This determines
-
# if the json object should contain full messages or not (false by default).
-
#
-
# person.errors.as_json # => {:name=>["cannot be nil"]}
-
# person.errors.as_json(full_messages: true) # => {:name=>["name cannot be nil"]}
-
1
def as_json(options=nil)
-
to_hash(options && options[:full_messages])
-
end
-
-
# Returns a Hash of attributes with their error messages. If +full_messages+
-
# is +true+, it will contain full messages (see +full_message+).
-
#
-
# person.errors.to_hash # => {:name=>["cannot be nil"]}
-
# person.errors.to_hash(true) # => {:name=>["name cannot be nil"]}
-
1
def to_hash(full_messages = false)
-
if full_messages
-
self.messages.each_with_object({}) do |(attribute, array), messages|
-
messages[attribute] = array.map { |message| full_message(attribute, message) }
-
end
-
else
-
self.messages.dup
-
end
-
end
-
-
# Adds +message+ to the error messages on +attribute+. More than one error
-
# can be added to the same +attribute+. If no +message+ is supplied,
-
# <tt>:invalid</tt> is assumed.
-
#
-
# person.errors.add(:name)
-
# # => ["is invalid"]
-
# person.errors.add(:name, 'must be implemented')
-
# # => ["is invalid", "must be implemented"]
-
#
-
# person.errors.messages
-
# # => {:name=>["must be implemented", "is invalid"]}
-
#
-
# If +message+ is a symbol, it will be translated using the appropriate
-
# scope (see +generate_message+).
-
#
-
# If +message+ is a proc, it will be called, allowing for things like
-
# <tt>Time.now</tt> to be used within an error.
-
#
-
# If the <tt>:strict</tt> option is set to +true+, it will raise
-
# ActiveModel::StrictValidationFailed instead of adding the error.
-
# <tt>:strict</tt> option can also be set to any other exception.
-
#
-
# person.errors.add(:name, nil, strict: true)
-
# # => ActiveModel::StrictValidationFailed: name is invalid
-
# person.errors.add(:name, nil, strict: NameIsInvalid)
-
# # => NameIsInvalid: name is invalid
-
#
-
# person.errors.messages # => {}
-
#
-
# +attribute+ should be set to <tt>:base</tt> if the error is not
-
# directly associated with a single attribute.
-
#
-
# person.errors.add(:base, "either name or email must be present")
-
# person.errors.messages
-
# # => {:base=>["either name or email must be present"]}
-
1
def add(attribute, message = :invalid, options = {})
-
message = normalize_message(attribute, message, options)
-
if exception = options[:strict]
-
exception = ActiveModel::StrictValidationFailed if exception == true
-
raise exception, full_message(attribute, message)
-
end
-
-
self[attribute] << message
-
end
-
-
# Will add an error message to each of the attributes in +attributes+
-
# that is empty.
-
#
-
# person.errors.add_on_empty(:name)
-
# person.errors.messages
-
# # => {:name=>["can't be empty"]}
-
1
def add_on_empty(attributes, options = {})
-
Array(attributes).each do |attribute|
-
value = @base.send(:read_attribute_for_validation, attribute)
-
is_empty = value.respond_to?(:empty?) ? value.empty? : false
-
add(attribute, :empty, options) if value.nil? || is_empty
-
end
-
end
-
-
# Will add an error message to each of the attributes in +attributes+ that
-
# is blank (using Object#blank?).
-
#
-
# person.errors.add_on_blank(:name)
-
# person.errors.messages
-
# # => {:name=>["can't be blank"]}
-
1
def add_on_blank(attributes, options = {})
-
Array(attributes).each do |attribute|
-
value = @base.send(:read_attribute_for_validation, attribute)
-
add(attribute, :blank, options) if value.blank?
-
end
-
end
-
-
# Returns +true+ if an error on the attribute with the given message is
-
# present, +false+ otherwise. +message+ is treated the same as for +add+.
-
#
-
# person.errors.add :name, :blank
-
# person.errors.added? :name, :blank # => true
-
1
def added?(attribute, message = :invalid, options = {})
-
message = normalize_message(attribute, message, options)
-
self[attribute].include? message
-
end
-
-
# Returns all the full error messages in an array.
-
#
-
# class Person
-
# validates_presence_of :name, :address, :email
-
# validates_length_of :name, in: 5..30
-
# end
-
#
-
# person = Person.create(address: '123 First St.')
-
# person.errors.full_messages
-
# # => ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"]
-
1
def full_messages
-
map { |attribute, message| full_message(attribute, message) }
-
end
-
-
# Returns all the full error messages for a given attribute in an array.
-
#
-
# class Person
-
# validates_presence_of :name, :email
-
# validates_length_of :name, in: 5..30
-
# end
-
#
-
# person = Person.create()
-
# person.errors.full_messages_for(:name)
-
# # => ["Name is too short (minimum is 5 characters)", "Name can't be blank"]
-
1
def full_messages_for(attribute)
-
(get(attribute) || []).map { |message| full_message(attribute, message) }
-
end
-
-
# Returns a full message for a given attribute.
-
#
-
# person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
-
1
def full_message(attribute, message)
-
return message if attribute == :base
-
attr_name = attribute.to_s.tr('.', '_').humanize
-
attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
-
I18n.t(:"errors.format", {
-
default: "%{attribute} %{message}",
-
attribute: attr_name,
-
message: message
-
})
-
end
-
-
# Translates an error message in its default scope
-
# (<tt>activemodel.errors.messages</tt>).
-
#
-
# Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>,
-
# if it's not there, it's looked up in <tt>models.MODEL.MESSAGE</tt> and if
-
# that is not there also, it returns the translation of the default message
-
# (e.g. <tt>activemodel.errors.messages.MESSAGE</tt>). The translated model
-
# name, translated attribute name and the value are available for
-
# interpolation.
-
#
-
# When using inheritance in your models, it will check all the inherited
-
# models too, but only if the model itself hasn't been found. Say you have
-
# <tt>class Admin < User; end</tt> and you wanted the translation for
-
# the <tt>:blank</tt> error message for the <tt>title</tt> attribute,
-
# it looks for these translations:
-
#
-
# * <tt>activemodel.errors.models.admin.attributes.title.blank</tt>
-
# * <tt>activemodel.errors.models.admin.blank</tt>
-
# * <tt>activemodel.errors.models.user.attributes.title.blank</tt>
-
# * <tt>activemodel.errors.models.user.blank</tt>
-
# * any default you provided through the +options+ hash (in the <tt>activemodel.errors</tt> scope)
-
# * <tt>activemodel.errors.messages.blank</tt>
-
# * <tt>errors.attributes.title.blank</tt>
-
# * <tt>errors.messages.blank</tt>
-
1
def generate_message(attribute, type = :invalid, options = {})
-
type = options.delete(:message) if options[:message].is_a?(Symbol)
-
-
if @base.class.respond_to?(:i18n_scope)
-
defaults = @base.class.lookup_ancestors.map do |klass|
-
[ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}",
-
:"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ]
-
end
-
else
-
defaults = []
-
end
-
-
defaults << options.delete(:message)
-
defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope)
-
defaults << :"errors.attributes.#{attribute}.#{type}"
-
defaults << :"errors.messages.#{type}"
-
-
defaults.compact!
-
defaults.flatten!
-
-
key = defaults.shift
-
value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)
-
-
options = {
-
default: defaults,
-
model: @base.model_name.human,
-
attribute: @base.class.human_attribute_name(attribute),
-
value: value
-
}.merge!(options)
-
-
I18n.translate(key, options)
-
end
-
-
1
private
-
1
def normalize_message(attribute, message, options)
-
case message
-
when Symbol
-
generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
-
when Proc
-
message.call
-
else
-
message
-
end
-
end
-
end
-
-
# Raised when a validation cannot be corrected by end users and are considered
-
# exceptional.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
#
-
# validates_presence_of :name, strict: true
-
# end
-
#
-
# person = Person.new
-
# person.name = nil
-
# person.valid?
-
# # => ActiveModel::StrictValidationFailed: Name can't be blank
-
1
class StrictValidationFailed < StandardError
-
end
-
end
-
1
module ActiveModel
-
# Raised when forbidden attributes are used for mass assignment.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# params = ActionController::Parameters.new(name: 'Bob')
-
# Person.new(params)
-
# # => ActiveModel::ForbiddenAttributesError
-
#
-
# params.permit!
-
# Person.new(params)
-
# # => #<Person id: nil, name: "Bob">
-
1
class ForbiddenAttributesError < StandardError
-
end
-
-
1
module ForbiddenAttributesProtection # :nodoc:
-
1
protected
-
1
def sanitize_for_mass_assignment(attributes)
-
37
if attributes.respond_to?(:permitted?) && !attributes.permitted?
-
raise ActiveModel::ForbiddenAttributesError
-
else
-
37
attributes
-
end
-
end
-
1
alias :sanitize_forbidden_attributes :sanitize_for_mass_assignment
-
end
-
end
-
1
module ActiveModel
-
# Returns the version of the currently loaded Active Model as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 2
-
1
TINY = 5
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/module/remove_method'
-
-
1
module ActiveModel
-
1
class Name
-
1
include Comparable
-
-
1
attr_reader :singular, :plural, :element, :collection,
-
:singular_route_key, :route_key, :param_key, :i18n_key,
-
:name
-
-
1
alias_method :cache_key, :collection
-
-
##
-
# :method: ==
-
#
-
# :call-seq:
-
# ==(other)
-
#
-
# Equivalent to <tt>String#==</tt>. Returns +true+ if the class name and
-
# +other+ are equal, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name == 'BlogPost' # => true
-
# BlogPost.model_name == 'Blog Post' # => false
-
-
##
-
# :method: ===
-
#
-
# :call-seq:
-
# ===(other)
-
#
-
# Equivalent to <tt>#==</tt>.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name === 'BlogPost' # => true
-
# BlogPost.model_name === 'Blog Post' # => false
-
-
##
-
# :method: <=>
-
#
-
# :call-seq:
-
# ==(other)
-
#
-
# Equivalent to <tt>String#<=></tt>.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name <=> 'BlogPost' # => 0
-
# BlogPost.model_name <=> 'Blog' # => 1
-
# BlogPost.model_name <=> 'BlogPosts' # => -1
-
-
##
-
# :method: =~
-
#
-
# :call-seq:
-
# =~(regexp)
-
#
-
# Equivalent to <tt>String#=~</tt>. Match the class name against the given
-
# regexp. Returns the position where the match starts or +nil+ if there is
-
# no match.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name =~ /Post/ # => 4
-
# BlogPost.model_name =~ /\d/ # => nil
-
-
##
-
# :method: !~
-
#
-
# :call-seq:
-
# !~(regexp)
-
#
-
# Equivalent to <tt>String#!~</tt>. Match the class name against the given
-
# regexp. Returns +true+ if there is no match, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name !~ /Post/ # => false
-
# BlogPost.model_name !~ /\d/ # => true
-
-
##
-
# :method: eql?
-
#
-
# :call-seq:
-
# eql?(other)
-
#
-
# Equivalent to <tt>String#eql?</tt>. Returns +true+ if the class name and
-
# +other+ have the same length and content, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.eql?('BlogPost') # => true
-
# BlogPost.model_name.eql?('Blog Post') # => false
-
-
##
-
# :method: to_s
-
#
-
# :call-seq:
-
# to_s()
-
#
-
# Returns the class name.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.to_s # => "BlogPost"
-
-
##
-
# :method: to_str
-
#
-
# :call-seq:
-
# to_str()
-
#
-
# Equivalent to +to_s+.
-
1
delegate :==, :===, :<=>, :=~, :"!~", :eql?, :to_s,
-
:to_str, :as_json, to: :name
-
-
# Returns a new ActiveModel::Name instance. By default, the +namespace+
-
# and +name+ option will take the namespace and name of the given class
-
# respectively.
-
#
-
# module Foo
-
# class Bar
-
# end
-
# end
-
#
-
# ActiveModel::Name.new(Foo::Bar).to_s
-
# # => "Foo::Bar"
-
1
def initialize(klass, namespace = nil, name = nil)
-
4
@name = name || klass.name
-
-
4
raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if @name.blank?
-
-
4
@unnamespaced = @name.sub(/^#{namespace.name}::/, '') if namespace
-
4
@klass = klass
-
4
@singular = _singularize(@name)
-
4
@plural = ActiveSupport::Inflector.pluralize(@singular)
-
4
@element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name))
-
4
@human = ActiveSupport::Inflector.humanize(@element)
-
4
@collection = ActiveSupport::Inflector.tableize(@name)
-
4
@param_key = (namespace ? _singularize(@unnamespaced) : @singular)
-
4
@i18n_key = @name.underscore.to_sym
-
-
4
@route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural.dup)
-
4
@singular_route_key = ActiveSupport::Inflector.singularize(@route_key)
-
4
@route_key << "_index" if @plural == @singular
-
end
-
-
# Transform the model name into a more humane format, using I18n. By default,
-
# it will underscore then humanize the class name.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.human # => "Blog post"
-
#
-
# Specify +options+ with additional translating options.
-
1
def human(options={})
-
return @human unless @klass.respond_to?(:lookup_ancestors) &&
-
6
@klass.respond_to?(:i18n_scope)
-
-
6
defaults = @klass.lookup_ancestors.map do |klass|
-
6
klass.model_name.i18n_key
-
end
-
-
6
defaults << options[:default] if options[:default]
-
6
defaults << @human
-
-
6
options = { scope: [@klass.i18n_scope, :models], count: 1, default: defaults }.merge!(options.except(:default))
-
6
I18n.translate(defaults.shift, options)
-
end
-
-
1
private
-
-
1
def _singularize(string, replacement='_')
-
4
ActiveSupport::Inflector.underscore(string).tr('/', replacement)
-
end
-
end
-
-
# == Active \Model \Naming
-
#
-
# Creates a +model_name+ method on your object.
-
#
-
# To implement, just extend ActiveModel::Naming in your object:
-
#
-
# class BookCover
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BookCover.model_name.name # => "BookCover"
-
# BookCover.model_name.human # => "Book cover"
-
#
-
# BookCover.model_name.i18n_key # => :book_cover
-
# BookModule::BookCover.model_name.i18n_key # => :"book_module/book_cover"
-
#
-
# Providing the functionality that ActiveModel::Naming provides in your object
-
# is required to pass the Active Model Lint test. So either extending the
-
# provided method below, or rolling your own is required.
-
1
module Naming
-
1
def self.extended(base) #:nodoc:
-
4
base.remove_possible_method :model_name
-
4
base.delegate :model_name, to: :class
-
end
-
-
# Returns an ActiveModel::Name object for module. It can be
-
# used to retrieve all kinds of naming-related information
-
# (See ActiveModel::Name for more information).
-
#
-
# class Person
-
# extend ActiveModel::Naming
-
# end
-
#
-
# Person.model_name.name # => "Person"
-
# Person.model_name.class # => ActiveModel::Name
-
# Person.model_name.singular # => "person"
-
# Person.model_name.plural # => "people"
-
1
def model_name
-
@_model_name ||= begin
-
4
namespace = self.parents.detect do |n|
-
4
n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming?
-
end
-
4
ActiveModel::Name.new(self, namespace)
-
66
end
-
end
-
-
# Returns the plural class name of a record or class.
-
#
-
# ActiveModel::Naming.plural(post) # => "posts"
-
# ActiveModel::Naming.plural(Highrise::Person) # => "highrise_people"
-
1
def self.plural(record_or_class)
-
model_name_from_record_or_class(record_or_class).plural
-
end
-
-
# Returns the singular class name of a record or class.
-
#
-
# ActiveModel::Naming.singular(post) # => "post"
-
# ActiveModel::Naming.singular(Highrise::Person) # => "highrise_person"
-
1
def self.singular(record_or_class)
-
model_name_from_record_or_class(record_or_class).singular
-
end
-
-
# Identifies whether the class name of a record or class is uncountable.
-
#
-
# ActiveModel::Naming.uncountable?(Sheep) # => true
-
# ActiveModel::Naming.uncountable?(Post) # => false
-
1
def self.uncountable?(record_or_class)
-
plural(record_or_class) == singular(record_or_class)
-
end
-
-
# Returns string to use while generating route names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.singular_route_key(Blog::Post) # => "post"
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.singular_route_key(Blog::Post) # => "blog_post"
-
1
def self.singular_route_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).singular_route_key
-
end
-
-
# Returns string to use while generating route names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.route_key(Blog::Post) # => "posts"
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.route_key(Blog::Post) # => "blog_posts"
-
#
-
# The route key also considers if the noun is uncountable and, in
-
# such cases, automatically appends _index.
-
1
def self.route_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).route_key
-
end
-
-
# Returns string to use for params names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.param_key(Blog::Post) # => "post"
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.param_key(Blog::Post) # => "blog_post"
-
1
def self.param_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).param_key
-
end
-
-
1
def self.model_name_from_record_or_class(record_or_class) #:nodoc:
-
if record_or_class.respond_to?(:to_model)
-
record_or_class.to_model.model_name
-
else
-
record_or_class.model_name
-
end
-
end
-
1
private_class_method :model_name_from_record_or_class
-
end
-
end
-
1
require "active_model"
-
1
require "rails"
-
-
1
module ActiveModel
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.eager_load_namespaces << ActiveModel
-
-
1
initializer "active_model.secure_password" do
-
1
ActiveModel::SecurePassword.min_cost = Rails.env.test?
-
end
-
end
-
end
-
1
module ActiveModel
-
1
module SecurePassword
-
1
extend ActiveSupport::Concern
-
-
# BCrypt hash function can handle maximum 72 characters, and if we pass
-
# password of length more than 72 characters it ignores extra characters.
-
# Hence need to put a restriction on password length.
-
1
MAX_PASSWORD_LENGTH_ALLOWED = 72
-
-
1
class << self
-
1
attr_accessor :min_cost # :nodoc:
-
end
-
1
self.min_cost = false
-
-
1
module ClassMethods
-
# Adds methods to set and authenticate against a BCrypt password.
-
# This mechanism requires you to have a +password_digest+ attribute.
-
#
-
# The following validations are added automatically:
-
# * Password must be present on creation
-
# * Password length should be less than or equal to 72 characters
-
# * Confirmation of password (using a +password_confirmation+ attribute)
-
#
-
# If password confirmation validation is not needed, simply leave out the
-
# value for +password_confirmation+ (i.e. don't provide a form field for
-
# it). When this attribute has a +nil+ value, the validation will not be
-
# triggered.
-
#
-
# For further customizability, it is possible to supress the default
-
# validations by passing <tt>validations: false</tt> as an argument.
-
#
-
# Add bcrypt (~> 3.1.7) to Gemfile to use #has_secure_password:
-
#
-
# gem 'bcrypt', '~> 3.1.7'
-
#
-
# Example using Active Record (which automatically includes ActiveModel::SecurePassword):
-
#
-
# # Schema: User(name:string, password_digest:string)
-
# class User < ActiveRecord::Base
-
# has_secure_password
-
# end
-
#
-
# user = User.new(name: 'david', password: '', password_confirmation: 'nomatch')
-
# user.save # => false, password required
-
# user.password = 'mUc3m00RsqyRe'
-
# user.save # => false, confirmation doesn't match
-
# user.password_confirmation = 'mUc3m00RsqyRe'
-
# user.save # => true
-
# user.authenticate('notright') # => false
-
# user.authenticate('mUc3m00RsqyRe') # => user
-
# User.find_by(name: 'david').try(:authenticate, 'notright') # => false
-
# User.find_by(name: 'david').try(:authenticate, 'mUc3m00RsqyRe') # => user
-
1
def has_secure_password(options = {})
-
# Load bcrypt gem only when has_secure_password is used.
-
# This is to avoid ActiveModel (and by extension the entire framework)
-
# being dependent on a binary library.
-
begin
-
require 'bcrypt'
-
rescue LoadError
-
$stderr.puts "You don't have bcrypt installed in your application. Please add it to your Gemfile and run bundle install"
-
raise
-
end
-
-
include InstanceMethodsOnActivation
-
-
if options.fetch(:validations, true)
-
include ActiveModel::Validations
-
-
# This ensures the model has a password by checking whether the password_digest
-
# is present, so that this works with both new and existing records. However,
-
# when there is an error, the message is added to the password attribute instead
-
# so that the error message will make sense to the end-user.
-
validate do |record|
-
record.errors.add(:password, :blank) unless record.password_digest.present?
-
end
-
-
validates_length_of :password, maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED
-
validates_confirmation_of :password, allow_blank: true
-
end
-
-
# This code is necessary as long as the protected_attributes gem is supported.
-
if respond_to?(:attributes_protected_by_default)
-
def self.attributes_protected_by_default #:nodoc:
-
super + ['password_digest']
-
end
-
end
-
end
-
end
-
-
1
module InstanceMethodsOnActivation
-
# Returns +self+ if the password is correct, otherwise +false+.
-
#
-
# class User < ActiveRecord::Base
-
# has_secure_password validations: false
-
# end
-
#
-
# user = User.new(name: 'david', password: 'mUc3m00RsqyRe')
-
# user.save
-
# user.authenticate('notright') # => false
-
# user.authenticate('mUc3m00RsqyRe') # => user
-
1
def authenticate(unencrypted_password)
-
BCrypt::Password.new(password_digest) == unencrypted_password && self
-
end
-
-
1
attr_reader :password
-
-
# Encrypts the password into the +password_digest+ attribute, only if the
-
# new password is not empty.
-
#
-
# class User < ActiveRecord::Base
-
# has_secure_password validations: false
-
# end
-
#
-
# user = User.new
-
# user.password = nil
-
# user.password_digest # => nil
-
# user.password = 'mUc3m00RsqyRe'
-
# user.password_digest # => "$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/xeUVtMTYqwIvYY76EW5GUqDiP4."
-
1
def password=(unencrypted_password)
-
if unencrypted_password.nil?
-
self.password_digest = nil
-
elsif !unencrypted_password.empty?
-
@password = unencrypted_password
-
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
-
self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost)
-
end
-
end
-
-
1
def password_confirmation=(unencrypted_password)
-
@password_confirmation = unencrypted_password
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActiveModel
-
# == Active \Model \Serialization
-
#
-
# Provides a basic serialization to a serializable_hash for your objects.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Serialization
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# {'name' => nil}
-
# end
-
# end
-
#
-
# Which would provide you with:
-
#
-
# person = Person.new
-
# person.serializable_hash # => {"name"=>nil}
-
# person.name = "Bob"
-
# person.serializable_hash # => {"name"=>"Bob"}
-
#
-
# An +attributes+ hash must be defined and should contain any attributes you
-
# need to be serialized. Attributes must be strings, not symbols.
-
# When called, serializable hash will use instance methods that match the name
-
# of the attributes hash's keys. In order to override this behavior, take a look
-
# at the private method +read_attribute_for_serialization+.
-
#
-
# Most of the time though, either the JSON or XML serializations are needed.
-
# Both of these modules automatically include the
-
# <tt>ActiveModel::Serialization</tt> module, so there is no need to
-
# explicitly include it.
-
#
-
# A minimal implementation including XML and JSON would be:
-
#
-
# class Person
-
# include ActiveModel::Serializers::JSON
-
# include ActiveModel::Serializers::Xml
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# {'name' => nil}
-
# end
-
# end
-
#
-
# Which would provide you with:
-
#
-
# person = Person.new
-
# person.serializable_hash # => {"name"=>nil}
-
# person.as_json # => {"name"=>nil}
-
# person.to_json # => "{\"name\":null}"
-
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
#
-
# person.name = "Bob"
-
# person.serializable_hash # => {"name"=>"Bob"}
-
# person.as_json # => {"name"=>"Bob"}
-
# person.to_json # => "{\"name\":\"Bob\"}"
-
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
#
-
# Valid options are <tt>:only</tt>, <tt>:except</tt>, <tt>:methods</tt> and
-
# <tt>:include</tt>. The following are all valid examples:
-
#
-
# person.serializable_hash(only: 'name')
-
# person.serializable_hash(include: :address)
-
# person.serializable_hash(include: { address: { only: 'city' }})
-
1
module Serialization
-
# Returns a serialized hash of your object.
-
#
-
# class Person
-
# include ActiveModel::Serialization
-
#
-
# attr_accessor :name, :age
-
#
-
# def attributes
-
# {'name' => nil, 'age' => nil}
-
# end
-
#
-
# def capitalized_name
-
# name.capitalize
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'bob'
-
# person.age = 22
-
# person.serializable_hash # => {"name"=>"bob", "age"=>22}
-
# person.serializable_hash(only: :name) # => {"name"=>"bob"}
-
# person.serializable_hash(except: :name) # => {"age"=>22}
-
# person.serializable_hash(methods: :capitalized_name)
-
# # => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"}
-
1
def serializable_hash(options = nil)
-
options ||= {}
-
-
attribute_names = attributes.keys
-
if only = options[:only]
-
attribute_names &= Array(only).map(&:to_s)
-
elsif except = options[:except]
-
attribute_names -= Array(except).map(&:to_s)
-
end
-
-
hash = {}
-
attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }
-
-
Array(options[:methods]).each { |m| hash[m.to_s] = send(m) if respond_to?(m) }
-
-
serializable_add_includes(options) do |association, records, opts|
-
hash[association.to_s] = if records.respond_to?(:to_ary)
-
records.to_ary.map { |a| a.serializable_hash(opts) }
-
else
-
records.serializable_hash(opts)
-
end
-
end
-
-
hash
-
end
-
-
1
private
-
-
# Hook method defining how an attribute value should be retrieved for
-
# serialization. By default this is assumed to be an instance named after
-
# the attribute. Override this method in subclasses should you need to
-
# retrieve the value for a given attribute differently:
-
#
-
# class MyClass
-
# include ActiveModel::Serialization
-
#
-
# def initialize(data = {})
-
# @data = data
-
# end
-
#
-
# def read_attribute_for_serialization(key)
-
# @data[key]
-
# end
-
# end
-
1
alias :read_attribute_for_serialization :send
-
-
# Add associations specified via the <tt>:include</tt> option.
-
#
-
# Expects a block that takes as arguments:
-
# +association+ - name of the association
-
# +records+ - the association record(s) to be serialized
-
# +opts+ - options for the association records
-
1
def serializable_add_includes(options = {}) #:nodoc:
-
return unless includes = options[:include]
-
-
unless includes.is_a?(Hash)
-
includes = Hash[Array(includes).map { |n| n.is_a?(Hash) ? n.to_a.first : [n, {}] }]
-
end
-
-
includes.each do |association, opts|
-
if records = send(association)
-
yield association, records, opts
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/json'
-
-
1
module ActiveModel
-
1
module Serializers
-
# == Active \Model \JSON \Serializer
-
1
module JSON
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Serialization
-
-
1
included do
-
1
extend ActiveModel::Naming
-
-
1
class_attribute :include_root_in_json
-
1
self.include_root_in_json = false
-
end
-
-
# Returns a hash representing the model. Some configuration can be
-
# passed through +options+.
-
#
-
# The option <tt>include_root_in_json</tt> controls the top-level behavior
-
# of +as_json+. If +true+, +as_json+ will emit a single root node named
-
# after the object's type. The default value for <tt>include_root_in_json</tt>
-
# option is +false+.
-
#
-
# user = User.find(1)
-
# user.as_json
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true}
-
#
-
# ActiveRecord::Base.include_root_in_json = true
-
#
-
# user.as_json
-
# # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true } }
-
#
-
# This behavior can also be achieved by setting the <tt>:root</tt> option
-
# to +true+ as in:
-
#
-
# user = User.find(1)
-
# user.as_json(root: true)
-
# # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true } }
-
#
-
# Without any +options+, the returned Hash will include all the model's
-
# attributes.
-
#
-
# user = User.find(1)
-
# user.as_json
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true}
-
#
-
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit
-
# the attributes included, and work similar to the +attributes+ method.
-
#
-
# user.as_json(only: [:id, :name])
-
# # => { "id" => 1, "name" => "Konata Izumi" }
-
#
-
# user.as_json(except: [:id, :created_at, :age])
-
# # => { "name" => "Konata Izumi", "awesome" => true }
-
#
-
# To include the result of some method calls on the model use <tt>:methods</tt>:
-
#
-
# user.as_json(methods: :permalink)
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "permalink" => "1-konata-izumi" }
-
#
-
# To include associations use <tt>:include</tt>:
-
#
-
# user.as_json(include: :posts)
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "posts" => [ { "id" => 1, "author_id" => 1, "title" => "Welcome to the weblog" },
-
# # { "id" => 2, "author_id" => 1, "title" => "So I was thinking" } ] }
-
#
-
# Second level and higher order associations work as well:
-
#
-
# user.as_json(include: { posts: {
-
# include: { comments: {
-
# only: :body } },
-
# only: :title } })
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "posts" => [ { "comments" => [ { "body" => "1st post!" }, { "body" => "Second!" } ],
-
# # "title" => "Welcome to the weblog" },
-
# # { "comments" => [ { "body" => "Don't think too hard" } ],
-
# # "title" => "So I was thinking" } ] }
-
1
def as_json(options = nil)
-
root = if options && options.key?(:root)
-
options[:root]
-
else
-
include_root_in_json
-
end
-
-
if root
-
root = model_name.element if root == true
-
{ root => serializable_hash(options) }
-
else
-
serializable_hash(options)
-
end
-
end
-
-
# Sets the model +attributes+ from a JSON string. Returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Serializers::JSON
-
#
-
# attr_accessor :name, :age, :awesome
-
#
-
# def attributes=(hash)
-
# hash.each do |key, value|
-
# send("#{key}=", value)
-
# end
-
# end
-
#
-
# def attributes
-
# instance_values
-
# end
-
# end
-
#
-
# json = { name: 'bob', age: 22, awesome:true }.to_json
-
# person = Person.new
-
# person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
#
-
# The default value for +include_root+ is +false+. You can change it to
-
# +true+ if the given JSON string includes a single root node.
-
#
-
# json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
-
# person = Person.new
-
# person.from_json(json, true) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
1
def from_json(json, include_root=include_root_in_json)
-
hash = ActiveSupport::JSON.decode(json)
-
hash = hash.values.first if include_root
-
self.attributes = hash
-
self
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/time/acts_like'
-
-
1
module ActiveModel
-
1
module Serializers
-
# == Active Model XML Serializer
-
1
module Xml
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Serialization
-
-
1
included do
-
1
extend ActiveModel::Naming
-
end
-
-
1
class Serializer #:nodoc:
-
1
class Attribute #:nodoc:
-
1
attr_reader :name, :value, :type
-
-
1
def initialize(name, serializable, value)
-
@name, @serializable = name, serializable
-
-
if value.acts_like?(:time) && value.respond_to?(:in_time_zone)
-
value = value.in_time_zone
-
end
-
-
@value = value
-
@type = compute_type
-
end
-
-
1
def decorations
-
decorations = {}
-
decorations[:encoding] = 'base64' if type == :binary
-
decorations[:type] = (type == :string) ? nil : type
-
decorations[:nil] = true if value.nil?
-
decorations
-
end
-
-
1
protected
-
-
1
def compute_type
-
return if value.nil?
-
type = ActiveSupport::XmlMini::TYPE_NAMES[value.class.name]
-
type ||= :string if value.respond_to?(:to_str)
-
type ||= :yaml
-
type
-
end
-
end
-
-
1
class MethodAttribute < Attribute #:nodoc:
-
end
-
-
1
attr_reader :options
-
-
1
def initialize(serializable, options = nil)
-
@serializable = serializable
-
@options = options ? options.dup : {}
-
end
-
-
1
def serializable_hash
-
@serializable.serializable_hash(@options.except(:include))
-
end
-
-
1
def serializable_collection
-
methods = Array(options[:methods]).map(&:to_s)
-
serializable_hash.map do |name, value|
-
name = name.to_s
-
if methods.include?(name)
-
self.class::MethodAttribute.new(name, @serializable, value)
-
else
-
self.class::Attribute.new(name, @serializable, value)
-
end
-
end
-
end
-
-
1
def serialize
-
require 'builder' unless defined? ::Builder
-
-
options[:indent] ||= 2
-
options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
-
-
@builder = options[:builder]
-
@builder.instruct! unless options[:skip_instruct]
-
-
root = (options[:root] || @serializable.model_name.element).to_s
-
root = ActiveSupport::XmlMini.rename_key(root, options)
-
-
args = [root]
-
args << { xmlns: options[:namespace] } if options[:namespace]
-
args << { type: options[:type] } if options[:type] && !options[:skip_types]
-
-
@builder.tag!(*args) do
-
add_attributes_and_methods
-
add_includes
-
add_extra_behavior
-
add_procs
-
yield @builder if block_given?
-
end
-
end
-
-
1
private
-
-
1
def add_extra_behavior
-
end
-
-
1
def add_attributes_and_methods
-
serializable_collection.each do |attribute|
-
key = ActiveSupport::XmlMini.rename_key(attribute.name, options)
-
ActiveSupport::XmlMini.to_tag(key, attribute.value,
-
options.merge(attribute.decorations))
-
end
-
end
-
-
1
def add_includes
-
@serializable.send(:serializable_add_includes, options) do |association, records, opts|
-
add_associations(association, records, opts)
-
end
-
end
-
-
# TODO: This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
-
1
def add_associations(association, records, opts)
-
merged_options = opts.merge(options.slice(:builder, :indent))
-
merged_options[:skip_instruct] = true
-
-
[:skip_types, :dasherize, :camelize].each do |key|
-
merged_options[key] = options[key] if merged_options[key].nil? && !options[key].nil?
-
end
-
-
if records.respond_to?(:to_ary)
-
records = records.to_ary
-
-
tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
-
type = options[:skip_types] ? { } : { type: "array" }
-
association_name = association.to_s.singularize
-
merged_options[:root] = association_name
-
-
if records.empty?
-
@builder.tag!(tag, type)
-
else
-
@builder.tag!(tag, type) do
-
records.each do |record|
-
if options[:skip_types]
-
record_type = {}
-
else
-
record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
-
record_type = { type: record_class }
-
end
-
-
record.to_xml merged_options.merge(record_type)
-
end
-
end
-
end
-
else
-
merged_options[:root] = association.to_s
-
-
unless records.class.to_s.underscore == association.to_s
-
merged_options[:type] = records.class.name
-
end
-
-
records.to_xml merged_options
-
end
-
end
-
-
1
def add_procs
-
if procs = options.delete(:procs)
-
Array(procs).each do |proc|
-
if proc.arity == 1
-
proc.call(options)
-
else
-
proc.call(options, @serializable)
-
end
-
end
-
end
-
end
-
end
-
-
# Returns XML representing the model. Configuration can be
-
# passed through +options+.
-
#
-
# Without any +options+, the returned XML string will include all the
-
# model's attributes.
-
#
-
# user = User.find(1)
-
# user.to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <user>
-
# <id type="integer">1</id>
-
# <name>David</name>
-
# <age type="integer">16</age>
-
# <created-at type="dateTime">2011-01-30T22:29:23Z</created-at>
-
# </user>
-
#
-
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the
-
# attributes included, and work similar to the +attributes+ method.
-
#
-
# To include the result of some method calls on the model use <tt>:methods</tt>.
-
#
-
# To include associations use <tt>:include</tt>.
-
#
-
# For further documentation, see <tt>ActiveRecord::Serialization#to_xml</tt>
-
1
def to_xml(options = {}, &block)
-
Serializer.new(self, options).serialize(&block)
-
end
-
-
# Sets the model +attributes+ from an XML string. Returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Serializers::Xml
-
#
-
# attr_accessor :name, :age, :awesome
-
#
-
# def attributes=(hash)
-
# hash.each do |key, value|
-
# instance_variable_set("@#{key}", value)
-
# end
-
# end
-
#
-
# def attributes
-
# instance_values
-
# end
-
# end
-
#
-
# xml = { name: 'bob', age: 22, awesome:true }.to_xml
-
# person = Person.new
-
# person.from_xml(xml) # => #<Person:0x007fec5e3b3c40 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
1
def from_xml(xml)
-
self.attributes = Hash.from_xml(xml).values.first
-
self
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
# == Active \Model \Translation
-
#
-
# Provides integration between your object and the Rails internationalization
-
# (i18n) framework.
-
#
-
# A minimal implementation could be:
-
#
-
# class TranslatedPerson
-
# extend ActiveModel::Translation
-
# end
-
#
-
# TranslatedPerson.human_attribute_name('my_attribute')
-
# # => "My attribute"
-
#
-
# This also provides the required class methods for hooking into the
-
# Rails internationalization API, including being able to define a
-
# class based +i18n_scope+ and +lookup_ancestors+ to find translations in
-
# parent classes.
-
1
module Translation
-
1
include ActiveModel::Naming
-
-
# Returns the +i18n_scope+ for the class. Overwrite if you want custom lookup.
-
1
def i18n_scope
-
:activemodel
-
end
-
-
# When localizing a string, it goes through the lookup returned by this
-
# method, which is used in ActiveModel::Name#human,
-
# ActiveModel::Errors#full_messages and
-
# ActiveModel::Translation#human_attribute_name.
-
1
def lookup_ancestors
-
self.ancestors.select { |x| x.respond_to?(:model_name) }
-
end
-
-
# Transforms attribute names into a more human format, such as "First name"
-
# instead of "first_name".
-
#
-
# Person.human_attribute_name("first_name") # => "First name"
-
#
-
# Specify +options+ with additional translating options.
-
1
def human_attribute_name(attribute, options = {})
-
2
options = { count: 1 }.merge!(options)
-
2
parts = attribute.to_s.split(".")
-
2
attribute = parts.pop
-
2
namespace = parts.join("/") unless parts.empty?
-
2
attributes_scope = "#{self.i18n_scope}.attributes"
-
-
2
if namespace
-
defaults = lookup_ancestors.map do |klass|
-
:"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}"
-
end
-
defaults << :"#{attributes_scope}.#{namespace}.#{attribute}"
-
else
-
2
defaults = lookup_ancestors.map do |klass|
-
2
:"#{attributes_scope}.#{klass.model_name.i18n_key}.#{attribute}"
-
end
-
end
-
-
2
defaults << :"attributes.#{attribute}"
-
2
defaults << options.delete(:default) if options[:default]
-
2
defaults << attribute.humanize
-
-
2
options[:default] = defaults
-
2
I18n.translate(defaults.shift, options)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/hash/except'
-
-
1
module ActiveModel
-
-
# == Active \Model \Validations
-
#
-
# Provides a full validation framework to your objects.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :first_name, :last_name
-
#
-
# validates_each :first_name, :last_name do |record, attr, value|
-
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
-
# end
-
# end
-
#
-
# Which provides you with the full standard validation stack that you
-
# know from Active Record:
-
#
-
# person = Person.new
-
# person.valid? # => true
-
# person.invalid? # => false
-
#
-
# person.first_name = 'zoolander'
-
# person.valid? # => false
-
# person.invalid? # => true
-
# person.errors.messages # => {first_name:["starts with z."]}
-
#
-
# Note that <tt>ActiveModel::Validations</tt> automatically adds an +errors+
-
# method to your instances initialized with a new <tt>ActiveModel::Errors</tt>
-
# object, so there is no need for you to do this manually.
-
1
module Validations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
extend ActiveModel::Naming
-
1
extend ActiveModel::Callbacks
-
1
extend ActiveModel::Translation
-
-
1
extend HelperMethods
-
1
include HelperMethods
-
-
1
attr_accessor :validation_context
-
1
define_callbacks :validate, scope: :name
-
-
1
class_attribute :_validators
-
14
self._validators = Hash.new { |h,k| h[k] = [] }
-
end
-
-
1
module ClassMethods
-
# Validates each attribute against a block.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :first_name, :last_name
-
#
-
# validates_each :first_name, :last_name, allow_blank: true do |record, attr, value|
-
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
-
# end
-
# end
-
#
-
# Options:
-
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
-
# Runs in all validation contexts by default (nil). You can pass a symbol
-
# or an array of symbols. (e.g. <tt>on: :create</tt> or
-
# <tt>on: :custom_validation_context</tt> or
-
# <tt>on: [:create, :custom_validation_context]</tt>)
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
-
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
1
def validates_each(*attr_names, &block)
-
validates_with BlockValidator, _merge_attributes(attr_names), &block
-
end
-
-
1
VALID_OPTIONS_FOR_VALIDATE = [:on, :if, :unless, :prepend].freeze # :nodoc:
-
-
# Adds a validation method or block to the class. This is useful when
-
# overriding the +validate+ instance method becomes too unwieldy and
-
# you're looking for more descriptive declaration of your validations.
-
#
-
# This can be done with a symbol pointing to a method:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate :must_be_friends
-
#
-
# def must_be_friends
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# With a block which is passed with the current record to be validated:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate do |comment|
-
# comment.must_be_friends
-
# end
-
#
-
# def must_be_friends
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# Or with a block where self points to the current record to be validated:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate do
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# Note that the return value of validation methods is not relevant.
-
# It's not possible to halt the validate callback chain.
-
#
-
# Options:
-
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
-
# Runs in all validation contexts by default (nil). You can pass a symbol
-
# or an array of symbols. (e.g. <tt>on: :create</tt> or
-
# <tt>on: :custom_validation_context</tt> or
-
# <tt>on: [:create, :custom_validation_context]</tt>)
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
1
def validate(*args, &block)
-
5
options = args.extract_options!
-
-
10
if args.all? { |arg| arg.is_a?(Symbol) }
-
1
options.each_key do |k|
-
unless VALID_OPTIONS_FOR_VALIDATE.include?(k)
-
raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{VALID_OPTIONS_FOR_VALIDATE.map(&:inspect).join(', ')}. Perhaps you meant to call `validates` instead of `validate`?")
-
end
-
end
-
end
-
-
5
if options.key?(:on)
-
options = options.dup
-
options[:if] = Array(options[:if])
-
options[:if].unshift ->(o) {
-
Array(options[:on]).include?(o.validation_context)
-
}
-
end
-
-
5
args << options
-
5
set_callback(:validate, *args, &block)
-
end
-
-
# List all validators that are being used to validate the model using
-
# +validates_with+ method.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validates_with MyValidator
-
# validates_with OtherValidator, on: :create
-
# validates_with StrictValidator, strict: true
-
# end
-
#
-
# Person.validators
-
# # => [
-
# # #<MyValidator:0x007fbff403e808 @options={}>,
-
# # #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
-
# # #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
-
# # ]
-
1
def validators
-
_validators.values.flatten.uniq
-
end
-
-
# Clears all of the validators and validations.
-
#
-
# Note that this will clear anything that is being used to validate
-
# the model for both the +validates_with+ and +validate+ methods.
-
# It clears the validators that are created with an invocation of
-
# +validates_with+ and the callbacks that are set by an invocation
-
# of +validate+.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validates_with MyValidator
-
# validates_with OtherValidator, on: :create
-
# validates_with StrictValidator, strict: true
-
# validate :cannot_be_robot
-
#
-
# def cannot_be_robot
-
# errors.add(:base, 'A person cannot be a robot') if person_is_robot
-
# end
-
# end
-
#
-
# Person.validators
-
# # => [
-
# # #<MyValidator:0x007fbff403e808 @options={}>,
-
# # #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
-
# # #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
-
# # ]
-
#
-
# If one runs <tt>Person.clear_validators!</tt> and then checks to see what
-
# validators this class has, you would obtain:
-
#
-
# Person.validators # => []
-
#
-
# Also, the callback set by <tt>validate :cannot_be_robot</tt> will be erased
-
# so that:
-
#
-
# Person._validate_callbacks.empty? # => true
-
#
-
1
def clear_validators!
-
reset_callbacks(:validate)
-
_validators.clear
-
end
-
-
# List all validators that are being used to validate a specific attribute.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name , :age
-
#
-
# validates_presence_of :name
-
# validates_inclusion_of :age, in: 0..99
-
# end
-
#
-
# Person.validators_on(:name)
-
# # => [
-
# # #<ActiveModel::Validations::PresenceValidator:0x007fe604914e60 @attributes=[:name], @options={}>,
-
# # ]
-
1
def validators_on(*attributes)
-
attributes.flat_map do |attribute|
-
_validators[attribute.to_sym]
-
end
-
end
-
-
# Returns +true+ if +attribute+ is an attribute method, +false+ otherwise.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# end
-
#
-
# User.attribute_method?(:name) # => true
-
# User.attribute_method?(:age) # => false
-
1
def attribute_method?(attribute)
-
method_defined?(attribute)
-
end
-
-
# Copy validators on inheritance.
-
1
def inherited(base) #:nodoc:
-
5
dup = _validators.dup
-
5
base._validators = dup.each { |k, v| dup[k] = v.dup }
-
5
super
-
end
-
end
-
-
# Clean the +Errors+ object if instance is duped.
-
1
def initialize_dup(other) #:nodoc:
-
@errors = nil
-
super
-
end
-
-
# Returns the +Errors+ object that holds all information about attribute
-
# error messages.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.valid? # => false
-
# person.errors # => #<ActiveModel::Errors:0x007fe603816640 @messages={name:["can't be blank"]}>
-
1
def errors
-
199
@errors ||= Errors.new(self)
-
end
-
-
# Runs all the specified validations and returns +true+ if no errors were
-
# added otherwise +false+.
-
#
-
# Aliased as validate.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid? # => false
-
# person.name = 'david'
-
# person.valid? # => true
-
#
-
# Context can optionally be supplied to define which callbacks to test
-
# against (the context is defined on the validations using <tt>:on</tt>).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name, on: :new
-
# end
-
#
-
# person = Person.new
-
# person.valid? # => true
-
# person.valid?(:new) # => false
-
1
def valid?(context = nil)
-
29
current_context, self.validation_context = validation_context, context
-
29
errors.clear
-
29
run_validations!
-
ensure
-
29
self.validation_context = current_context
-
end
-
-
1
alias_method :validate, :valid?
-
-
# Performs the opposite of <tt>valid?</tt>. Returns +true+ if errors were
-
# added, +false+ otherwise.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.invalid? # => true
-
# person.name = 'david'
-
# person.invalid? # => false
-
#
-
# Context can optionally be supplied to define which callbacks to test
-
# against (the context is defined on the validations using <tt>:on</tt>).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name, on: :new
-
# end
-
#
-
# person = Person.new
-
# person.invalid? # => false
-
# person.invalid?(:new) # => true
-
1
def invalid?(context = nil)
-
!valid?(context)
-
end
-
-
# Hook method defining how an attribute value should be retrieved. By default
-
# this is assumed to be an instance named after the attribute. Override this
-
# method in subclasses should you need to retrieve the value for a given
-
# attribute differently:
-
#
-
# class MyClass
-
# include ActiveModel::Validations
-
#
-
# def initialize(data = {})
-
# @data = data
-
# end
-
#
-
# def read_attribute_for_validation(key)
-
# @data[key]
-
# end
-
# end
-
1
alias :read_attribute_for_validation :send
-
-
1
protected
-
-
1
def run_validations! #:nodoc:
-
29
_run_validate_callbacks
-
29
errors.empty?
-
end
-
end
-
end
-
-
14
Dir[File.dirname(__FILE__) + "/validations/*.rb"].each { |file| require file }
-
1
module ActiveModel
-
1
module Validations
-
# == Active Model Absence Validator
-
1
class AbsenceValidator < EachValidator #:nodoc:
-
1
def validate_each(record, attr_name, value)
-
record.errors.add(attr_name, :present, options) if value.present?
-
end
-
end
-
-
1
module HelperMethods
-
# Validates that the specified attributes are blank (as defined by
-
# Object#blank?). Happens by default on save.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_absence_of :first_name
-
# end
-
#
-
# The first_name attribute must be in the object and it must be blank.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "must be blank").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_absence_of(*attr_names)
-
validates_with AbsenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class AcceptanceValidator < EachValidator # :nodoc:
-
1
def initialize(options)
-
super({ allow_nil: true, accept: "1" }.merge!(options))
-
setup!(options[:class])
-
end
-
-
1
def validate_each(record, attribute, value)
-
unless value == options[:accept]
-
record.errors.add(attribute, :accepted, options.except(:accept, :allow_nil))
-
end
-
end
-
-
1
private
-
1
def setup!(klass)
-
attr_readers = attributes.reject { |name| klass.attribute_method?(name) }
-
attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") }
-
klass.send(:attr_reader, *attr_readers)
-
klass.send(:attr_writer, *attr_writers)
-
end
-
end
-
-
1
module HelperMethods
-
# Encapsulates the pattern of wanting to validate the acceptance of a
-
# terms of service check box (or similar agreement).
-
#
-
# class Person < ActiveRecord::Base
-
# validates_acceptance_of :terms_of_service
-
# validates_acceptance_of :eula, message: 'must be abided'
-
# end
-
#
-
# If the database column does not exist, the +terms_of_service+ attribute
-
# is entirely virtual. This check is performed only if +terms_of_service+
-
# is not +nil+ and by default on save.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "must be
-
# accepted").
-
# * <tt>:accept</tt> - Specifies value that is considered accepted.
-
# The default value is a string "1", which makes it easy to relate to
-
# an HTML checkbox. This should be set to +true+ if you are validating
-
# a database column, since the attribute is typecast from "1" to +true+
-
# before validation.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information.
-
1
def validates_acceptance_of(*attr_names)
-
validates_with AcceptanceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
1
module Validations
-
# == Active \Model \Validation \Callbacks
-
#
-
# Provides an interface for any class to have +before_validation+ and
-
# +after_validation+ callbacks.
-
#
-
# First, include ActiveModel::Validations::Callbacks from the class you are
-
# creating:
-
#
-
# class MyModel
-
# include ActiveModel::Validations::Callbacks
-
#
-
# before_validation :do_stuff_before_validation
-
# after_validation :do_stuff_after_validation
-
# end
-
#
-
# Like other <tt>before_*</tt> callbacks if +before_validation+ returns
-
# +false+ then <tt>valid?</tt> will not be called.
-
1
module Callbacks
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
include ActiveSupport::Callbacks
-
1
define_callbacks :validation,
-
terminator: ->(_,result) { result == false },
-
skip_after_callbacks_if_terminated: true,
-
scope: [:kind, :name]
-
end
-
-
1
module ClassMethods
-
# Defines a callback that will get called right before validation
-
# happens.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# include ActiveModel::Validations::Callbacks
-
#
-
# attr_accessor :name
-
#
-
# validates_length_of :name, maximum: 6
-
#
-
# before_validation :remove_whitespaces
-
#
-
# private
-
#
-
# def remove_whitespaces
-
# name.strip!
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = ' bob '
-
# person.valid? # => true
-
# person.name # => "bob"
-
1
def before_validation(*args, &block)
-
options = args.last
-
if options.is_a?(Hash) && options[:on]
-
options[:if] = Array(options[:if])
-
options[:on] = Array(options[:on])
-
options[:if].unshift ->(o) {
-
options[:on].include? o.validation_context
-
}
-
end
-
set_callback(:validation, :before, *args, &block)
-
end
-
-
# Defines a callback that will get called right after validation
-
# happens.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# include ActiveModel::Validations::Callbacks
-
#
-
# attr_accessor :name, :status
-
#
-
# validates_presence_of :name
-
#
-
# after_validation :set_status
-
#
-
# private
-
#
-
# def set_status
-
# self.status = errors.empty?
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid? # => false
-
# person.status # => false
-
# person.name = 'bob'
-
# person.valid? # => true
-
# person.status # => true
-
1
def after_validation(*args, &block)
-
options = args.extract_options!
-
options[:prepend] = true
-
options[:if] = Array(options[:if])
-
if options[:on]
-
options[:on] = Array(options[:on])
-
options[:if].unshift ->(o) {
-
options[:on].include? o.validation_context
-
}
-
end
-
set_callback(:validation, :after, *(args << options), &block)
-
end
-
end
-
-
1
protected
-
-
# Overwrite run validations to include callbacks.
-
1
def run_validations! #:nodoc:
-
58
_run_validation_callbacks { super }
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/range'
-
-
1
module ActiveModel
-
1
module Validations
-
1
module Clusivity #:nodoc:
-
1
ERROR_MESSAGE = "An object with the method #include? or a proc, lambda or symbol is required, " \
-
"and must be supplied as the :in (or :within) option of the configuration hash"
-
-
1
def check_validity!
-
unless delimiter.respond_to?(:include?) || delimiter.respond_to?(:call) || delimiter.respond_to?(:to_sym)
-
raise ArgumentError, ERROR_MESSAGE
-
end
-
end
-
-
1
private
-
-
1
def include?(record, value)
-
members = if delimiter.respond_to?(:call)
-
delimiter.call(record)
-
elsif delimiter.respond_to?(:to_sym)
-
record.send(delimiter)
-
else
-
delimiter
-
end
-
-
members.send(inclusion_method(members), value)
-
end
-
-
1
def delimiter
-
@delimiter ||= options[:in] || options[:within]
-
end
-
-
# In Ruby 1.9 <tt>Range#include?</tt> on non-number-or-time-ish ranges checks all
-
# possible values in the range for equality, which is slower but more accurate.
-
# <tt>Range#cover?</tt> uses the previous logic of comparing a value with the range
-
# endpoints, which is fast but is only accurate on Numeric, Time, or DateTime ranges.
-
1
def inclusion_method(enumerable)
-
if enumerable.is_a? Range
-
case enumerable.first
-
when Numeric, Time, DateTime
-
:cover?
-
else
-
:include?
-
end
-
else
-
:include?
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class ConfirmationValidator < EachValidator # :nodoc:
-
1
def initialize(options)
-
super
-
setup!(options[:class])
-
end
-
-
1
def validate_each(record, attribute, value)
-
if (confirmed = record.send("#{attribute}_confirmation")) && (value != confirmed)
-
human_attribute_name = record.class.human_attribute_name(attribute)
-
record.errors.add(:"#{attribute}_confirmation", :confirmation, options.merge(attribute: human_attribute_name))
-
end
-
end
-
-
1
private
-
1
def setup!(klass)
-
klass.send(:attr_reader, *attributes.map do |attribute|
-
:"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation")
-
end.compact)
-
-
klass.send(:attr_writer, *attributes.map do |attribute|
-
:"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation=")
-
end.compact)
-
end
-
end
-
-
1
module HelperMethods
-
# Encapsulates the pattern of wanting to validate a password or email
-
# address field with a confirmation.
-
#
-
# Model:
-
# class Person < ActiveRecord::Base
-
# validates_confirmation_of :user_name, :password
-
# validates_confirmation_of :email_address,
-
# message: 'should match confirmation'
-
# end
-
#
-
# View:
-
# <%= password_field "person", "password" %>
-
# <%= password_field "person", "password_confirmation" %>
-
#
-
# The added +password_confirmation+ attribute is virtual; it exists only
-
# as an in-memory attribute for validating the password. To achieve this,
-
# the validation adds accessors to the model for the confirmation
-
# attribute.
-
#
-
# NOTE: This check is performed only if +password_confirmation+ is not
-
# +nil+. To require confirmation, make sure to add a presence check for
-
# the confirmation attribute:
-
#
-
# validates_presence_of :password_confirmation, if: :password_changed?
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "doesn't match
-
# <tt>%{translated_attribute_name}</tt>").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_confirmation_of(*attr_names)
-
validates_with ConfirmationValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require "active_model/validations/clusivity"
-
-
1
module ActiveModel
-
-
1
module Validations
-
1
class ExclusionValidator < EachValidator # :nodoc:
-
1
include Clusivity
-
-
1
def validate_each(record, attribute, value)
-
if include?(record, value)
-
record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(value: value))
-
end
-
end
-
end
-
-
1
module HelperMethods
-
# Validates that the value of the specified attribute is not in a
-
# particular enumerable object.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_exclusion_of :username, in: %w( admin superuser ), message: "You don't belong here"
-
# validates_exclusion_of :age, in: 30..60, message: 'This site is only for under 30 and over 60'
-
# validates_exclusion_of :format, in: %w( mov avi ), message: "extension %{value} is not allowed"
-
# validates_exclusion_of :password, in: ->(person) { [person.username, person.first_name] },
-
# message: 'should not be the same as your username or first name'
-
# validates_exclusion_of :karma, in: :reserved_karmas
-
# end
-
#
-
# Configuration options:
-
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't
-
# be part of. This can be supplied as a proc, lambda or symbol which returns an
-
# enumerable. If the enumerable is a range the test is performed with
-
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
-
# <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>.
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
-
# reserved").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_exclusion_of(*attr_names)
-
validates_with ExclusionValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class FormatValidator < EachValidator # :nodoc:
-
1
def validate_each(record, attribute, value)
-
if options[:with]
-
regexp = option_call(record, :with)
-
record_error(record, attribute, :with, value) if value.to_s !~ regexp
-
elsif options[:without]
-
regexp = option_call(record, :without)
-
record_error(record, attribute, :without, value) if value.to_s =~ regexp
-
end
-
end
-
-
1
def check_validity!
-
unless options.include?(:with) ^ options.include?(:without) # ^ == xor, or "exclusive or"
-
raise ArgumentError, "Either :with or :without must be supplied (but not both)"
-
end
-
-
check_options_validity :with
-
check_options_validity :without
-
end
-
-
1
private
-
-
1
def option_call(record, name)
-
option = options[name]
-
option.respond_to?(:call) ? option.call(record) : option
-
end
-
-
1
def record_error(record, attribute, name, value)
-
record.errors.add(attribute, :invalid, options.except(name).merge!(value: value))
-
end
-
-
1
def check_options_validity(name)
-
if option = options[name]
-
if option.is_a?(Regexp)
-
if options[:multiline] != true && regexp_using_multiline_anchors?(option)
-
raise ArgumentError, "The provided regular expression is using multiline anchors (^ or $), " \
-
"which may present a security risk. Did you mean to use \\A and \\z, or forgot to add the " \
-
":multiline => true option?"
-
end
-
elsif !option.respond_to?(:call)
-
raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}"
-
end
-
end
-
end
-
-
1
def regexp_using_multiline_anchors?(regexp)
-
source = regexp.source
-
source.start_with?("^") || (source.end_with?("$") && !source.end_with?("\\$"))
-
end
-
end
-
-
1
module HelperMethods
-
# Validates whether the value of the specified attribute is of the correct
-
# form, going by the regular expression provided. You can require that the
-
# attribute matches the regular expression:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create
-
# end
-
#
-
# Alternatively, you can require that the specified attribute does _not_
-
# match the regular expression:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_format_of :email, without: /NOSPAM/
-
# end
-
#
-
# You can also provide a proc or lambda which will determine the regular
-
# expression that will be used to validate the attribute.
-
#
-
# class Person < ActiveRecord::Base
-
# # Admin can have number as a first letter in their screen name
-
# validates_format_of :screen_name,
-
# with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
-
# end
-
#
-
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the
-
# string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
-
#
-
# Due to frequent misuse of <tt>^</tt> and <tt>$</tt>, you need to pass
-
# the <tt>multiline: true</tt> option in case you use any of these two
-
# anchors in the provided regular expression. In most cases, you should be
-
# using <tt>\A</tt> and <tt>\z</tt>.
-
#
-
# You must pass either <tt>:with</tt> or <tt>:without</tt> as an option.
-
# In addition, both must be a regular expression or a proc or lambda, or
-
# else an exception will be raised.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
-
# * <tt>:with</tt> - Regular expression that if the attribute matches will
-
# result in a successful validation. This can be provided as a proc or
-
# lambda returning regular expression which will be called at runtime.
-
# * <tt>:without</tt> - Regular expression that if the attribute does not
-
# match will result in a successful validation. This can be provided as
-
# a proc or lambda returning regular expression which will be called at
-
# runtime.
-
# * <tt>:multiline</tt> - Set to true if your regular expression contains
-
# anchors that match the beginning or end of lines as opposed to the
-
# beginning or end of the string. These anchors are <tt>^</tt> and <tt>$</tt>.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_format_of(*attr_names)
-
validates_with FormatValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require "active_model/validations/clusivity"
-
-
1
module ActiveModel
-
-
1
module Validations
-
1
class InclusionValidator < EachValidator # :nodoc:
-
1
include Clusivity
-
-
1
def validate_each(record, attribute, value)
-
unless include?(record, value)
-
record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(value: value))
-
end
-
end
-
end
-
-
1
module HelperMethods
-
# Validates whether the value of the specified attribute is available in a
-
# particular enumerable object.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_inclusion_of :gender, in: %w( m f )
-
# validates_inclusion_of :age, in: 0..99
-
# validates_inclusion_of :format, in: %w( jpg gif png ), message: "extension %{value} is not included in the list"
-
# validates_inclusion_of :states, in: ->(person) { STATES[person.country] }
-
# validates_inclusion_of :karma, in: :available_karmas
-
# end
-
#
-
# Configuration options:
-
# * <tt>:in</tt> - An enumerable object of available items. This can be
-
# supplied as a proc, lambda or symbol which returns an enumerable. If the
-
# enumerable is a numerical range the test is performed with <tt>Range#cover?</tt>,
-
# otherwise with <tt>include?</tt>. When using a proc or lambda the instance
-
# under validation is passed as an argument.
-
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
-
# not included in the list").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_inclusion_of(*attr_names)
-
validates_with InclusionValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
# == Active \Model Length Validator
-
1
module Validations
-
1
class LengthValidator < EachValidator # :nodoc:
-
1
MESSAGES = { is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze
-
1
CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze
-
-
1
RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]
-
-
1
def initialize(options)
-
if range = (options.delete(:in) || options.delete(:within))
-
raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
-
options[:minimum], options[:maximum] = range.min, range.max
-
end
-
-
if options[:allow_blank] == false && options[:minimum].nil? && options[:is].nil?
-
options[:minimum] = 1
-
end
-
-
super
-
end
-
-
1
def check_validity!
-
keys = CHECKS.keys & options.keys
-
-
if keys.empty?
-
raise ArgumentError, 'Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option.'
-
end
-
-
keys.each do |key|
-
value = options[key]
-
-
unless (value.is_a?(Integer) && value >= 0) || value == Float::INFINITY
-
raise ArgumentError, ":#{key} must be a nonnegative Integer or Infinity"
-
end
-
end
-
end
-
-
1
def validate_each(record, attribute, value)
-
value = tokenize(value)
-
value_length = value.respond_to?(:length) ? value.length : value.to_s.length
-
errors_options = options.except(*RESERVED_OPTIONS)
-
-
CHECKS.each do |key, validity_check|
-
next unless check_value = options[key]
-
-
if !value.nil? || skip_nil_check?(key)
-
next if value_length.send(validity_check, check_value)
-
end
-
-
errors_options[:count] = check_value
-
-
default_message = options[MESSAGES[key]]
-
errors_options[:message] ||= default_message if default_message
-
-
record.errors.add(attribute, MESSAGES[key], errors_options)
-
end
-
end
-
-
1
private
-
-
1
def tokenize(value)
-
if options[:tokenizer] && value.kind_of?(String)
-
options[:tokenizer].call(value)
-
end || value
-
end
-
-
1
def skip_nil_check?(key)
-
key == :maximum && options[:allow_nil].nil? && options[:allow_blank].nil?
-
end
-
end
-
-
1
module HelperMethods
-
-
# Validates that the specified attribute matches the length restrictions
-
# supplied. Only one option can be used at a time:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_length_of :first_name, maximum: 30
-
# validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind"
-
# validates_length_of :fax, in: 7..32, allow_nil: true
-
# validates_length_of :phone, in: 7..32, allow_blank: true
-
# validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
-
# validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
-
# validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
-
# validates_length_of :essay, minimum: 100, too_short: 'Your essay must be at least 100 words.',
-
# tokenizer: ->(str) { str.scan(/\w+/) }
-
# end
-
#
-
# Configuration options:
-
# * <tt>:minimum</tt> - The minimum size of the attribute.
-
# * <tt>:maximum</tt> - The maximum size of the attribute. Allows +nil+ by
-
# default if not used with :minimum.
-
# * <tt>:is</tt> - The exact size of the attribute.
-
# * <tt>:within</tt> - A range specifying the minimum and maximum size of
-
# the attribute.
-
# * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>.
-
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
-
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
-
# * <tt>:too_long</tt> - The error message if the attribute goes over the
-
# maximum (default is: "is too long (maximum is %{count} characters)").
-
# * <tt>:too_short</tt> - The error message if the attribute goes under the
-
# minimum (default is: "is too short (min is %{count} characters)").
-
# * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt>
-
# method and the attribute is the wrong size (default is: "is the wrong
-
# length (should be %{count} characters)").
-
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>,
-
# <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate
-
# <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
-
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string.
-
# (e.g. <tt>tokenizer: ->(str) { str.scan(/\w+/) }</tt> to count words
-
# as in above example). Defaults to <tt>->(value) { value.split(//) }</tt>
-
# which counts individual characters.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_length_of(*attr_names)
-
validates_with LengthValidator, _merge_attributes(attr_names)
-
end
-
-
1
alias_method :validates_size_of, :validates_length_of
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class NumericalityValidator < EachValidator # :nodoc:
-
1
CHECKS = { greater_than: :>, greater_than_or_equal_to: :>=,
-
equal_to: :==, less_than: :<, less_than_or_equal_to: :<=,
-
odd: :odd?, even: :even?, other_than: :!= }.freeze
-
-
1
RESERVED_OPTIONS = CHECKS.keys + [:only_integer]
-
-
1
def check_validity!
-
keys = CHECKS.keys - [:odd, :even]
-
options.slice(*keys).each do |option, value|
-
unless value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol)
-
raise ArgumentError, ":#{option} must be a number, a symbol or a proc"
-
end
-
end
-
end
-
-
1
def validate_each(record, attr_name, value)
-
before_type_cast = :"#{attr_name}_before_type_cast"
-
-
raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast)
-
raw_value ||= value
-
-
if record_attribute_changed_in_place?(record, attr_name)
-
raw_value = value
-
end
-
-
return if options[:allow_nil] && raw_value.nil?
-
-
unless value = parse_raw_value_as_a_number(raw_value)
-
record.errors.add(attr_name, :not_a_number, filtered_options(raw_value))
-
return
-
end
-
-
if allow_only_integer?(record)
-
unless value = parse_raw_value_as_an_integer(raw_value)
-
record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value))
-
return
-
end
-
end
-
-
options.slice(*CHECKS.keys).each do |option, option_value|
-
case option
-
when :odd, :even
-
unless value.to_i.send(CHECKS[option])
-
record.errors.add(attr_name, option, filtered_options(value))
-
end
-
else
-
case option_value
-
when Proc
-
option_value = option_value.call(record)
-
when Symbol
-
option_value = record.send(option_value)
-
end
-
-
unless value.send(CHECKS[option], option_value)
-
record.errors.add(attr_name, option, filtered_options(value).merge!(count: option_value))
-
end
-
end
-
end
-
end
-
-
1
protected
-
-
1
def parse_raw_value_as_a_number(raw_value)
-
Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/
-
rescue ArgumentError, TypeError
-
nil
-
end
-
-
1
def parse_raw_value_as_an_integer(raw_value)
-
raw_value.to_i if raw_value.to_s =~ /\A[+-]?\d+\z/
-
end
-
-
1
def filtered_options(value)
-
filtered = options.except(*RESERVED_OPTIONS)
-
filtered[:value] = value
-
filtered
-
end
-
-
1
def allow_only_integer?(record)
-
case options[:only_integer]
-
when Symbol
-
record.send(options[:only_integer])
-
when Proc
-
options[:only_integer].call(record)
-
else
-
options[:only_integer]
-
end
-
end
-
-
1
private
-
-
1
def record_attribute_changed_in_place?(record, attr_name)
-
record.respond_to?(:attribute_changed_in_place?) &&
-
record.attribute_changed_in_place?(attr_name.to_s)
-
end
-
end
-
-
1
module HelperMethods
-
# Validates whether the value of the specified attribute is numeric by
-
# trying to convert it to a float with Kernel.Float (if <tt>only_integer</tt>
-
# is +false+) or applying it to the regular expression <tt>/\A[\+\-]?\d+\Z/</tt>
-
# (if <tt>only_integer</tt> is set to +true+).
-
#
-
# class Person < ActiveRecord::Base
-
# validates_numericality_of :value, on: :create
-
# end
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
-
# * <tt>:only_integer</tt> - Specifies whether the value has to be an
-
# integer, e.g. an integral value (default is +false+).
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is
-
# +false+). Notice that for fixnum and float columns empty strings are
-
# converted to +nil+.
-
# * <tt>:greater_than</tt> - Specifies the value must be greater than the
-
# supplied value.
-
# * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be
-
# greater than or equal the supplied value.
-
# * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied
-
# value.
-
# * <tt>:less_than</tt> - Specifies the value must be less than the
-
# supplied value.
-
# * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less
-
# than or equal the supplied value.
-
# * <tt>:other_than</tt> - Specifies the value must be other than the
-
# supplied value.
-
# * <tt>:odd</tt> - Specifies the value must be an odd number.
-
# * <tt>:even</tt> - Specifies the value must be an even number.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+ .
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
#
-
# The following checks can also be supplied with a proc or a symbol which
-
# corresponds to a method:
-
#
-
# * <tt>:greater_than</tt>
-
# * <tt>:greater_than_or_equal_to</tt>
-
# * <tt>:equal_to</tt>
-
# * <tt>:less_than</tt>
-
# * <tt>:less_than_or_equal_to</tt>
-
# * <tt>:only_integer</tt>
-
#
-
# For example:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_numericality_of :width, less_than: ->(person) { person.height }
-
# validates_numericality_of :width, greater_than: :minimum_weight
-
# end
-
1
def validates_numericality_of(*attr_names)
-
validates_with NumericalityValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
-
1
module ActiveModel
-
-
1
module Validations
-
1
class PresenceValidator < EachValidator # :nodoc:
-
1
def validate_each(record, attr_name, value)
-
93
record.errors.add(attr_name, :blank, options) if value.blank?
-
end
-
end
-
-
1
module HelperMethods
-
# Validates that the specified attributes are not blank (as defined by
-
# Object#blank?). Happens by default on save.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_presence_of :first_name
-
# end
-
#
-
# The first_name attribute must be in the object and it cannot be blank.
-
#
-
# If you want to validate the presence of a boolean field (where the real
-
# values are +true+ and +false+), you will want to use
-
# <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
-
#
-
# This is due to the way Object#blank? handles boolean values:
-
# <tt>false.blank? # => true</tt>.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_presence_of(*attr_names)
-
validates_with PresenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActiveModel
-
1
module Validations
-
1
module ClassMethods
-
# This method is a shortcut to all default validators and any custom
-
# validator classes ending in 'Validator'. Note that Rails default
-
# validators can be overridden inside specific classes by creating
-
# custom validator classes in their place such as PresenceValidator.
-
#
-
# Examples of using the default rails validators:
-
#
-
# validates :terms, acceptance: true
-
# validates :password, confirmation: true
-
# validates :username, exclusion: { in: %w(admin superuser) }
-
# validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
-
# validates :age, inclusion: { in: 0..9 }
-
# validates :first_name, length: { maximum: 30 }
-
# validates :age, numericality: true
-
# validates :username, presence: true
-
# validates :username, uniqueness: true
-
#
-
# The power of the +validates+ method comes when using custom validators
-
# and default validators in one call for a given attribute.
-
#
-
# class EmailValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, (options[:message] || "is not an email") unless
-
# value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
-
# end
-
# end
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# attr_accessor :name, :email
-
#
-
# validates :name, presence: true, uniqueness: true, length: { maximum: 100 }
-
# validates :email, presence: true, email: true
-
# end
-
#
-
# Validator classes may also exist within the class being validated
-
# allowing custom modules of validators to be included as needed.
-
#
-
# class Film
-
# include ActiveModel::Validations
-
#
-
# class TitleValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i
-
# end
-
# end
-
#
-
# validates :name, title: true
-
# end
-
#
-
# Additionally validator classes may be in another namespace and still
-
# used within any class.
-
#
-
# validates :name, :'film/title' => true
-
#
-
# The validators hash can also handle regular expressions, ranges, arrays
-
# and strings in shortcut form.
-
#
-
# validates :email, format: /@/
-
# validates :gender, inclusion: %w(male female)
-
# validates :password, length: 6..20
-
#
-
# When using shortcut form, ranges and arrays are passed to your
-
# validator's initializer as <tt>options[:in]</tt> while other types
-
# including regular expressions and strings are passed as <tt>options[:with]</tt>.
-
#
-
# There is also a list of options that could be used along with validators:
-
#
-
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
-
# Runs in all validation contexts by default (nil). You can pass a symbol
-
# or an array of symbols. (e.g. <tt>on: :create</tt> or
-
# <tt>on: :custom_validation_context</tt> or
-
# <tt>on: [:create, :custom_validation_context]</tt>)
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:allow_nil</tt> - Skip validation if the attribute is +nil+.
-
# * <tt>:allow_blank</tt> - Skip validation if the attribute is blank.
-
# * <tt>:strict</tt> - If the <tt>:strict</tt> option is set to true
-
# will raise ActiveModel::StrictValidationFailed instead of adding the error.
-
# <tt>:strict</tt> option can also be set to any other exception.
-
#
-
# Example:
-
#
-
# validates :password, presence: true, confirmation: true, if: :password_required?
-
# validates :token, uniqueness: true, strict: TokenGenerationException
-
#
-
#
-
# Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+, +:strict+
-
# and +:message+ can be given to one specific validator, as a hash:
-
#
-
# validates :password, presence: { if: :password_required?, message: 'is forgotten.' }, confirmation: true
-
1
def validates(*attributes)
-
defaults = attributes.extract_options!.dup
-
validations = defaults.slice!(*_validates_default_keys)
-
-
raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
-
raise ArgumentError, "You need to supply at least one validation" if validations.empty?
-
-
defaults[:attributes] = attributes
-
-
validations.each do |key, options|
-
next unless options
-
key = "#{key.to_s.camelize}Validator"
-
-
begin
-
validator = key.include?('::') ? key.constantize : const_get(key)
-
rescue NameError
-
raise ArgumentError, "Unknown validator: '#{key}'"
-
end
-
-
validates_with(validator, defaults.merge(_parse_validates_options(options)))
-
end
-
end
-
-
# This method is used to define validations that cannot be corrected by end
-
# users and are considered exceptional. So each validator defined with bang
-
# or <tt>:strict</tt> option set to <tt>true</tt> will always raise
-
# <tt>ActiveModel::StrictValidationFailed</tt> instead of adding error
-
# when validation fails. See <tt>validates</tt> for more information about
-
# the validation itself.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates! :name, presence: true
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid?
-
# # => ActiveModel::StrictValidationFailed: Name can't be blank
-
1
def validates!(*attributes)
-
options = attributes.extract_options!
-
options[:strict] = true
-
validates(*(attributes << options))
-
end
-
-
1
protected
-
-
# When creating custom validators, it might be useful to be able to specify
-
# additional default keys. This can be done by overwriting this method.
-
1
def _validates_default_keys # :nodoc:
-
[:if, :unless, :on, :allow_blank, :allow_nil , :strict]
-
end
-
-
1
def _parse_validates_options(options) # :nodoc:
-
case options
-
when TrueClass
-
{}
-
when Hash
-
options
-
when Range, Array
-
{ in: options }
-
else
-
{ with: options }
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
1
module Validations
-
1
module HelperMethods
-
1
private
-
1
def _merge_attributes(attr_names)
-
4
options = attr_names.extract_options!.symbolize_keys
-
4
attr_names.flatten!
-
4
options[:attributes] = attr_names
-
4
options
-
end
-
end
-
-
1
class WithValidator < EachValidator # :nodoc:
-
1
def validate_each(record, attr, val)
-
method_name = options[:with]
-
-
if record.method(method_name).arity == 0
-
record.send method_name
-
else
-
record.send method_name, attr
-
end
-
end
-
end
-
-
1
module ClassMethods
-
# Passes the record off to the class or classes specified and allows them
-
# to add errors based on more complex conditions.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# if some_complex_logic
-
# record.errors.add :base, 'This record is invalid'
-
# end
-
# end
-
#
-
# private
-
# def some_complex_logic
-
# # ...
-
# end
-
# end
-
#
-
# You may also pass it multiple classes, like so:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator, MyOtherValidator, on: :create
-
# end
-
#
-
# Configuration options:
-
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
-
# Runs in all validation contexts by default (nil). You can pass a symbol
-
# or an array of symbols. (e.g. <tt>on: :create</tt> or
-
# <tt>on: :custom_validation_context</tt> or
-
# <tt>on: [:create, :custom_validation_context]</tt>)
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>).
-
# The method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur
-
# (e.g. <tt>unless: :skip_validation</tt>, or
-
# <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>).
-
# The method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
#
-
# If you pass any additional configuration options, they will be passed
-
# to the class and available as +options+:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator, my_custom_key: 'my custom value'
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# options[:my_custom_key] # => "my custom value"
-
# end
-
# end
-
1
def validates_with(*args, &block)
-
4
options = args.extract_options!
-
4
options[:class] = self
-
-
4
args.each do |klass|
-
4
validator = klass.new(options, &block)
-
-
4
if validator.respond_to?(:attributes) && !validator.attributes.empty?
-
4
validator.attributes.each do |attribute|
-
13
_validators[attribute.to_sym] << validator
-
end
-
else
-
_validators[nil] << validator
-
end
-
-
4
validate(validator, options)
-
end
-
end
-
end
-
-
# Passes the record off to the class or classes specified and allows them
-
# to add errors based on more complex conditions.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validate :instance_validations
-
#
-
# def instance_validations
-
# validates_with MyValidator
-
# end
-
# end
-
#
-
# Please consult the class method documentation for more information on
-
# creating your own validator.
-
#
-
# You may also pass it multiple classes, like so:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validate :instance_validations, on: :create
-
#
-
# def instance_validations
-
# validates_with MyValidator, MyOtherValidator
-
# end
-
# end
-
#
-
# Standard configuration options (<tt>:on</tt>, <tt>:if</tt> and
-
# <tt>:unless</tt>), which are available on the class version of
-
# +validates_with+, should instead be placed on the +validates+ method
-
# as these are applied and tested in the callback.
-
#
-
# If you pass any additional configuration options, they will be passed
-
# to the class and available as +options+, please refer to the
-
# class version of this method for more information.
-
1
def validates_with(*args, &block)
-
options = args.extract_options!
-
options[:class] = self.class
-
-
args.each do |klass|
-
validator = klass.new(options, &block)
-
validator.validate(self)
-
end
-
end
-
end
-
end
-
1
require "active_support/core_ext/module/anonymous"
-
-
1
module ActiveModel
-
-
# == Active \Model \Validator
-
#
-
# A simple base class that can be used along with
-
# ActiveModel::Validations::ClassMethods.validates_with
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# if some_complex_logic
-
# record.errors[:base] = "This record is invalid"
-
# end
-
# end
-
#
-
# private
-
# def some_complex_logic
-
# # ...
-
# end
-
# end
-
#
-
# Any class that inherits from ActiveModel::Validator must implement a method
-
# called +validate+ which accepts a +record+.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# record # => The person instance being validated
-
# options # => Any non-standard options passed to validates_with
-
# end
-
# end
-
#
-
# To cause a validation error, you must add to the +record+'s errors directly
-
# from within the validators message.
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# record.errors.add :base, "This is some custom error message"
-
# record.errors.add :first_name, "This is some complex validation"
-
# # etc...
-
# end
-
# end
-
#
-
# To add behavior to the initialize method, use the following signature:
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def initialize(options)
-
# super
-
# @my_custom_field = options[:field_name] || :first_name
-
# end
-
# end
-
#
-
# Note that the validator is initialized only once for the whole application
-
# life cycle, and not on each validation run.
-
#
-
# The easiest way to add custom validators for validating individual attributes
-
# is with the convenient <tt>ActiveModel::EachValidator</tt>.
-
#
-
# class TitleValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, 'must be Mr., Mrs., or Dr.' unless %w(Mr. Mrs. Dr.).include?(value)
-
# end
-
# end
-
#
-
# This can now be used in combination with the +validates+ method
-
# (see <tt>ActiveModel::Validations::ClassMethods.validates</tt> for more on this).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# attr_accessor :title
-
#
-
# validates :title, presence: true, title: true
-
# end
-
#
-
# It can be useful to access the class that is using that validator when there are prerequisites such
-
# as an +attr_accessor+ being present. This class is accessible via +options[:class]+ in the constructor.
-
# To setup your validator override the constructor.
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def initialize(options={})
-
# super
-
# options[:class].send :attr_accessor, :custom_attribute
-
# end
-
# end
-
1
class Validator
-
1
attr_reader :options
-
-
# Returns the kind of the validator.
-
#
-
# PresenceValidator.kind # => :presence
-
# UniquenessValidator.kind # => :uniqueness
-
1
def self.kind
-
@kind ||= name.split('::').last.underscore.sub(/_validator$/, '').to_sym unless anonymous?
-
end
-
-
# Accepts options that will be made available through the +options+ reader.
-
1
def initialize(options = {})
-
4
@options = options.except(:class).freeze
-
end
-
-
# Returns the kind for this validator.
-
#
-
# PresenceValidator.new.kind # => :presence
-
# UniquenessValidator.new.kind # => :uniqueness
-
1
def kind
-
self.class.kind
-
end
-
-
# Override this method in subclasses with validation logic, adding errors
-
# to the records +errors+ array where necessary.
-
1
def validate(record)
-
raise NotImplementedError, "Subclasses must implement a validate(record) method."
-
end
-
end
-
-
# +EachValidator+ is a validator which iterates through the attributes given
-
# in the options hash invoking the <tt>validate_each</tt> method passing in the
-
# record, attribute and value.
-
#
-
# All Active Model validations are built on top of this validator.
-
1
class EachValidator < Validator #:nodoc:
-
1
attr_reader :attributes
-
-
# Returns a new validator instance. All options will be available via the
-
# +options+ reader, however the <tt>:attributes</tt> option will be removed
-
# and instead be made available through the +attributes+ reader.
-
1
def initialize(options)
-
4
@attributes = Array(options.delete(:attributes))
-
4
raise ArgumentError, ":attributes cannot be blank" if @attributes.empty?
-
4
super
-
4
check_validity!
-
end
-
-
# Performs validation on the supplied record. By default this will call
-
# +validates_each+ to determine validity therefore subclasses should
-
# override +validates_each+ with validation logic.
-
1
def validate(record)
-
29
attributes.each do |attribute|
-
93
value = record.read_attribute_for_validation(attribute)
-
93
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
-
93
validate_each(record, attribute, value)
-
end
-
end
-
-
# Override this method in subclasses with the validation logic, adding
-
# errors to the records +errors+ array where necessary.
-
1
def validate_each(record, attribute, value)
-
raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method"
-
end
-
-
# Hook method that gets called by the initializer allowing verification
-
# that the arguments supplied are valid. You could for example raise an
-
# +ArgumentError+ when invalid options are supplied.
-
1
def check_validity!
-
end
-
end
-
-
# +BlockValidator+ is a special +EachValidator+ which receives a block on initialization
-
# and call this block for each attribute being validated. +validates_each+ uses this validator.
-
1
class BlockValidator < EachValidator #:nodoc:
-
1
def initialize(options, &block)
-
@block = block
-
super
-
end
-
-
1
private
-
-
1
def validate_each(record, attribute, value)
-
@block.call(record, attribute, value)
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActiveModel
-
# Returns the version of the currently loaded ActiveModel as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'active_model'
-
1
require 'arel'
-
-
1
require 'active_record/version'
-
1
require 'active_record/attribute_set'
-
-
1
module ActiveRecord
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Attribute
-
1
autoload :Base
-
1
autoload :Callbacks
-
1
autoload :Core
-
1
autoload :ConnectionHandling
-
1
autoload :CounterCache
-
1
autoload :DynamicMatchers
-
1
autoload :Enum
-
1
autoload :Explain
-
1
autoload :Inheritance
-
1
autoload :Integration
-
1
autoload :LegacyYamlAdapter
-
1
autoload :Migration
-
1
autoload :Migrator, 'active_record/migration'
-
1
autoload :ModelSchema
-
1
autoload :NestedAttributes
-
1
autoload :NoTouching
-
1
autoload :Persistence
-
1
autoload :QueryCache
-
1
autoload :Querying
-
1
autoload :ReadonlyAttributes
-
1
autoload :RecordInvalid, 'active_record/validations'
-
1
autoload :Reflection
-
1
autoload :RuntimeRegistry
-
1
autoload :Sanitization
-
1
autoload :Schema
-
1
autoload :SchemaDumper
-
1
autoload :SchemaMigration
-
1
autoload :Scoping
-
1
autoload :Serialization
-
1
autoload :StatementCache
-
1
autoload :Store
-
1
autoload :Timestamp
-
1
autoload :Transactions
-
1
autoload :Translation
-
1
autoload :Validations
-
-
1
eager_autoload do
-
1
autoload :ActiveRecordError, 'active_record/errors'
-
1
autoload :ConnectionNotEstablished, 'active_record/errors'
-
1
autoload :ConnectionAdapters, 'active_record/connection_adapters/abstract_adapter'
-
-
1
autoload :Aggregations
-
1
autoload :Associations
-
1
autoload :AttributeAssignment
-
1
autoload :AttributeMethods
-
1
autoload :AutosaveAssociation
-
-
1
autoload :Relation
-
1
autoload :AssociationRelation
-
1
autoload :NullRelation
-
-
1
autoload_under 'relation' do
-
1
autoload :QueryMethods
-
1
autoload :FinderMethods
-
1
autoload :Calculations
-
1
autoload :PredicateBuilder
-
1
autoload :SpawnMethods
-
1
autoload :Batches
-
1
autoload :Delegation
-
end
-
-
1
autoload :Result
-
end
-
-
1
module Coders
-
1
autoload :YAMLColumn, 'active_record/coders/yaml_column'
-
1
autoload :JSON, 'active_record/coders/json'
-
end
-
-
1
module AttributeMethods
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :BeforeTypeCast
-
1
autoload :Dirty
-
1
autoload :PrimaryKey
-
1
autoload :Query
-
1
autoload :Read
-
1
autoload :TimeZoneConversion
-
1
autoload :Write
-
1
autoload :Serialization
-
end
-
end
-
-
1
module Locking
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Optimistic
-
1
autoload :Pessimistic
-
end
-
end
-
-
1
module ConnectionAdapters
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :AbstractAdapter
-
1
autoload :ConnectionManagement, "active_record/connection_adapters/abstract/connection_pool"
-
end
-
end
-
-
1
module Scoping
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Named
-
1
autoload :Default
-
end
-
end
-
-
1
module Tasks
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :DatabaseTasks
-
1
autoload :SQLiteDatabaseTasks, 'active_record/tasks/sqlite_database_tasks'
-
1
autoload :MySQLDatabaseTasks, 'active_record/tasks/mysql_database_tasks'
-
1
autoload :PostgreSQLDatabaseTasks,
-
'active_record/tasks/postgresql_database_tasks'
-
end
-
-
1
autoload :TestFixtures, 'active_record/fixtures'
-
-
1
def self.eager_load!
-
super
-
ActiveRecord::Locking.eager_load!
-
ActiveRecord::Scoping.eager_load!
-
ActiveRecord::Associations.eager_load!
-
ActiveRecord::AttributeMethods.eager_load!
-
ActiveRecord::ConnectionAdapters.eager_load!
-
end
-
end
-
-
1
ActiveSupport.on_load(:active_record) do
-
1
Arel::Table.engine = self
-
end
-
-
1
ActiveSupport.on_load(:i18n) do
-
1
I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
-
end
-
1
module ActiveRecord
-
# = Active Record Aggregations
-
1
module Aggregations # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
def clear_aggregation_cache #:nodoc:
-
@aggregation_cache.clear if persisted?
-
end
-
-
# Active Record implements aggregation through a macro-like class method called +composed_of+
-
# for representing attributes as value objects. It expresses relationships like "Account [is]
-
# composed of Money [among other things]" or "Person [is] composed of [an] address". Each call
-
# to the macro adds a description of how the value objects are created from the attributes of
-
# the entity object (when the entity is initialized either as a new object or from finding an
-
# existing object) and how it can be turned back into attributes (when the entity is saved to
-
# the database).
-
#
-
# class Customer < ActiveRecord::Base
-
# composed_of :balance, class_name: "Money", mapping: %w(balance amount)
-
# composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
-
# end
-
#
-
# The customer class now has the following methods to manipulate the value objects:
-
# * <tt>Customer#balance, Customer#balance=(money)</tt>
-
# * <tt>Customer#address, Customer#address=(address)</tt>
-
#
-
# These methods will operate with value objects like the ones described below:
-
#
-
# class Money
-
# include Comparable
-
# attr_reader :amount, :currency
-
# EXCHANGE_RATES = { "USD_TO_DKK" => 6 }
-
#
-
# def initialize(amount, currency = "USD")
-
# @amount, @currency = amount, currency
-
# end
-
#
-
# def exchange_to(other_currency)
-
# exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
-
# Money.new(exchanged_amount, other_currency)
-
# end
-
#
-
# def ==(other_money)
-
# amount == other_money.amount && currency == other_money.currency
-
# end
-
#
-
# def <=>(other_money)
-
# if currency == other_money.currency
-
# amount <=> other_money.amount
-
# else
-
# amount <=> other_money.exchange_to(currency).amount
-
# end
-
# end
-
# end
-
#
-
# class Address
-
# attr_reader :street, :city
-
# def initialize(street, city)
-
# @street, @city = street, city
-
# end
-
#
-
# def close_to?(other_address)
-
# city == other_address.city
-
# end
-
#
-
# def ==(other_address)
-
# city == other_address.city && street == other_address.street
-
# end
-
# end
-
#
-
# Now it's possible to access attributes from the database through the value objects instead. If
-
# you choose to name the composition the same as the attribute's name, it will be the only way to
-
# access that attribute. That's the case with our +balance+ attribute. You interact with the value
-
# objects just like you would with any other attribute:
-
#
-
# customer.balance = Money.new(20) # sets the Money value object and the attribute
-
# customer.balance # => Money value object
-
# customer.balance.exchange_to("DKK") # => Money.new(120, "DKK")
-
# customer.balance > Money.new(10) # => true
-
# customer.balance == Money.new(20) # => true
-
# customer.balance < Money.new(5) # => false
-
#
-
# Value objects can also be composed of multiple attributes, such as the case of Address. The order
-
# of the mappings will determine the order of the parameters.
-
#
-
# customer.address_street = "Hyancintvej"
-
# customer.address_city = "Copenhagen"
-
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
-
#
-
# customer.address_street = "Vesterbrogade"
-
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
-
# customer.clear_aggregation_cache
-
# customer.address # => Address.new("Vesterbrogade", "Copenhagen")
-
#
-
# customer.address = Address.new("May Street", "Chicago")
-
# customer.address_street # => "May Street"
-
# customer.address_city # => "Chicago"
-
#
-
# == Writing value objects
-
#
-
# Value objects are immutable and interchangeable objects that represent a given value, such as
-
# a Money object representing $5. Two Money objects both representing $5 should be equal (through
-
# methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking makes sense). This is
-
# unlike entity objects where equality is determined by identity. An entity class such as Customer can
-
# easily have two different objects that both have an address on Hyancintvej. Entity identity is
-
# determined by object or relational unique identifiers (such as primary keys). Normal
-
# ActiveRecord::Base classes are entity objects.
-
#
-
# It's also important to treat the value objects as immutable. Don't allow the Money object to have
-
# its amount changed after creation. Create a new Money object with the new value instead. The
-
# Money#exchange_to method is an example of this. It returns a new value object instead of changing
-
# its own values. Active Record won't persist value objects that have been changed through means
-
# other than the writer method.
-
#
-
# The immutable requirement is enforced by Active Record by freezing any object assigned as a value
-
# object. Attempting to change it afterwards will result in a RuntimeError.
-
#
-
# Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not
-
# keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
-
#
-
# == Custom constructors and converters
-
#
-
# By default value objects are initialized by calling the <tt>new</tt> constructor of the value
-
# class passing each of the mapped attributes, in the order specified by the <tt>:mapping</tt>
-
# option, as arguments. If the value class doesn't support this convention then +composed_of+ allows
-
# a custom constructor to be specified.
-
#
-
# When a new value is assigned to the value object, the default assumption is that the new value
-
# is an instance of the value class. Specifying a custom converter allows the new value to be automatically
-
# converted to an instance of value class if necessary.
-
#
-
# For example, the NetworkResource model has +network_address+ and +cidr_range+ attributes that should be
-
# aggregated using the NetAddr::CIDR value class (http://www.ruby-doc.org/gems/docs/n/netaddr-1.5.0/NetAddr/CIDR.html).
-
# The constructor for the value class is called +create+ and it expects a CIDR address string as a parameter.
-
# New values can be assigned to the value object using either another NetAddr::CIDR object, a string
-
# or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to meet
-
# these requirements:
-
#
-
# class NetworkResource < ActiveRecord::Base
-
# composed_of :cidr,
-
# class_name: 'NetAddr::CIDR',
-
# mapping: [ %w(network_address network), %w(cidr_range bits) ],
-
# allow_nil: true,
-
# constructor: Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
-
# converter: Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
-
# end
-
#
-
# # This calls the :constructor
-
# network_resource = NetworkResource.new(network_address: '192.168.0.1', cidr_range: 24)
-
#
-
# # These assignments will both use the :converter
-
# network_resource.cidr = [ '192.168.2.1', 8 ]
-
# network_resource.cidr = '192.168.0.1/24'
-
#
-
# # This assignment won't use the :converter as the value is already an instance of the value class
-
# network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8')
-
#
-
# # Saving and then reloading will use the :constructor on reload
-
# network_resource.save
-
# network_resource.reload
-
#
-
# == Finding records by a value object
-
#
-
# Once a +composed_of+ relationship is specified for a model, records can be loaded from the database
-
# by specifying an instance of the value object in the conditions hash. The following example
-
# finds all customers with +balance_amount+ equal to 20 and +balance_currency+ equal to "USD":
-
#
-
# Customer.where(balance: Money.new(20, "USD"))
-
#
-
1
module ClassMethods
-
# Adds reader and writer methods for manipulating a value object:
-
# <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
-
#
-
# Options are:
-
# * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name
-
# can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked
-
# to the Address class, but if the real class name is CompanyAddress, you'll have to specify it
-
# with this option.
-
# * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
-
# object. Each mapping is represented as an array where the first item is the name of the
-
# entity attribute and the second item is the name of the attribute in the value object. The
-
# order in which mappings are defined determines the order in which attributes are sent to the
-
# value class constructor.
-
# * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped
-
# attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all
-
# mapped attributes.
-
# This defaults to +false+.
-
# * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that
-
# is called to initialize the value object. The constructor is passed all of the mapped attributes,
-
# in the order that they are defined in the <tt>:mapping option</tt>, as arguments and uses them
-
# to instantiate a <tt>:class_name</tt> object.
-
# The default is <tt>:new</tt>.
-
# * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt>
-
# or a Proc that is called when a new value is assigned to the value object. The converter is
-
# passed the single value that is used in the assignment and is only called if the new value is
-
# not an instance of <tt>:class_name</tt>. If <tt>:allow_nil</tt> is set to true, the converter
-
# can return nil to skip the assignment.
-
#
-
# Option examples:
-
# composed_of :temperature, mapping: %w(reading celsius)
-
# composed_of :balance, class_name: "Money", mapping: %w(balance amount),
-
# converter: Proc.new { |balance| balance.to_money }
-
# composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
-
# composed_of :gps_location
-
# composed_of :gps_location, allow_nil: true
-
# composed_of :ip_address,
-
# class_name: 'IPAddr',
-
# mapping: %w(ip to_i),
-
# constructor: Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
-
# converter: Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
-
#
-
1
def composed_of(part_id, options = {})
-
options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter)
-
-
name = part_id.id2name
-
class_name = options[:class_name] || name.camelize
-
mapping = options[:mapping] || [ name, name ]
-
mapping = [ mapping ] unless mapping.first.is_a?(Array)
-
allow_nil = options[:allow_nil] || false
-
constructor = options[:constructor] || :new
-
converter = options[:converter]
-
-
reader_method(name, class_name, mapping, allow_nil, constructor)
-
writer_method(name, class_name, mapping, allow_nil, converter)
-
-
reflection = ActiveRecord::Reflection.create(:composed_of, part_id, nil, options, self)
-
Reflection.add_aggregate_reflection self, part_id, reflection
-
end
-
-
1
private
-
1
def reader_method(name, class_name, mapping, allow_nil, constructor)
-
define_method(name) do
-
if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|key, _| !_read_attribute(key).nil? })
-
attrs = mapping.collect {|key, _| _read_attribute(key)}
-
object = constructor.respond_to?(:call) ?
-
constructor.call(*attrs) :
-
class_name.constantize.send(constructor, *attrs)
-
@aggregation_cache[name] = object
-
end
-
@aggregation_cache[name]
-
end
-
end
-
-
1
def writer_method(name, class_name, mapping, allow_nil, converter)
-
define_method("#{name}=") do |part|
-
klass = class_name.constantize
-
if part.is_a?(Hash)
-
part = klass.new(*part.values)
-
end
-
-
unless part.is_a?(klass) || converter.nil? || part.nil?
-
part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part)
-
end
-
-
if part.nil? && allow_nil
-
mapping.each { |key, _| self[key] = nil }
-
@aggregation_cache[name] = nil
-
else
-
mapping.each { |key, value| self[key] = part.send(value) }
-
@aggregation_cache[name] = part.freeze
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class AssociationRelation < Relation
-
1
def initialize(klass, table, association)
-
super(klass, table)
-
@association = association
-
end
-
-
1
def proxy_association
-
@association
-
end
-
-
1
def ==(other)
-
other == to_a
-
end
-
-
1
def build(*args, &block)
-
scoping { @association.build(*args, &block) }
-
end
-
1
alias new build
-
-
1
def create(*args, &block)
-
scoping { @association.create(*args, &block) }
-
end
-
-
1
def create!(*args, &block)
-
scoping { @association.create!(*args, &block) }
-
end
-
-
1
private
-
-
1
def exec_queries
-
super.each { |r| @association.set_inverse_instance r }
-
end
-
end
-
end
-
1
require 'active_support/core_ext/enumerable'
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_record/errors'
-
-
1
module ActiveRecord
-
1
class AssociationNotFoundError < ConfigurationError #:nodoc:
-
1
def initialize(record, association_name)
-
super("Association named '#{association_name}' was not found on #{record.class.name}; perhaps you misspelled it?")
-
end
-
end
-
-
1
class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
-
1
def initialize(reflection, associated_class = nil)
-
super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{associated_class.nil? ? reflection.class_name : associated_class.name})")
-
end
-
end
-
-
1
class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection)
-
super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}")
-
end
-
end
-
-
1
class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection, source_reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}' without 'source_type'. Try adding 'source_type: \"#{reflection.name.to_s.classify}\"' to 'has_many :through' definition.")
-
end
-
end
-
-
1
class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.")
-
end
-
end
-
-
1
class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection, source_reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
-
end
-
end
-
-
1
class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection, through_reflection)
-
super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.")
-
end
-
end
-
-
1
class HasOneAssociationPolymorphicThroughError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection)
-
super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.")
-
end
-
end
-
-
1
class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc:
-
1
def initialize(reflection)
-
through_reflection = reflection.through_reflection
-
source_reflection_names = reflection.source_reflection_names
-
source_associations = reflection.through_reflection.klass._reflections.keys
-
super("Could not find the source association(s) #{source_reflection_names.collect{ |a| a.inspect }.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
-
end
-
end
-
-
1
class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.")
-
end
-
end
-
-
1
class HasManyThroughCantAssociateNewRecords < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.")
-
end
-
end
-
-
1
class HasManyThroughCantDissociateNewRecords < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot dissociate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to delete the has_many :through record associating them.")
-
end
-
end
-
-
1
class HasManyThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.")
-
end
-
end
-
-
1
class EagerLoadPolymorphicError < ActiveRecordError #:nodoc:
-
1
def initialize(reflection)
-
super("Cannot eagerly load the polymorphic association #{reflection.name.inspect}")
-
end
-
end
-
-
1
class ReadOnlyAssociation < ActiveRecordError #:nodoc:
-
1
def initialize(reflection)
-
super("Cannot add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.")
-
end
-
end
-
-
# This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations
-
# (has_many, has_one) when there is at least 1 child associated instance.
-
# ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project
-
1
class DeleteRestrictionError < ActiveRecordError #:nodoc:
-
1
def initialize(name)
-
super("Cannot delete record because of dependent #{name}")
-
end
-
end
-
-
# See ActiveRecord::Associations::ClassMethods for documentation.
-
1
module Associations # :nodoc:
-
1
extend ActiveSupport::Autoload
-
1
extend ActiveSupport::Concern
-
-
# These classes will be loaded when associations are created.
-
# So there is no need to eager load them.
-
1
autoload :Association, 'active_record/associations/association'
-
1
autoload :SingularAssociation, 'active_record/associations/singular_association'
-
1
autoload :CollectionAssociation, 'active_record/associations/collection_association'
-
1
autoload :ForeignAssociation, 'active_record/associations/foreign_association'
-
1
autoload :CollectionProxy, 'active_record/associations/collection_proxy'
-
-
1
autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
-
1
autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
-
1
autoload :HasManyAssociation, 'active_record/associations/has_many_association'
-
1
autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
-
1
autoload :HasOneAssociation, 'active_record/associations/has_one_association'
-
1
autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
-
1
autoload :ThroughAssociation, 'active_record/associations/through_association'
-
-
1
module Builder #:nodoc:
-
1
autoload :Association, 'active_record/associations/builder/association'
-
1
autoload :SingularAssociation, 'active_record/associations/builder/singular_association'
-
1
autoload :CollectionAssociation, 'active_record/associations/builder/collection_association'
-
-
1
autoload :BelongsTo, 'active_record/associations/builder/belongs_to'
-
1
autoload :HasOne, 'active_record/associations/builder/has_one'
-
1
autoload :HasMany, 'active_record/associations/builder/has_many'
-
1
autoload :HasAndBelongsToMany, 'active_record/associations/builder/has_and_belongs_to_many'
-
end
-
-
1
eager_autoload do
-
1
autoload :Preloader, 'active_record/associations/preloader'
-
1
autoload :JoinDependency, 'active_record/associations/join_dependency'
-
1
autoload :AssociationScope, 'active_record/associations/association_scope'
-
1
autoload :AliasTracker, 'active_record/associations/alias_tracker'
-
end
-
-
# Clears out the association cache.
-
1
def clear_association_cache #:nodoc:
-
@association_cache.clear if persisted?
-
end
-
-
# :nodoc:
-
1
attr_reader :association_cache
-
-
# Returns the association instance for the given name, instantiating it if it doesn't already exist
-
1
def association(name) #:nodoc:
-
association = association_instance_get(name)
-
-
if association.nil?
-
raise AssociationNotFoundError.new(self, name) unless reflection = self.class._reflect_on_association(name)
-
association = reflection.association_class.new(self, reflection)
-
association_instance_set(name, association)
-
end
-
-
association
-
end
-
-
1
private
-
# Returns the specified association instance if it responds to :loaded?, nil otherwise.
-
1
def association_instance_get(name)
-
35
@association_cache[name]
-
end
-
-
# Set the specified association instance.
-
1
def association_instance_set(name, association)
-
@association_cache[name] = association
-
end
-
-
# \Associations are a set of macro-like class methods for tying objects together through
-
# foreign keys. They express relationships like "Project has one Project Manager"
-
# or "Project belongs to a Portfolio". Each macro adds a number of methods to the
-
# class which are specialized according to the collection or association symbol and the
-
# options hash. It works much the same way as Ruby's own <tt>attr*</tt>
-
# methods.
-
#
-
# class Project < ActiveRecord::Base
-
# belongs_to :portfolio
-
# has_one :project_manager
-
# has_many :milestones
-
# has_and_belongs_to_many :categories
-
# end
-
#
-
# The project class now has the following methods (and more) to ease the traversal and
-
# manipulation of its relationships:
-
# * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
-
# * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
-
# * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
-
# <tt>Project#milestones.delete(milestone), Project#milestones.destroy(milestone), Project#milestones.find(milestone_id),</tt>
-
# <tt>Project#milestones.build, Project#milestones.create</tt>
-
# * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
-
# <tt>Project#categories.delete(category1), Project#categories.destroy(category1)</tt>
-
#
-
# === A word of warning
-
#
-
# Don't create associations that have the same name as instance methods of
-
# <tt>ActiveRecord::Base</tt>. Since the association adds a method with that name to
-
# its model, it will override the inherited method and break things.
-
# For instance, +attributes+ and +connection+ would be bad choices for association names.
-
#
-
# == Auto-generated methods
-
# See also Instance Public methods below for more details.
-
#
-
# === Singular associations (one-to-one)
-
# | | belongs_to |
-
# generated methods | belongs_to | :polymorphic | has_one
-
# ----------------------------------+------------+--------------+---------
-
# other(force_reload=false) | X | X | X
-
# other=(other) | X | X | X
-
# build_other(attributes={}) | X | | X
-
# create_other(attributes={}) | X | | X
-
# create_other!(attributes={}) | X | | X
-
#
-
# ===Collection associations (one-to-many / many-to-many)
-
# | | | has_many
-
# generated methods | habtm | has_many | :through
-
# ----------------------------------+-------+----------+----------
-
# others(force_reload=false) | X | X | X
-
# others=(other,other,...) | X | X | X
-
# other_ids | X | X | X
-
# other_ids=(id,id,...) | X | X | X
-
# others<< | X | X | X
-
# others.push | X | X | X
-
# others.concat | X | X | X
-
# others.build(attributes={}) | X | X | X
-
# others.create(attributes={}) | X | X | X
-
# others.create!(attributes={}) | X | X | X
-
# others.size | X | X | X
-
# others.length | X | X | X
-
# others.count | X | X | X
-
# others.sum(*args) | X | X | X
-
# others.empty? | X | X | X
-
# others.clear | X | X | X
-
# others.delete(other,other,...) | X | X | X
-
# others.delete_all | X | X | X
-
# others.destroy(other,other,...) | X | X | X
-
# others.destroy_all | X | X | X
-
# others.find(*args) | X | X | X
-
# others.exists? | X | X | X
-
# others.distinct | X | X | X
-
# others.uniq | X | X | X
-
# others.reset | X | X | X
-
#
-
# === Overriding generated methods
-
#
-
# Association methods are generated in a module that is included into the model class,
-
# which allows you to easily override with your own methods and call the original
-
# generated method with +super+. For example:
-
#
-
# class Car < ActiveRecord::Base
-
# belongs_to :owner
-
# belongs_to :old_owner
-
# def owner=(new_owner)
-
# self.old_owner = self.owner
-
# super
-
# end
-
# end
-
#
-
# If your model class is <tt>Project</tt>, the module is
-
# named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
-
# included in the model class immediately after the (anonymous) generated attributes methods
-
# module, meaning an association will override the methods for an attribute with the same name.
-
#
-
# == Cardinality and associations
-
#
-
# Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
-
# relationships between models. Each model uses an association to describe its role in
-
# the relation. The +belongs_to+ association is always used in the model that has
-
# the foreign key.
-
#
-
# === One-to-one
-
#
-
# Use +has_one+ in the base, and +belongs_to+ in the associated model.
-
#
-
# class Employee < ActiveRecord::Base
-
# has_one :office
-
# end
-
# class Office < ActiveRecord::Base
-
# belongs_to :employee # foreign key - employee_id
-
# end
-
#
-
# === One-to-many
-
#
-
# Use +has_many+ in the base, and +belongs_to+ in the associated model.
-
#
-
# class Manager < ActiveRecord::Base
-
# has_many :employees
-
# end
-
# class Employee < ActiveRecord::Base
-
# belongs_to :manager # foreign key - manager_id
-
# end
-
#
-
# === Many-to-many
-
#
-
# There are two ways to build a many-to-many relationship.
-
#
-
# The first way uses a +has_many+ association with the <tt>:through</tt> option and a join model, so
-
# there are two stages of associations.
-
#
-
# class Assignment < ActiveRecord::Base
-
# belongs_to :programmer # foreign key - programmer_id
-
# belongs_to :project # foreign key - project_id
-
# end
-
# class Programmer < ActiveRecord::Base
-
# has_many :assignments
-
# has_many :projects, through: :assignments
-
# end
-
# class Project < ActiveRecord::Base
-
# has_many :assignments
-
# has_many :programmers, through: :assignments
-
# end
-
#
-
# For the second way, use +has_and_belongs_to_many+ in both models. This requires a join table
-
# that has no corresponding model or primary key.
-
#
-
# class Programmer < ActiveRecord::Base
-
# has_and_belongs_to_many :projects # foreign keys in the join table
-
# end
-
# class Project < ActiveRecord::Base
-
# has_and_belongs_to_many :programmers # foreign keys in the join table
-
# end
-
#
-
# Choosing which way to build a many-to-many relationship is not always simple.
-
# If you need to work with the relationship model as its own entity,
-
# use <tt>has_many :through</tt>. Use +has_and_belongs_to_many+ when working with legacy schemas or when
-
# you never work directly with the relationship itself.
-
#
-
# == Is it a +belongs_to+ or +has_one+ association?
-
#
-
# Both express a 1-1 relationship. The difference is mostly where to place the foreign
-
# key, which goes on the table for the class declaring the +belongs_to+ relationship.
-
#
-
# class User < ActiveRecord::Base
-
# # I reference an account.
-
# belongs_to :account
-
# end
-
#
-
# class Account < ActiveRecord::Base
-
# # One user references me.
-
# has_one :user
-
# end
-
#
-
# The tables for these classes could look something like:
-
#
-
# CREATE TABLE users (
-
# id int(11) NOT NULL auto_increment,
-
# account_id int(11) default NULL,
-
# name varchar default NULL,
-
# PRIMARY KEY (id)
-
# )
-
#
-
# CREATE TABLE accounts (
-
# id int(11) NOT NULL auto_increment,
-
# name varchar default NULL,
-
# PRIMARY KEY (id)
-
# )
-
#
-
# == Unsaved objects and associations
-
#
-
# You can manipulate objects and associations before they are saved to the database, but
-
# there is some special behavior you should be aware of, mostly involving the saving of
-
# associated objects.
-
#
-
# You can set the <tt>:autosave</tt> option on a <tt>has_one</tt>, <tt>belongs_to</tt>,
-
# <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association. Setting it
-
# to +true+ will _always_ save the members, whereas setting it to +false+ will
-
# _never_ save the members. More details about <tt>:autosave</tt> option is available at
-
# AutosaveAssociation.
-
#
-
# === One-to-one associations
-
#
-
# * Assigning an object to a +has_one+ association automatically saves that object and
-
# the object being replaced (if there is one), in order to update their foreign
-
# keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
-
# * If either of these saves fail (due to one of the objects being invalid), an
-
# <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
-
# cancelled.
-
# * If you wish to assign an object to a +has_one+ association without saving it,
-
# use the <tt>build_association</tt> method (documented below). The object being
-
# replaced will still be saved to update its foreign key.
-
# * Assigning an object to a +belongs_to+ association does not save the object, since
-
# the foreign key field belongs on the parent. It does not save the parent either.
-
#
-
# === Collections
-
#
-
# * Adding an object to a collection (+has_many+ or +has_and_belongs_to_many+) automatically
-
# saves that object, except if the parent object (the owner of the collection) is not yet
-
# stored in the database.
-
# * If saving any of the objects being added to a collection (via <tt>push</tt> or similar)
-
# fails, then <tt>push</tt> returns +false+.
-
# * If saving fails while replacing the collection (via <tt>association=</tt>), an
-
# <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
-
# cancelled.
-
# * You can add an object to a collection without automatically saving it by using the
-
# <tt>collection.build</tt> method (documented below).
-
# * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
-
# saved when the parent is saved.
-
#
-
# == Customizing the query
-
#
-
# \Associations are built from <tt>Relation</tt>s, and you can use the <tt>Relation</tt> syntax
-
# to customize them. For example, to add a condition:
-
#
-
# class Blog < ActiveRecord::Base
-
# has_many :published_posts, -> { where published: true }, class_name: 'Post'
-
# end
-
#
-
# Inside the <tt>-> { ... }</tt> block you can use all of the usual <tt>Relation</tt> methods.
-
#
-
# === Accessing the owner object
-
#
-
# Sometimes it is useful to have access to the owner object when building the query. The owner
-
# is passed as a parameter to the block. For example, the following association would find all
-
# events that occur on the user's birthday:
-
#
-
# class User < ActiveRecord::Base
-
# has_many :birthday_events, ->(user) { where starts_on: user.birthday }, class_name: 'Event'
-
# end
-
#
-
# Note: Joining, eager loading and preloading of these associations is not fully possible.
-
# These operations happen before instance creation and the scope will be called with a +nil+ argument.
-
# This can lead to unexpected behavior and is deprecated.
-
#
-
# == Association callbacks
-
#
-
# Similar to the normal callbacks that hook into the life cycle of an Active Record object,
-
# you can also define callbacks that get triggered when you add an object to or remove an
-
# object from an association collection.
-
#
-
# class Project
-
# has_and_belongs_to_many :developers, after_add: :evaluate_velocity
-
#
-
# def evaluate_velocity(developer)
-
# ...
-
# end
-
# end
-
#
-
# It's possible to stack callbacks by passing them as an array. Example:
-
#
-
# class Project
-
# has_and_belongs_to_many :developers,
-
# after_add: [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
-
# end
-
#
-
# Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
-
#
-
# If any of the +before_add+ callbacks throw an exception, the object will not be
-
# added to the collection.
-
#
-
# Similarly, if any of the +before_remove+ callbacks throw an exception, the object
-
# will not be removed from the collection.
-
#
-
# == Association extensions
-
#
-
# The proxy objects that control the access to associations can be extended through anonymous
-
# modules. This is especially beneficial for adding new finders, creators, and other
-
# factory-type methods that are only used as part of this association.
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people do
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by(first_name: first_name, last_name: last_name)
-
# end
-
# end
-
# end
-
#
-
# person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
-
# person.first_name # => "David"
-
# person.last_name # => "Heinemeier Hansson"
-
#
-
# If you need to share the same extensions between many associations, you can use a named
-
# extension module.
-
#
-
# module FindOrCreateByNameExtension
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by(first_name: first_name, last_name: last_name)
-
# end
-
# end
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people, -> { extending FindOrCreateByNameExtension }
-
# end
-
#
-
# class Company < ActiveRecord::Base
-
# has_many :people, -> { extending FindOrCreateByNameExtension }
-
# end
-
#
-
# Some extensions can only be made to work with knowledge of the association's internals.
-
# Extensions can access relevant state using the following methods (where +items+ is the
-
# name of the association):
-
#
-
# * <tt>record.association(:items).owner</tt> - Returns the object the association is part of.
-
# * <tt>record.association(:items).reflection</tt> - Returns the reflection object that describes the association.
-
# * <tt>record.association(:items).target</tt> - Returns the associated object for +belongs_to+ and +has_one+, or
-
# the collection of associated objects for +has_many+ and +has_and_belongs_to_many+.
-
#
-
# However, inside the actual extension code, you will not have access to the <tt>record</tt> as
-
# above. In this case, you can access <tt>proxy_association</tt>. For example,
-
# <tt>record.association(:items)</tt> and <tt>record.items.proxy_association</tt> will return
-
# the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside
-
# association extensions.
-
#
-
# == Association Join Models
-
#
-
# Has Many associations can be configured with the <tt>:through</tt> option to use an
-
# explicit join model to retrieve the data. This operates similarly to a
-
# +has_and_belongs_to_many+ association. The advantage is that you're able to add validations,
-
# callbacks, and extra attributes on the join model. Consider the following schema:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :authorships
-
# has_many :books, through: :authorships
-
# end
-
#
-
# class Authorship < ActiveRecord::Base
-
# belongs_to :author
-
# belongs_to :book
-
# end
-
#
-
# @author = Author.first
-
# @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to
-
# @author.books # selects all books by using the Authorship join model
-
#
-
# You can also go through a +has_many+ association on the join model:
-
#
-
# class Firm < ActiveRecord::Base
-
# has_many :clients
-
# has_many :invoices, through: :clients
-
# end
-
#
-
# class Client < ActiveRecord::Base
-
# belongs_to :firm
-
# has_many :invoices
-
# end
-
#
-
# class Invoice < ActiveRecord::Base
-
# belongs_to :client
-
# end
-
#
-
# @firm = Firm.first
-
# @firm.clients.flat_map { |c| c.invoices } # select all invoices for all clients of the firm
-
# @firm.invoices # selects all invoices by going through the Client join model
-
#
-
# Similarly you can go through a +has_one+ association on the join model:
-
#
-
# class Group < ActiveRecord::Base
-
# has_many :users
-
# has_many :avatars, through: :users
-
# end
-
#
-
# class User < ActiveRecord::Base
-
# belongs_to :group
-
# has_one :avatar
-
# end
-
#
-
# class Avatar < ActiveRecord::Base
-
# belongs_to :user
-
# end
-
#
-
# @group = Group.first
-
# @group.users.collect { |u| u.avatar }.compact # select all avatars for all users in the group
-
# @group.avatars # selects all avatars by going through the User join model.
-
#
-
# An important caveat with going through +has_one+ or +has_many+ associations on the
-
# join model is that these associations are *read-only*. For example, the following
-
# would not work following the previous example:
-
#
-
# @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around
-
# @group.avatars.delete(@group.avatars.last) # so would this
-
#
-
# == Setting Inverses
-
#
-
# If you are using a +belongs_to+ on the join model, it is a good idea to set the
-
# <tt>:inverse_of</tt> option on the +belongs_to+, which will mean that the following example
-
# works correctly (where <tt>tags</tt> is a +has_many+ <tt>:through</tt> association):
-
#
-
# @post = Post.first
-
# @tag = @post.tags.build name: "ruby"
-
# @tag.save
-
#
-
# The last line ought to save the through record (a <tt>Taggable</tt>). This will only work if the
-
# <tt>:inverse_of</tt> is set:
-
#
-
# class Taggable < ActiveRecord::Base
-
# belongs_to :post
-
# belongs_to :tag, inverse_of: :taggings
-
# end
-
#
-
# If you do not set the <tt>:inverse_of</tt> record, the association will
-
# do its best to match itself up with the correct inverse. Automatic
-
# inverse detection only works on <tt>has_many</tt>, <tt>has_one</tt>, and
-
# <tt>belongs_to</tt> associations.
-
#
-
# Extra options on the associations, as defined in the
-
# <tt>AssociationReflection::INVALID_AUTOMATIC_INVERSE_OPTIONS</tt> constant, will
-
# also prevent the association's inverse from being found automatically.
-
#
-
# The automatic guessing of the inverse association uses a heuristic based
-
# on the name of the class, so it may not work for all associations,
-
# especially the ones with non-standard names.
-
#
-
# You can turn off the automatic detection of inverse associations by setting
-
# the <tt>:inverse_of</tt> option to <tt>false</tt> like so:
-
#
-
# class Taggable < ActiveRecord::Base
-
# belongs_to :tag, inverse_of: false
-
# end
-
#
-
# == Nested \Associations
-
#
-
# You can actually specify *any* association with the <tt>:through</tt> option, including an
-
# association which has a <tt>:through</tt> option itself. For example:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# has_many :comments, through: :posts
-
# has_many :commenters, through: :comments
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# end
-
#
-
# class Comment < ActiveRecord::Base
-
# belongs_to :commenter
-
# end
-
#
-
# @author = Author.first
-
# @author.commenters # => People who commented on posts written by the author
-
#
-
# An equivalent way of setting up this association this would be:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# has_many :commenters, through: :posts
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# has_many :commenters, through: :comments
-
# end
-
#
-
# class Comment < ActiveRecord::Base
-
# belongs_to :commenter
-
# end
-
#
-
# When using a nested association, you will not be able to modify the association because there
-
# is not enough information to know what modification to make. For example, if you tried to
-
# add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the
-
# intermediate <tt>Post</tt> and <tt>Comment</tt> objects.
-
#
-
# == Polymorphic \Associations
-
#
-
# Polymorphic associations on models are not restricted on what types of models they
-
# can be associated with. Rather, they specify an interface that a +has_many+ association
-
# must adhere to.
-
#
-
# class Asset < ActiveRecord::Base
-
# belongs_to :attachable, polymorphic: true
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :assets, as: :attachable # The :as option specifies the polymorphic interface to use.
-
# end
-
#
-
# @asset.attachable = @post
-
#
-
# This works by using a type column in addition to a foreign key to specify the associated
-
# record. In the Asset example, you'd need an +attachable_id+ integer column and an
-
# +attachable_type+ string column.
-
#
-
# Using polymorphic associations in combination with single table inheritance (STI) is
-
# a little tricky. In order for the associations to work as expected, ensure that you
-
# store the base model for the STI models in the type column of the polymorphic
-
# association. To continue with the asset example above, suppose there are guest posts
-
# and member posts that use the posts table for STI. In this case, there must be a +type+
-
# column in the posts table.
-
#
-
# Note: The <tt>attachable_type=</tt> method is being called when assigning an +attachable+.
-
# The +class_name+ of the +attachable+ is passed as a String.
-
#
-
# class Asset < ActiveRecord::Base
-
# belongs_to :attachable, polymorphic: true
-
#
-
# def attachable_type=(class_name)
-
# super(class_name.constantize.base_class.to_s)
-
# end
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# # because we store "Post" in attachable_type now dependent: :destroy will work
-
# has_many :assets, as: :attachable, dependent: :destroy
-
# end
-
#
-
# class GuestPost < Post
-
# end
-
#
-
# class MemberPost < Post
-
# end
-
#
-
# == Caching
-
#
-
# All of the methods are built on a simple caching principle that will keep the result
-
# of the last query around unless specifically instructed not to. The cache is even
-
# shared across methods to make it even cheaper to use the macro-added methods without
-
# worrying too much about performance at the first go.
-
#
-
# project.milestones # fetches milestones from the database
-
# project.milestones.size # uses the milestone cache
-
# project.milestones.empty? # uses the milestone cache
-
# project.milestones(true).size # fetches milestones from the database
-
# project.milestones # uses the milestone cache
-
#
-
# == Eager loading of associations
-
#
-
# Eager loading is a way to find objects of a certain class and a number of named associations.
-
# It is one of the easiest ways to prevent the dreaded N+1 problem in which fetching 100
-
# posts that each need to display their author triggers 101 database queries. Through the
-
# use of eager loading, the number of queries will be reduced from 101 to 2.
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# has_many :comments
-
# end
-
#
-
# Consider the following loop using the class above:
-
#
-
# Post.all.each do |post|
-
# puts "Post: " + post.title
-
# puts "Written by: " + post.author.name
-
# puts "Last comment on: " + post.comments.first.created_on
-
# end
-
#
-
# To iterate over these one hundred posts, we'll generate 201 database queries. Let's
-
# first just optimize it for retrieving the author:
-
#
-
# Post.includes(:author).each do |post|
-
#
-
# This references the name of the +belongs_to+ association that also used the <tt>:author</tt>
-
# symbol. After loading the posts, find will collect the +author_id+ from each one and load
-
# all the referenced authors with one query. Doing so will cut down the number of queries
-
# from 201 to 102.
-
#
-
# We can improve upon the situation further by referencing both associations in the finder with:
-
#
-
# Post.includes(:author, :comments).each do |post|
-
#
-
# This will load all comments with a single query. This reduces the total number of queries
-
# to 3. In general, the number of queries will be 1 plus the number of associations
-
# named (except if some of the associations are polymorphic +belongs_to+ - see below).
-
#
-
# To include a deep hierarchy of associations, use a hash:
-
#
-
# Post.includes(:author, { comments: { author: :gravatar } }).each do |post|
-
#
-
# The above code will load all the comments and all of their associated
-
# authors and gravatars. You can mix and match any combination of symbols,
-
# arrays, and hashes to retrieve the associations you want to load.
-
#
-
# All of this power shouldn't fool you into thinking that you can pull out huge amounts
-
# of data with no performance penalty just because you've reduced the number of queries.
-
# The database still needs to send all the data to Active Record and it still needs to
-
# be processed. So it's no catch-all for performance problems, but it's a great way to
-
# cut down on the number of queries in a situation as the one described above.
-
#
-
# Since only one table is loaded at a time, conditions or orders cannot reference tables
-
# other than the main one. If this is the case, Active Record falls back to the previously
-
# used LEFT OUTER JOIN based strategy. For example:
-
#
-
# Post.includes([:author, :comments]).where(['comments.approved = ?', true])
-
#
-
# This will result in a single SQL query with joins along the lines of:
-
# <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
-
# <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions
-
# like this can have unintended consequences.
-
# In the above example posts with no approved comments are not returned at all, because
-
# the conditions apply to the SQL statement as a whole and not just to the association.
-
#
-
# You must disambiguate column references for this fallback to happen, for example
-
# <tt>order: "author.name DESC"</tt> will work but <tt>order: "name DESC"</tt> will not.
-
#
-
# If you want to load all posts (including posts with no approved comments) then write
-
# your own LEFT OUTER JOIN query using ON
-
#
-
# Post.joins("LEFT OUTER JOIN comments ON comments.post_id = posts.id AND comments.approved = '1'")
-
#
-
# In this case it is usually more natural to include an association which has conditions defined on it:
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :approved_comments, -> { where approved: true }, class_name: 'Comment'
-
# end
-
#
-
# Post.includes(:approved_comments)
-
#
-
# This will load posts and eager load the +approved_comments+ association, which contains
-
# only those comments that have been approved.
-
#
-
# If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored,
-
# returning all the associated objects:
-
#
-
# class Picture < ActiveRecord::Base
-
# has_many :most_recent_comments, -> { order('id DESC').limit(10) }, class_name: 'Comment'
-
# end
-
#
-
# Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
-
#
-
# Eager loading is supported with polymorphic associations.
-
#
-
# class Address < ActiveRecord::Base
-
# belongs_to :addressable, polymorphic: true
-
# end
-
#
-
# A call that tries to eager load the addressable model
-
#
-
# Address.includes(:addressable)
-
#
-
# This will execute one query to load the addresses and load the addressables with one
-
# query per addressable type.
-
# For example if all the addressables are either of class Person or Company then a total
-
# of 3 queries will be executed. The list of addressable types to load is determined on
-
# the back of the addresses loaded. This is not supported if Active Record has to fallback
-
# to the previous implementation of eager loading and will raise <tt>ActiveRecord::EagerLoadPolymorphicError</tt>.
-
# The reason is that the parent model's type is a column value so its corresponding table
-
# name cannot be put in the +FROM+/+JOIN+ clauses of that query.
-
#
-
# == Table Aliasing
-
#
-
# Active Record uses table aliasing in the case that a table is referenced multiple times
-
# in a join. If a table is referenced only once, the standard table name is used. The
-
# second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>.
-
# Indexes are appended for any more successive uses of the table name.
-
#
-
# Post.joins(:comments)
-
# # => SELECT ... FROM posts INNER JOIN comments ON ...
-
# Post.joins(:special_comments) # STI
-
# # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
-
# Post.joins(:comments, :special_comments) # special_comments is the reflection name, posts is the parent table name
-
# # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
-
#
-
# Acts as tree example:
-
#
-
# TreeMixin.joins(:children)
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# TreeMixin.joins(children: :parent)
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# INNER JOIN parents_mixins ...
-
# TreeMixin.joins(children: {parent: :children})
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# INNER JOIN parents_mixins ...
-
# INNER JOIN mixins childrens_mixins_2
-
#
-
# Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix:
-
#
-
# Post.joins(:categories)
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# Post.joins(categories: :posts)
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
-
# Post.joins(categories: {posts: :categories})
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
-
# INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
-
#
-
# If you wish to specify your own custom joins using <tt>joins</tt> method, those table
-
# names will take precedence over the eager associations:
-
#
-
# Post.joins(:comments).joins("inner join comments ...")
-
# # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
-
# Post.joins(:comments, :special_comments).joins("inner join comments ...")
-
# # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
-
# INNER JOIN comments special_comments_posts ...
-
# INNER JOIN comments ...
-
#
-
# Table aliases are automatically truncated according to the maximum length of table identifiers
-
# according to the specific database.
-
#
-
# == Modules
-
#
-
# By default, associations will look for objects within the current module scope. Consider:
-
#
-
# module MyApplication
-
# module Business
-
# class Firm < ActiveRecord::Base
-
# has_many :clients
-
# end
-
#
-
# class Client < ActiveRecord::Base; end
-
# end
-
# end
-
#
-
# When <tt>Firm#clients</tt> is called, it will in turn call
-
# <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
-
# If you want to associate with a class in another module scope, this can be done by
-
# specifying the complete class name.
-
#
-
# module MyApplication
-
# module Business
-
# class Firm < ActiveRecord::Base; end
-
# end
-
#
-
# module Billing
-
# class Account < ActiveRecord::Base
-
# belongs_to :firm, class_name: "MyApplication::Business::Firm"
-
# end
-
# end
-
# end
-
#
-
# == Bi-directional associations
-
#
-
# When you specify an association there is usually an association on the associated model
-
# that specifies the same relationship in reverse. For example, with the following models:
-
#
-
# class Dungeon < ActiveRecord::Base
-
# has_many :traps
-
# has_one :evil_wizard
-
# end
-
#
-
# class Trap < ActiveRecord::Base
-
# belongs_to :dungeon
-
# end
-
#
-
# class EvilWizard < ActiveRecord::Base
-
# belongs_to :dungeon
-
# end
-
#
-
# The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are
-
# the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+
-
# is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
-
# Active Record doesn't know anything about these inverse relationships and so no object
-
# loading optimization is possible. For example:
-
#
-
# d = Dungeon.first
-
# t = d.traps.first
-
# d.level == t.dungeon.level # => true
-
# d.level = 10
-
# d.level == t.dungeon.level # => false
-
#
-
# The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to
-
# the same object data from the database, but are actually different in-memory copies
-
# of that data. Specifying the <tt>:inverse_of</tt> option on associations lets you tell
-
# Active Record about inverse relationships and it will optimise object loading. For
-
# example, if we changed our model definitions to:
-
#
-
# class Dungeon < ActiveRecord::Base
-
# has_many :traps, inverse_of: :dungeon
-
# has_one :evil_wizard, inverse_of: :dungeon
-
# end
-
#
-
# class Trap < ActiveRecord::Base
-
# belongs_to :dungeon, inverse_of: :traps
-
# end
-
#
-
# class EvilWizard < ActiveRecord::Base
-
# belongs_to :dungeon, inverse_of: :evil_wizard
-
# end
-
#
-
# Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same
-
# in-memory instance and our final <tt>d.level == t.dungeon.level</tt> will return +true+.
-
#
-
# There are limitations to <tt>:inverse_of</tt> support:
-
#
-
# * does not work with <tt>:through</tt> associations.
-
# * does not work with <tt>:polymorphic</tt> associations.
-
# * for +belongs_to+ associations +has_many+ inverse associations are ignored.
-
#
-
# == Deleting from associations
-
#
-
# === Dependent associations
-
#
-
# +has_many+, +has_one+ and +belongs_to+ associations support the <tt>:dependent</tt> option.
-
# This allows you to specify that associated records should be deleted when the owner is
-
# deleted.
-
#
-
# For example:
-
#
-
# class Author
-
# has_many :posts, dependent: :destroy
-
# end
-
# Author.find(1).destroy # => Will destroy all of the author's posts, too
-
#
-
# The <tt>:dependent</tt> option can have different values which specify how the deletion
-
# is done. For more information, see the documentation for this option on the different
-
# specific association types. When no option is given, the behavior is to do nothing
-
# with the associated records when destroying a record.
-
#
-
# Note that <tt>:dependent</tt> is implemented using Rails' callback
-
# system, which works by processing callbacks in order. Therefore, other
-
# callbacks declared either before or after the <tt>:dependent</tt> option
-
# can affect what it does.
-
#
-
# === Delete or destroy?
-
#
-
# +has_many+ and +has_and_belongs_to_many+ associations have the methods <tt>destroy</tt>,
-
# <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>.
-
#
-
# For +has_and_belongs_to_many+, <tt>delete</tt> and <tt>destroy</tt> are the same: they
-
# cause the records in the join table to be removed.
-
#
-
# For +has_many+, <tt>destroy</tt> and <tt>destroy_all</tt> will always call the <tt>destroy</tt> method of the
-
# record(s) being removed so that callbacks are run. However <tt>delete</tt> and <tt>delete_all</tt> will either
-
# do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or
-
# if no <tt>:dependent</tt> option is given, then it will follow the default strategy.
-
# The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for
-
# +has_many+ <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete
-
# the join records, without running their callbacks).
-
#
-
# There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that
-
# it returns the association rather than the records which have been deleted.
-
#
-
# === What gets deleted?
-
#
-
# There is a potential pitfall here: +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>
-
# associations have records in join tables, as well as the associated records. So when we
-
# call one of these deletion methods, what exactly should be deleted?
-
#
-
# The answer is that it is assumed that deletion on an association is about removing the
-
# <i>link</i> between the owner and the associated object(s), rather than necessarily the
-
# associated objects themselves. So with +has_and_belongs_to_many+ and +has_many+
-
# <tt>:through</tt>, the join records will be deleted, but the associated records won't.
-
#
-
# This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by(name: 'food'))</tt>
-
# you would want the 'food' tag to be unlinked from the post, rather than for the tag itself
-
# to be removed from the database.
-
#
-
# However, there are examples where this strategy doesn't make sense. For example, suppose
-
# a person has many projects, and each project has many tasks. If we deleted one of a person's
-
# tasks, we would probably not want the project to be deleted. In this scenario, the delete method
-
# won't actually work: it can only be used if the association on the join model is a
-
# +belongs_to+. In other situations you are expected to perform operations directly on
-
# either the associated records or the <tt>:through</tt> association.
-
#
-
# With a regular +has_many+ there is no distinction between the "associated records"
-
# and the "link", so there is only one choice for what gets deleted.
-
#
-
# With +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>, if you want to delete the
-
# associated records themselves, you can always do something along the lines of
-
# <tt>person.tasks.each(&:destroy)</tt>.
-
#
-
# == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
-
#
-
# If you attempt to assign an object to an association that doesn't match the inferred
-
# or specified <tt>:class_name</tt>, you'll get an <tt>ActiveRecord::AssociationTypeMismatch</tt>.
-
#
-
# == Options
-
#
-
# All of the association macros can be specialized through options. This makes cases
-
# more complex than the simple and guessable ones possible.
-
1
module ClassMethods
-
# Specifies a one-to-many association. The following methods for retrieval and query of
-
# collections of associated objects will be added:
-
#
-
# +collection+ is a placeholder for the symbol passed as the +name+ argument, so
-
# <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.
-
#
-
# [collection(force_reload = false)]
-
# Returns an array of all the associated objects.
-
# An empty array is returned if none are found.
-
# [collection<<(object, ...)]
-
# Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
-
# Note that this operation instantly fires update SQL without waiting for the save or update call on the
-
# parent object, unless the parent object is a new record.
-
# [collection.delete(object, ...)]
-
# Removes one or more objects from the collection by setting their foreign keys to +NULL+.
-
# Objects will be in addition destroyed if they're associated with <tt>dependent: :destroy</tt>,
-
# and deleted if they're associated with <tt>dependent: :delete_all</tt>.
-
#
-
# If the <tt>:through</tt> option is used, then the join records are deleted (rather than
-
# nullified) by default, but you can specify <tt>dependent: :destroy</tt> or
-
# <tt>dependent: :nullify</tt> to override this.
-
# [collection.destroy(object, ...)]
-
# Removes one or more objects from the collection by running <tt>destroy</tt> on
-
# each record, regardless of any dependent option, ensuring callbacks are run.
-
#
-
# If the <tt>:through</tt> option is used, then the join records are destroyed
-
# instead, not the objects themselves.
-
# [collection=objects]
-
# Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt>
-
# option is true callbacks in the join models are triggered except destroy callbacks, since deletion is
-
# direct.
-
# [collection_singular_ids]
-
# Returns an array of the associated objects' ids
-
# [collection_singular_ids=ids]
-
# Replace the collection with the objects identified by the primary keys in +ids+. This
-
# method loads the models and calls <tt>collection=</tt>. See above.
-
# [collection.clear]
-
# Removes every object from the collection. This destroys the associated objects if they
-
# are associated with <tt>dependent: :destroy</tt>, deletes them directly from the
-
# database if <tt>dependent: :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
-
# If the <tt>:through</tt> option is true no destroy callbacks are invoked on the join models.
-
# Join models are directly deleted.
-
# [collection.empty?]
-
# Returns +true+ if there are no associated objects.
-
# [collection.size]
-
# Returns the number of associated objects.
-
# [collection.find(...)]
-
# Finds an associated object according to the same rules as <tt>ActiveRecord::Base.find</tt>.
-
# [collection.exists?(...)]
-
# Checks whether an associated object with the given conditions exists.
-
# Uses the same rules as <tt>ActiveRecord::Base.exists?</tt>.
-
# [collection.build(attributes = {}, ...)]
-
# Returns one or more new objects of the collection type that have been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but have not yet
-
# been saved.
-
# [collection.create(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that has already
-
# been saved (if it passed the validation). *Note*: This only works if the base model
-
# already exists in the DB, not if it is a new (unsaved) record!
-
# [collection.create!(attributes = {})]
-
# Does the same as <tt>collection.create</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# === Example
-
#
-
# A <tt>Firm</tt> class declares <tt>has_many :clients</tt>, which will add:
-
# * <tt>Firm#clients</tt> (similar to <tt>Client.where(firm_id: id)</tt>)
-
# * <tt>Firm#clients<<</tt>
-
# * <tt>Firm#clients.delete</tt>
-
# * <tt>Firm#clients.destroy</tt>
-
# * <tt>Firm#clients=</tt>
-
# * <tt>Firm#client_ids</tt>
-
# * <tt>Firm#client_ids=</tt>
-
# * <tt>Firm#clients.clear</tt>
-
# * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
-
# * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
-
# * <tt>Firm#clients.find</tt> (similar to <tt>Client.where(firm_id: id).find(id)</tt>)
-
# * <tt>Firm#clients.exists?(name: 'ACME')</tt> (similar to <tt>Client.exists?(name: 'ACME', firm_id: firm.id)</tt>)
-
# * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
-
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
-
# * <tt>Firm#clients.create!</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save!</tt>)
-
# The declaration can also include an +options+ hash to specialize the behavior of the association.
-
#
-
# === Scopes
-
#
-
# You can pass a second argument +scope+ as a callable (i.e. proc or
-
# lambda) to retrieve a specific set of records or customize the generated
-
# query when you access the associated collection.
-
#
-
# Scope examples:
-
# has_many :comments, -> { where(author_id: 1) }
-
# has_many :employees, -> { joins(:address) }
-
# has_many :posts, ->(post) { where("max_post_length > ?", post.length) }
-
#
-
# === Extensions
-
#
-
# The +extension+ argument allows you to pass a block into a has_many
-
# association. This is useful for adding new finders, creators and other
-
# factory-type methods to be used as part of the association.
-
#
-
# Extension examples:
-
# has_many :employees do
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by(first_name: first_name, last_name: last_name)
-
# end
-
# end
-
#
-
# === Options
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_many :products</tt> will by default be linked
-
# to the Product class, but if the real class name is SpecialProduct, you'll have to
-
# specify it with this option.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+
-
# association will use "person_id" as the default <tt>:foreign_key</tt>.
-
# [:foreign_type]
-
# Specify the column used to store the associated object's type, if this is a polymorphic
-
# association. By default this is guessed to be the name of the polymorphic association
-
# specified on "as" option with a "_type" suffix. So a class that defines a
-
# <tt>has_many :tags, as: :taggable</tt> association will use "taggable_type" as the
-
# default <tt>:foreign_type</tt>.
-
# [:primary_key]
-
# Specify the name of the column to use as the primary key for the association. By default this is +id+.
-
# [:dependent]
-
# Controls what happens to the associated objects when
-
# their owner is destroyed. Note that these are implemented as
-
# callbacks, and Rails executes callbacks in order. Therefore, other
-
# similar callbacks may affect the <tt>:dependent</tt> behavior, and the
-
# <tt>:dependent</tt> behavior may affect other callbacks.
-
#
-
# * <tt>:destroy</tt> causes all the associated objects to also be destroyed.
-
# * <tt>:delete_all</tt> causes all the associated objects to be deleted directly from the database (so callbacks will not be executed).
-
# * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed.
-
# * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records.
-
# * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects.
-
#
-
# If using with the <tt>:through</tt> option, the association on the join model must be
-
# a +belongs_to+, and the records which get deleted are the join records, rather than
-
# the associated records.
-
# [:counter_cache]
-
# This option can be used to configure a custom named <tt>:counter_cache.</tt> You only need this option,
-
# when you customized the name of your <tt>:counter_cache</tt> on the <tt>belongs_to</tt> association.
-
# [:as]
-
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
-
# [:through]
-
# Specifies an association through which to perform the query. This can be any other type
-
# of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>,
-
# <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the
-
# source reflection.
-
#
-
# If the association on the join model is a +belongs_to+, the collection can be modified
-
# and the records on the <tt>:through</tt> model will be automatically created and removed
-
# as appropriate. Otherwise, the collection is read-only, so you should manipulate the
-
# <tt>:through</tt> association directly.
-
#
-
# If you are going to modify the association (rather than just read from it), then it is
-
# a good idea to set the <tt>:inverse_of</tt> option on the source association on the
-
# join model. This allows associated records to be built which will automatically create
-
# the appropriate join model records when they are saved. (See the 'Association Join Models'
-
# section above.)
-
# [:source]
-
# Specifies the source association name used by <tt>has_many :through</tt> queries.
-
# Only use it if the name cannot be inferred from the association.
-
# <tt>has_many :subscribers, through: :subscriptions</tt> will look for either <tt>:subscribers</tt> or
-
# <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
-
# [:source_type]
-
# Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
-
# association is a polymorphic +belongs_to+.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. true by default.
-
# [:autosave]
-
# If true, always save the associated objects or destroy them if marked for destruction,
-
# when saving the parent object. If false, never save or destroy the associated objects.
-
# By default, only save associated objects that are new records. This option is implemented as a
-
# +before_save+ callback. Because callbacks are run in the order they are defined, associated objects
-
# may need to be explicitly saved in any user-defined +before_save+ callbacks.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:inverse_of]
-
# Specifies the name of the <tt>belongs_to</tt> association on the associated object
-
# that is the inverse of this <tt>has_many</tt> association. Does not work in combination
-
# with <tt>:through</tt> or <tt>:as</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# has_many :comments, -> { order "posted_on" }
-
# has_many :comments, -> { includes :author }
-
# has_many :people, -> { where(deleted: false).order("name") }, class_name: "Person"
-
# has_many :tracks, -> { order "position" }, dependent: :destroy
-
# has_many :comments, dependent: :nullify
-
# has_many :tags, as: :taggable
-
# has_many :reports, -> { readonly }
-
# has_many :subscribers, through: :subscriptions, source: :user
-
1
def has_many(name, scope = nil, options = {}, &extension)
-
1
reflection = Builder::HasMany.build(self, name, scope, options, &extension)
-
1
Reflection.add_reflection self, name, reflection
-
end
-
-
# Specifies a one-to-one association with another class. This method should only be used
-
# if the other class contains the foreign key. If the current class contains the foreign key,
-
# then you should use +belongs_to+ instead. See also ActiveRecord::Associations::ClassMethods's overview
-
# on when to use +has_one+ and when to use +belongs_to+.
-
#
-
# The following methods for retrieval and query of a single associated object will be added:
-
#
-
# +association+ is a placeholder for the symbol passed as the +name+ argument, so
-
# <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.
-
#
-
# [association(force_reload = false)]
-
# Returns the associated object. +nil+ is returned if none is found.
-
# [association=(associate)]
-
# Assigns the associate object, extracts the primary key, sets it as the foreign key,
-
# and saves the associate object. To avoid database inconsistencies, permanently deletes an existing
-
# associated object when assigning a new one, even if the new one isn't saved to database.
-
# [build_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but has not
-
# yet been saved.
-
# [create_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that
-
# has already been saved (if it passed the validation).
-
# [create_association!(attributes = {})]
-
# Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# === Example
-
#
-
# An Account class declares <tt>has_one :beneficiary</tt>, which will add:
-
# * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.where(account_id: id).first</tt>)
-
# * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
-
# * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
-
# * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
-
# * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save!; b</tt>)
-
#
-
# === Scopes
-
#
-
# You can pass a second argument +scope+ as a callable (i.e. proc or
-
# lambda) to retrieve a specific record or customize the generated query
-
# when you access the associated object.
-
#
-
# Scope examples:
-
# has_one :author, -> { where(comment_id: 1) }
-
# has_one :employer, -> { joins(:company) }
-
# has_one :dob, ->(dob) { where("Date.new(2000, 01, 01) > ?", dob) }
-
#
-
# === Options
-
#
-
# The declaration can also include an +options+ hash to specialize the behavior of the association.
-
#
-
# Options are:
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
-
# if the real class name is Person, you'll have to specify it with this option.
-
# [:dependent]
-
# Controls what happens to the associated object when
-
# its owner is destroyed:
-
#
-
# * <tt>:destroy</tt> causes the associated object to also be destroyed
-
# * <tt>:delete</tt> causes the associated object to be deleted directly from the database (so callbacks will not execute)
-
# * <tt>:nullify</tt> causes the foreign key to be set to +NULL+. Callbacks are not executed.
-
# * <tt>:restrict_with_exception</tt> causes an exception to be raised if there is an associated record
-
# * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there is an associated object
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association
-
# will use "person_id" as the default <tt>:foreign_key</tt>.
-
# [:foreign_type]
-
# Specify the column used to store the associated object's type, if this is a polymorphic
-
# association. By default this is guessed to be the name of the polymorphic association
-
# specified on "as" option with a "_type" suffix. So a class that defines a
-
# <tt>has_one :tag, as: :taggable</tt> association will use "taggable_type" as the
-
# default <tt>:foreign_type</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key used for the association. By default this is +id+.
-
# [:as]
-
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
-
# [:through]
-
# Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>,
-
# <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the
-
# source reflection. You can only use a <tt>:through</tt> query through a <tt>has_one</tt>
-
# or <tt>belongs_to</tt> association on the join model.
-
# [:source]
-
# Specifies the source association name used by <tt>has_one :through</tt> queries.
-
# Only use it if the name cannot be inferred from the association.
-
# <tt>has_one :favorite, through: :favorites</tt> will look for a
-
# <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
-
# [:source_type]
-
# Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
-
# association is a polymorphic +belongs_to+.
-
# [:validate]
-
# If +false+, don't validate the associated object when saving the parent object. +false+ by default.
-
# [:autosave]
-
# If true, always save the associated object or destroy it if marked for destruction,
-
# when saving the parent object. If false, never save or destroy the associated object.
-
# By default, only save the associated object if it's a new record.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:inverse_of]
-
# Specifies the name of the <tt>belongs_to</tt> association on the associated object
-
# that is the inverse of this <tt>has_one</tt> association. Does not work in combination
-
# with <tt>:through</tt> or <tt>:as</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
# [:required]
-
# When set to +true+, the association will also have its presence validated.
-
# This will validate the association itself, not the id. You can use
-
# +:inverse_of+ to avoid an extra query during validation.
-
#
-
# Option examples:
-
# has_one :credit_card, dependent: :destroy # destroys the associated credit card
-
# has_one :credit_card, dependent: :nullify # updates the associated records foreign
-
# # key value to NULL rather than destroying it
-
# has_one :last_comment, -> { order 'posted_on' }, class_name: "Comment"
-
# has_one :project_manager, -> { where role: 'project_manager' }, class_name: "Person"
-
# has_one :attachment, as: :attachable
-
# has_one :boss, -> { readonly }
-
# has_one :club, through: :membership
-
# has_one :primary_address, -> { where primary: true }, through: :addressables, source: :addressable
-
# has_one :credit_card, required: true
-
1
def has_one(name, scope = nil, options = {})
-
reflection = Builder::HasOne.build(self, name, scope, options)
-
Reflection.add_reflection self, name, reflection
-
end
-
-
# Specifies a one-to-one association with another class. This method should only be used
-
# if this class contains the foreign key. If the other class contains the foreign key,
-
# then you should use +has_one+ instead. See also ActiveRecord::Associations::ClassMethods's overview
-
# on when to use +has_one+ and when to use +belongs_to+.
-
#
-
# Methods will be added for retrieval and query for a single associated object, for which
-
# this object holds an id:
-
#
-
# +association+ is a placeholder for the symbol passed as the +name+ argument, so
-
# <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.
-
#
-
# [association(force_reload = false)]
-
# Returns the associated object. +nil+ is returned if none is found.
-
# [association=(associate)]
-
# Assigns the associate object, extracts the primary key, and sets it as the foreign key.
-
# [build_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
-
# [create_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that
-
# has already been saved (if it passed the validation).
-
# [create_association!(attributes = {})]
-
# Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# === Example
-
#
-
# A Post class declares <tt>belongs_to :author</tt>, which will add:
-
# * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
-
# * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
-
# * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
-
# * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
-
# * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>)
-
# The declaration can also include an +options+ hash to specialize the behavior of the association.
-
#
-
# === Scopes
-
#
-
# You can pass a second argument +scope+ as a callable (i.e. proc or
-
# lambda) to retrieve a specific record or customize the generated query
-
# when you access the associated object.
-
#
-
# Scope examples:
-
# belongs_to :user, -> { where(id: 2) }
-
# belongs_to :user, -> { joins(:friends) }
-
# belongs_to :level, ->(level) { where("game_level > ?", level.current) }
-
#
-
# === Options
-
#
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but
-
# if the real class name is Person, you'll have to specify it with this option.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
-
# association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
-
# <tt>belongs_to :favorite_person, class_name: "Person"</tt> will use a foreign key
-
# of "favorite_person_id".
-
# [:foreign_type]
-
# Specify the column used to store the associated object's type, if this is a polymorphic
-
# association. By default this is guessed to be the name of the association with a "_type"
-
# suffix. So a class that defines a <tt>belongs_to :taggable, polymorphic: true</tt>
-
# association will use "taggable_type" as the default <tt>:foreign_type</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key of associated object used for the association.
-
# By default this is id.
-
# [:dependent]
-
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
-
# <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
-
# This option should not be specified when <tt>belongs_to</tt> is used in conjunction with
-
# a <tt>has_many</tt> relationship on another class because of the potential to leave
-
# orphaned records behind.
-
# [:counter_cache]
-
# Caches the number of belonging objects on the associate class through the use of +increment_counter+
-
# and +decrement_counter+. The counter cache is incremented when an object of this
-
# class is created and decremented when it's destroyed. This requires that a column
-
# named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
-
# is used on the associate class (such as a Post class) - that is the migration for
-
# <tt>#{table_name}_count</tt> is created on the associate class (such that <tt>Post.comments_count</tt> will
-
# return the count cached, see note below). You can also specify a custom counter
-
# cache column by providing a column name instead of a +true+/+false+ value to this
-
# option (e.g., <tt>counter_cache: :my_custom_counter</tt>.)
-
# Note: Specifying a counter cache will add it to that model's list of readonly attributes
-
# using +attr_readonly+.
-
# [:polymorphic]
-
# Specify this association is a polymorphic association by passing +true+.
-
# Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
-
# to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. +false+ by default.
-
# [:autosave]
-
# If true, always save the associated object or destroy it if marked for destruction, when
-
# saving the parent object.
-
# If false, never save or destroy the associated object.
-
# By default, only save the associated object if it's a new record.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:touch]
-
# If true, the associated object will be touched (the updated_at/on attributes set to current time)
-
# when this record is either saved or destroyed. If you specify a symbol, that attribute
-
# will be updated with the current time in addition to the updated_at/on attribute.
-
# [:inverse_of]
-
# Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated
-
# object that is the inverse of this <tt>belongs_to</tt> association. Does not work in
-
# combination with the <tt>:polymorphic</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
# [:required]
-
# When set to +true+, the association will also have its presence validated.
-
# This will validate the association itself, not the id. You can use
-
# +:inverse_of+ to avoid an extra query during validation.
-
#
-
# Option examples:
-
# belongs_to :firm, foreign_key: "client_of"
-
# belongs_to :person, primary_key: "name", foreign_key: "person_name"
-
# belongs_to :author, class_name: "Person", foreign_key: "author_id"
-
# belongs_to :valid_coupon, ->(o) { where "discounts > ?", o.payments_count },
-
# class_name: "Coupon", foreign_key: "coupon_id"
-
# belongs_to :attachable, polymorphic: true
-
# belongs_to :project, -> { readonly }
-
# belongs_to :post, counter_cache: true
-
# belongs_to :company, touch: true
-
# belongs_to :company, touch: :employees_last_updated_at
-
# belongs_to :company, required: true
-
1
def belongs_to(name, scope = nil, options = {})
-
3
reflection = Builder::BelongsTo.build(self, name, scope, options)
-
3
Reflection.add_reflection self, name, reflection
-
end
-
-
# Specifies a many-to-many relationship with another class. This associates two classes via an
-
# intermediate join table. Unless the join table is explicitly specified as an option, it is
-
# guessed using the lexical order of the class names. So a join between Developer and Project
-
# will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically.
-
# Note that this precedence is calculated using the <tt><</tt> operator for String. This
-
# means that if the strings are of different lengths, and the strings are equal when compared
-
# up to the shortest length, then the longer string is considered of higher
-
# lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers"
-
# to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes",
-
# but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the
-
# custom <tt>:join_table</tt> option if you need to.
-
# If your tables share a common prefix, it will only appear once at the beginning. For example,
-
# the tables "catalog_categories" and "catalog_products" generate a join table name of "catalog_categories_products".
-
#
-
# The join table should not have a primary key or a model associated with it. You must manually generate the
-
# join table with a migration such as this:
-
#
-
# class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
-
# def change
-
# create_table :developers_projects, id: false do |t|
-
# t.integer :developer_id
-
# t.integer :project_id
-
# end
-
# end
-
# end
-
#
-
# It's also a good idea to add indexes to each of those columns to speed up the joins process.
-
# However, in MySQL it is advised to add a compound index for both of the columns as MySQL only
-
# uses one index per table during the lookup.
-
#
-
# Adds the following methods for retrieval and query:
-
#
-
# +collection+ is a placeholder for the symbol passed as the +name+ argument, so
-
# <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.
-
#
-
# [collection(force_reload = false)]
-
# Returns an array of all the associated objects.
-
# An empty array is returned if none are found.
-
# [collection<<(object, ...)]
-
# Adds one or more objects to the collection by creating associations in the join table
-
# (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
-
# Note that this operation instantly fires update SQL without waiting for the save or update call on the
-
# parent object, unless the parent object is a new record.
-
# [collection.delete(object, ...)]
-
# Removes one or more objects from the collection by removing their associations from the join table.
-
# This does not destroy the objects.
-
# [collection.destroy(object, ...)]
-
# Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option.
-
# This does not destroy the objects.
-
# [collection=objects]
-
# Replaces the collection's content by deleting and adding objects as appropriate.
-
# [collection_singular_ids]
-
# Returns an array of the associated objects' ids.
-
# [collection_singular_ids=ids]
-
# Replace the collection by the objects identified by the primary keys in +ids+.
-
# [collection.clear]
-
# Removes every object from the collection. This does not destroy the objects.
-
# [collection.empty?]
-
# Returns +true+ if there are no associated objects.
-
# [collection.size]
-
# Returns the number of associated objects.
-
# [collection.find(id)]
-
# Finds an associated object responding to the +id+ and that
-
# meets the condition that it has to be associated with this object.
-
# Uses the same rules as <tt>ActiveRecord::Base.find</tt>.
-
# [collection.exists?(...)]
-
# Checks whether an associated object with the given conditions exists.
-
# Uses the same rules as <tt>ActiveRecord::Base.exists?</tt>.
-
# [collection.build(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+ and linked to this object through the join table, but has not yet been saved.
-
# [collection.create(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+, linked to this object through the join table, and that has already been
-
# saved (if it passed the validation).
-
#
-
# === Example
-
#
-
# A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
-
# * <tt>Developer#projects</tt>
-
# * <tt>Developer#projects<<</tt>
-
# * <tt>Developer#projects.delete</tt>
-
# * <tt>Developer#projects.destroy</tt>
-
# * <tt>Developer#projects=</tt>
-
# * <tt>Developer#project_ids</tt>
-
# * <tt>Developer#project_ids=</tt>
-
# * <tt>Developer#projects.clear</tt>
-
# * <tt>Developer#projects.empty?</tt>
-
# * <tt>Developer#projects.size</tt>
-
# * <tt>Developer#projects.find(id)</tt>
-
# * <tt>Developer#projects.exists?(...)</tt>
-
# * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("developer_id" => id)</tt>)
-
# * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("developer_id" => id); c.save; c</tt>)
-
# The declaration may include an +options+ hash to specialize the behavior of the association.
-
#
-
# === Scopes
-
#
-
# You can pass a second argument +scope+ as a callable (i.e. proc or
-
# lambda) to retrieve a specific set of records or customize the generated
-
# query when you access the associated collection.
-
#
-
# Scope examples:
-
# has_and_belongs_to_many :projects, -> { includes :milestones, :manager }
-
# has_and_belongs_to_many :categories, ->(category) {
-
# where("default_category = ?", category.name)
-
# }
-
#
-
# === Extensions
-
#
-
# The +extension+ argument allows you to pass a block into a
-
# has_and_belongs_to_many association. This is useful for adding new
-
# finders, creators and other factory-type methods to be used as part of
-
# the association.
-
#
-
# Extension examples:
-
# has_and_belongs_to_many :contractors do
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by(first_name: first_name, last_name: last_name)
-
# end
-
# end
-
#
-
# === Options
-
#
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
-
# Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
-
# [:join_table]
-
# Specify the name of the join table if the default based on lexical order isn't what you want.
-
# <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
-
# MUST be declared underneath any +has_and_belongs_to_many+ declaration in order to work.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes
-
# a +has_and_belongs_to_many+ association to Project will use "person_id" as the
-
# default <tt>:foreign_key</tt>.
-
# [:association_foreign_key]
-
# Specify the foreign key used for the association on the receiving side of the association.
-
# By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
-
# So if a Person class makes a +has_and_belongs_to_many+ association to Project,
-
# the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
-
# [:readonly]
-
# If true, all the associated objects are readonly through the association.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. +true+ by default.
-
# [:autosave]
-
# If true, always save the associated objects or destroy them if marked for destruction, when
-
# saving the parent object.
-
# If false, never save or destroy the associated objects.
-
# By default, only save associated objects that are new records.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
#
-
# Option examples:
-
# has_and_belongs_to_many :projects
-
# has_and_belongs_to_many :projects, -> { includes :milestones, :manager }
-
# has_and_belongs_to_many :nations, class_name: "Country"
-
# has_and_belongs_to_many :categories, join_table: "prods_cats"
-
# has_and_belongs_to_many :categories, -> { readonly }
-
1
def has_and_belongs_to_many(name, scope = nil, options = {}, &extension)
-
if scope.is_a?(Hash)
-
options = scope
-
scope = nil
-
end
-
-
habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self)
-
-
builder = Builder::HasAndBelongsToMany.new name, self, options
-
-
join_model = builder.through_model
-
-
# FIXME: we should move this to the internal constants. Also people
-
# should never directly access this constant so I'm not happy about
-
# setting it.
-
const_set join_model.name, join_model
-
-
middle_reflection = builder.middle_reflection join_model
-
-
Builder::HasMany.define_callbacks self, middle_reflection
-
Reflection.add_reflection self, middle_reflection.name, middle_reflection
-
middle_reflection.parent_reflection = [name.to_s, habtm_reflection]
-
-
include Module.new {
-
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def destroy_associations
-
association(:#{middle_reflection.name}).delete_all(:delete_all)
-
association(:#{name}).reset
-
super
-
end
-
RUBY
-
}
-
-
hm_options = {}
-
hm_options[:through] = middle_reflection.name
-
hm_options[:source] = join_model.right_reflection.name
-
-
[:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table, :class_name, :extend].each do |k|
-
hm_options[k] = options[k] if options.key? k
-
end
-
-
has_many name, scope, hm_options, &extension
-
self._reflections[name.to_s].parent_reflection = [name.to_s, habtm_reflection]
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
# This is the parent Association class which defines the variables
-
# used by all associations.
-
#
-
# The hierarchy is defined as follows:
-
# Association
-
# - SingularAssociation
-
# - BelongsToAssociation
-
# - HasOneAssociation
-
# - CollectionAssociation
-
# - HasManyAssociation
-
-
1
module ActiveRecord::Associations::Builder
-
1
class Association #:nodoc:
-
1
class << self
-
1
attr_accessor :extensions
-
# TODO: This class accessor is needed to make activerecord-deprecated_finders work.
-
# We can move it to a constant in 5.0.
-
1
attr_accessor :valid_options
-
end
-
1
self.extensions = []
-
-
1
self.valid_options = [:class_name, :anonymous_class, :foreign_key, :validate]
-
-
1
attr_reader :name, :scope, :options
-
-
1
def self.build(model, name, scope, options, &block)
-
4
if model.dangerous_attribute_method?(name)
-
raise ArgumentError, "You tried to define an association named #{name} on the model #{model.name}, but " \
-
"this will conflict with a method #{name} already defined by Active Record. " \
-
"Please choose a different association name."
-
end
-
-
4
builder = create_builder model, name, scope, options, &block
-
4
reflection = builder.build(model)
-
4
define_accessors model, reflection
-
4
define_callbacks model, reflection
-
4
define_validations model, reflection
-
4
builder.define_extensions model
-
4
reflection
-
end
-
-
1
def self.create_builder(model, name, scope, options, &block)
-
4
raise ArgumentError, "association names must be a Symbol" unless name.kind_of?(Symbol)
-
-
4
new(model, name, scope, options, &block)
-
end
-
-
1
def initialize(model, name, scope, options)
-
# TODO: Move this to create_builder as soon we drop support to activerecord-deprecated_finders.
-
4
if scope.is_a?(Hash)
-
options = scope
-
scope = nil
-
end
-
-
# TODO: Remove this model argument as soon we drop support to activerecord-deprecated_finders.
-
4
@name = name
-
4
@scope = scope
-
4
@options = options
-
-
4
validate_options
-
-
4
if scope && scope.arity == 0
-
@scope = proc { instance_exec(&scope) }
-
end
-
end
-
-
1
def build(model)
-
4
ActiveRecord::Reflection.create(macro, name, scope, options, model)
-
end
-
-
1
def macro
-
raise NotImplementedError
-
end
-
-
1
def valid_options
-
4
Association.valid_options + Association.extensions.flat_map(&:valid_options)
-
end
-
-
1
def validate_options
-
4
options.assert_valid_keys(valid_options)
-
end
-
-
1
def define_extensions(model)
-
end
-
-
1
def self.define_callbacks(model, reflection)
-
4
if dependent = reflection.options[:dependent]
-
check_dependent_options(dependent)
-
add_destroy_callbacks(model, reflection)
-
end
-
-
4
Association.extensions.each do |extension|
-
4
extension.build model, reflection
-
end
-
end
-
-
# Defines the setter and getter methods for the association
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# end
-
#
-
# Post.first.comments and Post.first.comments= methods are defined by this method...
-
1
def self.define_accessors(model, reflection)
-
4
mixin = model.generated_association_methods
-
4
name = reflection.name
-
4
define_readers(mixin, name)
-
4
define_writers(mixin, name)
-
end
-
-
1
def self.define_readers(mixin, name)
-
4
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}(*args)
-
association(:#{name}).reader(*args)
-
end
-
CODE
-
end
-
-
1
def self.define_writers(mixin, name)
-
4
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}=(value)
-
association(:#{name}).writer(value)
-
end
-
CODE
-
end
-
-
1
def self.define_validations(model, reflection)
-
# noop
-
end
-
-
1
def self.valid_dependent_options
-
raise NotImplementedError
-
end
-
-
1
private
-
-
1
def self.check_dependent_options(dependent)
-
unless valid_dependent_options.include? dependent
-
raise ArgumentError, "The :dependent option must be one of #{valid_dependent_options}, but is :#{dependent}"
-
end
-
end
-
-
1
def self.add_destroy_callbacks(model, reflection)
-
name = reflection.name
-
model.before_destroy lambda { |o| o.association(name).handle_dependency }
-
end
-
end
-
end
-
1
module ActiveRecord::Associations::Builder
-
1
class BelongsTo < SingularAssociation #:nodoc:
-
1
def macro
-
3
:belongs_to
-
end
-
-
1
def valid_options
-
3
super + [:foreign_type, :polymorphic, :touch, :counter_cache]
-
end
-
-
1
def self.valid_dependent_options
-
[:destroy, :delete]
-
end
-
-
1
def self.define_callbacks(model, reflection)
-
3
super
-
3
add_counter_cache_callbacks(model, reflection) if reflection.options[:counter_cache]
-
3
add_touch_callbacks(model, reflection) if reflection.options[:touch]
-
end
-
-
1
def self.define_accessors(mixin, reflection)
-
3
super
-
3
add_counter_cache_methods mixin
-
end
-
-
1
private
-
-
1
def self.add_counter_cache_methods(mixin)
-
3
return if mixin.method_defined? :belongs_to_counter_cache_after_update
-
-
3
mixin.class_eval do
-
3
def belongs_to_counter_cache_after_update(reflection)
-
foreign_key = reflection.foreign_key
-
cache_column = reflection.counter_cache_column
-
-
if (@_after_create_counter_called ||= false)
-
@_after_create_counter_called = false
-
elsif attribute_changed?(foreign_key) && !new_record? && reflection.constructable?
-
model = reflection.klass
-
foreign_key_was = attribute_was foreign_key
-
foreign_key = attribute foreign_key
-
-
if foreign_key && model.respond_to?(:increment_counter)
-
model.increment_counter(cache_column, foreign_key)
-
end
-
if foreign_key_was && model.respond_to?(:decrement_counter)
-
model.decrement_counter(cache_column, foreign_key_was)
-
end
-
end
-
end
-
end
-
end
-
-
1
def self.add_counter_cache_callbacks(model, reflection)
-
cache_column = reflection.counter_cache_column
-
-
model.after_update lambda { |record|
-
record.belongs_to_counter_cache_after_update(reflection)
-
}
-
-
klass = reflection.class_name.safe_constantize
-
klass.attr_readonly cache_column if klass && klass.respond_to?(:attr_readonly)
-
end
-
-
1
def self.touch_record(o, foreign_key, name, touch) # :nodoc:
-
old_foreign_id = o.changed_attributes[foreign_key]
-
-
if old_foreign_id
-
association = o.association(name)
-
reflection = association.reflection
-
if reflection.polymorphic?
-
klass = o.public_send("#{reflection.foreign_type}_was").constantize
-
else
-
klass = association.klass
-
end
-
old_record = klass.find_by(klass.primary_key => old_foreign_id)
-
-
if old_record
-
if touch != true
-
old_record.touch touch
-
else
-
old_record.touch
-
end
-
end
-
end
-
-
record = o.send name
-
if record && record.persisted?
-
if touch != true
-
record.touch touch
-
else
-
record.touch
-
end
-
end
-
end
-
-
1
def self.add_touch_callbacks(model, reflection)
-
foreign_key = reflection.foreign_key
-
n = reflection.name
-
touch = reflection.options[:touch]
-
-
callback = lambda { |record|
-
BelongsTo.touch_record(record, foreign_key, n, touch)
-
}
-
-
model.after_save callback, if: :changed?
-
model.after_touch callback
-
model.after_destroy callback
-
end
-
-
1
def self.add_destroy_callbacks(model, reflection)
-
name = reflection.name
-
model.after_destroy lambda { |o| o.association(name).handle_dependency }
-
end
-
end
-
end
-
# This class is inherited by the has_many and has_many_and_belongs_to_many association classes
-
-
1
require 'active_record/associations'
-
-
1
module ActiveRecord::Associations::Builder
-
1
class CollectionAssociation < Association #:nodoc:
-
-
1
CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove]
-
-
1
def valid_options
-
super + [:table_name, :before_add,
-
1
:after_add, :before_remove, :after_remove, :extend]
-
end
-
-
1
attr_reader :block_extension
-
-
1
def initialize(model, name, scope, options)
-
1
super
-
1
@mod = nil
-
1
if block_given?
-
@mod = Module.new(&Proc.new)
-
@scope = wrap_scope @scope, @mod
-
end
-
end
-
-
1
def self.define_callbacks(model, reflection)
-
1
super
-
1
name = reflection.name
-
1
options = reflection.options
-
1
CALLBACKS.each { |callback_name|
-
4
define_callback(model, callback_name, name, options)
-
}
-
end
-
-
1
def define_extensions(model)
-
1
if @mod
-
extension_module_name = "#{model.name.demodulize}#{name.to_s.camelize}AssociationExtension"
-
model.parent.const_set(extension_module_name, @mod)
-
end
-
end
-
-
1
def self.define_callback(model, callback_name, name, options)
-
4
full_callback_name = "#{callback_name}_for_#{name}"
-
-
# TODO : why do i need method_defined? I think its because of the inheritance chain
-
4
model.class_attribute full_callback_name unless model.method_defined?(full_callback_name)
-
4
callbacks = Array(options[callback_name.to_sym]).map do |callback|
-
case callback
-
when Symbol
-
->(method, owner, record) { owner.send(callback, record) }
-
when Proc
-
->(method, owner, record) { callback.call(owner, record) }
-
else
-
->(method, owner, record) { callback.send(method, owner, record) }
-
end
-
end
-
4
model.send "#{full_callback_name}=", callbacks
-
end
-
-
# Defines the setter and getter methods for the collection_singular_ids.
-
1
def self.define_readers(mixin, name)
-
1
super
-
-
1
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name.to_s.singularize}_ids
-
association(:#{name}).ids_reader
-
end
-
CODE
-
end
-
-
1
def self.define_writers(mixin, name)
-
1
super
-
-
1
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name.to_s.singularize}_ids=(ids)
-
association(:#{name}).ids_writer(ids)
-
end
-
CODE
-
end
-
-
1
private
-
-
1
def wrap_scope(scope, mod)
-
if scope
-
if scope.arity > 0
-
proc { |owner| instance_exec(owner, &scope).extending(mod) }
-
else
-
proc { instance_exec(&scope).extending(mod) }
-
end
-
else
-
proc { extending(mod) }
-
end
-
end
-
end
-
end
-
1
module ActiveRecord::Associations::Builder
-
1
class HasMany < CollectionAssociation #:nodoc:
-
1
def macro
-
1
:has_many
-
end
-
-
1
def valid_options
-
1
super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type]
-
end
-
-
1
def self.valid_dependent_options
-
[:destroy, :delete_all, :nullify, :restrict_with_error, :restrict_with_exception]
-
end
-
end
-
end
-
# This class is inherited by the has_one and belongs_to association classes
-
-
1
module ActiveRecord::Associations::Builder
-
1
class SingularAssociation < Association #:nodoc:
-
1
def valid_options
-
3
super + [:dependent, :primary_key, :inverse_of, :required]
-
end
-
-
1
def self.define_accessors(model, reflection)
-
3
super
-
3
define_constructors(model.generated_association_methods, reflection.name) if reflection.constructable?
-
end
-
-
# Defines the (build|create)_association methods for belongs_to or has_one association
-
1
def self.define_constructors(mixin, name)
-
3
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def build_#{name}(*args, &block)
-
association(:#{name}).build(*args, &block)
-
end
-
-
def create_#{name}(*args, &block)
-
association(:#{name}).create(*args, &block)
-
end
-
-
def create_#{name}!(*args, &block)
-
association(:#{name}).create!(*args, &block)
-
end
-
CODE
-
end
-
-
1
def self.define_validations(model, reflection)
-
3
super
-
3
if reflection.options[:required]
-
model.validates_presence_of reflection.name
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
# Association proxies in Active Record are middlemen between the object that
-
# holds the association, known as the <tt>@owner</tt>, and the actual associated
-
# object, known as the <tt>@target</tt>. The kind of association any proxy is
-
# about is available in <tt>@reflection</tt>. That's an instance of the class
-
# ActiveRecord::Reflection::AssociationReflection.
-
#
-
# For example, given
-
#
-
# class Blog < ActiveRecord::Base
-
# has_many :posts
-
# end
-
#
-
# blog = Blog.first
-
#
-
# the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
-
# <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
-
# the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
-
#
-
# This class delegates unknown methods to <tt>@target</tt> via
-
# <tt>method_missing</tt>.
-
#
-
# The <tt>@target</tt> object is not \loaded until needed. For example,
-
#
-
# blog.posts.count
-
#
-
# is computed directly through SQL and does not trigger by itself the
-
# instantiation of the actual post records.
-
1
class CollectionProxy < Relation
-
1
delegate(*(ActiveRecord::Calculations.public_instance_methods - [:count]), to: :scope)
-
1
delegate :find_nth, to: :scope
-
-
1
def initialize(klass, association) #:nodoc:
-
@association = association
-
super klass, klass.arel_table
-
merge! association.scope(nullify: false)
-
end
-
-
1
def target
-
@association.target
-
end
-
-
1
def load_target
-
@association.load_target
-
end
-
-
# Returns +true+ if the association has been loaded, otherwise +false+.
-
#
-
# person.pets.loaded? # => false
-
# person.pets
-
# person.pets.loaded? # => true
-
1
def loaded?
-
@association.loaded?
-
end
-
-
# Works in two ways.
-
#
-
# *First:* Specify a subset of fields to be selected from the result set.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.select(:name)
-
# # => [
-
# # #<Pet id: nil, name: "Fancy-Fancy">,
-
# # #<Pet id: nil, name: "Spook">,
-
# # #<Pet id: nil, name: "Choo-Choo">
-
# # ]
-
#
-
# person.pets.select(:id, :name )
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy">,
-
# # #<Pet id: 2, name: "Spook">,
-
# # #<Pet id: 3, name: "Choo-Choo">
-
# # ]
-
#
-
# Be careful because this also means you're initializing a model
-
# object with only the fields that you've selected. If you attempt
-
# to access a field except +id+ that is not in the initialized record you'll
-
# receive:
-
#
-
# person.pets.select(:name).first.person_id
-
# # => ActiveModel::MissingAttributeError: missing attribute: person_id
-
#
-
# *Second:* You can pass a block so it can be used just like Array#select.
-
# This builds an array of objects from the database for the scope,
-
# converting them into an array and iterating through them using
-
# Array#select.
-
#
-
# person.pets.select { |pet| pet.name =~ /oo/ }
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.select(:name) { |pet| pet.name =~ /oo/ }
-
# # => [
-
# # #<Pet id: 2, name: "Spook">,
-
# # #<Pet id: 3, name: "Choo-Choo">
-
# # ]
-
1
def select(*fields, &block)
-
@association.select(*fields, &block)
-
end
-
-
# Finds an object in the collection responding to the +id+. Uses the same
-
# rules as <tt>ActiveRecord::Base.find</tt>. Returns <tt>ActiveRecord::RecordNotFound</tt>
-
# error if the object cannot be found.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.find(1) # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
# person.pets.find(4) # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=4
-
#
-
# person.pets.find(2) { |pet| pet.name.downcase! }
-
# # => #<Pet id: 2, name: "fancy-fancy", person_id: 1>
-
#
-
# person.pets.find(2, 3)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def find(*args, &block)
-
@association.find(*args, &block)
-
end
-
-
# Returns the first record, or the first +n+ records, from the collection.
-
# If the collection is empty, the first form returns +nil+, and the second
-
# form returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.first # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.first(2)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>
-
# # ]
-
#
-
# another_person_without.pets # => []
-
# another_person_without.pets.first # => nil
-
# another_person_without.pets.first(3) # => []
-
1
def first(*args)
-
@association.first(*args)
-
end
-
-
# Same as +first+ except returns only the second record.
-
1
def second(*args)
-
@association.second(*args)
-
end
-
-
# Same as +first+ except returns only the third record.
-
1
def third(*args)
-
@association.third(*args)
-
end
-
-
# Same as +first+ except returns only the fourth record.
-
1
def fourth(*args)
-
@association.fourth(*args)
-
end
-
-
# Same as +first+ except returns only the fifth record.
-
1
def fifth(*args)
-
@association.fifth(*args)
-
end
-
-
# Same as +first+ except returns only the forty second record.
-
# Also known as accessing "the reddit".
-
1
def forty_two(*args)
-
@association.forty_two(*args)
-
end
-
-
# Returns the last record, or the last +n+ records, from the collection.
-
# If the collection is empty, the first form returns +nil+, and the second
-
# form returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.last # => #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
#
-
# person.pets.last(2)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# another_person_without.pets # => []
-
# another_person_without.pets.last # => nil
-
# another_person_without.pets.last(3) # => []
-
1
def last(*args)
-
@association.last(*args)
-
end
-
-
1
def take(n = nil)
-
@association.take(n)
-
end
-
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+ and linked to this object, but have not yet been saved.
-
# You can pass an array of attributes hashes, this will return an array
-
# with the new objects.
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# person.pets.build
-
# # => #<Pet id: nil, name: nil, person_id: 1>
-
#
-
# person.pets.build(name: 'Fancy-Fancy')
-
# # => #<Pet id: nil, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.build([{name: 'Spook'}, {name: 'Choo-Choo'}, {name: 'Brain'}])
-
# # => [
-
# # #<Pet id: nil, name: "Spook", person_id: 1>,
-
# # #<Pet id: nil, name: "Choo-Choo", person_id: 1>,
-
# # #<Pet id: nil, name: "Brain", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 5 # size of the collection
-
# person.pets.count # => 0 # count from database
-
1
def build(attributes = {}, &block)
-
@association.build(attributes, &block)
-
end
-
1
alias_method :new, :build
-
-
# Returns a new object of the collection type that has been instantiated with
-
# attributes, linked to this object and that has already been saved (if it
-
# passes the validations).
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# person.pets.create(name: 'Fancy-Fancy')
-
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.create([{name: 'Spook'}, {name: 'Choo-Choo'}])
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 3
-
# person.pets.count # => 3
-
#
-
# person.pets.find(1, 2, 3)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def create(attributes = {}, &block)
-
@association.create(attributes, &block)
-
end
-
-
# Like +create+, except that if the record is invalid, raises an exception.
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# class Pet
-
# validates :name, presence: true
-
# end
-
#
-
# person.pets.create!(name: nil)
-
# # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
-
1
def create!(attributes = {}, &block)
-
@association.create!(attributes, &block)
-
end
-
-
# Add one or more records to the collection by setting their foreign keys
-
# to the association's primary key. Since << flattens its argument list and
-
# inserts each record, +push+ and +concat+ behave identically. Returns +self+
-
# so method calls may be chained.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 0
-
# person.pets.concat(Pet.new(name: 'Fancy-Fancy'))
-
# person.pets.concat(Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo'))
-
# person.pets.size # => 3
-
#
-
# person.id # => 1
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')])
-
# person.pets.size # => 5
-
1
def concat(*records)
-
@association.concat(*records)
-
end
-
-
# Replaces this collection with +other_array+. This will perform a diff
-
# and delete/add only records that have changed.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [#<Pet id: 1, name: "Gorby", group: "cats", person_id: 1>]
-
#
-
# other_pets = [Pet.new(name: 'Puff', group: 'celebrities']
-
#
-
# person.pets.replace(other_pets)
-
#
-
# person.pets
-
# # => [#<Pet id: 2, name: "Puff", group: "celebrities", person_id: 1>]
-
#
-
# If the supplied array has an incorrect association type, it raises
-
# an <tt>ActiveRecord::AssociationTypeMismatch</tt> error:
-
#
-
# person.pets.replace(["doo", "ggie", "gaga"])
-
# # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String
-
1
def replace(other_array)
-
@association.replace(other_array)
-
end
-
-
# Deletes all the records from the collection according to the strategy
-
# specified by the +:dependent+ option. If no +:dependent+ option is given,
-
# then it will follow the default strategy.
-
#
-
# For +has_many :through+ associations, the default deletion strategy is
-
# +:delete_all+.
-
#
-
# For +has_many+ associations, the default deletion strategy is +:nullify+.
-
# This sets the foreign keys to +NULL+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets # dependent: :nullify option by default
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1, 2, 3)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>,
-
# # #<Pet id: 2, name: "Spook", person_id: nil>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: nil>
-
# # ]
-
#
-
# Both +has_many+ and +has_many :through+ dependencies default to the
-
# +:delete_all+ strategy if the +:dependent+ option is set to +:destroy+.
-
# Records are not instantiated and callbacks will not be fired.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :destroy
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
#
-
# Pet.find(1, 2, 3)
-
# # => ActiveRecord::RecordNotFound
-
#
-
# If it is set to <tt>:delete_all</tt>, all the objects are deleted
-
# *without* calling their +destroy+ method.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :delete_all
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
#
-
# Pet.find(1, 2, 3)
-
# # => ActiveRecord::RecordNotFound
-
1
def delete_all(dependent = nil)
-
@association.delete_all(dependent)
-
end
-
-
# Deletes the records of the collection directly from the database
-
# ignoring the +:dependent+ option. Records are instantiated and it
-
# invokes +before_remove+, +after_remove+ , +before_destroy+ and
-
# +after_destroy+ callbacks.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy_all
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1) # => Couldn't find Pet with id=1
-
1
def destroy_all
-
@association.destroy_all
-
end
-
-
# Deletes the +records+ supplied from the collection according to the strategy
-
# specified by the +:dependent+ option. If no +:dependent+ option is given,
-
# then it will follow the default strategy. Returns an array with the
-
# deleted records.
-
#
-
# For +has_many :through+ associations, the default deletion strategy is
-
# +:delete_all+.
-
#
-
# For +has_many+ associations, the default deletion strategy is +:nullify+.
-
# This sets the foreign keys to +NULL+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets # dependent: :nullify option by default
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1)
-
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>
-
#
-
# If it is set to <tt>:destroy</tt> all the +records+ are removed by calling
-
# their +destroy+ method. See +destroy+ for more information.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :destroy
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1), Pet.find(3))
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 1
-
# person.pets
-
# # => [#<Pet id: 2, name: "Spook", person_id: 1>]
-
#
-
# Pet.find(1, 3)
-
# # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 3)
-
#
-
# If it is set to <tt>:delete_all</tt>, all the +records+ are deleted
-
# *without* calling their +destroy+ method.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :delete_all
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1)
-
# # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=1
-
#
-
# You can pass +Fixnum+ or +String+ values, it finds the records
-
# responding to the +id+ and executes delete on them.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete("1")
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.delete(2, 3)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def delete(*records)
-
@association.delete(*records)
-
end
-
-
# Destroys the +records+ supplied and removes them from the collection.
-
# This method will _always_ remove record from the database ignoring
-
# the +:dependent+ option. Returns an array with the removed records.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(Pet.find(2), Pet.find(3))
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1, 2, 3) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 2, 3)
-
#
-
# You can pass +Fixnum+ or +String+ values, it finds the records
-
# responding to the +id+ and then deletes them from the database.
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy("4")
-
# # => #<Pet id: 4, name: "Benny", person_id: 1>
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(5, 6)
-
# # => [
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (4, 5, 6)
-
1
def destroy(*records)
-
@association.destroy(*records)
-
end
-
-
# Specifies whether the records should be unique or not.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.select(:name)
-
# # => [
-
# # #<Pet name: "Fancy-Fancy">,
-
# # #<Pet name: "Fancy-Fancy">
-
# # ]
-
#
-
# person.pets.select(:name).distinct
-
# # => [#<Pet name: "Fancy-Fancy">]
-
1
def distinct
-
@association.distinct
-
end
-
1
alias uniq distinct
-
-
# Count all records using SQL.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def count(column_name = nil, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
@association.count(column_name, options)
-
end
-
-
# Returns the size of the collection. If the collection hasn't been loaded,
-
# it executes a <tt>SELECT COUNT(*)</tt> query. Else it calls <tt>collection.size</tt>.
-
#
-
# If the collection has been already loaded +size+ and +length+ are
-
# equivalent. If not and you are going to need the records anyway
-
# +length+ will take one less query. Otherwise +size+ is more efficient.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# # executes something like SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" = 1
-
#
-
# person.pets # This will execute a SELECT * FROM query
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 3
-
# # Because the collection is already loaded, this will behave like
-
# # collection.size and no SQL count query is executed.
-
1
def size
-
@association.size
-
end
-
-
# Returns the size of the collection calling +size+ on the target.
-
# If the collection has been already loaded, +length+ and +size+ are
-
# equivalent. If not and you are going to need the records anyway this
-
# method will take one less query. Otherwise +size+ is more efficient.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.length # => 3
-
# # executes something like SELECT "pets".* FROM "pets" WHERE "pets"."person_id" = 1
-
#
-
# # Because the collection is loaded, you can
-
# # call the collection with no additional queries:
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def length
-
@association.length
-
end
-
-
# Returns +true+ if the collection is empty. If the collection has been
-
# loaded it is equivalent
-
# to <tt>collection.size.zero?</tt>. If the collection has not been loaded,
-
# it is equivalent to <tt>collection.exists?</tt>. If the collection has
-
# not already been loaded and you are going to fetch the records anyway it
-
# is better to check <tt>collection.length.zero?</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 1
-
# person.pets.empty? # => false
-
#
-
# person.pets.delete_all
-
#
-
# person.pets.count # => 0
-
# person.pets.empty? # => true
-
1
def empty?
-
@association.empty?
-
end
-
-
# Returns +true+ if the collection is not empty.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 0
-
# person.pets.any? # => false
-
#
-
# person.pets << Pet.new(name: 'Snoop')
-
# person.pets.count # => 0
-
# person.pets.any? # => true
-
#
-
# You can also pass a +block+ to define criteria. The behavior
-
# is the same, it returns true if the collection based on the
-
# criteria is not empty.
-
#
-
# person.pets
-
# # => [#<Pet name: "Snoop", group: "dogs">]
-
#
-
# person.pets.any? do |pet|
-
# pet.group == 'cats'
-
# end
-
# # => false
-
#
-
# person.pets.any? do |pet|
-
# pet.group == 'dogs'
-
# end
-
# # => true
-
1
def any?(&block)
-
@association.any?(&block)
-
end
-
-
# Returns true if the collection has more than one record.
-
# Equivalent to <tt>collection.size > 1</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 1
-
# person.pets.many? # => false
-
#
-
# person.pets << Pet.new(name: 'Snoopy')
-
# person.pets.count # => 2
-
# person.pets.many? # => true
-
#
-
# You can also pass a +block+ to define criteria. The
-
# behavior is the same, it returns true if the collection
-
# based on the criteria has more than one record.
-
#
-
# person.pets
-
# # => [
-
# # #<Pet name: "Gorby", group: "cats">,
-
# # #<Pet name: "Puff", group: "cats">,
-
# # #<Pet name: "Snoop", group: "dogs">
-
# # ]
-
#
-
# person.pets.many? do |pet|
-
# pet.group == 'dogs'
-
# end
-
# # => false
-
#
-
# person.pets.many? do |pet|
-
# pet.group == 'cats'
-
# end
-
# # => true
-
1
def many?(&block)
-
@association.many?(&block)
-
end
-
-
# Returns +true+ if the given +record+ is present in the collection.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # => [#<Pet id: 20, name: "Snoop">]
-
#
-
# person.pets.include?(Pet.find(20)) # => true
-
# person.pets.include?(Pet.find(21)) # => false
-
1
def include?(record)
-
!!@association.include?(record)
-
end
-
-
1
def arel
-
scope.arel
-
end
-
-
1
def proxy_association
-
@association
-
end
-
-
# We don't want this object to be put on the scoping stack, because
-
# that could create an infinite loop where we call an @association
-
# method, which gets the current scope, which is this object, which
-
# delegates to @association, and so on.
-
1
def scoping
-
@association.scope.scoping { yield }
-
end
-
-
# Returns a <tt>Relation</tt> object for the records in this association
-
1
def scope
-
@association.scope
-
end
-
1
alias spawn scope
-
-
# Equivalent to <tt>Array#==</tt>. Returns +true+ if the two arrays
-
# contain the same number of elements and if each element is equal
-
# to the corresponding element in the +other+ array, otherwise returns
-
# +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>
-
# # ]
-
#
-
# other = person.pets.to_ary
-
#
-
# person.pets == other
-
# # => true
-
#
-
# other = [Pet.new(id: 1), Pet.new(id: 2)]
-
#
-
# person.pets == other
-
# # => false
-
1
def ==(other)
-
load_target == other
-
end
-
-
# Returns a new array of objects from the collection. If the collection
-
# hasn't been loaded, it fetches the records from the database.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# other_pets = person.pets.to_ary
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# other_pets.replace([Pet.new(name: 'BooGoo')])
-
#
-
# other_pets
-
# # => [#<Pet id: nil, name: "BooGoo", person_id: 1>]
-
#
-
# person.pets
-
# # This is not affected by replace
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
1
def to_ary
-
load_target.dup
-
end
-
1
alias_method :to_a, :to_ary
-
-
# Adds one or more +records+ to the collection by setting their foreign keys
-
# to the association's primary key. Returns +self+, so several appends may be
-
# chained together.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 0
-
# person.pets << Pet.new(name: 'Fancy-Fancy')
-
# person.pets << [Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo')]
-
# person.pets.size # => 3
-
#
-
# person.id # => 1
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def <<(*records)
-
proxy_association.concat(records) && self
-
end
-
1
alias_method :push, :<<
-
1
alias_method :append, :<<
-
-
1
def prepend(*args)
-
raise NoMethodError, "prepend on association is not defined. Please use << or append"
-
end
-
-
# Equivalent to +delete_all+. The difference is that returns +self+, instead
-
# of an array with the deleted objects, so methods can be chained. See
-
# +delete_all+ for more information.
-
1
def clear
-
delete_all
-
self
-
end
-
-
# Reloads the collection from the database. Returns +self+.
-
# Equivalent to <tt>collection(true)</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets # uses the pets cache
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets.reload # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets(true) # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
1
def reload
-
proxy_association.reload
-
self
-
end
-
-
# Unloads the association. Returns +self+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets # uses the pets cache
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets.reset # clears the pets cache
-
#
-
# person.pets # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
1
def reset
-
proxy_association.reset
-
proxy_association.reset_scope
-
self
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
# Implements the details of eager loading of Active Record associations.
-
#
-
# Suppose that you have the following two Active Record models:
-
#
-
# class Author < ActiveRecord::Base
-
# # columns: name, age
-
# has_many :books
-
# end
-
#
-
# class Book < ActiveRecord::Base
-
# # columns: title, sales, author_id
-
# end
-
#
-
# When you load an author with all associated books Active Record will make
-
# multiple queries like this:
-
#
-
# Author.includes(:books).where(name: ['bell hooks', 'Homer']).to_a
-
#
-
# => SELECT `authors`.* FROM `authors` WHERE `name` IN ('bell hooks', 'Homer')
-
# => SELECT `books`.* FROM `books` WHERE `author_id` IN (2, 5)
-
#
-
# Active Record saves the ids of the records from the first query to use in
-
# the second. Depending on the number of associations involved there can be
-
# arbitrarily many SQL queries made.
-
#
-
# However, if there is a WHERE clause that spans across tables Active
-
# Record will fall back to a slightly more resource-intensive single query:
-
#
-
# Author.includes(:books).where(books: {title: 'Illiad'}).to_a
-
# => SELECT `authors`.`id` AS t0_r0, `authors`.`name` AS t0_r1, `authors`.`age` AS t0_r2,
-
# `books`.`id` AS t1_r0, `books`.`title` AS t1_r1, `books`.`sales` AS t1_r2
-
# FROM `authors`
-
# LEFT OUTER JOIN `books` ON `authors`.`id` = `books`.`author_id`
-
# WHERE `books`.`title` = 'Illiad'
-
#
-
# This could result in many rows that contain redundant data and it performs poorly at scale
-
# and is therefore only used when necessary.
-
#
-
1
class Preloader #:nodoc:
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Association, 'active_record/associations/preloader/association'
-
1
autoload :SingularAssociation, 'active_record/associations/preloader/singular_association'
-
1
autoload :CollectionAssociation, 'active_record/associations/preloader/collection_association'
-
1
autoload :ThroughAssociation, 'active_record/associations/preloader/through_association'
-
-
1
autoload :HasMany, 'active_record/associations/preloader/has_many'
-
1
autoload :HasManyThrough, 'active_record/associations/preloader/has_many_through'
-
1
autoload :HasOne, 'active_record/associations/preloader/has_one'
-
1
autoload :HasOneThrough, 'active_record/associations/preloader/has_one_through'
-
1
autoload :BelongsTo, 'active_record/associations/preloader/belongs_to'
-
end
-
-
# Eager loads the named associations for the given Active Record record(s).
-
#
-
# In this description, 'association name' shall refer to the name passed
-
# to an association creation method. For example, a model that specifies
-
# <tt>belongs_to :author</tt>, <tt>has_many :buyers</tt> has association
-
# names +:author+ and +:buyers+.
-
#
-
# == Parameters
-
# +records+ is an array of ActiveRecord::Base. This array needs not be flat,
-
# i.e. +records+ itself may also contain arrays of records. In any case,
-
# +preload_associations+ will preload the all associations records by
-
# flattening +records+.
-
#
-
# +associations+ specifies one or more associations that you want to
-
# preload. It may be:
-
# - a Symbol or a String which specifies a single association name. For
-
# example, specifying +:books+ allows this method to preload all books
-
# for an Author.
-
# - an Array which specifies multiple association names. This array
-
# is processed recursively. For example, specifying <tt>[:avatar, :books]</tt>
-
# allows this method to preload an author's avatar as well as all of his
-
# books.
-
# - a Hash which specifies multiple association names, as well as
-
# association names for the to-be-preloaded association objects. For
-
# example, specifying <tt>{ author: :avatar }</tt> will preload a
-
# book's author, as well as that author's avatar.
-
#
-
# +:associations+ has the same format as the +:include+ option for
-
# <tt>ActiveRecord::Base.find</tt>. So +associations+ could look like this:
-
#
-
# :books
-
# [ :books, :author ]
-
# { author: :avatar }
-
# [ :books, { author: :avatar } ]
-
-
1
NULL_RELATION = Struct.new(:values, :bind_values).new({}, [])
-
-
1
def preload(records, associations, preload_scope = nil)
-
records = Array.wrap(records).compact.uniq
-
associations = Array.wrap(associations)
-
preload_scope = preload_scope || NULL_RELATION
-
-
if records.empty?
-
[]
-
else
-
associations.flat_map { |association|
-
preloaders_on association, records, preload_scope
-
}
-
end
-
end
-
-
1
private
-
-
1
def preloaders_on(association, records, scope)
-
case association
-
when Hash
-
preloaders_for_hash(association, records, scope)
-
when Symbol
-
preloaders_for_one(association, records, scope)
-
when String
-
preloaders_for_one(association.to_sym, records, scope)
-
else
-
raise ArgumentError, "#{association.inspect} was not recognised for preload"
-
end
-
end
-
-
1
def preloaders_for_hash(association, records, scope)
-
association.flat_map { |parent, child|
-
loaders = preloaders_for_one parent, records, scope
-
-
recs = loaders.flat_map(&:preloaded_records).uniq
-
loaders.concat Array.wrap(child).flat_map { |assoc|
-
preloaders_on assoc, recs, scope
-
}
-
loaders
-
}
-
end
-
-
# Not all records have the same class, so group then preload group on the reflection
-
# itself so that if various subclass share the same association then we do not split
-
# them unnecessarily
-
#
-
# Additionally, polymorphic belongs_to associations can have multiple associated
-
# classes, depending on the polymorphic_type field. So we group by the classes as
-
# well.
-
1
def preloaders_for_one(association, records, scope)
-
grouped_records(association, records).flat_map do |reflection, klasses|
-
klasses.map do |rhs_klass, rs|
-
loader = preloader_for(reflection, rs, rhs_klass).new(rhs_klass, rs, reflection, scope)
-
loader.run self
-
loader
-
end
-
end
-
end
-
-
1
def grouped_records(association, records)
-
h = {}
-
records.each do |record|
-
next unless record
-
assoc = record.association(association)
-
klasses = h[assoc.reflection] ||= {}
-
(klasses[assoc.klass] ||= []) << record
-
end
-
h
-
end
-
-
1
class AlreadyLoaded # :nodoc:
-
1
attr_reader :owners, :reflection
-
-
1
def initialize(klass, owners, reflection, preload_scope)
-
@owners = owners
-
@reflection = reflection
-
end
-
-
1
def run(preloader); end
-
-
1
def preloaded_records
-
owners.flat_map { |owner| owner.association(reflection.name).target }
-
end
-
end
-
-
1
class NullPreloader # :nodoc:
-
1
def self.new(klass, owners, reflection, preload_scope); self; end
-
1
def self.run(preloader); end
-
1
def self.preloaded_records; []; end
-
end
-
-
1
def preloader_for(reflection, owners, rhs_klass)
-
return NullPreloader unless rhs_klass
-
-
if owners.first.association(reflection.name).loaded?
-
return AlreadyLoaded
-
end
-
reflection.check_preloadable!
-
-
case reflection.macro
-
when :has_many
-
reflection.options[:through] ? HasManyThrough : HasMany
-
when :has_one
-
reflection.options[:through] ? HasOneThrough : HasOne
-
when :belongs_to
-
BelongsTo
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class Attribute # :nodoc:
-
1
class << self
-
1
def from_database(name, value, type)
-
388
FromDatabase.new(name, value, type)
-
end
-
-
1
def from_user(name, value, type)
-
172
FromUser.new(name, value, type)
-
end
-
-
1
def with_cast_value(name, value, type)
-
WithCastValue.new(name, value, type)
-
end
-
-
1
def null(name)
-
Null.new(name)
-
end
-
-
1
def uninitialized(name, type)
-
Uninitialized.new(name, type)
-
end
-
end
-
-
1
attr_reader :name, :value_before_type_cast, :type
-
-
# This method should not be called directly.
-
# Use #from_database or #from_user
-
1
def initialize(name, value_before_type_cast, type)
-
560
@name = name
-
560
@value_before_type_cast = value_before_type_cast
-
560
@type = type
-
end
-
-
1
def value
-
# `defined?` is cheaper than `||=` when we get back falsy values
-
2021
@value = original_value unless defined?(@value)
-
2021
@value
-
end
-
-
1
def original_value
-
560
type_cast(value_before_type_cast)
-
end
-
-
1
def value_for_database
-
366
type.type_cast_for_database(value)
-
end
-
-
1
def changed_from?(old_value)
-
172
type.changed?(old_value, value, value_before_type_cast)
-
end
-
-
1
def changed_in_place_from?(old_value)
-
595
has_been_read? && type.changed_in_place?(old_value, value)
-
end
-
-
1
def with_value_from_user(value)
-
172
self.class.from_user(name, value, type)
-
end
-
-
1
def with_value_from_database(value)
-
self.class.from_database(name, value, type)
-
end
-
-
1
def with_cast_value(value)
-
self.class.with_cast_value(name, value, type)
-
end
-
-
1
def type_cast(*)
-
raise NotImplementedError
-
end
-
-
1
def initialized?
-
50
true
-
end
-
-
1
def came_from_user?
-
20
false
-
end
-
-
1
def ==(other)
-
self.class == other.class &&
-
name == other.name &&
-
value_before_type_cast == other.value_before_type_cast &&
-
type == other.type
-
end
-
-
1
protected
-
-
1
def initialize_dup(other)
-
if defined?(@value) && @value.duplicable?
-
@value = @value.dup
-
end
-
end
-
-
1
private
-
-
1
def has_been_read?
-
595
defined?(@value)
-
end
-
-
1
class FromDatabase < Attribute # :nodoc:
-
1
def type_cast(value)
-
388
type.type_cast_from_database(value)
-
end
-
end
-
-
1
class FromUser < Attribute # :nodoc:
-
1
def type_cast(value)
-
172
type.type_cast_from_user(value)
-
end
-
-
1
def came_from_user?
-
true
-
end
-
end
-
-
1
class WithCastValue < Attribute # :nodoc:
-
1
def type_cast(value)
-
value
-
end
-
-
1
def changed_in_place_from?(old_value)
-
false
-
end
-
end
-
-
1
class Null < Attribute # :nodoc:
-
1
def initialize(name)
-
super(name, nil, Type::Value.new)
-
end
-
-
1
def value
-
nil
-
end
-
-
1
def with_value_from_database(value)
-
raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{name}`"
-
end
-
1
alias_method :with_value_from_user, :with_value_from_database
-
end
-
-
1
class Uninitialized < Attribute # :nodoc:
-
1
def initialize(name, type)
-
super(name, nil, type)
-
end
-
-
1
def value
-
if block_given?
-
yield name
-
end
-
end
-
-
1
def value_for_database
-
end
-
-
1
def initialized?
-
false
-
end
-
end
-
1
private_constant :FromDatabase, :FromUser, :Null, :Uninitialized
-
end
-
end
-
1
require 'active_model/forbidden_attributes_protection'
-
-
1
module ActiveRecord
-
1
module AttributeAssignment
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::ForbiddenAttributesProtection
-
-
# Allows you to set all the attributes by passing in a hash of attributes with
-
# keys matching the attribute names (which again matches the column names).
-
#
-
# If the passed hash responds to <tt>permitted?</tt> method and the return value
-
# of this method is +false+ an <tt>ActiveModel::ForbiddenAttributesError</tt>
-
# exception is raised.
-
#
-
# cat = Cat.new(name: "Gorby", status: "yawning")
-
# cat.attributes # => { "name" => "Gorby", "status" => "yawning", "created_at" => nil, "updated_at" => nil}
-
# cat.assign_attributes(status: "sleeping")
-
# cat.attributes # => { "name" => "Gorby", "status" => "sleeping", "created_at" => nil, "updated_at" => nil }
-
#
-
# New attributes will be persisted in the database when the object is saved.
-
#
-
# Aliased to <tt>attributes=</tt>.
-
1
def assign_attributes(new_attributes)
-
29
if !new_attributes.respond_to?(:stringify_keys)
-
raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
-
end
-
29
return if new_attributes.blank?
-
-
29
attributes = new_attributes.stringify_keys
-
29
multi_parameter_attributes = []
-
29
nested_parameter_attributes = []
-
-
29
attributes = sanitize_for_mass_assignment(attributes)
-
-
29
attributes.each do |k, v|
-
97
if k.include?("(")
-
6
multi_parameter_attributes << [ k, v ]
-
elsif v.is_a?(Hash)
-
nested_parameter_attributes << [ k, v ]
-
else
-
91
_assign_attribute(k, v)
-
end
-
end
-
-
29
assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty?
-
29
assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty?
-
end
-
-
1
alias attributes= assign_attributes
-
-
1
private
-
-
1
def _assign_attribute(k, v)
-
91
public_send("#{k}=", v)
-
rescue NoMethodError, NameError
-
if respond_to?("#{k}=")
-
raise
-
else
-
raise UnknownAttributeError.new(self, k)
-
end
-
end
-
-
# Assign any deferred nested attributes after the base attributes have been set.
-
1
def assign_nested_parameter_attributes(pairs)
-
pairs.each { |k, v| _assign_attribute(k, v) }
-
end
-
-
# Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
-
# by calling new on the column type or aggregation type (through composed_of) object with these parameters.
-
# So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
-
# written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
-
# parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum and
-
# f for Float. If all the values for a given attribute are empty, the attribute will be set to +nil+.
-
1
def assign_multiparameter_attributes(pairs)
-
2
execute_callstack_for_multiparameter_attributes(
-
extract_callstack_for_multiparameter_attributes(pairs)
-
)
-
end
-
-
1
def execute_callstack_for_multiparameter_attributes(callstack)
-
2
errors = []
-
2
callstack.each do |name, values_with_empty_parameters|
-
2
begin
-
2
send("#{name}=", MultiparameterAttribute.new(self, name, values_with_empty_parameters).read_value)
-
rescue => ex
-
errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name} (#{ex.message})", ex, name)
-
end
-
end
-
2
unless errors.empty?
-
error_descriptions = errors.map { |ex| ex.message }.join(",")
-
raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes [#{error_descriptions}]"
-
end
-
end
-
-
1
def extract_callstack_for_multiparameter_attributes(pairs)
-
2
attributes = {}
-
-
2
pairs.each do |(multiparameter_name, value)|
-
6
attribute_name = multiparameter_name.split("(").first
-
6
attributes[attribute_name] ||= {}
-
-
6
parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value)
-
6
attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value
-
end
-
-
2
attributes
-
end
-
-
1
def type_cast_attribute_value(multiparameter_name, value)
-
6
multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value
-
end
-
-
1
def find_parameter_position(multiparameter_name)
-
6
multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i
-
end
-
-
1
class MultiparameterAttribute #:nodoc:
-
1
attr_reader :object, :name, :values, :cast_type
-
-
1
def initialize(object, name, values)
-
2
@object = object
-
2
@name = name
-
2
@values = values
-
end
-
-
1
def read_value
-
2
return if values.values.compact.empty?
-
-
2
@cast_type = object.type_for_attribute(name)
-
2
klass = cast_type.klass
-
-
2
if klass == Time
-
read_time
-
2
elsif klass == Date
-
2
read_date
-
else
-
read_other
-
end
-
end
-
-
1
private
-
-
1
def instantiate_time_object(set_values)
-
if object.class.send(:create_time_zone_conversion_attribute?, name, cast_type)
-
Time.zone.local(*set_values)
-
else
-
Time.send(object.class.default_timezone, *set_values)
-
end
-
end
-
-
1
def read_time
-
# If column is a :time (and not :date or :datetime) there is no need to validate if
-
# there are year/month/day fields
-
if cast_type.type == :time
-
# if the column is a time set the values to their defaults as January 1, 1970, but only if they're nil
-
{ 1 => 1970, 2 => 1, 3 => 1 }.each do |key,value|
-
values[key] ||= value
-
end
-
else
-
# else column is a timestamp, so if Date bits were not provided, error
-
validate_required_parameters!([1,2,3])
-
-
# If Date bits were provided but blank, then return nil
-
return if blank_date_parameter?
-
end
-
-
max_position = extract_max_param(6)
-
set_values = values.values_at(*(1..max_position))
-
# If Time bits are not there, then default to 0
-
(3..5).each { |i| set_values[i] = set_values[i].presence || 0 }
-
instantiate_time_object(set_values)
-
end
-
-
1
def read_date
-
2
return if blank_date_parameter?
-
2
set_values = values.values_at(1,2,3)
-
2
begin
-
2
Date.new(*set_values)
-
rescue ArgumentError # if Date.new raises an exception on an invalid date
-
instantiate_time_object(set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
-
end
-
end
-
-
1
def read_other
-
max_position = extract_max_param
-
positions = (1..max_position)
-
validate_required_parameters!(positions)
-
-
values.slice(*positions)
-
end
-
-
# Checks whether some blank date parameter exists. Note that this is different
-
# than the validate_required_parameters! method, since it just checks for blank
-
# positions instead of missing ones, and does not raise in case one blank position
-
# exists. The caller is responsible to handle the case of this returning true.
-
1
def blank_date_parameter?
-
8
(1..3).any? { |position| values[position].blank? }
-
end
-
-
# If some position is not provided, it errors out a missing parameter exception.
-
1
def validate_required_parameters!(positions)
-
if missing_parameter = positions.detect { |position| !values.key?(position) }
-
raise ArgumentError.new("Missing Parameter - #{name}(#{missing_parameter})")
-
end
-
end
-
-
1
def extract_max_param(upper_cap = 100)
-
[values.keys.max, upper_cap].min
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeDecorators # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :attribute_type_decorations, instance_accessor: false # :internal:
-
1
self.attribute_type_decorations = TypeDecorator.new
-
end
-
-
1
module ClassMethods # :nodoc:
-
1
def decorate_attribute_type(column_name, decorator_name, &block)
-
matcher = ->(name, _) { name == column_name.to_s }
-
key = "_#{column_name}_#{decorator_name}"
-
decorate_matching_attribute_types(matcher, key, &block)
-
end
-
-
1
def decorate_matching_attribute_types(matcher, decorator_name, &block)
-
10
clear_caches_calculated_from_columns
-
10
decorator_name = decorator_name.to_s
-
-
# Create new hashes so we don't modify parent classes
-
10
self.attribute_type_decorations = attribute_type_decorations.merge(decorator_name => [matcher, block])
-
end
-
-
1
private
-
-
1
def add_user_provided_columns(*)
-
5
super.map do |column|
-
28
decorated_type = attribute_type_decorations.apply(column.name, column.cast_type)
-
28
column.with_type(decorated_type)
-
end
-
end
-
end
-
-
1
class TypeDecorator # :nodoc:
-
1
delegate :clear, to: :@decorations
-
-
1
def initialize(decorations = {})
-
11
@decorations = decorations
-
end
-
-
1
def merge(*args)
-
10
TypeDecorator.new(@decorations.merge(*args))
-
end
-
-
1
def apply(name, type)
-
28
decorations = decorators_for(name, type)
-
28
decorations.inject(type) do |new_type, block|
-
8
block.call(new_type)
-
end
-
end
-
-
1
private
-
-
1
def decorators_for(name, type)
-
28
matching(name, type).map(&:last)
-
end
-
-
1
def matching(name, type)
-
28
@decorations.values.select do |(matcher, _)|
-
56
matcher.call(name, type)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/enumerable'
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'mutex_m'
-
1
require 'thread_safe'
-
-
1
module ActiveRecord
-
# = Active Record Attribute Methods
-
1
module AttributeMethods
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::AttributeMethods
-
-
1
included do
-
1
initialize_generated_modules
-
1
include Read
-
1
include Write
-
1
include BeforeTypeCast
-
1
include Query
-
1
include PrimaryKey
-
1
include TimeZoneConversion
-
1
include Dirty
-
1
include Serialization
-
-
1
delegate :column_for_attribute, to: :class
-
end
-
-
1
AttrNames = Module.new {
-
1
def self.set_name_cache(name, value)
-
36
const_name = "ATTR_#{name}"
-
36
unless const_defined? const_name
-
18
const_set const_name, value.dup.freeze
-
end
-
end
-
}
-
-
1
BLACKLISTED_CLASS_METHODS = %w(private public protected allocate new name parent superclass)
-
-
1
class AttributeMethodCache
-
1
def initialize
-
2
@module = Module.new
-
2
@method_cache = ThreadSafe::Cache.new
-
end
-
-
1
def [](name)
-
56
@method_cache.compute_if_absent(name) do
-
36
safe_name = name.unpack('h*').first
-
36
temp_method = "__temp__#{safe_name}"
-
36
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
-
36
@module.module_eval method_body(temp_method, safe_name), __FILE__, __LINE__
-
36
@module.instance_method temp_method
-
end
-
end
-
-
1
private
-
-
# Override this method in the subclasses for method body.
-
1
def method_body(method_name, const_name)
-
raise NotImplementedError, "Subclasses must implement a method_body(method_name, const_name) method."
-
end
-
end
-
-
1
class GeneratedAttributeMethods < Module; end # :nodoc:
-
-
1
module ClassMethods
-
1
def inherited(child_class) #:nodoc:
-
5
child_class.initialize_generated_modules
-
5
super
-
end
-
-
1
def initialize_generated_modules # :nodoc:
-
12
@generated_attribute_methods = GeneratedAttributeMethods.new { extend Mutex_m }
-
6
@attribute_methods_generated = false
-
6
include @generated_attribute_methods
-
-
6
super
-
end
-
-
# Generates all the attribute related methods for columns in the database
-
# accessors, mutators and query methods.
-
1
def define_attribute_methods # :nodoc:
-
137
return false if @attribute_methods_generated
-
# Use a mutex; we don't want two threads simultaneously trying to define
-
# attribute methods.
-
5
generated_attribute_methods.synchronize do
-
5
return false if @attribute_methods_generated
-
5
superclass.define_attribute_methods unless self == base_class
-
5
super(column_names)
-
5
@attribute_methods_generated = true
-
end
-
5
true
-
end
-
-
1
def undefine_attribute_methods # :nodoc:
-
7
generated_attribute_methods.synchronize do
-
7
super if defined?(@attribute_methods_generated) && @attribute_methods_generated
-
7
@attribute_methods_generated = false
-
end
-
end
-
-
# Raises a <tt>ActiveRecord::DangerousAttributeError</tt> exception when an
-
# \Active \Record method is defined in the model, otherwise +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# def save
-
# 'already defined by Active Record'
-
# end
-
# end
-
#
-
# Person.instance_method_already_implemented?(:save)
-
# # => ActiveRecord::DangerousAttributeError: save is defined by ActiveRecord
-
#
-
# Person.instance_method_already_implemented?(:name)
-
# # => false
-
1
def instance_method_already_implemented?(method_name)
-
308
if dangerous_attribute_method?(method_name)
-
raise DangerousAttributeError, "#{method_name} is defined by Active Record. Check to make sure that you don't have an attribute or method with the same name."
-
end
-
-
308
if superclass == Base
-
308
super
-
else
-
# If ThisClass < ... < SomeSuperClass < ... < Base and SomeSuperClass
-
# defines its own attribute method, then we don't want to overwrite that.
-
defined = method_defined_within?(method_name, superclass, Base) &&
-
! superclass.instance_method(method_name).owner.is_a?(GeneratedAttributeMethods)
-
defined || super
-
end
-
end
-
-
# A method name is 'dangerous' if it is already (re)defined by Active Record, but
-
# not by any ancestors. (So 'puts' is not dangerous but 'save' is.)
-
1
def dangerous_attribute_method?(name) # :nodoc:
-
312
method_defined_within?(name, Base)
-
end
-
-
1
def method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
-
312
if klass.method_defined?(name) || klass.private_method_defined?(name)
-
20
if superklass.method_defined?(name) || superklass.private_method_defined?(name)
-
klass.instance_method(name).owner != superklass.instance_method(name).owner
-
else
-
20
true
-
end
-
else
-
292
false
-
end
-
end
-
-
# A class method is 'dangerous' if it is already (re)defined by Active Record, but
-
# not by any ancestors. (So 'puts' is not dangerous but 'new' is.)
-
1
def dangerous_class_method?(method_name)
-
BLACKLISTED_CLASS_METHODS.include?(method_name.to_s) || class_method_defined_within?(method_name, Base)
-
end
-
-
1
def class_method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc
-
if klass.respond_to?(name, true)
-
if superklass.respond_to?(name, true)
-
klass.method(name).owner != superklass.method(name).owner
-
else
-
true
-
end
-
else
-
false
-
end
-
end
-
-
# Returns +true+ if +attribute+ is an attribute method and table exists,
-
# +false+ otherwise.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# Person.attribute_method?('name') # => true
-
# Person.attribute_method?(:age=) # => true
-
# Person.attribute_method?(:nothing) # => false
-
1
def attribute_method?(attribute)
-
super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
-
end
-
-
# Returns an array of column names as strings if it's not an abstract class and
-
# table exists. Otherwise it returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# Person.attribute_names
-
# # => ["id", "created_at", "updated_at", "name", "age"]
-
1
def attribute_names
-
@attribute_names ||= if !abstract_class? && table_exists?
-
4
column_names
-
else
-
[]
-
62
end
-
end
-
-
# Returns the column object for the named attribute.
-
# Returns nil if the named attribute does not exist.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.column_for_attribute(:name) # the result depends on the ConnectionAdapter
-
# # => #<ActiveRecord::ConnectionAdapters::Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...>
-
#
-
# person.column_for_attribute(:nothing)
-
# # => nil
-
1
def column_for_attribute(name)
-
column = columns_hash[name.to_s]
-
if column.nil?
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
`#column_for_attribute` will return a null object for non-existent
-
columns in Rails 5. Use `#has_attribute?` if you need to check for
-
an attribute's existence.
-
MSG
-
end
-
column
-
end
-
end
-
-
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
-
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
-
# which will all return +true+. It also define the attribute methods if they have
-
# not been generated.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.respond_to(:name) # => true
-
# person.respond_to(:name=) # => true
-
# person.respond_to(:name?) # => true
-
# person.respond_to('age') # => true
-
# person.respond_to('age=') # => true
-
# person.respond_to('age?') # => true
-
# person.respond_to(:nothing) # => false
-
1
def respond_to?(name, include_private = false)
-
141
return false unless super
-
134
name = name.to_s
-
-
# If the result is true then check for the select case.
-
# For queries selecting a subset of columns, return false for unselected columns.
-
# We check defined?(@attributes) not to issue warnings if called on objects that
-
# have been allocated but not yet initialized.
-
134
if defined?(@attributes) && self.class.column_names.include?(name)
-
return has_attribute?(name)
-
end
-
-
134
return true
-
end
-
-
# Returns +true+ if the given attribute is in the attributes hash, otherwise +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.has_attribute?(:name) # => true
-
# person.has_attribute?('age') # => true
-
# person.has_attribute?(:nothing) # => false
-
1
def has_attribute?(attr_name)
-
100
@attributes.key?(attr_name.to_s)
-
end
-
-
# Returns an array of names for the attributes available on this object.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.attribute_names
-
# # => ["id", "created_at", "updated_at", "name", "age"]
-
1
def attribute_names
-
29
@attributes.keys
-
end
-
-
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.create(name: 'Francesco', age: 22)
-
# person.attributes
-
# # => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}
-
1
def attributes
-
@attributes.to_hash
-
end
-
-
# Returns an <tt>#inspect</tt>-like string for the value of the
-
# attribute +attr_name+. String attributes are truncated up to 50
-
# characters, Date and Time attributes are returned in the
-
# <tt>:db</tt> format, Array attributes are truncated up to 10 values.
-
# Other attributes return the value of <tt>#inspect</tt> without
-
# modification.
-
#
-
# person = Person.create!(name: 'David Heinemeier Hansson ' * 3)
-
#
-
# person.attribute_for_inspect(:name)
-
# # => "\"David Heinemeier Hansson David Heinemeier Hansson ...\""
-
#
-
# person.attribute_for_inspect(:created_at)
-
# # => "\"2012-10-22 00:15:07\""
-
#
-
# person.attribute_for_inspect(:tag_ids)
-
# # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]"
-
1
def attribute_for_inspect(attr_name)
-
value = read_attribute(attr_name)
-
-
if value.is_a?(String) && value.length > 50
-
"#{value[0, 50]}...".inspect
-
elsif value.is_a?(Date) || value.is_a?(Time)
-
%("#{value.to_s(:db)}")
-
elsif value.is_a?(Array) && value.size > 10
-
inspected = value.first(10).inspect
-
%(#{inspected[0...-1]}, ...])
-
else
-
value.inspect
-
end
-
end
-
-
# Returns +true+ if the specified +attribute+ has been set by the user or by a
-
# database load and is neither +nil+ nor <tt>empty?</tt> (the latter only applies
-
# to objects that respond to <tt>empty?</tt>, most notably Strings). Otherwise, +false+.
-
# Note that it always returns +true+ with boolean attributes.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(title: '', is_done: false)
-
# task.attribute_present?(:title) # => false
-
# task.attribute_present?(:is_done) # => true
-
# task.title = 'Buy milk'
-
# task.is_done = true
-
# task.attribute_present?(:title) # => true
-
# task.attribute_present?(:is_done) # => true
-
1
def attribute_present?(attribute)
-
50
value = _read_attribute(attribute)
-
50
!value.nil? && !(value.respond_to?(:empty?) && value.empty?)
-
end
-
-
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
-
# "2004-12-12" in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises
-
# <tt>ActiveModel::MissingAttributeError</tt> if the identified attribute is missing.
-
#
-
# Note: +:id+ is always present.
-
#
-
# Alias for the <tt>read_attribute</tt> method.
-
#
-
# class Person < ActiveRecord::Base
-
# belongs_to :organization
-
# end
-
#
-
# person = Person.new(name: 'Francesco', age: '22')
-
# person[:name] # => "Francesco"
-
# person[:age] # => 22
-
#
-
# person = Person.select('id').first
-
# person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name
-
# person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id
-
1
def [](attr_name)
-
read_attribute(attr_name) { |n| missing_attribute(n, caller) }
-
end
-
-
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
-
# (Alias for the protected <tt>write_attribute</tt> method).
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person[:age] = '22'
-
# person[:age] # => 22
-
# person[:age] # => Fixnum
-
1
def []=(attr_name, value)
-
write_attribute(attr_name, value)
-
end
-
-
1
protected
-
-
1
def clone_attribute_value(reader_method, attribute_name) # :nodoc:
-
172
value = send(reader_method, attribute_name)
-
172
value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
value
-
end
-
-
1
def arel_attributes_with_values_for_create(attribute_names) # :nodoc:
-
25
arel_attributes_with_values(attributes_for_create(attribute_names))
-
end
-
-
1
def arel_attributes_with_values_for_update(attribute_names) # :nodoc:
-
4
arel_attributes_with_values(attributes_for_update(attribute_names))
-
end
-
-
1
def attribute_method?(attr_name) # :nodoc:
-
# We check defined? because Syck calls respond_to? before actually calling initialize.
-
7
defined?(@attributes) && @attributes.key?(attr_name)
-
end
-
-
1
private
-
-
# Returns a Hash of the Arel::Attributes and attribute values that have been
-
# typecasted for use in an Arel insert/update method.
-
1
def arel_attributes_with_values(attribute_names)
-
29
attrs = {}
-
29
arel_table = self.class.arel_table
-
-
29
attribute_names.each do |name|
-
139
attrs[arel_table[name]] = typecasted_attribute_value(name)
-
end
-
29
attrs
-
end
-
-
# Filters the primary keys and readonly attributes from the attribute names.
-
1
def attributes_for_update(attribute_names)
-
4
attribute_names.reject do |name|
-
9
readonly_attribute?(name)
-
end
-
end
-
-
# Filters out the primary keys, from the attribute names, when the primary
-
# key is to be generated (e.g. the id attribute has no value).
-
1
def attributes_for_create(attribute_names)
-
25
attribute_names.reject do |name|
-
130
pk_attribute?(name) && id.nil?
-
end
-
end
-
-
1
def readonly_attribute?(name)
-
9
self.class.readonly_attributes.include?(name)
-
end
-
-
1
def pk_attribute?(name)
-
130
name == self.class.primary_key
-
end
-
-
1
def typecasted_attribute_value(name)
-
139
_read_attribute(name)
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
# = Active Record Attribute Methods Before Type Cast
-
#
-
# <tt>ActiveRecord::AttributeMethods::BeforeTypeCast</tt> provides a way to
-
# read the value of the attributes before typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(id: '1', completed_on: '2012-10-21')
-
# task.id # => 1
-
# task.completed_on # => Sun, 21 Oct 2012
-
#
-
# task.attributes_before_type_cast
-
# # => {"id"=>"1", "completed_on"=>"2012-10-21", ... }
-
# task.read_attribute_before_type_cast('id') # => "1"
-
# task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
-
#
-
# In addition to #read_attribute_before_type_cast and #attributes_before_type_cast,
-
# it declares a method for all attributes with the <tt>*_before_type_cast</tt>
-
# suffix.
-
#
-
# task.id_before_type_cast # => "1"
-
# task.completed_on_before_type_cast # => "2012-10-21"
-
1
module BeforeTypeCast
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attribute_method_suffix "_before_type_cast"
-
1
attribute_method_suffix "_came_from_user?"
-
end
-
-
# Returns the value of the attribute identified by +attr_name+ before
-
# typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(id: '1', completed_on: '2012-10-21')
-
# task.read_attribute('id') # => 1
-
# task.read_attribute_before_type_cast('id') # => '1'
-
# task.read_attribute('completed_on') # => Sun, 21 Oct 2012
-
# task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
-
# task.read_attribute_before_type_cast(:completed_on) # => "2012-10-21"
-
1
def read_attribute_before_type_cast(attr_name)
-
263
@attributes[attr_name.to_s].value_before_type_cast
-
end
-
-
# Returns a hash of attributes before typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(title: nil, is_done: true, completed_on: '2012-10-21')
-
# task.attributes
-
# # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>Sun, 21 Oct 2012, "created_at"=>nil, "updated_at"=>nil}
-
# task.attributes_before_type_cast
-
# # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>"2012-10-21", "created_at"=>nil, "updated_at"=>nil}
-
1
def attributes_before_type_cast
-
@attributes.values_before_type_cast
-
end
-
-
1
private
-
-
# Handle *_before_type_cast for method_missing.
-
1
def attribute_before_type_cast(attribute_name)
-
read_attribute_before_type_cast(attribute_name)
-
end
-
-
1
def attribute_came_from_user?(attribute_name)
-
20
@attributes[attribute_name].came_from_user?
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Dirty # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
include ActiveModel::Dirty
-
-
1
included do
-
1
if self < ::ActiveRecord::Timestamp
-
raise "You cannot include Dirty after Timestamp"
-
end
-
-
1
class_attribute :partial_writes, instance_writer: false
-
1
self.partial_writes = true
-
end
-
-
# Attempts to +save+ the record and clears changed attributes if successful.
-
1
def save(*)
-
6
if status = super
-
6
changes_applied
-
end
-
6
status
-
end
-
-
# Attempts to <tt>save!</tt> the record and clears changed attributes if successful.
-
1
def save!(*)
-
23
super.tap do
-
23
changes_applied
-
end
-
end
-
-
# <tt>reload</tt> the record and clears changed attributes.
-
1
def reload(*)
-
super.tap do
-
clear_changes_information
-
end
-
end
-
-
1
def initialize_dup(other) # :nodoc:
-
super
-
calculate_changes_from_defaults
-
end
-
-
1
def changes_applied
-
29
super
-
29
store_original_raw_attributes
-
end
-
-
1
def clear_changes_information
-
super
-
original_raw_attributes.clear
-
end
-
-
1
def changed_attributes
-
# This should only be set by methods which will call changed_attributes
-
# multiple times when it is known that the computed value cannot change.
-
255
if defined?(@cached_changed_attributes)
-
193
@cached_changed_attributes
-
else
-
62
super.reverse_merge(attributes_changed_in_place).freeze
-
end
-
end
-
-
1
def changes
-
29
cache_changed_attributes do
-
29
super
-
end
-
end
-
-
1
def attribute_changed_in_place?(attr_name)
-
595
old_value = original_raw_attribute(attr_name)
-
595
@attributes[attr_name].changed_in_place_from?(old_value)
-
end
-
-
1
private
-
-
1
def changes_include?(attr_name)
-
344
super || attribute_changed_in_place?(attr_name)
-
end
-
-
1
def calculate_changes_from_defaults
-
@changed_attributes = nil
-
self.class.column_defaults.each do |attr, orig_value|
-
set_attribute_was(attr, orig_value) if _field_changed?(attr, orig_value)
-
end
-
end
-
-
# Wrap write_attribute to remember original attribute value.
-
1
def write_attribute(attr, value)
-
172
attr = attr.to_s
-
-
172
old_value = old_attribute_value(attr)
-
-
172
result = super
-
172
store_original_raw_attribute(attr)
-
172
save_changed_attribute(attr, old_value)
-
172
result
-
end
-
-
1
def raw_write_attribute(attr, value)
-
attr = attr.to_s
-
-
result = super
-
original_raw_attributes[attr] = value
-
result
-
end
-
-
1
def save_changed_attribute(attr, old_value)
-
172
clear_changed_attributes_cache
-
172
if attribute_changed_by_setter?(attr)
-
clear_attribute_changes(attr) unless _field_changed?(attr, old_value)
-
else
-
172
set_attribute_was(attr, old_value) if _field_changed?(attr, old_value)
-
end
-
end
-
-
1
def old_attribute_value(attr)
-
172
if attribute_changed?(attr)
-
changed_attributes[attr]
-
else
-
172
clone_attribute_value(:_read_attribute, attr)
-
end
-
end
-
-
1
def _update_record(*)
-
4
partial_writes? ? super(keys_for_partial_write) : super
-
end
-
-
1
def _create_record(*)
-
25
partial_writes? ? super(keys_for_partial_write) : super
-
end
-
-
# Serialized attributes should always be written in case they've been
-
# changed in place.
-
1
def keys_for_partial_write
-
29
changed & persistable_attribute_names
-
end
-
-
1
def _field_changed?(attr, old_value)
-
172
@attributes[attr].changed_from?(old_value)
-
end
-
-
1
def attributes_changed_in_place
-
62
changed_in_place.each_with_object({}) do |attr_name, h|
-
orig = @attributes[attr_name].original_value
-
h[attr_name] = orig
-
end
-
end
-
-
1
def changed_in_place
-
62
self.class.attribute_names.select do |attr_name|
-
415
attribute_changed_in_place?(attr_name)
-
end
-
end
-
-
1
def original_raw_attribute(attr_name)
-
595
original_raw_attributes.fetch(attr_name) do
-
263
read_attribute_before_type_cast(attr_name)
-
end
-
end
-
-
1
def original_raw_attributes
-
961
@original_raw_attributes ||= {}
-
end
-
-
1
def store_original_raw_attribute(attr_name)
-
366
original_raw_attributes[attr_name] = @attributes[attr_name].value_for_database rescue nil
-
end
-
-
1
def store_original_raw_attributes
-
29
attribute_names.each do |attr|
-
194
store_original_raw_attribute(attr)
-
end
-
end
-
-
1
def cache_changed_attributes
-
29
@cached_changed_attributes = changed_attributes
-
29
yield
-
ensure
-
29
clear_changed_attributes_cache
-
end
-
-
1
def clear_changed_attributes_cache
-
201
remove_instance_variable(:@cached_changed_attributes) if defined?(@cached_changed_attributes)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Query
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attribute_method_suffix "?"
-
end
-
-
1
def query_attribute(attr_name)
-
value = self[attr_name]
-
-
case value
-
when true then true
-
when false, nil then false
-
else
-
column = self.class.columns_hash[attr_name]
-
if column.nil?
-
if Numeric === value || value !~ /[^0-9]/
-
!value.to_i.zero?
-
else
-
return false if ActiveRecord::ConnectionAdapters::Column::FALSE_VALUES.include?(value)
-
!value.blank?
-
end
-
elsif column.number?
-
!value.zero?
-
else
-
!value.blank?
-
end
-
end
-
end
-
-
1
private
-
# Handle *? for method_missing.
-
1
def attribute?(attribute_name)
-
query_attribute(attribute_name)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/method_transplanting'
-
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Read
-
1
ReaderMethodCache = Class.new(AttributeMethodCache) {
-
1
private
-
# We want to generate the methods via module_eval rather than
-
# define_method, because define_method is slower on dispatch.
-
# Evaluating many similar methods may use more memory as the instruction
-
# sequences are duplicated and cached (in MRI). define_method may
-
# be slower on dispatch, but if you're careful about the closure
-
# created, then define_method will consume much less memory.
-
#
-
# But sometimes the database might return columns with
-
# characters that are not allowed in normal method names (like
-
# 'my_column(omg)'. So to work around this we first define with
-
# the __temp__ identifier, and then use alias method to rename
-
# it to what we want.
-
#
-
# We are also defining a constant to hold the frozen string of
-
# the attribute name. Using a constant means that we do not have
-
# to allocate an object on each call to the attribute method.
-
# Making it frozen means that it doesn't get duped when used to
-
# key the @attributes in read_attribute.
-
1
def method_body(method_name, const_name)
-
<<-EOMETHOD
-
18
def #{method_name}
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{const_name}
-
_read_attribute(name) { |n| missing_attribute(n, caller) }
-
end
-
EOMETHOD
-
end
-
}.new
-
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
1
[:cache_attributes, :cached_attributes, :cache_attribute?].each do |method_name|
-
3
define_method method_name do |*|
-
cached_attributes_deprecation_warning(method_name)
-
true
-
end
-
end
-
-
1
protected
-
-
1
def cached_attributes_deprecation_warning(method_name)
-
ActiveSupport::Deprecation.warn "Calling `#{method_name}` is no longer necessary. All attributes are cached."
-
end
-
-
1
if Module.methods_transplantable?
-
1
def define_method_attribute(name)
-
28
method = ReaderMethodCache[name]
-
56
generated_attribute_methods.module_eval { define_method name, method }
-
end
-
else
-
def define_method_attribute(name)
-
safe_name = name.unpack('h*').first
-
temp_method = "__temp__#{safe_name}"
-
-
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
-
-
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
-
def #{temp_method}
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name}
-
_read_attribute(name) { |n| missing_attribute(n, caller) }
-
end
-
STR
-
-
generated_attribute_methods.module_eval do
-
alias_method name, temp_method
-
undef_method temp_method
-
end
-
end
-
end
-
end
-
-
1
ID = 'id'.freeze
-
-
# Returns the value of the attribute identified by <tt>attr_name</tt> after
-
# it has been typecast (for example, "2004-12-12" in a date column is cast
-
# to a date object, like Date.new(2004, 12, 12)).
-
1
def read_attribute(attr_name, &block)
-
name = attr_name.to_s
-
name = self.class.primary_key if name == ID
-
_read_attribute(name, &block)
-
end
-
-
# This method exists to avoid the expensive primary_key check internally, without
-
# breaking compatibility with the read_attribute API
-
1
def _read_attribute(attr_name) # :nodoc:
-
1035
@attributes.fetch_value(attr_name.to_s) { |n| yield n if block_given? }
-
end
-
-
1
private
-
-
1
def attribute(attribute_name)
-
_read_attribute(attribute_name)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/filters'
-
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Serialization
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# If you have an attribute that needs to be saved to the database as an
-
# object, and retrieved as the same object, then specify the name of that
-
# attribute using this method and it will be handled automatically. The
-
# serialization is done through YAML. If +class_name+ is specified, the
-
# serialized object must be of that class on assignment and retrieval.
-
# Otherwise <tt>SerializationTypeMismatch</tt> will be raised.
-
#
-
# ==== Parameters
-
#
-
# * +attr_name+ - The field name that should be serialized.
-
# * +class_name_or_coder+ - Optional, a coder object, which responds to `.load` / `.dump`
-
# or a class name that the object type should be equal to.
-
#
-
# ==== Example
-
#
-
# # Serialize a preferences attribute.
-
# class User < ActiveRecord::Base
-
# serialize :preferences
-
# end
-
#
-
# # Serialize preferences using JSON as coder.
-
# class User < ActiveRecord::Base
-
# serialize :preferences, JSON
-
# end
-
#
-
# # Serialize preferences as Hash using YAML coder.
-
# class User < ActiveRecord::Base
-
# serialize :preferences, Hash
-
# end
-
1
def serialize(attr_name, class_name_or_coder = Object)
-
# When ::JSON is used, force it to go through the Active Support JSON encoder
-
# to ensure special objects (e.g. Active Record models) are dumped correctly
-
# using the #as_json hook.
-
coder = if class_name_or_coder == ::JSON
-
Coders::JSON
-
elsif [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) }
-
class_name_or_coder
-
else
-
Coders::YAMLColumn.new(class_name_or_coder)
-
end
-
-
decorate_attribute_type(attr_name, :serialize) do |type|
-
Type::Serialized.new(type, coder)
-
end
-
end
-
-
1
def serialized_attributes
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
`serialized_attributes` is deprecated without replacement, and will
-
be removed in Rails 5.0.
-
MSG
-
-
@serialized_attributes ||= Hash[
-
columns.select { |t| t.cast_type.is_a?(Type::Serialized) }.map { |c|
-
[c.name, c.cast_type.coder]
-
}
-
]
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module TimeZoneConversion
-
1
class TimeZoneConverter < DelegateClass(Type::Value) # :nodoc:
-
1
include Type::Decorator
-
-
1
def type_cast_from_database(value)
-
58
convert_time_to_time_zone(super)
-
end
-
-
1
def type_cast_from_user(value)
-
54
if value.is_a?(Array)
-
value.map { |v| type_cast_from_user(v) }
-
54
elsif value.respond_to?(:in_time_zone)
-
54
begin
-
54
value.in_time_zone || super
-
rescue ArgumentError
-
nil
-
end
-
end
-
end
-
-
1
def convert_time_to_time_zone(value)
-
58
if value.is_a?(Array)
-
value.map { |v| convert_time_to_time_zone(v) }
-
58
elsif value.acts_like?(:time)
-
8
value.in_time_zone
-
else
-
50
value
-
end
-
end
-
end
-
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
mattr_accessor :time_zone_aware_attributes, instance_writer: false
-
1
self.time_zone_aware_attributes = false
-
-
1
class_attribute :skip_time_zone_conversion_for_attributes, instance_writer: false
-
1
self.skip_time_zone_conversion_for_attributes = []
-
end
-
-
1
module ClassMethods
-
1
private
-
-
1
def inherited(subclass)
-
# We need to apply this decorator here, rather than on module inclusion. The closure
-
# created by the matcher would otherwise evaluate for `ActiveRecord::Base`, not the
-
# sub class being decorated. As such, changes to `time_zone_aware_attributes`, or
-
# `skip_time_zone_conversion_for_attributes` would not be picked up.
-
5
subclass.class_eval do
-
33
matcher = ->(name, type) { create_time_zone_conversion_attribute?(name, type) }
-
5
decorate_matching_attribute_types(matcher, :_time_zone_conversion) do |type|
-
8
TimeZoneConverter.new(type)
-
end
-
end
-
5
super
-
end
-
-
1
def create_time_zone_conversion_attribute?(name, cast_type)
-
time_zone_aware_attributes &&
-
28
!self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) &&
-
28
(:datetime == cast_type.type)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/method_transplanting'
-
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Write
-
1
WriterMethodCache = Class.new(AttributeMethodCache) {
-
1
private
-
-
1
def method_body(method_name, const_name)
-
<<-EOMETHOD
-
18
def #{method_name}(value)
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{const_name}
-
write_attribute(name, value)
-
end
-
EOMETHOD
-
end
-
}.new
-
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attribute_method_suffix "="
-
end
-
-
1
module ClassMethods
-
1
protected
-
-
1
if Module.methods_transplantable?
-
1
def define_method_attribute=(name)
-
28
method = WriterMethodCache[name]
-
28
generated_attribute_methods.module_eval {
-
28
define_method "#{name}=", method
-
}
-
end
-
else
-
def define_method_attribute=(name)
-
safe_name = name.unpack('h*').first
-
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
-
-
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
-
def __temp__#{safe_name}=(value)
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name}
-
write_attribute(name, value)
-
end
-
alias_method #{(name + '=').inspect}, :__temp__#{safe_name}=
-
undef_method :__temp__#{safe_name}=
-
STR
-
end
-
end
-
end
-
-
# Updates the attribute identified by <tt>attr_name</tt> with the
-
# specified +value+. Empty strings for fixnum and float columns are
-
# turned into +nil+.
-
1
def write_attribute(attr_name, value)
-
172
write_attribute_with_type_cast(attr_name, value, true)
-
end
-
-
1
def raw_write_attribute(attr_name, value)
-
write_attribute_with_type_cast(attr_name, value, false)
-
end
-
-
1
private
-
# Handle *= for method_missing.
-
1
def attribute=(attribute_name, value)
-
write_attribute(attribute_name, value)
-
end
-
-
1
def write_attribute_with_type_cast(attr_name, value, should_type_cast)
-
172
attr_name = attr_name.to_s
-
172
attr_name = self.class.primary_key if attr_name == 'id' && self.class.primary_key
-
-
172
if should_type_cast
-
172
@attributes.write_from_user(attr_name, value)
-
else
-
@attributes.write_cast_value(attr_name, value)
-
end
-
-
172
value
-
end
-
end
-
end
-
end
-
1
require 'active_record/attribute_set/builder'
-
-
1
module ActiveRecord
-
1
class AttributeSet # :nodoc:
-
1
def initialize(attributes)
-
58
@attributes = attributes
-
end
-
-
1
def [](name)
-
2673
attributes[name] || Attribute.null(name)
-
end
-
-
1
def values_before_type_cast
-
attributes.transform_values(&:value_before_type_cast)
-
end
-
-
1
def to_hash
-
initialized_attributes.transform_values(&:value)
-
end
-
1
alias_method :to_h, :to_hash
-
-
1
def key?(name)
-
107
attributes.key?(name) && self[name].initialized?
-
end
-
-
1
def keys
-
29
attributes.initialized_keys
-
end
-
-
1
def fetch_value(name)
-
1035
self[name].value { |n| yield n if block_given? }
-
end
-
-
1
def write_from_database(name, value)
-
attributes[name] = self[name].with_value_from_database(value)
-
end
-
-
1
def write_from_user(name, value)
-
172
attributes[name] = self[name].with_value_from_user(value)
-
end
-
-
1
def write_cast_value(name, value)
-
attributes[name] = self[name].with_cast_value(value)
-
end
-
-
1
def freeze
-
3
@attributes.freeze
-
3
super
-
end
-
-
1
def initialize_dup(_)
-
29
@attributes = attributes.dup
-
29
super
-
end
-
-
1
def initialize_clone(_)
-
3
@attributes = attributes.clone
-
3
super
-
end
-
-
1
def reset(key)
-
if key?(key)
-
write_from_database(key, nil)
-
end
-
end
-
-
1
def ==(other)
-
attributes == other.attributes
-
end
-
-
1
protected
-
-
1
attr_reader :attributes
-
-
1
private
-
-
1
def initialized_attributes
-
attributes.select { |_, attr| attr.initialized? }
-
end
-
end
-
end
-
1
require 'active_record/attribute'
-
-
1
module ActiveRecord
-
1
class AttributeSet # :nodoc:
-
1
class Builder # :nodoc:
-
1
attr_reader :types, :always_initialized
-
-
1
def initialize(types, always_initialized = nil)
-
5
@types = types
-
5
@always_initialized = always_initialized
-
end
-
-
1
def build_from_database(values = {}, additional_types = {})
-
58
if always_initialized && !values.key?(always_initialized)
-
values[always_initialized] = nil
-
end
-
-
58
attributes = LazyAttributeHash.new(types, values, additional_types)
-
58
AttributeSet.new(attributes)
-
end
-
end
-
end
-
-
1
class LazyAttributeHash # :nodoc:
-
1
delegate :transform_values, to: :materialize
-
-
1
def initialize(types, values, additional_types)
-
58
@types = types
-
58
@values = values
-
58
@additional_types = additional_types
-
58
@materialized = false
-
58
@delegate_hash = {}
-
end
-
-
1
def key?(key)
-
107
delegate_hash.key?(key) || values.key?(key) || types.key?(key)
-
end
-
-
1
def [](key)
-
2673
delegate_hash[key] || assign_default_value(key)
-
end
-
-
1
def []=(key, value)
-
172
if frozen?
-
raise RuntimeError, "Can't modify frozen hash"
-
end
-
172
delegate_hash[key] = value
-
end
-
-
1
def initialized_keys
-
29
delegate_hash.keys | values.keys
-
end
-
-
1
def initialize_dup(_)
-
29
@delegate_hash = delegate_hash.transform_values(&:dup)
-
29
super
-
end
-
-
1
def select
-
keys = types.keys | values.keys | delegate_hash.keys
-
keys.each_with_object({}) do |key, hash|
-
attribute = self[key]
-
if yield(key, attribute)
-
hash[key] = attribute
-
end
-
end
-
end
-
-
1
def ==(other)
-
if other.is_a?(LazyAttributeHash)
-
materialize == other.materialize
-
else
-
materialize == other
-
end
-
end
-
-
1
protected
-
-
1
attr_reader :types, :values, :additional_types, :delegate_hash
-
-
1
def materialize
-
unless @materialized
-
values.each_key { |key| self[key] }
-
types.each_key { |key| self[key] }
-
unless frozen?
-
@materialized = true
-
end
-
end
-
delegate_hash
-
end
-
-
1
private
-
-
1
def assign_default_value(name)
-
388
type = additional_types.fetch(name, types[name])
-
388
value_present = true
-
388
value = values.fetch(name) { value_present = false }
-
-
388
if value_present
-
388
delegate_hash[name] = Attribute.from_database(name, value, type)
-
elsif types.key?(name)
-
delegate_hash[name] = Attribute.uninitialized(name, type)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Attributes # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
Type = ActiveRecord::Type
-
-
1
included do
-
1
class_attribute :user_provided_columns, instance_accessor: false # :internal:
-
1
class_attribute :user_provided_defaults, instance_accessor: false # :internal:
-
1
self.user_provided_columns = {}
-
1
self.user_provided_defaults = {}
-
-
1
delegate :persistable_attribute_names, to: :class
-
end
-
-
1
module ClassMethods # :nodoc:
-
# Defines or overrides a attribute on this model. This allows customization of
-
# Active Record's type casting behavior, as well as adding support for user defined
-
# types.
-
#
-
# +name+ The name of the methods to define attribute methods for, and the column which
-
# this will persist to.
-
#
-
# +cast_type+ A type object that contains information about how to type cast the value.
-
# See the examples section for more information.
-
#
-
# ==== Options
-
# The options hash accepts the following options:
-
#
-
# +default+ is the default value that the column should use on a new record.
-
#
-
# ==== Examples
-
#
-
# The type detected by Active Record can be overridden.
-
#
-
# # db/schema.rb
-
# create_table :store_listings, force: true do |t|
-
# t.decimal :price_in_cents
-
# end
-
#
-
# # app/models/store_listing.rb
-
# class StoreListing < ActiveRecord::Base
-
# end
-
#
-
# store_listing = StoreListing.new(price_in_cents: '10.1')
-
#
-
# # before
-
# store_listing.price_in_cents # => BigDecimal.new(10.1)
-
#
-
# class StoreListing < ActiveRecord::Base
-
# attribute :price_in_cents, Type::Integer.new
-
# end
-
#
-
# # after
-
# store_listing.price_in_cents # => 10
-
#
-
# Users may also define their own custom types, as long as they respond to the methods
-
# defined on the value type. The `type_cast` method on your type object will be called
-
# with values both from the database, and from your controllers. See
-
# `ActiveRecord::Attributes::Type::Value` for the expected API. It is recommended that your
-
# type objects inherit from an existing type, or the base value type.
-
#
-
# class MoneyType < ActiveRecord::Type::Integer
-
# def type_cast(value)
-
# if value.include?('$')
-
# price_in_dollars = value.gsub(/\$/, '').to_f
-
# price_in_dollars * 100
-
# else
-
# value.to_i
-
# end
-
# end
-
# end
-
#
-
# class StoreListing < ActiveRecord::Base
-
# attribute :price_in_cents, MoneyType.new
-
# end
-
#
-
# store_listing = StoreListing.new(price_in_cents: '$10.00')
-
# store_listing.price_in_cents # => 1000
-
1
def attribute(name, cast_type, options = {})
-
name = name.to_s
-
clear_caches_calculated_from_columns
-
# Assign a new hash to ensure that subclasses do not share a hash
-
self.user_provided_columns = user_provided_columns.merge(name => cast_type)
-
-
if options.key?(:default)
-
self.user_provided_defaults = user_provided_defaults.merge(name => options[:default])
-
end
-
end
-
-
# Returns an array of column objects for the table associated with this class.
-
1
def columns
-
10
@columns ||= add_user_provided_columns(connection.schema_cache.columns(table_name))
-
end
-
-
# Returns a hash of column objects for the table associated with this class.
-
1
def columns_hash
-
327
@columns_hash ||= Hash[columns.map { |c| [c.name, c] }]
-
end
-
-
1
def persistable_attribute_names # :nodoc:
-
29
@persistable_attribute_names ||= connection.schema_cache.columns_hash(table_name).keys
-
end
-
-
1
def reset_column_information # :nodoc:
-
super
-
clear_caches_calculated_from_columns
-
end
-
-
1
private
-
-
1
def add_user_provided_columns(schema_columns)
-
5
existing_columns = schema_columns.map do |column|
-
28
new_type = user_provided_columns[column.name]
-
28
if new_type
-
column.with_type(new_type)
-
else
-
28
column
-
end
-
end
-
-
5
existing_column_names = existing_columns.map(&:name)
-
5
new_columns = user_provided_columns.except(*existing_column_names).map do |(name, type)|
-
connection.new_column(name, nil, type)
-
end
-
-
5
existing_columns + new_columns
-
end
-
-
1
def clear_caches_calculated_from_columns
-
15
@attributes_builder = nil
-
15
@column_names = nil
-
15
@column_types = nil
-
15
@columns = nil
-
15
@columns_hash = nil
-
15
@content_columns = nil
-
15
@default_attributes = nil
-
15
@persistable_attribute_names = nil
-
end
-
-
1
def raw_default_values
-
4
super.merge(user_provided_defaults)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Autosave Association
-
#
-
# +AutosaveAssociation+ is a module that takes care of automatically saving
-
# associated records when their parent is saved. In addition to saving, it
-
# also destroys any associated records that were marked for destruction.
-
# (See +mark_for_destruction+ and <tt>marked_for_destruction?</tt>).
-
#
-
# Saving of the parent, its associations, and the destruction of marked
-
# associations, all happen inside a transaction. This should never leave the
-
# database in an inconsistent state.
-
#
-
# If validations for any of the associations fail, their error messages will
-
# be applied to the parent.
-
#
-
# Note that it also means that associations marked for destruction won't
-
# be destroyed directly. They will however still be marked for destruction.
-
#
-
# Note that <tt>autosave: false</tt> is not same as not declaring <tt>:autosave</tt>.
-
# When the <tt>:autosave</tt> option is not present then new association records are
-
# saved but the updated association records are not saved.
-
#
-
# == Validation
-
#
-
# Children records are validated unless <tt>:validate</tt> is +false+.
-
#
-
# == Callbacks
-
#
-
# Association with autosave option defines several callbacks on your
-
# model (before_save, after_create, after_update). Please note that
-
# callbacks are executed in the order they were defined in
-
# model. You should avoid modifying the association content, before
-
# autosave callbacks are executed. Placing your callbacks after
-
# associations is usually a good practice.
-
#
-
# === One-to-one Example
-
#
-
# class Post < ActiveRecord::Base
-
# has_one :author, autosave: true
-
# end
-
#
-
# Saving changes to the parent and its associated model can now be performed
-
# automatically _and_ atomically:
-
#
-
# post = Post.find(1)
-
# post.title # => "The current global position of migrating ducks"
-
# post.author.name # => "alloy"
-
#
-
# post.title = "On the migration of ducks"
-
# post.author.name = "Eloy Duran"
-
#
-
# post.save
-
# post.reload
-
# post.title # => "On the migration of ducks"
-
# post.author.name # => "Eloy Duran"
-
#
-
# Destroying an associated model, as part of the parent's save action, is as
-
# simple as marking it for destruction:
-
#
-
# post.author.mark_for_destruction
-
# post.author.marked_for_destruction? # => true
-
#
-
# Note that the model is _not_ yet removed from the database:
-
#
-
# id = post.author.id
-
# Author.find_by(id: id).nil? # => false
-
#
-
# post.save
-
# post.reload.author # => nil
-
#
-
# Now it _is_ removed from the database:
-
#
-
# Author.find_by(id: id).nil? # => true
-
#
-
# === One-to-many Example
-
#
-
# When <tt>:autosave</tt> is not declared new children are saved when their parent is saved:
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments # :autosave option is not declared
-
# end
-
#
-
# post = Post.new(title: 'ruby rocks')
-
# post.comments.build(body: 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# post = Post.create(title: 'ruby rocks')
-
# post.comments.build(body: 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# post = Post.create(title: 'ruby rocks')
-
# post.comments.create(body: 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# When <tt>:autosave</tt> is true all children are saved, no matter whether they
-
# are new records or not:
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments, autosave: true
-
# end
-
#
-
# post = Post.create(title: 'ruby rocks')
-
# post.comments.create(body: 'hello world')
-
# post.comments[0].body = 'hi everyone'
-
# post.comments.build(body: "good morning.")
-
# post.title += "!"
-
# post.save # => saves both post and comments.
-
#
-
# Destroying one of the associated models as part of the parent's save action
-
# is as simple as marking it for destruction:
-
#
-
# post.comments # => [#<Comment id: 1, ...>, #<Comment id: 2, ...]>
-
# post.comments[1].mark_for_destruction
-
# post.comments[1].marked_for_destruction? # => true
-
# post.comments.length # => 2
-
#
-
# Note that the model is _not_ yet removed from the database:
-
#
-
# id = post.comments.last.id
-
# Comment.find_by(id: id).nil? # => false
-
#
-
# post.save
-
# post.reload.comments.length # => 1
-
#
-
# Now it _is_ removed from the database:
-
#
-
# Comment.find_by(id: id).nil? # => true
-
-
1
module AutosaveAssociation
-
1
extend ActiveSupport::Concern
-
-
1
module AssociationBuilderExtension #:nodoc:
-
1
def self.build(model, reflection)
-
4
model.send(:add_autosave_association_callbacks, reflection)
-
end
-
-
1
def self.valid_options
-
4
[ :autosave ]
-
end
-
end
-
-
1
included do
-
1
Associations::Builder::Association.extensions << AssociationBuilderExtension
-
end
-
-
1
module ClassMethods
-
1
private
-
-
1
def define_non_cyclic_method(name, &block)
-
5
return if method_defined?(name)
-
4
define_method(name) do |*args|
-
35
result = true; @_already_called ||= {}
-
# Loop prevention for validation of associations
-
35
unless @_already_called[name]
-
35
begin
-
35
@_already_called[name]=true
-
35
result = instance_eval(&block)
-
ensure
-
35
@_already_called[name]=false
-
end
-
end
-
-
35
result
-
end
-
end
-
-
# Adds validation and save callbacks for the association as specified by
-
# the +reflection+.
-
#
-
# For performance reasons, we don't check whether to validate at runtime.
-
# However the validation and callback methods are lazy and those methods
-
# get created when they are invoked for the very first time. However,
-
# this can change, for instance, when using nested attributes, which is
-
# called _after_ the association has been defined. Since we don't want
-
# the callbacks to get defined multiple times, there are guards that
-
# check if the save or validation methods have already been defined
-
# before actually defining them.
-
1
def add_autosave_association_callbacks(reflection)
-
4
save_method = :"autosave_associated_records_for_#{reflection.name}"
-
-
4
if reflection.collection?
-
1
before_save :before_save_collection_association
-
-
15
define_non_cyclic_method(save_method) { save_collection_association(reflection) }
-
# Doesn't use after_save as that would save associations added in after_create/after_update twice
-
1
after_create save_method
-
1
after_update save_method
-
elsif reflection.has_one?
-
define_method(save_method) { save_has_one_association(reflection) } unless method_defined?(save_method)
-
# Configures two callbacks instead of a single after_save so that
-
# the model may rely on their execution order relative to its
-
# own callbacks.
-
#
-
# For example, given that after_creates run before after_saves, if
-
# we configured instead an after_save there would be no way to fire
-
# a custom after_create callback after the child association gets
-
# created.
-
after_create save_method
-
after_update save_method
-
else
-
17
define_non_cyclic_method(save_method) { save_belongs_to_association(reflection) }
-
3
before_save save_method
-
end
-
-
4
define_autosave_validation_callbacks(reflection)
-
end
-
-
1
def define_autosave_validation_callbacks(reflection)
-
4
validation_method = :"validate_associated_records_for_#{reflection.name}"
-
4
if reflection.validate? && !method_defined?(validation_method)
-
1
if reflection.collection?
-
1
method = :validate_collection_association
-
else
-
method = :validate_single_association
-
end
-
-
8
define_non_cyclic_method(validation_method) { send(method, reflection) }
-
1
validate validation_method
-
end
-
end
-
end
-
-
# Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag.
-
1
def reload(options = nil)
-
@marked_for_destruction = false
-
@destroyed_by_association = nil
-
super
-
end
-
-
# Marks this record to be destroyed as part of the parents save transaction.
-
# This does _not_ actually destroy the record instantly, rather child record will be destroyed
-
# when <tt>parent.save</tt> is called.
-
#
-
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
-
1
def mark_for_destruction
-
@marked_for_destruction = true
-
end
-
-
# Returns whether or not this record will be destroyed as part of the parents save transaction.
-
#
-
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
-
1
def marked_for_destruction?
-
@marked_for_destruction
-
end
-
-
# Records the association that is being destroyed and destroying this
-
# record in the process.
-
1
def destroyed_by_association=(reflection)
-
@destroyed_by_association = reflection
-
end
-
-
# Returns the association for the parent being destroyed.
-
#
-
# Used to avoid updating the counter cache unnecessarily.
-
1
def destroyed_by_association
-
@destroyed_by_association
-
end
-
-
# Returns whether or not this record has been changed in any way (including whether
-
# any of its nested autosave associations are likewise changed)
-
1
def changed_for_autosave?
-
new_record? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
-
end
-
-
1
private
-
-
# Returns the record for an association collection that should be validated
-
# or saved. If +autosave+ is +false+ only new records will be returned,
-
# unless the parent is/was a new record itself.
-
1
def associated_records_to_validate_or_save(association, new_record, autosave)
-
if new_record
-
association && association.target
-
elsif autosave
-
association.target.find_all { |record| record.changed_for_autosave? }
-
else
-
association.target.find_all { |record| record.new_record? }
-
end
-
end
-
-
# go through nested autosave associations that are loaded in memory (without loading
-
# any new ones), and return true if is changed for autosave
-
1
def nested_records_changed_for_autosave?
-
@_nested_records_changed_for_autosave_already_called ||= false
-
return false if @_nested_records_changed_for_autosave_already_called
-
begin
-
@_nested_records_changed_for_autosave_already_called = true
-
self.class._reflections.values.any? do |reflection|
-
if reflection.options[:autosave]
-
association = association_instance_get(reflection.name)
-
association && Array.wrap(association.target).any?(&:changed_for_autosave?)
-
end
-
end
-
ensure
-
@_nested_records_changed_for_autosave_already_called = false
-
end
-
end
-
-
# Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is
-
# turned on for the association.
-
1
def validate_single_association(reflection)
-
association = association_instance_get(reflection.name)
-
record = association && association.reader
-
association_valid?(reflection, record) if record
-
end
-
-
# Validate the associated records if <tt>:validate</tt> or
-
# <tt>:autosave</tt> is turned on for the association specified by
-
# +reflection+.
-
1
def validate_collection_association(reflection)
-
7
if association = association_instance_get(reflection.name)
-
if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave])
-
records.each { |record| association_valid?(reflection, record) }
-
end
-
end
-
end
-
-
# Returns whether or not the association is valid and applies any errors to
-
# the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt>
-
# enabled records if they're marked_for_destruction? or destroyed.
-
1
def association_valid?(reflection, record)
-
return true if record.destroyed? || (reflection.options[:autosave] && record.marked_for_destruction?)
-
-
validation_context = self.validation_context unless [:create, :update].include?(self.validation_context)
-
unless valid = record.valid?(validation_context)
-
if reflection.options[:autosave]
-
record.errors.each do |attribute, message|
-
attribute = "#{reflection.name}.#{attribute}"
-
errors[attribute] << message
-
errors[attribute].uniq!
-
end
-
else
-
errors.add(reflection.name)
-
end
-
end
-
valid
-
end
-
-
# Is used as a before_save callback to check while saving a collection
-
# association whether or not the parent was a new record before saving.
-
1
def before_save_collection_association
-
7
@new_record_before_save = new_record?
-
7
true
-
end
-
-
# Saves any new associated records, or all loaded autosave associations if
-
# <tt>:autosave</tt> is enabled on the association.
-
#
-
# In addition, it destroys all children that were marked for destruction
-
# with mark_for_destruction.
-
#
-
# This all happens inside a transaction, _if_ the Transactions module is included into
-
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
-
1
def save_collection_association(reflection)
-
14
if association = association_instance_get(reflection.name)
-
autosave = reflection.options[:autosave]
-
-
if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
-
if autosave
-
records_to_destroy = records.select(&:marked_for_destruction?)
-
records_to_destroy.each { |record| association.destroy(record) }
-
records -= records_to_destroy
-
end
-
-
records.each do |record|
-
next if record.destroyed?
-
-
saved = true
-
-
if autosave != false && (@new_record_before_save || record.new_record?)
-
if autosave
-
saved = association.insert_record(record, false)
-
else
-
association.insert_record(record) unless reflection.nested?
-
end
-
elsif autosave
-
saved = record.save(:validate => false)
-
end
-
-
raise ActiveRecord::Rollback unless saved
-
end
-
end
-
-
# reconstruct the scope now that we know the owner's id
-
association.reset_scope if association.respond_to?(:reset_scope)
-
end
-
end
-
-
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled
-
# on the association.
-
#
-
# In addition, it will destroy the association if it was marked for
-
# destruction with mark_for_destruction.
-
#
-
# This all happens inside a transaction, _if_ the Transactions module is included into
-
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
-
1
def save_has_one_association(reflection)
-
association = association_instance_get(reflection.name)
-
record = association && association.load_target
-
-
if record && !record.destroyed?
-
autosave = reflection.options[:autosave]
-
-
if autosave && record.marked_for_destruction?
-
record.destroy
-
elsif autosave != false
-
key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
-
-
if (autosave && record.changed_for_autosave?) || new_record? || record_changed?(reflection, record, key)
-
unless reflection.through_reflection
-
record[reflection.foreign_key] = key
-
end
-
-
saved = record.save(:validate => !autosave)
-
raise ActiveRecord::Rollback if !saved && autosave
-
saved
-
end
-
end
-
end
-
end
-
-
# If the record is new or it has changed, returns true.
-
1
def record_changed?(reflection, record, key)
-
record.new_record? ||
-
(record.has_attribute?(reflection.foreign_key) && record[reflection.foreign_key] != key) ||
-
record.attribute_changed?(reflection.foreign_key)
-
end
-
-
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled.
-
#
-
# In addition, it will destroy the association if it was marked for destruction.
-
1
def save_belongs_to_association(reflection)
-
14
association = association_instance_get(reflection.name)
-
14
record = association && association.load_target
-
14
if record && !record.destroyed?
-
autosave = reflection.options[:autosave]
-
-
if autosave && record.marked_for_destruction?
-
self[reflection.foreign_key] = nil
-
record.destroy
-
elsif autosave != false
-
saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
-
-
if association.updated?
-
association_id = record.send(reflection.options[:primary_key] || :id)
-
self[reflection.foreign_key] = association_id
-
association.loaded!
-
end
-
-
saved if autosave
-
end
-
end
-
end
-
end
-
end
-
1
require 'yaml'
-
1
require 'set'
-
1
require 'active_support/benchmarkable'
-
1
require 'active_support/dependencies'
-
1
require 'active_support/descendants_tracker'
-
1
require 'active_support/time'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/class/delegating_attributes'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/hash/deep_merge'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/hash/transform_values'
-
1
require 'active_support/core_ext/string/behavior'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'active_support/core_ext/class/subclasses'
-
1
require 'arel'
-
1
require 'active_record/attribute_decorators'
-
1
require 'active_record/errors'
-
1
require 'active_record/log_subscriber'
-
1
require 'active_record/explain_subscriber'
-
1
require 'active_record/relation/delegation'
-
1
require 'active_record/attributes'
-
-
1
module ActiveRecord #:nodoc:
-
# = Active Record
-
#
-
# Active Record objects don't specify their attributes directly, but rather infer them from
-
# the table definition with which they're linked. Adding, removing, and changing attributes
-
# and their type is done directly in the database. Any change is instantly reflected in the
-
# Active Record objects. The mapping that binds a given Active Record class to a certain
-
# database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
-
#
-
# See the mapping rules in table_name and the full example in link:files/activerecord/README_rdoc.html for more insight.
-
#
-
# == Creation
-
#
-
# Active Records accept constructor parameters either in a hash or as a block. The hash
-
# method is especially useful when you're receiving the data from somewhere else, like an
-
# HTTP request. It works like this:
-
#
-
# user = User.new(name: "David", occupation: "Code Artist")
-
# user.name # => "David"
-
#
-
# You can also use block initialization:
-
#
-
# user = User.new do |u|
-
# u.name = "David"
-
# u.occupation = "Code Artist"
-
# end
-
#
-
# And of course you can just create a bare object and specify the attributes after the fact:
-
#
-
# user = User.new
-
# user.name = "David"
-
# user.occupation = "Code Artist"
-
#
-
# == Conditions
-
#
-
# Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
-
# The array form is to be used when the condition input is tainted and requires sanitization. The string form can
-
# be used for statements that don't involve tainted data. The hash form works much like the array form, except
-
# only equality and range is possible. Examples:
-
#
-
# class User < ActiveRecord::Base
-
# def self.authenticate_unsafely(user_name, password)
-
# where("user_name = '#{user_name}' AND password = '#{password}'").first
-
# end
-
#
-
# def self.authenticate_safely(user_name, password)
-
# where("user_name = ? AND password = ?", user_name, password).first
-
# end
-
#
-
# def self.authenticate_safely_simply(user_name, password)
-
# where(user_name: user_name, password: password).first
-
# end
-
# end
-
#
-
# The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
-
# and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
-
# parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
-
# <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
-
# before inserting them in the query, which will ensure that an attacker can't escape the
-
# query and fake the login (or worse).
-
#
-
# When using multiple parameters in the conditions, it can easily become hard to read exactly
-
# what the fourth or fifth question mark is supposed to represent. In those cases, you can
-
# resort to named bind variables instead. That's done by replacing the question marks with
-
# symbols and supplying a hash with values for the matching symbol keys:
-
#
-
# Company.where(
-
# "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
-
# { id: 3, name: "37signals", division: "First", accounting_date: '2005-01-01' }
-
# ).first
-
#
-
# Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
-
# operator. For instance:
-
#
-
# Student.where(first_name: "Harvey", status: 1)
-
# Student.where(params[:student])
-
#
-
# A range may be used in the hash to use the SQL BETWEEN operator:
-
#
-
# Student.where(grade: 9..12)
-
#
-
# An array may be used in the hash to use the SQL IN operator:
-
#
-
# Student.where(grade: [9,11,12])
-
#
-
# When joining tables, nested hashes or keys written in the form 'table_name.column_name'
-
# can be used to qualify the table name of a particular condition. For instance:
-
#
-
# Student.joins(:schools).where(schools: { category: 'public' })
-
# Student.joins(:schools).where('schools.category' => 'public' )
-
#
-
# == Overwriting default accessors
-
#
-
# All column values are automatically available through basic accessors on the Active Record
-
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
-
# the default accessors (using the same name as the attribute) and calling
-
# +super+ to actually change things.
-
#
-
# class Song < ActiveRecord::Base
-
# # Uses an integer of seconds to hold the length of the song
-
#
-
# def length=(minutes)
-
# super(minutes.to_i * 60)
-
# end
-
#
-
# def length
-
# super / 60
-
# end
-
# end
-
#
-
# You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
-
# or <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
-
#
-
# == Attribute query methods
-
#
-
# In addition to the basic accessors, query methods are also automatically available on the Active Record object.
-
# Query methods allow you to test whether an attribute value is present.
-
# For numeric values, present is defined as non-zero.
-
#
-
# For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
-
# to determine whether the user has a name:
-
#
-
# user = User.new(name: "David")
-
# user.name? # => true
-
#
-
# anonymous = User.new(name: "")
-
# anonymous.name? # => false
-
#
-
# == Accessing attributes before they have been typecasted
-
#
-
# Sometimes you want to be able to read the raw attribute data without having the column-determined
-
# typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
-
# accessors that all attributes have. For example, if your Account model has a <tt>balance</tt> attribute,
-
# you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
-
#
-
# This is especially useful in validation situations where the user might supply a string for an
-
# integer field and you want to display the original string back in an error message. Accessing the
-
# attribute normally would typecast the string to 0, which isn't what you want.
-
#
-
# == Dynamic attribute-based finders
-
#
-
# Dynamic attribute-based finders are a mildly deprecated way of getting (and/or creating) objects
-
# by simple queries without turning to SQL. They work by appending the name of an attribute
-
# to <tt>find_by_</tt> like <tt>Person.find_by_user_name</tt>.
-
# Instead of writing <tt>Person.find_by(user_name: user_name)</tt>, you can use
-
# <tt>Person.find_by_user_name(user_name)</tt>.
-
#
-
# It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
-
# <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records,
-
# like <tt>Person.find_by_last_name!</tt>.
-
#
-
# It's also possible to use multiple attributes in the same find by separating them with "_and_".
-
#
-
# Person.find_by(user_name: user_name, password: password)
-
# Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
-
#
-
# It's even possible to call these dynamic finder methods on relations and named scopes.
-
#
-
# Payment.order("created_on").find_by_amount(50)
-
#
-
# == Saving arrays, hashes, and other non-mappable objects in text columns
-
#
-
# Active Record can serialize any object in text columns using YAML. To do so, you must
-
# specify this with a call to the class method +serialize+.
-
# This makes it possible to store arrays, hashes, and other non-mappable objects without doing
-
# any additional work.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences
-
# end
-
#
-
# user = User.create(preferences: { "background" => "black", "display" => large })
-
# User.find(user.id).preferences # => { "background" => "black", "display" => large }
-
#
-
# You can also specify a class option as the second parameter that'll raise an exception
-
# if a serialized object is retrieved as a descendant of a class not in the hierarchy.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences, Hash
-
# end
-
#
-
# user = User.create(preferences: %w( one two three ))
-
# User.find(user.id).preferences # raises SerializationTypeMismatch
-
#
-
# When you specify a class option, the default value for that attribute will be a new
-
# instance of that class.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences, OpenStruct
-
# end
-
#
-
# user = User.new
-
# user.preferences.theme_color = "red"
-
#
-
#
-
# == Single table inheritance
-
#
-
# Active Record allows inheritance by storing the name of the class in a
-
# column that is named "type" by default. See ActiveRecord::Inheritance for
-
# more details.
-
#
-
# == Connection to multiple databases in different models
-
#
-
# Connections are usually created through ActiveRecord::Base.establish_connection and retrieved
-
# by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this
-
# connection. But you can also set a class-specific connection. For example, if Course is an
-
# ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
-
# and Course and all of its subclasses will use this connection instead.
-
#
-
# This feature is implemented by keeping a connection pool in ActiveRecord::Base that is
-
# a Hash indexed by the class. If a connection is requested, the retrieve_connection method
-
# will go up the class-hierarchy until a connection is found in the connection pool.
-
#
-
# == Exceptions
-
#
-
# * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
-
# * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
-
# <tt>:adapter</tt> key.
-
# * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a
-
# non-existent adapter
-
# (or a bad spelling of an existing one).
-
# * AssociationTypeMismatch - The object assigned to the association wasn't of the type
-
# specified in the association definition.
-
# * AttributeAssignmentError - An error occurred while doing a mass assignment through the
-
# <tt>attributes=</tt> method.
-
# You can inspect the +attribute+ property of the exception object to determine which attribute
-
# triggered the error.
-
# * ConnectionNotEstablished - No connection has been established. Use <tt>establish_connection</tt>
-
# before querying.
-
# * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
-
# <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of
-
# AttributeAssignmentError
-
# objects that should be inspected to determine which attributes triggered the errors.
-
# * RecordInvalid - raised by save! and create! when the record is invalid.
-
# * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
-
# or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
-
# nothing was found, please check its documentation for further details.
-
# * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
-
# * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
-
#
-
# *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
-
# So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
-
# instances in the current object space.
-
1
class Base
-
1
extend ActiveModel::Naming
-
-
1
extend ActiveSupport::Benchmarkable
-
1
extend ActiveSupport::DescendantsTracker
-
-
1
extend ConnectionHandling
-
1
extend QueryCache::ClassMethods
-
1
extend Querying
-
1
extend Translation
-
1
extend DynamicMatchers
-
1
extend Explain
-
1
extend Enum
-
1
extend Delegation::DelegateCache
-
-
1
include Core
-
1
include Persistence
-
1
include ReadonlyAttributes
-
1
include ModelSchema
-
1
include Inheritance
-
1
include Scoping
-
1
include Sanitization
-
1
include AttributeAssignment
-
1
include ActiveModel::Conversion
-
1
include Integration
-
1
include Validations
-
1
include CounterCache
-
1
include Attributes
-
1
include AttributeDecorators
-
1
include Locking::Optimistic
-
1
include Locking::Pessimistic
-
1
include AttributeMethods
-
1
include Callbacks
-
1
include Timestamp
-
1
include Associations
-
1
include ActiveModel::SecurePassword
-
1
include AutosaveAssociation
-
1
include NestedAttributes
-
1
include Aggregations
-
1
include Transactions
-
1
include NoTouching
-
1
include Reflection
-
1
include Serialization
-
1
include Store
-
end
-
-
1
ActiveSupport.run_load_hooks(:active_record, Base)
-
end
-
1
module ActiveRecord
-
# = Active Record Callbacks
-
#
-
# Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic
-
# before or after an alteration of the object state. This can be used to make sure that associated and
-
# dependent objects are deleted when +destroy+ is called (by overwriting +before_destroy+) or to massage attributes
-
# before they're validated (by overwriting +before_validation+). As an example of the callbacks initiated, consider
-
# the <tt>Base#save</tt> call for a new record:
-
#
-
# * (-) <tt>save</tt>
-
# * (-) <tt>valid</tt>
-
# * (1) <tt>before_validation</tt>
-
# * (-) <tt>validate</tt>
-
# * (2) <tt>after_validation</tt>
-
# * (3) <tt>before_save</tt>
-
# * (4) <tt>before_create</tt>
-
# * (-) <tt>create</tt>
-
# * (5) <tt>after_create</tt>
-
# * (6) <tt>after_save</tt>
-
# * (7) <tt>after_commit</tt>
-
#
-
# Also, an <tt>after_rollback</tt> callback can be configured to be triggered whenever a rollback is issued.
-
# Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
-
# <tt>after_rollback</tt>.
-
#
-
# Additionally, an <tt>after_touch</tt> callback is triggered whenever an
-
# object is touched.
-
#
-
# Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that
-
# is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects
-
# are instantiated as well.
-
#
-
# There are nineteen callbacks in total, which give you immense power to react and prepare for each state in the
-
# Active Record life cycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
-
# except that each <tt>_create</tt> callback is replaced by the corresponding <tt>_update</tt> callback.
-
#
-
# Examples:
-
# class CreditCard < ActiveRecord::Base
-
# # Strip everything but digits, so the user can specify "555 234 34" or
-
# # "5552-3434" and both will mean "55523434"
-
# before_validation(on: :create) do
-
# self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number")
-
# end
-
# end
-
#
-
# class Subscription < ActiveRecord::Base
-
# before_create :record_signup
-
#
-
# private
-
# def record_signup
-
# self.signed_up_on = Date.today
-
# end
-
# end
-
#
-
# class Firm < ActiveRecord::Base
-
# # Destroys the associated clients and people when the firm is destroyed
-
# before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
-
# before_destroy { |record| Client.destroy_all "client_of = #{record.id}" }
-
# end
-
#
-
# == Inheritable callback queues
-
#
-
# Besides the overwritable callback methods, it's also possible to register callbacks through the
-
# use of the callback macros. Their main advantage is that the macros add behavior into a callback
-
# queue that is kept intact down through an inheritance hierarchy.
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy :destroy_author
-
# end
-
#
-
# class Reply < Topic
-
# before_destroy :destroy_readers
-
# end
-
#
-
# Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is
-
# run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the following situation
-
# where the +before_destroy+ method is overridden:
-
#
-
# class Topic < ActiveRecord::Base
-
# def before_destroy() destroy_author end
-
# end
-
#
-
# class Reply < Topic
-
# def before_destroy() destroy_readers end
-
# end
-
#
-
# In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+.
-
# So, use the callback macros when you want to ensure that a certain callback is called for the entire
-
# hierarchy, and use the regular overwritable methods when you want to leave it up to each descendant
-
# to decide whether they want to call +super+ and trigger the inherited callbacks.
-
#
-
# *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the
-
# callbacks before specifying the associations. Otherwise, you might trigger the loading of a
-
# child before the parent has registered the callbacks and they won't be inherited.
-
#
-
# == Types of callbacks
-
#
-
# There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
-
# inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects
-
# are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for
-
# creating mix-ins), and inline eval methods are deprecated.
-
#
-
# The method reference callbacks work by specifying a protected or private method available in the object, like this:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy :delete_parents
-
#
-
# private
-
# def delete_parents
-
# self.class.delete_all "parent_id = #{id}"
-
# end
-
# end
-
#
-
# The callback objects have methods named after the callback called with the record as the only parameter, such as:
-
#
-
# class BankAccount < ActiveRecord::Base
-
# before_save EncryptionWrapper.new
-
# after_save EncryptionWrapper.new
-
# after_initialize EncryptionWrapper.new
-
# end
-
#
-
# class EncryptionWrapper
-
# def before_save(record)
-
# record.credit_card_number = encrypt(record.credit_card_number)
-
# end
-
#
-
# def after_save(record)
-
# record.credit_card_number = decrypt(record.credit_card_number)
-
# end
-
#
-
# alias_method :after_initialize, :after_save
-
#
-
# private
-
# def encrypt(value)
-
# # Secrecy is committed
-
# end
-
#
-
# def decrypt(value)
-
# # Secrecy is unveiled
-
# end
-
# end
-
#
-
# So you specify the object you want messaged on a given callback. When that callback is triggered, the object has
-
# a method by the name of the callback messaged. You can make these callbacks more flexible by passing in other
-
# initialization data such as the name of the attribute to work with:
-
#
-
# class BankAccount < ActiveRecord::Base
-
# before_save EncryptionWrapper.new("credit_card_number")
-
# after_save EncryptionWrapper.new("credit_card_number")
-
# after_initialize EncryptionWrapper.new("credit_card_number")
-
# end
-
#
-
# class EncryptionWrapper
-
# def initialize(attribute)
-
# @attribute = attribute
-
# end
-
#
-
# def before_save(record)
-
# record.send("#{@attribute}=", encrypt(record.send("#{@attribute}")))
-
# end
-
#
-
# def after_save(record)
-
# record.send("#{@attribute}=", decrypt(record.send("#{@attribute}")))
-
# end
-
#
-
# alias_method :after_initialize, :after_save
-
#
-
# private
-
# def encrypt(value)
-
# # Secrecy is committed
-
# end
-
#
-
# def decrypt(value)
-
# # Secrecy is unveiled
-
# end
-
# end
-
#
-
# The callback macros usually accept a symbol for the method they're supposed to run, but you can also
-
# pass a "method string", which will then be evaluated within the binding of the callback. Example:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy 'self.class.delete_all "parent_id = #{id}"'
-
# end
-
#
-
# Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
-
# is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy 'self.class.delete_all "parent_id = #{id}"',
-
# 'puts "Evaluated after parents are destroyed"'
-
# end
-
#
-
# == <tt>before_validation*</tt> returning statements
-
#
-
# If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
-
# aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
-
# ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.
-
#
-
# == Canceling callbacks
-
#
-
# If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are
-
# cancelled.
-
# Callbacks are generally run in the order they are defined, with the exception of callbacks defined as
-
# methods on the model, which are called last.
-
#
-
# == Ordering callbacks
-
#
-
# Sometimes the code needs that the callbacks execute in a specific order. For example, a +before_destroy+
-
# callback (+log_children+ in this case) should be executed before the children get destroyed by the +dependent: destroy+ option.
-
#
-
# Let's look at the code below:
-
#
-
# class Topic < ActiveRecord::Base
-
# has_many :children, dependent: destroy
-
#
-
# before_destroy :log_children
-
#
-
# private
-
# def log_children
-
# # Child processing
-
# end
-
# end
-
#
-
# In this case, the problem is that when the +before_destroy+ callback is executed, the children are not available
-
# because the +destroy+ callback gets executed first. You can use the +prepend+ option on the +before_destroy+ callback to avoid this.
-
#
-
# class Topic < ActiveRecord::Base
-
# has_many :children, dependent: destroy
-
#
-
# before_destroy :log_children, prepend: true
-
#
-
# private
-
# def log_children
-
# # Child processing
-
# end
-
# end
-
#
-
# This way, the +before_destroy+ gets executed before the <tt>dependent: destroy</tt> is called, and the data is still available.
-
#
-
# == Transactions
-
#
-
# The entire callback chain of a +save+, <tt>save!</tt>, or +destroy+ call runs
-
# within a transaction. That includes <tt>after_*</tt> hooks. If everything
-
# goes fine a COMMIT is executed once the chain has been completed.
-
#
-
# If a <tt>before_*</tt> callback cancels the action a ROLLBACK is issued. You
-
# can also trigger a ROLLBACK raising an exception in any of the callbacks,
-
# including <tt>after_*</tt> hooks. Note, however, that in that case the client
-
# needs to be aware of it because an ordinary +save+ will raise such exception
-
# instead of quietly returning +false+.
-
#
-
# == Debugging callbacks
-
#
-
# The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support
-
# <tt>:before</tt>, <tt>:after</tt> and <tt>:around</tt> as values for the <tt>kind</tt> property. The <tt>kind</tt> property
-
# defines what part of the chain the callback runs in.
-
#
-
# To find all callbacks in the before_save callback chain:
-
#
-
# Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }
-
#
-
# Returns an array of callback objects that form the before_save chain.
-
#
-
# To further check if the before_save chain contains a proc defined as <tt>rest_when_dead</tt> use the <tt>filter</tt> property of the callback object:
-
#
-
# Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }.collect(&:filter).include?(:rest_when_dead)
-
#
-
# Returns true or false depending on whether the proc is contained in the before_save callback chain on a Topic model.
-
#
-
1
module Callbacks
-
1
extend ActiveSupport::Concern
-
-
1
CALLBACKS = [
-
:after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
-
:before_save, :around_save, :after_save, :before_create, :around_create,
-
:after_create, :before_update, :around_update, :after_update,
-
:before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
-
]
-
-
1
module ClassMethods
-
1
include ActiveModel::Callbacks
-
end
-
-
1
included do
-
1
include ActiveModel::Validations::Callbacks
-
-
1
define_model_callbacks :initialize, :find, :touch, :only => :after
-
1
define_model_callbacks :save, :create, :update, :destroy
-
end
-
-
1
def destroy #:nodoc:
-
6
_run_destroy_callbacks { super }
-
end
-
-
1
def touch(*) #:nodoc:
-
_run_touch_callbacks { super }
-
end
-
-
1
private
-
-
1
def create_or_update #:nodoc:
-
58
_run_save_callbacks { super }
-
end
-
-
1
def _create_record #:nodoc:
-
50
_run_create_callbacks { super }
-
end
-
-
1
def _update_record(*) #:nodoc:
-
8
_run_update_callbacks { super }
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'thread_safe'
-
1
require 'monitor'
-
1
require 'set'
-
1
require 'active_support/core_ext/string/filters'
-
-
1
module ActiveRecord
-
# Raised when a connection could not be obtained within the connection
-
# acquisition timeout period: because max connections in pool
-
# are in use.
-
1
class ConnectionTimeoutError < ConnectionNotEstablished
-
end
-
-
1
module ConnectionAdapters
-
# Connection pool base class for managing Active Record database
-
# connections.
-
#
-
# == Introduction
-
#
-
# A connection pool synchronizes thread access to a limited number of
-
# database connections. The basic idea is that each thread checks out a
-
# database connection from the pool, uses that connection, and checks the
-
# connection back in. ConnectionPool is completely thread-safe, and will
-
# ensure that a connection cannot be used by two threads at the same time,
-
# as long as ConnectionPool's contract is correctly followed. It will also
-
# handle cases in which there are more threads than connections: if all
-
# connections have been checked out, and a thread tries to checkout a
-
# connection anyway, then ConnectionPool will wait until some other thread
-
# has checked in a connection.
-
#
-
# == Obtaining (checking out) a connection
-
#
-
# Connections can be obtained and used from a connection pool in several
-
# ways:
-
#
-
# 1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and
-
# earlier (pre-connection-pooling). Eventually, when you're done with
-
# the connection(s) and wish it to be returned to the pool, you call
-
# ActiveRecord::Base.clear_active_connections!. This will be the
-
# default behavior for Active Record when used in conjunction with
-
# Action Pack's request handling cycle.
-
# 2. Manually check out a connection from the pool with
-
# ActiveRecord::Base.connection_pool.checkout. You are responsible for
-
# returning this connection to the pool when finished by calling
-
# ActiveRecord::Base.connection_pool.checkin(connection).
-
# 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which
-
# obtains a connection, yields it as the sole argument to the block,
-
# and returns it to the pool after the block completes.
-
#
-
# Connections in the pool are actually AbstractAdapter objects (or objects
-
# compatible with AbstractAdapter's interface).
-
#
-
# == Options
-
#
-
# There are several connection-pooling-related options that you can add to
-
# your database connection configuration:
-
#
-
# * +pool+: number indicating size of connection pool (default 5)
-
# * +checkout_timeout+: number of seconds to block and wait for a connection
-
# before giving up and raising a timeout error (default 5 seconds).
-
# * +reaping_frequency+: frequency in seconds to periodically run the
-
# Reaper, which attempts to find and recover connections from dead
-
# threads, which can occur if a programmer forgets to close a
-
# connection at the end of a thread or a thread dies unexpectedly.
-
# Regardless of this setting, the Reaper will be invoked before every
-
# blocking wait. (Default nil, which means don't schedule the Reaper).
-
1
class ConnectionPool
-
# Threadsafe, fair, FIFO queue. Meant to be used by ConnectionPool
-
# with which it shares a Monitor. But could be a generic Queue.
-
#
-
# The Queue in stdlib's 'thread' could replace this class except
-
# stdlib's doesn't support waiting with a timeout.
-
1
class Queue
-
1
def initialize(lock = Monitor.new)
-
1
@lock = lock
-
1
@cond = @lock.new_cond
-
1
@num_waiting = 0
-
1
@queue = []
-
end
-
-
# Test if any threads are currently waiting on the queue.
-
1
def any_waiting?
-
synchronize do
-
@num_waiting > 0
-
end
-
end
-
-
# Returns the number of threads currently waiting on this
-
# queue.
-
1
def num_waiting
-
synchronize do
-
@num_waiting
-
end
-
end
-
-
# Add +element+ to the queue. Never blocks.
-
1
def add(element)
-
synchronize do
-
@queue.push element
-
@cond.signal
-
end
-
end
-
-
# If +element+ is in the queue, remove and return it, or nil.
-
1
def delete(element)
-
synchronize do
-
@queue.delete(element)
-
end
-
end
-
-
# Remove all elements from the queue.
-
1
def clear
-
synchronize do
-
@queue.clear
-
end
-
end
-
-
# Remove the head of the queue.
-
#
-
# If +timeout+ is not given, remove and return the head the
-
# queue if the number of available elements is strictly
-
# greater than the number of threads currently waiting (that
-
# is, don't jump ahead in line). Otherwise, return nil.
-
#
-
# If +timeout+ is given, block if it there is no element
-
# available, waiting up to +timeout+ seconds for an element to
-
# become available.
-
#
-
# Raises:
-
# - ConnectionTimeoutError if +timeout+ is given and no element
-
# becomes available after +timeout+ seconds,
-
1
def poll(timeout = nil)
-
1
synchronize do
-
1
if timeout
-
no_wait_poll || wait_poll(timeout)
-
else
-
1
no_wait_poll
-
end
-
end
-
end
-
-
1
private
-
-
1
def synchronize(&block)
-
1
@lock.synchronize(&block)
-
end
-
-
# Test if the queue currently contains any elements.
-
1
def any?
-
!@queue.empty?
-
end
-
-
# A thread can remove an element from the queue without
-
# waiting if an only if the number of currently available
-
# connections is strictly greater than the number of waiting
-
# threads.
-
1
def can_remove_no_wait?
-
1
@queue.size > @num_waiting
-
end
-
-
# Removes and returns the head of the queue if possible, or nil.
-
1
def remove
-
@queue.shift
-
end
-
-
# Remove and return the head the queue if the number of
-
# available elements is strictly greater than the number of
-
# threads currently waiting. Otherwise, return nil.
-
1
def no_wait_poll
-
1
remove if can_remove_no_wait?
-
end
-
-
# Waits on the queue up to +timeout+ seconds, then removes and
-
# returns the head of the queue.
-
1
def wait_poll(timeout)
-
@num_waiting += 1
-
-
t0 = Time.now
-
elapsed = 0
-
loop do
-
@cond.wait(timeout - elapsed)
-
-
return remove if any?
-
-
elapsed = Time.now - t0
-
if elapsed >= timeout
-
msg = 'could not obtain a database connection within %0.3f seconds (waited %0.3f seconds)' %
-
[timeout, elapsed]
-
raise ConnectionTimeoutError, msg
-
end
-
end
-
ensure
-
@num_waiting -= 1
-
end
-
end
-
-
# Every +frequency+ seconds, the reaper will call +reap+ on +pool+.
-
# A reaper instantiated with a nil frequency will never reap the
-
# connection pool.
-
#
-
# Configure the frequency by setting "reaping_frequency" in your
-
# database yaml file.
-
1
class Reaper
-
1
attr_reader :pool, :frequency
-
-
1
def initialize(pool, frequency)
-
1
@pool = pool
-
1
@frequency = frequency
-
end
-
-
1
def run
-
1
return unless frequency
-
Thread.new(frequency, pool) { |t, p|
-
while true
-
sleep t
-
p.reap
-
end
-
}
-
end
-
end
-
-
1
include MonitorMixin
-
-
1
attr_accessor :automatic_reconnect, :checkout_timeout
-
1
attr_reader :spec, :connections, :size, :reaper
-
-
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
-
# object which describes database connection information (e.g. adapter,
-
# host name, username, password, etc), as well as the maximum size for
-
# this ConnectionPool.
-
#
-
# The default ConnectionPool maximum size is 5.
-
1
def initialize(spec)
-
1
super()
-
-
1
@spec = spec
-
-
1
@checkout_timeout = (spec.config[:checkout_timeout] && spec.config[:checkout_timeout].to_f) || 5
-
1
@reaper = Reaper.new(self, (spec.config[:reaping_frequency] && spec.config[:reaping_frequency].to_f))
-
1
@reaper.run
-
-
# default max pool size to 5
-
1
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
-
-
# The cache of reserved connections mapped to threads
-
1
@reserved_connections = ThreadSafe::Cache.new(:initial_capacity => @size)
-
-
1
@connections = []
-
1
@automatic_reconnect = true
-
-
1
@available = Queue.new self
-
end
-
-
# Retrieve the connection associated with the current thread, or call
-
# #checkout to obtain one if necessary.
-
#
-
# #connection can be called any number of times; the connection is
-
# held in a hash keyed by the thread id.
-
1
def connection
-
# this is correctly done double-checked locking
-
# (ThreadSafe::Cache's lookups have volatile semantics)
-
@reserved_connections[current_connection_id] || synchronize do
-
1
@reserved_connections[current_connection_id] ||= checkout
-
704
end
-
end
-
-
# Is there an open connection that is being used for the current thread?
-
1
def active_connection?
-
synchronize do
-
@reserved_connections.fetch(current_connection_id) {
-
return false
-
}.in_use?
-
end
-
end
-
-
# Signal that the thread is finished with the current connection.
-
# #release_connection releases the connection-thread association
-
# and returns the connection to the pool.
-
1
def release_connection(with_id = current_connection_id)
-
synchronize do
-
conn = @reserved_connections.delete(with_id)
-
checkin conn if conn
-
end
-
end
-
-
# If a connection already exists yield it to the block. If no connection
-
# exists checkout a connection, yield it to the block, and checkin the
-
# connection when finished.
-
1
def with_connection
-
connection_id = current_connection_id
-
fresh_connection = true unless active_connection?
-
yield connection
-
ensure
-
release_connection(connection_id) if fresh_connection
-
end
-
-
# Returns true if a connection has already been opened.
-
1
def connected?
-
242
synchronize { @connections.any? }
-
end
-
-
# Disconnects all connections in the pool, and clears the pool.
-
1
def disconnect!
-
synchronize do
-
@reserved_connections.clear
-
@connections.each do |conn|
-
checkin conn
-
conn.disconnect!
-
end
-
@connections = []
-
@available.clear
-
end
-
end
-
-
# Clears the cache which maps classes.
-
1
def clear_reloadable_connections!
-
synchronize do
-
@reserved_connections.clear
-
@connections.each do |conn|
-
checkin conn
-
conn.disconnect! if conn.requires_reloading?
-
end
-
@connections.delete_if do |conn|
-
conn.requires_reloading?
-
end
-
@available.clear
-
@connections.each do |conn|
-
@available.add conn
-
end
-
end
-
end
-
-
# Check-out a database connection from the pool, indicating that you want
-
# to use it. You should call #checkin when you no longer need this.
-
#
-
# This is done by either returning and leasing existing connection, or by
-
# creating a new connection and leasing it.
-
#
-
# If all connections are leased and the pool is at capacity (meaning the
-
# number of currently leased connections is greater than or equal to the
-
# size limit set), an ActiveRecord::ConnectionTimeoutError exception will be raised.
-
#
-
# Returns: an AbstractAdapter object.
-
#
-
# Raises:
-
# - ConnectionTimeoutError: no connection can be obtained from the pool.
-
1
def checkout
-
1
synchronize do
-
1
conn = acquire_connection
-
1
conn.lease
-
1
checkout_and_verify(conn)
-
end
-
end
-
-
# Check-in a database connection back into the pool, indicating that you
-
# no longer need this connection.
-
#
-
# +conn+: an AbstractAdapter object, which was obtained by earlier by
-
# calling +checkout+ on this pool.
-
1
def checkin(conn)
-
synchronize do
-
owner = conn.owner
-
-
conn._run_checkin_callbacks do
-
conn.expire
-
end
-
-
release conn, owner
-
-
@available.add conn
-
end
-
end
-
-
# Remove a connection from the connection pool. The connection will
-
# remain open and active but will no longer be managed by this pool.
-
1
def remove(conn)
-
synchronize do
-
@connections.delete conn
-
@available.delete conn
-
-
release conn, conn.owner
-
-
@available.add checkout_new_connection if @available.any_waiting?
-
end
-
end
-
-
# Recover lost connections for the pool. A lost connection can occur if
-
# a programmer forgets to checkin a connection at the end of a thread
-
# or a thread dies unexpectedly.
-
1
def reap
-
stale_connections = synchronize do
-
@connections.select do |conn|
-
conn.in_use? && !conn.owner.alive?
-
end
-
end
-
-
stale_connections.each do |conn|
-
synchronize do
-
if conn.active?
-
conn.reset!
-
checkin conn
-
else
-
remove conn
-
end
-
end
-
end
-
end
-
-
1
private
-
-
# Acquire a connection by one of 1) immediately removing one
-
# from the queue of available connections, 2) creating a new
-
# connection if the pool is not at capacity, 3) waiting on the
-
# queue for a connection to become available.
-
#
-
# Raises:
-
# - ConnectionTimeoutError if a connection could not be acquired
-
1
def acquire_connection
-
1
if conn = @available.poll
-
conn
-
1
elsif @connections.size < @size
-
1
checkout_new_connection
-
else
-
reap
-
@available.poll(@checkout_timeout)
-
end
-
end
-
-
1
def release(conn, owner)
-
thread_id = owner.object_id
-
-
if @reserved_connections[thread_id] == conn
-
@reserved_connections.delete thread_id
-
end
-
end
-
-
1
def new_connection
-
1
Base.send(spec.adapter_method, spec.config)
-
end
-
-
1
def current_connection_id #:nodoc:
-
705
Base.connection_id ||= Thread.current.object_id
-
end
-
-
1
def checkout_new_connection
-
1
raise ConnectionNotEstablished unless @automatic_reconnect
-
-
1
c = new_connection
-
1
c.pool = self
-
1
@connections << c
-
1
c
-
end
-
-
1
def checkout_and_verify(c)
-
1
c._run_checkout_callbacks do
-
1
c.verify!
-
end
-
1
c
-
rescue
-
remove c
-
c.disconnect!
-
raise
-
end
-
end
-
-
# ConnectionHandler is a collection of ConnectionPool objects. It is used
-
# for keeping separate connection pools for Active Record models that connect
-
# to different databases.
-
#
-
# For example, suppose that you have 5 models, with the following hierarchy:
-
#
-
# class Author < ActiveRecord::Base
-
# end
-
#
-
# class BankAccount < ActiveRecord::Base
-
# end
-
#
-
# class Book < ActiveRecord::Base
-
# establish_connection "library_db"
-
# end
-
#
-
# class ScaryBook < Book
-
# end
-
#
-
# class GoodBook < Book
-
# end
-
#
-
# And a database.yml that looked like this:
-
#
-
# development:
-
# database: my_application
-
# host: localhost
-
#
-
# library_db:
-
# database: library
-
# host: some.library.org
-
#
-
# Your primary database in the development environment is "my_application"
-
# but the Book model connects to a separate database called "library_db"
-
# (this can even be a database on a different machine).
-
#
-
# Book, ScaryBook and GoodBook will all use the same connection pool to
-
# "library_db" while Author, BankAccount, and any other models you create
-
# will use the default connection pool to "my_application".
-
#
-
# The various connection pools are managed by a single instance of
-
# ConnectionHandler accessible via ActiveRecord::Base.connection_handler.
-
# All Active Record models use this handler to determine the connection pool that they
-
# should use.
-
1
class ConnectionHandler
-
1
def initialize
-
# These caches are keyed by klass.name, NOT klass. Keying them by klass
-
# alone would lead to memory leaks in development mode as all previous
-
# instances of the class would stay in memory.
-
1
@owner_to_pool = ThreadSafe::Cache.new(:initial_capacity => 2) do |h,k|
-
1
h[k] = ThreadSafe::Cache.new(:initial_capacity => 2)
-
end
-
1
@class_to_pool = ThreadSafe::Cache.new(:initial_capacity => 2) do |h,k|
-
1
h[k] = ThreadSafe::Cache.new
-
end
-
end
-
-
1
def connection_pool_list
-
owner_to_pool.values.compact
-
end
-
-
1
def connection_pools
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
In the next release, this will return the same as `#connection_pool_list`.
-
(An array of pools, rather than a hash mapping specs to pools.)
-
MSG
-
-
Hash[connection_pool_list.map { |pool| [pool.spec, pool] }]
-
end
-
-
1
def establish_connection(owner, spec)
-
1
@class_to_pool.clear
-
1
raise RuntimeError, "Anonymous class is not allowed." unless owner.name
-
1
owner_to_pool[owner.name] = ConnectionAdapters::ConnectionPool.new(spec)
-
end
-
-
# Returns true if there are any active connections among the connection
-
# pools that the ConnectionHandler is managing.
-
1
def active_connections?
-
connection_pool_list.any?(&:active_connection?)
-
end
-
-
# Returns any connections in use by the current thread back to the pool,
-
# and also returns connections to the pool cached by threads that are no
-
# longer alive.
-
1
def clear_active_connections!
-
connection_pool_list.each(&:release_connection)
-
end
-
-
# Clears the cache which maps classes.
-
1
def clear_reloadable_connections!
-
connection_pool_list.each(&:clear_reloadable_connections!)
-
end
-
-
1
def clear_all_connections!
-
connection_pool_list.each(&:disconnect!)
-
end
-
-
# Locate the connection of the nearest super class. This can be an
-
# active or defined connection: if it is the latter, it will be
-
# opened and set as the active connection for the class it was defined
-
# for (not necessarily the current class).
-
1
def retrieve_connection(klass) #:nodoc:
-
704
pool = retrieve_connection_pool(klass)
-
704
raise ConnectionNotEstablished, "No connection pool for #{klass}" unless pool
-
704
conn = pool.connection
-
704
raise ConnectionNotEstablished, "No connection for #{klass} in connection pool" unless conn
-
704
conn
-
end
-
-
# Returns true if a connection that's accessible to this class has
-
# already been opened.
-
1
def connected?(klass)
-
121
conn = retrieve_connection_pool(klass)
-
121
conn && conn.connected?
-
end
-
-
# Remove the connection for this class. This will close the active
-
# connection and the defined connection (if they exist). The result
-
# can be used as an argument for establish_connection, for easily
-
# re-establishing the connection.
-
1
def remove_connection(owner)
-
1
if pool = owner_to_pool.delete(owner.name)
-
@class_to_pool.clear
-
pool.automatic_reconnect = false
-
pool.disconnect!
-
pool.spec.config
-
end
-
end
-
-
# Retrieving the connection pool happens a lot so we cache it in @class_to_pool.
-
# This makes retrieving the connection pool O(1) once the process is warm.
-
# When a connection is established or removed, we invalidate the cache.
-
#
-
# Ideally we would use #fetch here, as class_to_pool[klass] may sometimes be nil.
-
# However, benchmarking (https://gist.github.com/jonleighton/3552829) showed that
-
# #fetch is significantly slower than #[]. So in the nil case, no caching will
-
# take place, but that's ok since the nil case is not the common one that we wish
-
# to optimise for.
-
1
def retrieve_connection_pool(klass)
-
830
class_to_pool[klass.name] ||= begin
-
6
until pool = pool_for(klass)
-
5
klass = klass.superclass
-
5
break unless klass <= Base
-
end
-
-
6
class_to_pool[klass.name] = pool
-
end
-
end
-
-
1
private
-
-
1
def owner_to_pool
-
18
@owner_to_pool[Process.pid]
-
end
-
-
1
def class_to_pool
-
836
@class_to_pool[Process.pid]
-
end
-
-
1
def pool_for(owner)
-
11
owner_to_pool.fetch(owner.name) {
-
5
if ancestor_pool = pool_from_any_process_for(owner)
-
# A connection was established in an ancestor process that must have
-
# subsequently forked. We can't reuse the connection, but we can copy
-
# the specification and establish a new connection with it.
-
establish_connection owner, ancestor_pool.spec
-
else
-
5
owner_to_pool[owner.name] = nil
-
end
-
}
-
end
-
-
1
def pool_from_any_process_for(owner)
-
10
owner_to_pool = @owner_to_pool.values.find { |v| v[owner.name] }
-
5
owner_to_pool && owner_to_pool[owner.name]
-
end
-
end
-
-
1
class ConnectionManagement
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
66
testing = env['rack.test']
-
-
66
response = @app.call(env)
-
66
response[2] = ::Rack::BodyProxy.new(response[2]) do
-
66
ActiveRecord::Base.clear_active_connections! unless testing
-
end
-
-
66
response
-
rescue Exception
-
ActiveRecord::Base.clear_active_connections! unless testing
-
raise
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module DatabaseLimits
-
-
# Returns the maximum length of a table alias.
-
1
def table_alias_length
-
255
-
end
-
-
# Returns the maximum length of a column name.
-
1
def column_name_length
-
64
-
end
-
-
# Returns the maximum length of a table name.
-
1
def table_name_length
-
64
-
end
-
-
# Returns the maximum allowed length for an index name. This
-
# limit is enforced by rails and Is less than or equal to
-
# <tt>index_name_length</tt>. The gap between
-
# <tt>index_name_length</tt> is to allow internal rails
-
# operations to use prefixes in temporary operations.
-
1
def allowed_index_name_length
-
index_name_length
-
end
-
-
# Returns the maximum length of an index name.
-
1
def index_name_length
-
64
-
end
-
-
# Returns the maximum number of columns per table.
-
1
def columns_per_table
-
1024
-
end
-
-
# Returns the maximum number of indexes per table.
-
1
def indexes_per_table
-
16
-
end
-
-
# Returns the maximum number of columns in a multicolumn index.
-
1
def columns_per_multicolumn_index
-
16
-
end
-
-
# Returns the maximum number of elements in an IN (x,y,z) clause.
-
# nil means no limit.
-
1
def in_clause_length
-
nil
-
end
-
-
# Returns the maximum length of an SQL query.
-
1
def sql_query_length
-
1048575
-
end
-
-
# Returns maximum number of joins in a single query.
-
1
def joins_per_query
-
256
-
end
-
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module DatabaseStatements
-
1
def initialize
-
1
super
-
1
reset_transaction
-
end
-
-
# Converts an arel AST to SQL
-
1
def to_sql(arel, binds = [])
-
123
if arel.respond_to?(:ast)
-
56
collected = visitor.accept(arel.ast, collector)
-
56
collected.compile(binds.dup, self)
-
else
-
67
arel
-
end
-
end
-
-
# This is used in the StatementCache object. It returns an object that
-
# can be used to query the database repeatedly.
-
1
def cacheable_query(arel) # :nodoc:
-
4
if prepared_statements
-
4
ActiveRecord::StatementCache.query visitor, arel.ast
-
else
-
ActiveRecord::StatementCache.partial_query visitor, arel.ast, collector
-
end
-
end
-
-
# Returns an ActiveRecord::Result instance.
-
1
def select_all(arel, name = nil, binds = [])
-
46
arel, binds = binds_from_relation arel, binds
-
46
select(to_sql(arel, binds), name, binds)
-
end
-
-
# Returns a record hash with the column names as keys and column values
-
# as values.
-
1
def select_one(arel, name = nil, binds = [])
-
select_all(arel, name, binds).first
-
end
-
-
# Returns a single value from a record
-
1
def select_value(arel, name = nil, binds = [])
-
if result = select_one(arel, name, binds)
-
result.values.first
-
end
-
end
-
-
# Returns an array of the values of the first column in a select:
-
# select_values("SELECT id FROM companies LIMIT 3") => [1,2,3]
-
1
def select_values(arel, name = nil)
-
arel, binds = binds_from_relation arel, []
-
select_rows(to_sql(arel, binds), name, binds).map(&:first)
-
end
-
-
# Returns an array of arrays containing the field values.
-
# Order is the same as that returned by +columns+.
-
1
def select_rows(sql, name = nil, binds = [])
-
end
-
1
undef_method :select_rows
-
-
# Executes the SQL statement in the context of this connection.
-
1
def execute(sql, name = nil)
-
end
-
1
undef_method :execute
-
-
# Executes +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_query(sql, name = 'SQL', binds = [])
-
end
-
-
# Executes insert +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
-
25
exec_query(sql, name, binds)
-
end
-
-
# Executes delete +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_delete(sql, name, binds)
-
exec_query(sql, name, binds)
-
end
-
-
# Executes the truncate statement.
-
1
def truncate(table_name, name = nil)
-
raise NotImplementedError
-
end
-
-
# Executes update +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_update(sql, name, binds)
-
exec_query(sql, name, binds)
-
end
-
-
# Returns the last auto-generated ID from the affected table.
-
#
-
# +id_value+ will be returned unless the value is nil, in
-
# which case the database will attempt to calculate the last inserted
-
# id and return that value.
-
#
-
# If the next id was calculated in advance (as in Oracle), it should be
-
# passed in as +id_value+.
-
1
def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
-
25
sql, binds = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds)
-
25
value = exec_insert(sql, name, binds, pk, sequence_name)
-
25
id_value || last_inserted_id(value)
-
end
-
-
# Executes the update statement and returns the number of rows affected.
-
1
def update(arel, name = nil, binds = [])
-
4
exec_update(to_sql(arel, binds), name, binds)
-
end
-
-
# Executes the delete statement and returns the number of rows affected.
-
1
def delete(arel, name = nil, binds = [])
-
3
exec_delete(to_sql(arel, binds), name, binds)
-
end
-
-
# Returns +true+ when the connection adapter supports prepared statement
-
# caching, otherwise returns +false+
-
1
def supports_statement_cache?
-
false
-
end
-
-
# Runs the given block in a database transaction, and returns the result
-
# of the block.
-
#
-
# == Nested transactions support
-
#
-
# Most databases don't support true nested transactions. At the time of
-
# writing, the only database that supports true nested transactions that
-
# we're aware of, is MS-SQL.
-
#
-
# In order to get around this problem, #transaction will emulate the effect
-
# of nested transactions, by using savepoints:
-
# http://dev.mysql.com/doc/refman/5.0/en/savepoint.html
-
# Savepoints are supported by MySQL and PostgreSQL. SQLite3 version >= '3.6.8'
-
# supports savepoints.
-
#
-
# It is safe to call this method if a database transaction is already open,
-
# i.e. if #transaction is called within another #transaction block. In case
-
# of a nested call, #transaction will behave as follows:
-
#
-
# - The block will be run without doing anything. All database statements
-
# that happen within the block are effectively appended to the already
-
# open database transaction.
-
# - However, if +:requires_new+ is set, the block will be wrapped in a
-
# database savepoint acting as a sub-transaction.
-
#
-
# === Caveats
-
#
-
# MySQL doesn't support DDL transactions. If you perform a DDL operation,
-
# then any created savepoints will be automatically released. For example,
-
# if you've created a savepoint, then you execute a CREATE TABLE statement,
-
# then the savepoint that was created will be automatically released.
-
#
-
# This means that, on MySQL, you shouldn't execute DDL operations inside
-
# a #transaction call that you know might create a savepoint. Otherwise,
-
# #transaction will raise exceptions when it tries to release the
-
# already-automatically-released savepoints:
-
#
-
# Model.connection.transaction do # BEGIN
-
# Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
-
# Model.connection.create_table(...)
-
# # active_record_1 now automatically released
-
# end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error!
-
# end
-
#
-
# == Transaction isolation
-
#
-
# If your database supports setting the isolation level for a transaction, you can set
-
# it like so:
-
#
-
# Post.transaction(isolation: :serializable) do
-
# # ...
-
# end
-
#
-
# Valid isolation levels are:
-
#
-
# * <tt>:read_uncommitted</tt>
-
# * <tt>:read_committed</tt>
-
# * <tt>:repeatable_read</tt>
-
# * <tt>:serializable</tt>
-
#
-
# You should consult the documentation for your database to understand the
-
# semantics of these different levels:
-
#
-
# * http://www.postgresql.org/docs/9.1/static/transaction-iso.html
-
# * https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html
-
#
-
# An <tt>ActiveRecord::TransactionIsolationError</tt> will be raised if:
-
#
-
# * The adapter does not support setting the isolation level
-
# * You are joining an existing open transaction
-
# * You are creating a nested (savepoint) transaction
-
#
-
# The mysql, mysql2 and postgresql adapters support setting the transaction
-
# isolation level. However, support is disabled for MySQL versions below 5,
-
# because they are affected by a bug[http://bugs.mysql.com/bug.php?id=39170]
-
# which means the isolation level gets persisted outside the transaction.
-
1
def transaction(options = {})
-
54
options.assert_valid_keys :requires_new, :joinable, :isolation
-
-
54
if !options[:requires_new] && current_transaction.joinable?
-
4
if options[:isolation]
-
raise ActiveRecord::TransactionIsolationError, "cannot set isolation when joining a transaction"
-
end
-
4
yield
-
else
-
100
transaction_manager.within_new_transaction(options) { yield }
-
end
-
rescue ActiveRecord::Rollback
-
# rollbacks are silently swallowed
-
end
-
-
1
attr_reader :transaction_manager #:nodoc:
-
-
1
delegate :within_new_transaction, :open_transactions, :current_transaction, :begin_transaction, :commit_transaction, :rollback_transaction, to: :transaction_manager
-
-
1
def transaction_open?
-
current_transaction.open?
-
end
-
-
1
def reset_transaction #:nodoc:
-
1
@transaction_manager = TransactionManager.new(self)
-
end
-
-
# Register a record with the current transaction so that its after_commit and after_rollback callbacks
-
# can be called.
-
1
def add_transaction_record(record)
-
3
current_transaction.add_record(record)
-
end
-
-
1
def transaction_state
-
36
current_transaction.state
-
end
-
-
# Begins the transaction (and turns off auto-committing).
-
1
def begin_db_transaction() end
-
-
1
def transaction_isolation_levels
-
{
-
read_uncommitted: "READ UNCOMMITTED",
-
read_committed: "READ COMMITTED",
-
repeatable_read: "REPEATABLE READ",
-
serializable: "SERIALIZABLE"
-
}
-
end
-
-
# Begins the transaction with the isolation level set. Raises an error by
-
# default; adapters that support setting the isolation level should implement
-
# this method.
-
1
def begin_isolated_db_transaction(isolation)
-
raise ActiveRecord::TransactionIsolationError, "adapter does not support setting transaction isolation"
-
end
-
-
# Commits the transaction (and turns on auto-committing).
-
1
def commit_db_transaction() end
-
-
# Rolls back the transaction (and turns on auto-committing). Must be
-
# done if the transaction block raises an exception or returns false.
-
1
def rollback_db_transaction
-
18
exec_rollback_db_transaction
-
end
-
-
1
def exec_rollback_db_transaction() end #:nodoc:
-
-
1
def rollback_to_savepoint(name = nil)
-
exec_rollback_to_savepoint(name)
-
end
-
-
1
def exec_rollback_to_savepoint(name = nil) #:nodoc:
-
end
-
-
1
def default_sequence_name(table, column)
-
nil
-
end
-
-
# Set the sequence to the max value of the table's column.
-
1
def reset_sequence!(table, column, sequence = nil)
-
# Do nothing by default. Implement for PostgreSQL, Oracle, ...
-
end
-
-
# Inserts the given fixture into the table. Overridden in adapters that require
-
# something beyond a simple insert (eg. Oracle).
-
1
def insert_fixture(fixture, table_name)
-
columns = schema_cache.columns_hash(table_name)
-
-
key_list = []
-
value_list = fixture.map do |name, value|
-
if column = columns[name]
-
key_list << quote_column_name(name)
-
quote(value, column)
-
else
-
raise Fixture::FixtureError, %(table "#{table_name}" has no column named "#{name}".)
-
end
-
end
-
-
execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
-
end
-
-
1
def empty_insert_statement_value
-
"DEFAULT VALUES"
-
end
-
-
# Sanitizes the given LIMIT parameter in order to prevent SQL injection.
-
#
-
# The +limit+ may be anything that can evaluate to a string via #to_s. It
-
# should look like an integer, or a comma-delimited list of integers, or
-
# an Arel SQL literal.
-
#
-
# Returns Integer and Arel::Nodes::SqlLiteral limits as is.
-
# Returns the sanitized limit parameter, either as an integer, or as a
-
# string which contains a comma-delimited list of integers.
-
1
def sanitize_limit(limit)
-
4
if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
-
4
limit
-
elsif limit.to_s.include?(',')
-
Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
-
else
-
Integer(limit)
-
end
-
end
-
-
# The default strategy for an UPDATE with joins is to use a subquery. This doesn't work
-
# on MySQL (even when aliasing the tables), but MySQL allows using JOIN directly in
-
# an UPDATE statement, so in the MySQL adapters we redefine this to do that.
-
1
def join_to_update(update, select) #:nodoc:
-
key = update.key
-
subselect = subquery_for(key, select)
-
-
update.where key.in(subselect)
-
end
-
-
1
def join_to_delete(delete, select, key) #:nodoc:
-
subselect = subquery_for(key, select)
-
-
delete.where key.in(subselect)
-
end
-
-
1
protected
-
-
# Returns a subquery for the given key using the join information.
-
1
def subquery_for(key, select)
-
subselect = select.clone
-
subselect.projections = [key]
-
subselect
-
end
-
-
# Returns an ActiveRecord::Result instance.
-
1
def select(sql, name = nil, binds = [])
-
46
exec_query(sql, name, binds)
-
end
-
-
-
# Returns the last auto-generated ID from the affected table.
-
1
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
-
execute(sql, name)
-
id_value
-
end
-
-
# Executes the update statement and returns the number of rows affected.
-
1
def update_sql(sql, name = nil)
-
execute(sql, name)
-
end
-
-
# Executes the delete statement and returns the number of rows affected.
-
1
def delete_sql(sql, name = nil)
-
update_sql(sql, name)
-
end
-
-
1
def sql_for_insert(sql, pk, id_value, sequence_name, binds)
-
25
[sql, binds]
-
end
-
-
1
def last_inserted_id(result)
-
row = result.rows.first
-
row && row.first
-
end
-
-
1
def binds_from_relation(relation, binds)
-
91
if relation.is_a?(Relation) && binds.empty?
-
relation, binds = relation.arel, relation.bind_values
-
end
-
91
[relation, binds]
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module QueryCache
-
1
class << self
-
1
def included(base) #:nodoc:
-
1
dirties_query_cache base, :insert, :update, :delete, :rollback_to_savepoint, :rollback_db_transaction
-
end
-
-
1
def dirties_query_cache(base, *method_names)
-
1
method_names.each do |method_name|
-
5
base.class_eval <<-end_code, __FILE__, __LINE__ + 1
-
def #{method_name}(*)
-
clear_query_cache if @query_cache_enabled
-
super
-
end
-
end_code
-
end
-
end
-
end
-
-
1
attr_reader :query_cache, :query_cache_enabled
-
-
1
def initialize(*)
-
1
super
-
46
@query_cache = Hash.new { |h,sql| h[sql] = {} }
-
1
@query_cache_enabled = false
-
end
-
-
# Enable the query cache within the block.
-
1
def cache
-
old, @query_cache_enabled = @query_cache_enabled, true
-
yield
-
ensure
-
@query_cache_enabled = old
-
clear_query_cache unless @query_cache_enabled
-
end
-
-
1
def enable_query_cache!
-
66
@query_cache_enabled = true
-
end
-
-
1
def disable_query_cache!
-
66
@query_cache_enabled = false
-
end
-
-
# Disable the query cache within the block.
-
1
def uncached
-
old, @query_cache_enabled = @query_cache_enabled, false
-
yield
-
ensure
-
@query_cache_enabled = old
-
end
-
-
# Clears the query cache.
-
#
-
# One reason you may wish to call this method explicitly is between queries
-
# that ask the database to randomize results. Otherwise the cache would see
-
# the same SQL query and repeatedly return the same result each time, silently
-
# undermining the randomness you were expecting.
-
1
def clear_query_cache
-
77
@query_cache.clear
-
end
-
-
1
def select_all(arel, name = nil, binds = [])
-
46
if @query_cache_enabled && !locked?(arel)
-
45
arel, binds = binds_from_relation arel, binds
-
45
sql = to_sql(arel, binds)
-
90
cache_sql(sql, binds) { super(sql, name, binds) }
-
else
-
1
super
-
end
-
end
-
-
1
private
-
-
1
def cache_sql(sql, binds)
-
45
result =
-
if @query_cache[sql].key?(binds)
-
ActiveSupport::Notifications.instrument("sql.active_record",
-
:sql => sql, :binds => binds, :name => "CACHE", :connection_id => object_id)
-
@query_cache[sql][binds]
-
else
-
45
@query_cache[sql][binds] = yield
-
end
-
45
result.dup
-
end
-
-
# If arel is locked this is a SELECT ... FOR UPDATE or somesuch. Such
-
# queries should not be cached.
-
1
def locked?(arel)
-
45
arel.respond_to?(:locked) && arel.locked
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/big_decimal/conversions'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module Quoting
-
# Quotes the column value to help prevent
-
# {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection].
-
1
def quote(value, column = nil)
-
# records are quoted as their primary key
-
return value.quoted_id if value.respond_to?(:quoted_id)
-
-
if column
-
value = column.cast_type.type_cast_for_database(value)
-
end
-
-
_quote(value)
-
end
-
-
# Cast a +value+ to a type that the database understands. For example,
-
# SQLite does not understand dates, so this method will convert a Date
-
# to a String.
-
1
def type_cast(value, column)
-
168
if value.respond_to?(:quoted_id) && value.respond_to?(:id)
-
return value.id
-
end
-
-
168
if column
-
168
value = column.cast_type.type_cast_for_database(value)
-
end
-
-
168
_type_cast(value)
-
rescue TypeError
-
to_type = column ? " to #{column.type}" : ""
-
raise TypeError, "can't cast #{value.class}#{to_type}"
-
end
-
-
# Quotes a string, escaping any ' (single quote) and \ (backslash)
-
# characters.
-
1
def quote_string(s)
-
s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
-
end
-
-
# Quotes the column name. Defaults to no quoting.
-
1
def quote_column_name(column_name)
-
column_name
-
end
-
-
# Quotes the table name. Defaults to column name quoting.
-
1
def quote_table_name(table_name)
-
109
quote_column_name(table_name)
-
end
-
-
# Override to return the quoted table name for assignment. Defaults to
-
# table quoting.
-
#
-
# This works for mysql and mysql2 where table.column can be used to
-
# resolve ambiguity.
-
#
-
# We override this in the sqlite3 and postgresql adapters to use only
-
# the column name (as per syntax requirements).
-
1
def quote_table_name_for_assignment(table, attr)
-
quote_table_name("#{table}.#{attr}")
-
end
-
-
1
def quoted_true
-
"'t'"
-
end
-
-
1
def unquoted_true
-
't'
-
end
-
-
1
def quoted_false
-
"'f'"
-
end
-
-
1
def unquoted_false
-
'f'
-
end
-
-
1
def quoted_date(value)
-
60
if value.acts_like?(:time)
-
54
zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
-
-
54
if value.respond_to?(zone_conversion_method)
-
54
value = value.send(zone_conversion_method)
-
end
-
end
-
-
60
value.to_s(:db)
-
end
-
-
1
private
-
-
1
def types_which_need_no_typecasting
-
108
[nil, Numeric, String]
-
end
-
-
1
def _quote(value)
-
case value
-
when String, ActiveSupport::Multibyte::Chars, Type::Binary::Data
-
"'#{quote_string(value.to_s)}'"
-
when true then quoted_true
-
when false then quoted_false
-
when nil then "NULL"
-
# BigDecimals need to be put in a non-normalized form and quoted.
-
when BigDecimal then value.to_s('F')
-
when Numeric, ActiveSupport::Duration then value.to_s
-
when Date, Time then "'#{quoted_date(value)}'"
-
when Symbol then "'#{quote_string(value.to_s)}'"
-
when Class then "'#{value}'"
-
else
-
"'#{quote_string(YAML.dump(value))}'"
-
end
-
end
-
-
1
def _type_cast(value)
-
168
case value
-
when Symbol, ActiveSupport::Multibyte::Chars, Type::Binary::Data
-
value.to_s
-
when true then unquoted_true
-
when false then unquoted_false
-
# BigDecimals need to be put in a non-normalized form and quoted.
-
when BigDecimal then value.to_s('F')
-
60
when Date, Time then quoted_date(value)
-
when *types_which_need_no_typecasting
-
108
value
-
else raise TypeError
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
module Savepoints #:nodoc:
-
1
def supports_savepoints?
-
true
-
end
-
-
1
def create_savepoint(name = current_savepoint_name)
-
32
execute("SAVEPOINT #{name}")
-
end
-
-
1
def exec_rollback_to_savepoint(name = current_savepoint_name)
-
execute("ROLLBACK TO SAVEPOINT #{name}")
-
end
-
-
1
def release_savepoint(name = current_savepoint_name)
-
32
execute("RELEASE SAVEPOINT #{name}")
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/strip'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class AbstractAdapter
-
1
class SchemaCreation # :nodoc:
-
1
def initialize(conn)
-
@conn = conn
-
@cache = {}
-
end
-
-
1
def accept(o)
-
m = @cache[o.class] ||= "visit_#{o.class.name.split('::').last}"
-
send m, o
-
end
-
-
1
def visit_AddColumn(o)
-
"ADD #{accept(o)}"
-
end
-
-
1
private
-
-
1
def visit_AlterTable(o)
-
sql = "ALTER TABLE #{quote_table_name(o.name)} "
-
sql << o.adds.map { |col| visit_AddColumn col }.join(' ')
-
sql << o.foreign_key_adds.map { |fk| visit_AddForeignKey fk }.join(' ')
-
sql << o.foreign_key_drops.map { |fk| visit_DropForeignKey fk }.join(' ')
-
end
-
-
1
def visit_ColumnDefinition(o)
-
sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale)
-
column_sql = "#{quote_column_name(o.name)} #{sql_type}"
-
add_column_options!(column_sql, column_options(o)) unless o.primary_key?
-
column_sql
-
end
-
-
1
def visit_TableDefinition(o)
-
create_sql = "CREATE#{' TEMPORARY' if o.temporary} TABLE "
-
create_sql << "#{quote_table_name(o.name)} "
-
create_sql << "(#{o.columns.map { |c| accept c }.join(', ')}) " unless o.as
-
create_sql << "#{o.options}"
-
create_sql << " AS #{@conn.to_sql(o.as)}" if o.as
-
create_sql
-
end
-
-
1
def visit_AddForeignKey(o)
-
sql = <<-SQL.strip_heredoc
-
ADD CONSTRAINT #{quote_column_name(o.name)}
-
FOREIGN KEY (#{quote_column_name(o.column)})
-
REFERENCES #{quote_table_name(o.to_table)} (#{quote_column_name(o.primary_key)})
-
SQL
-
sql << " #{action_sql('DELETE', o.on_delete)}" if o.on_delete
-
sql << " #{action_sql('UPDATE', o.on_update)}" if o.on_update
-
sql
-
end
-
-
1
def visit_DropForeignKey(name)
-
"DROP CONSTRAINT #{quote_column_name(name)}"
-
end
-
-
1
def column_options(o)
-
column_options = {}
-
column_options[:null] = o.null unless o.null.nil?
-
column_options[:default] = o.default unless o.default.nil?
-
column_options[:column] = o
-
column_options[:first] = o.first
-
column_options[:after] = o.after
-
column_options
-
end
-
-
1
def quote_column_name(name)
-
@conn.quote_column_name name
-
end
-
-
1
def quote_table_name(name)
-
@conn.quote_table_name name
-
end
-
-
1
def type_to_sql(type, limit, precision, scale)
-
@conn.type_to_sql type.to_sym, limit, precision, scale
-
end
-
-
1
def add_column_options!(sql, options)
-
sql << " DEFAULT #{quote_value(options[:default], options[:column])}" if options_include_default?(options)
-
# must explicitly check for :null to allow change_column to work on migrations
-
if options[:null] == false
-
sql << " NOT NULL"
-
end
-
if options[:auto_increment] == true
-
sql << " AUTO_INCREMENT"
-
end
-
sql
-
end
-
-
1
def quote_value(value, column)
-
column.sql_type ||= type_to_sql(column.type, column.limit, column.precision, column.scale)
-
column.cast_type ||= type_for_column(column)
-
-
@conn.quote(value, column)
-
end
-
-
1
def options_include_default?(options)
-
options.include?(:default) && !(options[:null] == false && options[:default].nil?)
-
end
-
-
1
def action_sql(action, dependency)
-
case dependency
-
when :nullify then "ON #{action} SET NULL"
-
when :cascade then "ON #{action} CASCADE"
-
when :restrict then "ON #{action} RESTRICT"
-
else
-
raise ArgumentError, <<-MSG.strip_heredoc
-
'#{dependency}' is not supported for :on_update or :on_delete.
-
Supported values are: :nullify, :cascade, :restrict
-
MSG
-
end
-
end
-
-
1
def type_for_column(column)
-
@conn.lookup_cast_type(column.sql_type)
-
end
-
end
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'set'
-
1
require 'bigdecimal'
-
1
require 'bigdecimal/util'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters #:nodoc:
-
# Abstract representation of an index definition on a table. Instances of
-
# this type are typically created and returned by methods in database
-
# adapters. e.g. ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter#indexes
-
1
class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, :orders, :where, :type, :using) #:nodoc:
-
end
-
-
# Abstract representation of a column definition. Instances of this type
-
# are typically created by methods in TableDefinition, and added to the
-
# +columns+ attribute of said TableDefinition object, in order to be used
-
# for generating a number of table creation or table changing SQL statements.
-
1
class ColumnDefinition < Struct.new(:name, :type, :limit, :precision, :scale, :default, :null, :first, :after, :primary_key, :sql_type, :cast_type) #:nodoc:
-
-
1
def primary_key?
-
primary_key || type.to_sym == :primary_key
-
end
-
end
-
-
1
class ChangeColumnDefinition < Struct.new(:column, :type, :options) #:nodoc:
-
end
-
-
1
class ForeignKeyDefinition < Struct.new(:from_table, :to_table, :options) #:nodoc:
-
1
def name
-
options[:name]
-
end
-
-
1
def column
-
options[:column]
-
end
-
-
1
def primary_key
-
options[:primary_key] || default_primary_key
-
end
-
-
1
def on_delete
-
options[:on_delete]
-
end
-
-
1
def on_update
-
options[:on_update]
-
end
-
-
1
def custom_primary_key?
-
options[:primary_key] != default_primary_key
-
end
-
-
1
private
-
1
def default_primary_key
-
"id"
-
end
-
end
-
-
1
module TimestampDefaultDeprecation # :nodoc:
-
1
def emit_warning_if_null_unspecified(sym, options)
-
return if options.key?(:null)
-
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
`##{sym}` was called without specifying an option for `null`. In Rails 5,
-
this behavior will change to `null: false`. You should manually specify
-
`null: true` to prevent the behavior of your existing migrations from changing.
-
MSG
-
end
-
end
-
-
# Represents the schema of an SQL table in an abstract way. This class
-
# provides methods for manipulating the schema representation.
-
#
-
# Inside migration files, the +t+ object in +create_table+
-
# is actually of this type:
-
#
-
# class SomeMigration < ActiveRecord::Migration
-
# def up
-
# create_table :foo do |t|
-
# puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition"
-
# end
-
# end
-
#
-
# def down
-
# ...
-
# end
-
# end
-
#
-
# The table definitions
-
# The Columns are stored as a ColumnDefinition in the +columns+ attribute.
-
1
class TableDefinition
-
1
include TimestampDefaultDeprecation
-
-
# An array of ColumnDefinition objects, representing the column changes
-
# that have been defined.
-
1
attr_accessor :indexes
-
1
attr_reader :name, :temporary, :options, :as, :foreign_keys
-
-
1
def initialize(types, name, temporary, options, as = nil)
-
@columns_hash = {}
-
@indexes = {}
-
@foreign_keys = {}
-
@native = types
-
@temporary = temporary
-
@options = options
-
@as = as
-
@name = name
-
end
-
-
1
def columns; @columns_hash.values; end
-
-
# Appends a primary key definition to the table definition.
-
# Can be called multiple times, but this is probably not a good idea.
-
1
def primary_key(name, type = :primary_key, options = {})
-
column(name, type, options.merge(:primary_key => true))
-
end
-
-
# Returns a ColumnDefinition for the column with name +name+.
-
1
def [](name)
-
@columns_hash[name.to_s]
-
end
-
-
# Instantiates a new column for the table.
-
# The +type+ parameter is normally one of the migrations native types,
-
# which is one of the following:
-
# <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
-
# <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
-
# <tt>:datetime</tt>, <tt>:time</tt>, <tt>:date</tt>,
-
# <tt>:binary</tt>, <tt>:boolean</tt>.
-
#
-
# You may use a type not in this list as long as it is supported by your
-
# database (for example, "polygon" in MySQL), but this will not be database
-
# agnostic and should usually be avoided.
-
#
-
# Available options are (none of these exists by default):
-
# * <tt>:limit</tt> -
-
# Requests a maximum column length. This is number of characters for <tt>:string</tt> and
-
# <tt>:text</tt> columns and number of bytes for <tt>:binary</tt> and <tt>:integer</tt> columns.
-
# * <tt>:default</tt> -
-
# The column's default value. Use nil for NULL.
-
# * <tt>:null</tt> -
-
# Allows or disallows +NULL+ values in the column. This option could
-
# have been named <tt>:null_allowed</tt>.
-
# * <tt>:precision</tt> -
-
# Specifies the precision for a <tt>:decimal</tt> column.
-
# * <tt>:scale</tt> -
-
# Specifies the scale for a <tt>:decimal</tt> column.
-
# * <tt>:index</tt> -
-
# Create an index for the column. Can be either <tt>true</tt> or an options hash.
-
#
-
# Note: The precision is the total number of significant digits
-
# and the scale is the number of digits that can be stored following
-
# the decimal point. For example, the number 123.45 has a precision of 5
-
# and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
-
# range from -999.99 to 999.99.
-
#
-
# Please be aware of different RDBMS implementations behavior with
-
# <tt>:decimal</tt> columns:
-
# * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
-
# <tt>:precision</tt>, and makes no comments about the requirements of
-
# <tt>:precision</tt>.
-
# * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
-
# Default is (10,0).
-
# * PostgreSQL: <tt>:precision</tt> [1..infinity],
-
# <tt>:scale</tt> [0..infinity]. No default.
-
# * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
-
# Internal storage as strings. No default.
-
# * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
-
# but the maximum supported <tt>:precision</tt> is 16. No default.
-
# * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
-
# Default is (38,0).
-
# * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62].
-
# Default unknown.
-
# * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
-
# Default (38,0).
-
#
-
# This method returns <tt>self</tt>.
-
#
-
# == Examples
-
# # Assuming +td+ is an instance of TableDefinition
-
# td.column(:granted, :boolean)
-
# # granted BOOLEAN
-
#
-
# td.column(:picture, :binary, limit: 2.megabytes)
-
# # => picture BLOB(2097152)
-
#
-
# td.column(:sales_stage, :string, limit: 20, default: 'new', null: false)
-
# # => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL
-
#
-
# td.column(:bill_gates_money, :decimal, precision: 15, scale: 2)
-
# # => bill_gates_money DECIMAL(15,2)
-
#
-
# td.column(:sensor_reading, :decimal, precision: 30, scale: 20)
-
# # => sensor_reading DECIMAL(30,20)
-
#
-
# # While <tt>:scale</tt> defaults to zero on most databases, it
-
# # probably wouldn't hurt to include it.
-
# td.column(:huge_integer, :decimal, precision: 30)
-
# # => huge_integer DECIMAL(30)
-
#
-
# # Defines a column with a database-specific type.
-
# td.column(:foo, 'polygon')
-
# # => foo polygon
-
#
-
# == Short-hand examples
-
#
-
# Instead of calling +column+ directly, you can also work with the short-hand definitions for the default types.
-
# They use the type as the method name instead of as a parameter and allow for multiple columns to be defined
-
# in a single statement.
-
#
-
# What can be written like this with the regular calls to column:
-
#
-
# create_table :products do |t|
-
# t.column :shop_id, :integer
-
# t.column :creator_id, :integer
-
# t.column :item_number, :string
-
# t.column :name, :string, default: "Untitled"
-
# t.column :value, :string, default: "Untitled"
-
# t.column :created_at, :datetime
-
# t.column :updated_at, :datetime
-
# end
-
# add_index :products, :item_number
-
#
-
# can also be written as follows using the short-hand:
-
#
-
# create_table :products do |t|
-
# t.integer :shop_id, :creator_id
-
# t.string :item_number, index: true
-
# t.string :name, :value, default: "Untitled"
-
# t.timestamps null: false
-
# end
-
#
-
# There's a short-hand method for each of the type values declared at the top. And then there's
-
# TableDefinition#timestamps that'll add +created_at+ and +updated_at+ as datetimes.
-
#
-
# TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
-
# column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of
-
# options, these will be used when creating the <tt>_type</tt> column. The <tt>:index</tt> option
-
# will also create an index, similar to calling <tt>add_index</tt>. So what can be written like this:
-
#
-
# create_table :taggings do |t|
-
# t.integer :tag_id, :tagger_id, :taggable_id
-
# t.string :tagger_type
-
# t.string :taggable_type, default: 'Photo'
-
# end
-
# add_index :taggings, :tag_id, name: 'index_taggings_on_tag_id'
-
# add_index :taggings, [:tagger_id, :tagger_type]
-
#
-
# Can also be written as follows using references:
-
#
-
# create_table :taggings do |t|
-
# t.references :tag, index: { name: 'index_taggings_on_tag_id' }
-
# t.references :tagger, polymorphic: true, index: true
-
# t.references :taggable, polymorphic: { default: 'Photo' }
-
# end
-
1
def column(name, type, options = {})
-
name = name.to_s
-
type = type.to_sym
-
options = options.dup
-
-
if @columns_hash[name] && @columns_hash[name].primary_key?
-
raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table."
-
end
-
-
index_options = options.delete(:index)
-
index(name, index_options.is_a?(Hash) ? index_options : {}) if index_options
-
@columns_hash[name] = new_column_definition(name, type, options)
-
self
-
end
-
-
1
def remove_column(name)
-
@columns_hash.delete name.to_s
-
end
-
-
1
[:string, :text, :integer, :bigint, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
-
12
define_method column_type do |*args|
-
options = args.extract_options!
-
column_names = args
-
column_names.each { |name| column(name, column_type, options) }
-
end
-
end
-
-
# Adds index options to the indexes hash, keyed by column name
-
# This is primarily used to track indexes that need to be created after the table
-
#
-
# index(:account_id, name: 'index_projects_on_account_id')
-
1
def index(column_name, options = {})
-
indexes[column_name] = options
-
end
-
-
1
def foreign_key(table_name, options = {}) # :nodoc:
-
foreign_keys[table_name] = options
-
end
-
-
# Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
-
# <tt>:updated_at</tt> to the table. See SchemaStatements#add_timestamps
-
#
-
# t.timestamps null: false
-
1
def timestamps(*args)
-
options = args.extract_options!
-
emit_warning_if_null_unspecified(:timestamps, options)
-
column(:created_at, :datetime, options)
-
column(:updated_at, :datetime, options)
-
end
-
-
# Adds a reference.
-
#
-
# t.references(:user)
-
# t.belongs_to(:supplier, foreign_key: true)
-
#
-
# See SchemaStatements#add_reference for details of the options you can use.
-
1
def references(*args)
-
options = args.extract_options!
-
polymorphic = options.delete(:polymorphic)
-
index_options = options.delete(:index)
-
foreign_key_options = options.delete(:foreign_key)
-
type = options.delete(:type) || :integer
-
-
if polymorphic && foreign_key_options
-
raise ArgumentError, "Cannot add a foreign key on a polymorphic relation"
-
end
-
-
args.each do |col|
-
column("#{col}_id", type, options)
-
column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
-
index(polymorphic ? %w(type id).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
-
if foreign_key_options
-
to_table = Base.pluralize_table_names ? col.to_s.pluralize : col.to_s
-
foreign_key(to_table, foreign_key_options.is_a?(Hash) ? foreign_key_options : {})
-
end
-
end
-
end
-
1
alias :belongs_to :references
-
-
1
def new_column_definition(name, type, options) # :nodoc:
-
type = aliased_types(type.to_s, type)
-
column = create_column_definition name, type
-
limit = options.fetch(:limit) do
-
native[type][:limit] if native[type].is_a?(Hash)
-
end
-
-
column.limit = limit
-
column.precision = options[:precision]
-
column.scale = options[:scale]
-
column.default = options[:default]
-
column.null = options[:null]
-
column.first = options[:first]
-
column.after = options[:after]
-
column.primary_key = type == :primary_key || options[:primary_key]
-
column
-
end
-
-
1
private
-
1
def create_column_definition(name, type)
-
ColumnDefinition.new name, type
-
end
-
-
1
def native
-
@native
-
end
-
-
1
def aliased_types(name, fallback)
-
'timestamp' == name ? :datetime : fallback
-
end
-
end
-
-
1
class AlterTable # :nodoc:
-
1
attr_reader :adds
-
1
attr_reader :foreign_key_adds
-
1
attr_reader :foreign_key_drops
-
-
1
def initialize(td)
-
@td = td
-
@adds = []
-
@foreign_key_adds = []
-
@foreign_key_drops = []
-
end
-
-
1
def name; @td.name; end
-
-
1
def add_foreign_key(to_table, options)
-
@foreign_key_adds << ForeignKeyDefinition.new(name, to_table, options)
-
end
-
-
1
def drop_foreign_key(name)
-
@foreign_key_drops << name
-
end
-
-
1
def add_column(name, type, options)
-
name = name.to_s
-
type = type.to_sym
-
@adds << @td.new_column_definition(name, type, options)
-
end
-
end
-
-
# Represents an SQL table in an abstract way for updating a table.
-
# Also see TableDefinition and SchemaStatements#create_table
-
#
-
# Available transformations are:
-
#
-
# change_table :table do |t|
-
# t.column
-
# t.index
-
# t.rename_index
-
# t.timestamps
-
# t.change
-
# t.change_default
-
# t.rename
-
# t.references
-
# t.belongs_to
-
# t.string
-
# t.text
-
# t.integer
-
# t.float
-
# t.decimal
-
# t.datetime
-
# t.timestamp
-
# t.time
-
# t.date
-
# t.binary
-
# t.boolean
-
# t.remove
-
# t.remove_references
-
# t.remove_belongs_to
-
# t.remove_index
-
# t.remove_timestamps
-
# end
-
#
-
1
class Table
-
1
attr_reader :name
-
-
1
def initialize(table_name, base)
-
@name = table_name
-
@base = base
-
end
-
-
# Adds a new column to the named table.
-
# See TableDefinition#column for details of the options you can use.
-
#
-
# ====== Creating a simple column
-
# t.column(:name, :string)
-
1
def column(column_name, type, options = {})
-
@base.add_column(name, column_name, type, options)
-
end
-
-
# Checks to see if a column exists. See SchemaStatements#column_exists?
-
1
def column_exists?(column_name, type = nil, options = {})
-
@base.column_exists?(name, column_name, type, options)
-
end
-
-
# Adds a new index to the table. +column_name+ can be a single Symbol, or
-
# an Array of Symbols. See SchemaStatements#add_index
-
#
-
# ====== Creating a simple index
-
# t.index(:name)
-
# ====== Creating a unique index
-
# t.index([:branch_id, :party_id], unique: true)
-
# ====== Creating a named index
-
# t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')
-
1
def index(column_name, options = {})
-
@base.add_index(name, column_name, options)
-
end
-
-
# Checks to see if an index exists. See SchemaStatements#index_exists?
-
1
def index_exists?(column_name, options = {})
-
@base.index_exists?(name, column_name, options)
-
end
-
-
# Renames the given index on the table.
-
#
-
# t.rename_index(:user_id, :account_id)
-
1
def rename_index(index_name, new_index_name)
-
@base.rename_index(name, index_name, new_index_name)
-
end
-
-
# Adds timestamps (+created_at+ and +updated_at+) columns to the table. See SchemaStatements#add_timestamps
-
#
-
# t.timestamps null: false
-
1
def timestamps(options = {})
-
@base.add_timestamps(name, options)
-
end
-
-
# Changes the column's definition according to the new options.
-
# See TableDefinition#column for details of the options you can use.
-
#
-
# t.change(:name, :string, limit: 80)
-
# t.change(:description, :text)
-
1
def change(column_name, type, options = {})
-
@base.change_column(name, column_name, type, options)
-
end
-
-
# Sets a new default value for a column. See SchemaStatements#change_column_default
-
#
-
# t.change_default(:qualification, 'new')
-
# t.change_default(:authorized, 1)
-
1
def change_default(column_name, default)
-
@base.change_column_default(name, column_name, default)
-
end
-
-
# Removes the column(s) from the table definition.
-
#
-
# t.remove(:qualification)
-
# t.remove(:qualification, :experience)
-
1
def remove(*column_names)
-
@base.remove_columns(name, *column_names)
-
end
-
-
# Removes the given index from the table.
-
#
-
# ====== Remove the index_table_name_on_column in the table_name table
-
# t.remove_index :column
-
# ====== Remove the index named index_table_name_on_branch_id in the table_name table
-
# t.remove_index column: :branch_id
-
# ====== Remove the index named index_table_name_on_branch_id_and_party_id in the table_name table
-
# t.remove_index column: [:branch_id, :party_id]
-
# ====== Remove the index named by_branch_party in the table_name table
-
# t.remove_index name: :by_branch_party
-
1
def remove_index(options = {})
-
@base.remove_index(name, options)
-
end
-
-
# Removes the timestamp columns (+created_at+ and +updated_at+) from the table.
-
#
-
# t.remove_timestamps
-
1
def remove_timestamps(options = {})
-
@base.remove_timestamps(name, options)
-
end
-
-
# Renames a column.
-
#
-
# t.rename(:description, :name)
-
1
def rename(column_name, new_column_name)
-
@base.rename_column(name, column_name, new_column_name)
-
end
-
-
# Adds a reference.
-
#
-
# t.references(:user)
-
# t.belongs_to(:supplier, foreign_key: true)
-
#
-
# See SchemaStatements#add_reference for details of the options you can use.
-
1
def references(*args)
-
options = args.extract_options!
-
args.each do |ref_name|
-
@base.add_reference(name, ref_name, options)
-
end
-
end
-
1
alias :belongs_to :references
-
-
# Removes a reference. Optionally removes a +type+ column.
-
# <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
-
#
-
# t.remove_references(:user)
-
# t.remove_belongs_to(:supplier, polymorphic: true)
-
#
-
# See SchemaStatements#remove_reference
-
1
def remove_references(*args)
-
options = args.extract_options!
-
args.each do |ref_name|
-
@base.remove_reference(name, ref_name, options)
-
end
-
end
-
1
alias :remove_belongs_to :remove_references
-
-
# Adds a column or columns of a specified type
-
#
-
# t.string(:goat)
-
# t.string(:goat, :sheep)
-
1
[:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
-
11
define_method column_type do |*args|
-
options = args.extract_options!
-
args.each do |column_name|
-
@base.add_column(name, column_name, column_type, options)
-
end
-
end
-
end
-
-
1
private
-
1
def native
-
@base.native_database_types
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
# The goal of this module is to move Adapter specific column
-
# definitions to the Adapter instead of having it in the schema
-
# dumper itself. This code represents the normal case.
-
# We can then redefine how certain data types may be handled in the schema dumper on the
-
# Adapter level by over-writing this code inside the database specific adapters
-
1
module ColumnDumper
-
1
def column_spec(column, types)
-
spec = prepare_column_options(column, types)
-
(spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k}: ")}
-
spec
-
end
-
-
# This can be overridden on a Adapter level basis to support other
-
# extended datatypes (Example: Adding an array option in the
-
# PostgreSQLAdapter)
-
1
def prepare_column_options(column, types)
-
spec = {}
-
spec[:name] = column.name.inspect
-
spec[:type] = column.type.to_s
-
spec[:null] = 'false' unless column.null
-
-
limit = column.limit || types[column.type][:limit]
-
spec[:limit] = limit.inspect if limit
-
spec[:precision] = column.precision.inspect if column.precision
-
spec[:scale] = column.scale.inspect if column.scale
-
-
default = schema_default(column) if column.has_default?
-
spec[:default] = default unless default.nil?
-
-
spec
-
end
-
-
# Lists the valid migration options
-
1
def migration_keys
-
[:name, :limit, :precision, :scale, :default, :null]
-
end
-
-
1
private
-
-
1
def schema_default(column)
-
default = column.type_cast_from_database(column.default)
-
unless default.nil?
-
column.type_cast_for_schema(default)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_record/migration/join_table'
-
1
require 'active_support/core_ext/string/access'
-
1
require 'digest'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module SchemaStatements
-
1
include ActiveRecord::Migration::JoinTable
-
-
# Returns a hash of mappings from the abstract data types to the native
-
# database types. See TableDefinition#column for details on the recognized
-
# abstract data types.
-
1
def native_database_types
-
{}
-
end
-
-
# Truncates a table alias according to the limits of the current adapter.
-
1
def table_alias_for(table_name)
-
table_name[0...table_alias_length].tr('.', '_')
-
end
-
-
# Checks to see if the table +table_name+ exists on the database.
-
#
-
# table_exists?(:developers)
-
#
-
1
def table_exists?(table_name)
-
tables.include?(table_name.to_s)
-
end
-
-
# Returns an array of indexes for the given table.
-
# def indexes(table_name, name = nil) end
-
-
# Checks to see if an index exists on a table for a given index definition.
-
#
-
# # Check an index exists
-
# index_exists?(:suppliers, :company_id)
-
#
-
# # Check an index on multiple columns exists
-
# index_exists?(:suppliers, [:company_id, :company_type])
-
#
-
# # Check a unique index exists
-
# index_exists?(:suppliers, :company_id, unique: true)
-
#
-
# # Check an index with a custom name exists
-
# index_exists?(:suppliers, :company_id, name: "idx_company_id")
-
#
-
1
def index_exists?(table_name, column_name, options = {})
-
column_names = Array(column_name).map(&:to_s)
-
index_name = options.key?(:name) ? options[:name].to_s : index_name(table_name, column: column_names)
-
checks = []
-
checks << lambda { |i| i.name == index_name }
-
checks << lambda { |i| i.columns == column_names }
-
checks << lambda { |i| i.unique } if options[:unique]
-
-
indexes(table_name).any? { |i| checks.all? { |check| check[i] } }
-
end
-
-
# Returns an array of Column objects for the table specified by +table_name+.
-
# See the concrete implementation for details on the expected parameter values.
-
1
def columns(table_name) end
-
-
# Checks to see if a column exists in a given table.
-
#
-
# # Check a column exists
-
# column_exists?(:suppliers, :name)
-
#
-
# # Check a column exists of a particular type
-
# column_exists?(:suppliers, :name, :string)
-
#
-
# # Check a column exists with a specific definition
-
# column_exists?(:suppliers, :name, :string, limit: 100)
-
# column_exists?(:suppliers, :name, :string, default: 'default')
-
# column_exists?(:suppliers, :name, :string, null: false)
-
# column_exists?(:suppliers, :tax, :decimal, precision: 8, scale: 2)
-
#
-
1
def column_exists?(table_name, column_name, type = nil, options = {})
-
column_name = column_name.to_s
-
columns(table_name).any?{ |c| c.name == column_name &&
-
(!type || c.type == type) &&
-
(!options.key?(:limit) || c.limit == options[:limit]) &&
-
(!options.key?(:precision) || c.precision == options[:precision]) &&
-
(!options.key?(:scale) || c.scale == options[:scale]) &&
-
(!options.key?(:default) || c.default == options[:default]) &&
-
(!options.key?(:null) || c.null == options[:null]) }
-
end
-
-
# Creates a new table with the name +table_name+. +table_name+ may either
-
# be a String or a Symbol.
-
#
-
# There are two ways to work with +create_table+. You can use the block
-
# form or the regular form, like this:
-
#
-
# === Block form
-
#
-
# # create_table() passes a TableDefinition object to the block.
-
# # This form will not only create the table, but also columns for the
-
# # table.
-
#
-
# create_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# # Other fields here
-
# end
-
#
-
# === Block form, with shorthand
-
#
-
# # You can also use the column types as method calls, rather than calling the column method.
-
# create_table(:suppliers) do |t|
-
# t.string :name, limit: 60
-
# # Other fields here
-
# end
-
#
-
# === Regular form
-
#
-
# # Creates a table called 'suppliers' with no columns.
-
# create_table(:suppliers)
-
# # Add a column to 'suppliers'.
-
# add_column(:suppliers, :name, :string, {limit: 60})
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:id</tt>]
-
# Whether to automatically add a primary key column. Defaults to true.
-
# Join tables for +has_and_belongs_to_many+ should set it to false.
-
# [<tt>:primary_key</tt>]
-
# The name of the primary key, if one is to be added automatically.
-
# Defaults to +id+. If <tt>:id</tt> is false this option is ignored.
-
#
-
# Note that Active Record models will automatically detect their
-
# primary key. This can be avoided by using +self.primary_key=+ on the model
-
# to define the key explicitly.
-
#
-
# [<tt>:options</tt>]
-
# Any extra options you want appended to the table definition.
-
# [<tt>:temporary</tt>]
-
# Make a temporary table.
-
# [<tt>:force</tt>]
-
# Set to true to drop the table before creating it.
-
# Set to +:cascade+ to drop dependent objects as well.
-
# Defaults to false.
-
# [<tt>:as</tt>]
-
# SQL to use to generate the table. When this option is used, the block is
-
# ignored, as are the <tt>:id</tt> and <tt>:primary_key</tt> options.
-
#
-
# ====== Add a backend specific option to the generated SQL (MySQL)
-
#
-
# create_table(:suppliers, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
-
#
-
# generates:
-
#
-
# CREATE TABLE suppliers (
-
# id int(11) DEFAULT NULL auto_increment PRIMARY KEY
-
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8
-
#
-
# ====== Rename the primary key column
-
#
-
# create_table(:objects, primary_key: 'guid') do |t|
-
# t.column :name, :string, limit: 80
-
# end
-
#
-
# generates:
-
#
-
# CREATE TABLE objects (
-
# guid int(11) DEFAULT NULL auto_increment PRIMARY KEY,
-
# name varchar(80)
-
# )
-
#
-
# ====== Do not add a primary key column
-
#
-
# create_table(:categories_suppliers, id: false) do |t|
-
# t.column :category_id, :integer
-
# t.column :supplier_id, :integer
-
# end
-
#
-
# generates:
-
#
-
# CREATE TABLE categories_suppliers (
-
# category_id int,
-
# supplier_id int
-
# )
-
#
-
# ====== Create a temporary table based on a query
-
#
-
# create_table(:long_query, temporary: true,
-
# as: "SELECT * FROM orders INNER JOIN line_items ON order_id=orders.id")
-
#
-
# generates:
-
#
-
# CREATE TEMPORARY TABLE long_query AS
-
# SELECT * FROM orders INNER JOIN line_items ON order_id=orders.id
-
#
-
# See also TableDefinition#column for details on how to create columns.
-
1
def create_table(table_name, options = {})
-
td = create_table_definition table_name, options[:temporary], options[:options], options[:as]
-
-
if options[:id] != false && !options[:as]
-
pk = options.fetch(:primary_key) do
-
Base.get_primary_key table_name.to_s.singularize
-
end
-
-
td.primary_key pk, options.fetch(:id, :primary_key), options
-
end
-
-
yield td if block_given?
-
-
if options[:force] && table_exists?(table_name)
-
drop_table(table_name, options)
-
end
-
-
result = execute schema_creation.accept td
-
-
unless supports_indexes_in_create?
-
td.indexes.each_pair do |column_name, index_options|
-
add_index(table_name, column_name, index_options)
-
end
-
end
-
-
td.foreign_keys.each_pair do |other_table_name, foreign_key_options|
-
add_foreign_key(table_name, other_table_name, foreign_key_options)
-
end
-
-
result
-
end
-
-
# Creates a new join table with the name created using the lexical order of the first two
-
# arguments. These arguments can be a String or a Symbol.
-
#
-
# # Creates a table called 'assemblies_parts' with no id.
-
# create_join_table(:assemblies, :parts)
-
#
-
# You can pass a +options+ hash can include the following keys:
-
# [<tt>:table_name</tt>]
-
# Sets the table name overriding the default
-
# [<tt>:column_options</tt>]
-
# Any extra options you want appended to the columns definition.
-
# [<tt>:options</tt>]
-
# Any extra options you want appended to the table definition.
-
# [<tt>:temporary</tt>]
-
# Make a temporary table.
-
# [<tt>:force</tt>]
-
# Set to true to drop the table before creating it.
-
# Defaults to false.
-
#
-
# Note that +create_join_table+ does not create any indices by default; you can use
-
# its block form to do so yourself:
-
#
-
# create_join_table :products, :categories do |t|
-
# t.index :product_id
-
# t.index :category_id
-
# end
-
#
-
# ====== Add a backend specific option to the generated SQL (MySQL)
-
#
-
# create_join_table(:assemblies, :parts, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
-
#
-
# generates:
-
#
-
# CREATE TABLE assemblies_parts (
-
# assembly_id int NOT NULL,
-
# part_id int NOT NULL,
-
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8
-
#
-
1
def create_join_table(table_1, table_2, options = {})
-
join_table_name = find_join_table_name(table_1, table_2, options)
-
-
column_options = options.delete(:column_options) || {}
-
column_options.reverse_merge!(null: false)
-
-
t1_column, t2_column = [table_1, table_2].map{ |t| t.to_s.singularize.foreign_key }
-
-
create_table(join_table_name, options.merge!(id: false)) do |td|
-
td.integer t1_column, column_options
-
td.integer t2_column, column_options
-
yield td if block_given?
-
end
-
end
-
-
# Drops the join table specified by the given arguments.
-
# See +create_join_table+ for details.
-
#
-
# Although this command ignores the block if one is given, it can be helpful
-
# to provide one in a migration's +change+ method so it can be reverted.
-
# In that case, the block will be used by create_join_table.
-
1
def drop_join_table(table_1, table_2, options = {})
-
join_table_name = find_join_table_name(table_1, table_2, options)
-
drop_table(join_table_name)
-
end
-
-
# A block for changing columns in +table+.
-
#
-
# # change_table() yields a Table instance
-
# change_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# # Other column alterations here
-
# end
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:bulk</tt>]
-
# Set this to true to make this a bulk alter query, such as
-
#
-
# ALTER TABLE `users` ADD COLUMN age INT(11), ADD COLUMN birthdate DATETIME ...
-
#
-
# Defaults to false.
-
#
-
# ====== Add a column
-
#
-
# change_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# end
-
#
-
# ====== Add 2 integer columns
-
#
-
# change_table(:suppliers) do |t|
-
# t.integer :width, :height, null: false, default: 0
-
# end
-
#
-
# ====== Add created_at/updated_at columns
-
#
-
# change_table(:suppliers) do |t|
-
# t.timestamps
-
# end
-
#
-
# ====== Add a foreign key column
-
#
-
# change_table(:suppliers) do |t|
-
# t.references :company
-
# end
-
#
-
# Creates a <tt>company_id(integer)</tt> column.
-
#
-
# ====== Add a polymorphic foreign key column
-
#
-
# change_table(:suppliers) do |t|
-
# t.belongs_to :company, polymorphic: true
-
# end
-
#
-
# Creates <tt>company_type(varchar)</tt> and <tt>company_id(integer)</tt> columns.
-
#
-
# ====== Remove a column
-
#
-
# change_table(:suppliers) do |t|
-
# t.remove :company
-
# end
-
#
-
# ====== Remove several columns
-
#
-
# change_table(:suppliers) do |t|
-
# t.remove :company_id
-
# t.remove :width, :height
-
# end
-
#
-
# ====== Remove an index
-
#
-
# change_table(:suppliers) do |t|
-
# t.remove_index :company_id
-
# end
-
#
-
# See also Table for details on all of the various column transformation.
-
1
def change_table(table_name, options = {})
-
if supports_bulk_alter? && options[:bulk]
-
recorder = ActiveRecord::Migration::CommandRecorder.new(self)
-
yield update_table_definition(table_name, recorder)
-
bulk_change_table(table_name, recorder.commands)
-
else
-
yield update_table_definition(table_name, self)
-
end
-
end
-
-
# Renames a table.
-
#
-
# rename_table('octopuses', 'octopi')
-
#
-
1
def rename_table(table_name, new_name)
-
raise NotImplementedError, "rename_table is not implemented"
-
end
-
-
# Drops a table from the database.
-
#
-
# [<tt>:force</tt>]
-
# Set to +:cascade+ to drop dependent objects as well.
-
# Defaults to false.
-
#
-
# Although this command ignores most +options+ and the block if one is given,
-
# it can be helpful to provide these in a migration's +change+ method so it can be reverted.
-
# In that case, +options+ and the block will be used by create_table.
-
1
def drop_table(table_name, options = {})
-
execute "DROP TABLE #{quote_table_name(table_name)}"
-
end
-
-
# Adds a new column to the named table.
-
# See TableDefinition#column for details of the options you can use.
-
1
def add_column(table_name, column_name, type, options = {})
-
at = create_alter_table table_name
-
at.add_column(column_name, type, options)
-
execute schema_creation.accept at
-
end
-
-
# Removes the given columns from the table definition.
-
#
-
# remove_columns(:suppliers, :qualification, :experience)
-
#
-
1
def remove_columns(table_name, *column_names)
-
raise ArgumentError.new("You must specify at least one column name. Example: remove_columns(:people, :first_name)") if column_names.empty?
-
column_names.each do |column_name|
-
remove_column(table_name, column_name)
-
end
-
end
-
-
# Removes the column from the table definition.
-
#
-
# remove_column(:suppliers, :qualification)
-
#
-
# The +type+ and +options+ parameters will be ignored if present. It can be helpful
-
# to provide these in a migration's +change+ method so it can be reverted.
-
# In that case, +type+ and +options+ will be used by add_column.
-
1
def remove_column(table_name, column_name, type = nil, options = {})
-
execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{quote_column_name(column_name)}"
-
end
-
-
# Changes the column's definition according to the new options.
-
# See TableDefinition#column for details of the options you can use.
-
#
-
# change_column(:suppliers, :name, :string, limit: 80)
-
# change_column(:accounts, :description, :text)
-
#
-
1
def change_column(table_name, column_name, type, options = {})
-
raise NotImplementedError, "change_column is not implemented"
-
end
-
-
# Sets a new default value for a column:
-
#
-
# change_column_default(:suppliers, :qualification, 'new')
-
# change_column_default(:accounts, :authorized, 1)
-
#
-
# Setting the default to +nil+ effectively drops the default:
-
#
-
# change_column_default(:users, :email, nil)
-
#
-
1
def change_column_default(table_name, column_name, default)
-
raise NotImplementedError, "change_column_default is not implemented"
-
end
-
-
# Sets or removes a +NOT NULL+ constraint on a column. The +null+ flag
-
# indicates whether the value can be +NULL+. For example
-
#
-
# change_column_null(:users, :nickname, false)
-
#
-
# says nicknames cannot be +NULL+ (adds the constraint), whereas
-
#
-
# change_column_null(:users, :nickname, true)
-
#
-
# allows them to be +NULL+ (drops the constraint).
-
#
-
# The method accepts an optional fourth argument to replace existing
-
# +NULL+s with some other value. Use that one when enabling the
-
# constraint if needed, since otherwise those rows would not be valid.
-
#
-
# Please note the fourth argument does not set a column's default.
-
1
def change_column_null(table_name, column_name, null, default = nil)
-
raise NotImplementedError, "change_column_null is not implemented"
-
end
-
-
# Renames a column.
-
#
-
# rename_column(:suppliers, :description, :name)
-
#
-
1
def rename_column(table_name, column_name, new_column_name)
-
raise NotImplementedError, "rename_column is not implemented"
-
end
-
-
# Adds a new index to the table. +column_name+ can be a single Symbol, or
-
# an Array of Symbols.
-
#
-
# The index will be named after the table and the column name(s), unless
-
# you pass <tt>:name</tt> as an option.
-
#
-
# ====== Creating a simple index
-
#
-
# add_index(:suppliers, :name)
-
#
-
# generates:
-
#
-
# CREATE INDEX suppliers_name_index ON suppliers(name)
-
#
-
# ====== Creating a unique index
-
#
-
# add_index(:accounts, [:branch_id, :party_id], unique: true)
-
#
-
# generates:
-
#
-
# CREATE UNIQUE INDEX accounts_branch_id_party_id_index ON accounts(branch_id, party_id)
-
#
-
# ====== Creating a named index
-
#
-
# add_index(:accounts, [:branch_id, :party_id], unique: true, name: 'by_branch_party')
-
#
-
# generates:
-
#
-
# CREATE UNIQUE INDEX by_branch_party ON accounts(branch_id, party_id)
-
#
-
# ====== Creating an index with specific key length
-
#
-
# add_index(:accounts, :name, name: 'by_name', length: 10)
-
#
-
# generates:
-
#
-
# CREATE INDEX by_name ON accounts(name(10))
-
#
-
# add_index(:accounts, [:name, :surname], name: 'by_name_surname', length: {name: 10, surname: 15})
-
#
-
# generates:
-
#
-
# CREATE INDEX by_name_surname ON accounts(name(10), surname(15))
-
#
-
# Note: SQLite doesn't support index length.
-
#
-
# ====== Creating an index with a sort order (desc or asc, asc is the default)
-
#
-
# add_index(:accounts, [:branch_id, :party_id, :surname], order: {branch_id: :desc, party_id: :asc})
-
#
-
# generates:
-
#
-
# CREATE INDEX by_branch_desc_party ON accounts(branch_id DESC, party_id ASC, surname)
-
#
-
# Note: MySQL doesn't yet support index order (it accepts the syntax but ignores it).
-
#
-
# ====== Creating a partial index
-
#
-
# add_index(:accounts, [:branch_id, :party_id], unique: true, where: "active")
-
#
-
# generates:
-
#
-
# CREATE UNIQUE INDEX index_accounts_on_branch_id_and_party_id ON accounts(branch_id, party_id) WHERE active
-
#
-
# Note: Partial indexes are only supported for PostgreSQL and SQLite 3.8.0+.
-
#
-
# ====== Creating an index with a specific method
-
#
-
# add_index(:developers, :name, using: 'btree')
-
#
-
# generates:
-
#
-
# CREATE INDEX index_developers_on_name ON developers USING btree (name) -- PostgreSQL
-
# CREATE INDEX index_developers_on_name USING btree ON developers (name) -- MySQL
-
#
-
# Note: only supported by PostgreSQL and MySQL
-
#
-
# ====== Creating an index with a specific type
-
#
-
# add_index(:developers, :name, type: :fulltext)
-
#
-
# generates:
-
#
-
# CREATE FULLTEXT INDEX index_developers_on_name ON developers (name) -- MySQL
-
#
-
# Note: only supported by MySQL. Supported: <tt>:fulltext</tt> and <tt>:spatial</tt> on MyISAM tables.
-
1
def add_index(table_name, column_name, options = {})
-
index_name, index_type, index_columns, index_options = add_index_options(table_name, column_name, options)
-
execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})#{index_options}"
-
end
-
-
# Removes the given index from the table.
-
#
-
# Removes the +index_accounts_on_column+ in the +accounts+ table.
-
#
-
# remove_index :accounts, :column
-
#
-
# Removes the index named +index_accounts_on_branch_id+ in the +accounts+ table.
-
#
-
# remove_index :accounts, column: :branch_id
-
#
-
# Removes the index named +index_accounts_on_branch_id_and_party_id+ in the +accounts+ table.
-
#
-
# remove_index :accounts, column: [:branch_id, :party_id]
-
#
-
# Removes the index named +by_branch_party+ in the +accounts+ table.
-
#
-
# remove_index :accounts, name: :by_branch_party
-
#
-
1
def remove_index(table_name, options = {})
-
remove_index!(table_name, index_name_for_remove(table_name, options))
-
end
-
-
1
def remove_index!(table_name, index_name) #:nodoc:
-
execute "DROP INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)}"
-
end
-
-
# Renames an index.
-
#
-
# Rename the +index_people_on_last_name+ index to +index_users_on_last_name+:
-
#
-
# rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name'
-
#
-
1
def rename_index(table_name, old_name, new_name)
-
validate_index_length!(table_name, new_name)
-
-
# this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance)
-
old_index_def = indexes(table_name).detect { |i| i.name == old_name }
-
return unless old_index_def
-
add_index(table_name, old_index_def.columns, name: new_name, unique: old_index_def.unique)
-
remove_index(table_name, name: old_name)
-
end
-
-
1
def index_name(table_name, options) #:nodoc:
-
if Hash === options
-
if options[:column]
-
"index_#{table_name}_on_#{Array(options[:column]) * '_and_'}"
-
elsif options[:name]
-
options[:name]
-
else
-
raise ArgumentError, "You must specify the index name"
-
end
-
else
-
index_name(table_name, :column => options)
-
end
-
end
-
-
# Verifies the existence of an index with a given name.
-
#
-
# The default argument is returned if the underlying implementation does not define the indexes method,
-
# as there's no way to determine the correct answer in that case.
-
1
def index_name_exists?(table_name, index_name, default)
-
return default unless respond_to?(:indexes)
-
index_name = index_name.to_s
-
indexes(table_name).detect { |i| i.name == index_name }
-
end
-
-
# Adds a reference. The reference column is an integer by default,
-
# the <tt>:type</tt> option can be used to specify a different type.
-
# Optionally adds a +_type+ column, if <tt>:polymorphic</tt> option is provided.
-
# <tt>add_reference</tt> and <tt>add_belongs_to</tt> are acceptable.
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:type</tt>]
-
# The reference column type. Defaults to +:integer+.
-
# [<tt>:index</tt>]
-
# Add an appropriate index. Defaults to false.
-
# [<tt>:foreign_key</tt>]
-
# Add an appropriate foreign key. Defaults to false.
-
# [<tt>:polymorphic</tt>]
-
# Wether an additional +_type+ column should be added. Defaults to false.
-
#
-
# ====== Create a user_id integer column
-
#
-
# add_reference(:products, :user)
-
#
-
# ====== Create a user_id string column
-
#
-
# add_reference(:products, :user, type: :string)
-
#
-
# ====== Create supplier_id, supplier_type columns and appropriate index
-
#
-
# add_reference(:products, :supplier, polymorphic: true, index: true)
-
#
-
1
def add_reference(table_name, ref_name, options = {})
-
polymorphic = options.delete(:polymorphic)
-
index_options = options.delete(:index)
-
type = options.delete(:type) || :integer
-
foreign_key_options = options.delete(:foreign_key)
-
-
if polymorphic && foreign_key_options
-
raise ArgumentError, "Cannot add a foreign key to a polymorphic relation"
-
end
-
-
add_column(table_name, "#{ref_name}_id", type, options)
-
add_column(table_name, "#{ref_name}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
-
add_index(table_name, polymorphic ? %w[type id].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
-
if foreign_key_options
-
to_table = Base.pluralize_table_names ? ref_name.to_s.pluralize : ref_name
-
add_foreign_key(table_name, to_table, foreign_key_options.is_a?(Hash) ? foreign_key_options : {})
-
end
-
end
-
1
alias :add_belongs_to :add_reference
-
-
# Removes the reference(s). Also removes a +type+ column if one exists.
-
# <tt>remove_reference</tt>, <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
-
#
-
# ====== Remove the reference
-
#
-
# remove_reference(:products, :user, index: true)
-
#
-
# ====== Remove polymorphic reference
-
#
-
# remove_reference(:products, :supplier, polymorphic: true)
-
#
-
# ====== Remove the reference with a foreign key
-
#
-
# remove_reference(:products, :user, index: true, foreign_key: true)
-
#
-
1
def remove_reference(table_name, ref_name, options = {})
-
if options[:foreign_key]
-
to_table = Base.pluralize_table_names ? ref_name.to_s.pluralize : ref_name
-
remove_foreign_key(table_name, to_table)
-
end
-
-
remove_column(table_name, "#{ref_name}_id")
-
remove_column(table_name, "#{ref_name}_type") if options[:polymorphic]
-
end
-
1
alias :remove_belongs_to :remove_reference
-
-
# Returns an array of foreign keys for the given table.
-
# The foreign keys are represented as +ForeignKeyDefinition+ objects.
-
1
def foreign_keys(table_name)
-
raise NotImplementedError, "foreign_keys is not implemented"
-
end
-
-
# Adds a new foreign key. +from_table+ is the table with the key column,
-
# +to_table+ contains the referenced primary key.
-
#
-
# The foreign key will be named after the following pattern: <tt>fk_rails_<identifier></tt>.
-
# +identifier+ is a 10 character long string which is deterministically generated from the
-
# +from_table+ and +column+. A custom name can be specified with the <tt>:name</tt> option.
-
#
-
# ====== Creating a simple foreign key
-
#
-
# add_foreign_key :articles, :authors
-
#
-
# generates:
-
#
-
# ALTER TABLE "articles" ADD CONSTRAINT articles_author_id_fk FOREIGN KEY ("author_id") REFERENCES "authors" ("id")
-
#
-
# ====== Creating a foreign key on a specific column
-
#
-
# add_foreign_key :articles, :users, column: :author_id, primary_key: :lng_id
-
#
-
# generates:
-
#
-
# ALTER TABLE "articles" ADD CONSTRAINT fk_rails_58ca3d3a82 FOREIGN KEY ("author_id") REFERENCES "users" ("lng_id")
-
#
-
# ====== Creating a cascading foreign key
-
#
-
# add_foreign_key :articles, :authors, on_delete: :cascade
-
#
-
# generates:
-
#
-
# ALTER TABLE "articles" ADD CONSTRAINT articles_author_id_fk FOREIGN KEY ("author_id") REFERENCES "authors" ("id") ON DELETE CASCADE
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:column</tt>]
-
# The foreign key column name on +from_table+. Defaults to <tt>to_table.singularize + "_id"</tt>
-
# [<tt>:primary_key</tt>]
-
# The primary key column name on +to_table+. Defaults to +id+.
-
# [<tt>:name</tt>]
-
# The constraint name. Defaults to <tt>fk_rails_<identifier></tt>.
-
# [<tt>:on_delete</tt>]
-
# Action that happens <tt>ON DELETE</tt>. Valid values are +:nullify+, +:cascade:+ and +:restrict+
-
# [<tt>:on_update</tt>]
-
# Action that happens <tt>ON UPDATE</tt>. Valid values are +:nullify+, +:cascade:+ and +:restrict+
-
1
def add_foreign_key(from_table, to_table, options = {})
-
return unless supports_foreign_keys?
-
-
options[:column] ||= foreign_key_column_for(to_table)
-
-
options = {
-
column: options[:column],
-
primary_key: options[:primary_key],
-
name: foreign_key_name(from_table, options),
-
on_delete: options[:on_delete],
-
on_update: options[:on_update]
-
}
-
at = create_alter_table from_table
-
at.add_foreign_key to_table, options
-
-
execute schema_creation.accept(at)
-
end
-
-
# Removes the given foreign key from the table.
-
#
-
# Removes the foreign key on +accounts.branch_id+.
-
#
-
# remove_foreign_key :accounts, :branches
-
#
-
# Removes the foreign key on +accounts.owner_id+.
-
#
-
# remove_foreign_key :accounts, column: :owner_id
-
#
-
# Removes the foreign key named +special_fk_name+ on the +accounts+ table.
-
#
-
# remove_foreign_key :accounts, name: :special_fk_name
-
#
-
1
def remove_foreign_key(from_table, options_or_to_table = {})
-
return unless supports_foreign_keys?
-
-
if options_or_to_table.is_a?(Hash)
-
options = options_or_to_table
-
else
-
options = { column: foreign_key_column_for(options_or_to_table) }
-
end
-
-
fk_name_to_delete = options.fetch(:name) do
-
fk_to_delete = foreign_keys(from_table).detect {|fk| fk.column == options[:column].to_s }
-
-
if fk_to_delete
-
fk_to_delete.name
-
else
-
raise ArgumentError, "Table '#{from_table}' has no foreign key on column '#{options[:column]}'"
-
end
-
end
-
-
at = create_alter_table from_table
-
at.drop_foreign_key fk_name_to_delete
-
-
execute schema_creation.accept(at)
-
end
-
-
1
def foreign_key_column_for(table_name) # :nodoc:
-
prefix = Base.table_name_prefix
-
suffix = Base.table_name_suffix
-
name = table_name.to_s =~ /#{prefix}(.+)#{suffix}/ ? $1 : table_name.to_s
-
"#{name.singularize}_id"
-
end
-
-
1
def dump_schema_information #:nodoc:
-
sm_table = ActiveRecord::Migrator.schema_migrations_table_name
-
-
ActiveRecord::SchemaMigration.order('version').map { |sm|
-
"INSERT INTO #{sm_table} (version) VALUES ('#{sm.version}');"
-
}.join "\n\n"
-
end
-
-
# Should not be called normally, but this operation is non-destructive.
-
# The migrations module handles this automatically.
-
1
def initialize_schema_migrations_table
-
ActiveRecord::SchemaMigration.create_table
-
end
-
-
1
def assume_migrated_upto_version(version, migrations_paths = ActiveRecord::Migrator.migrations_paths)
-
migrations_paths = Array(migrations_paths)
-
version = version.to_i
-
sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)
-
-
migrated = select_values("SELECT version FROM #{sm_table}").map { |v| v.to_i }
-
paths = migrations_paths.map {|p| "#{p}/[0-9]*_*.rb" }
-
versions = Dir[*paths].map do |filename|
-
filename.split('/').last.split('_').first.to_i
-
end
-
-
unless migrated.include?(version)
-
execute "INSERT INTO #{sm_table} (version) VALUES ('#{version}')"
-
end
-
-
inserted = Set.new
-
(versions - migrated).each do |v|
-
if inserted.include?(v)
-
raise "Duplicate migration #{v}. Please renumber your migrations to resolve the conflict."
-
elsif v < version
-
execute "INSERT INTO #{sm_table} (version) VALUES ('#{v}')"
-
inserted << v
-
end
-
end
-
end
-
-
1
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
-
if native = native_database_types[type.to_sym]
-
column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup
-
-
if type == :decimal # ignore limit, use precision and scale
-
scale ||= native[:scale]
-
-
if precision ||= native[:precision]
-
if scale
-
column_type_sql << "(#{precision},#{scale})"
-
else
-
column_type_sql << "(#{precision})"
-
end
-
elsif scale
-
raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale is specified"
-
end
-
-
elsif (type != :primary_key) && (limit ||= native.is_a?(Hash) && native[:limit])
-
column_type_sql << "(#{limit})"
-
end
-
-
column_type_sql
-
else
-
type.to_s
-
end
-
end
-
-
# Given a set of columns and an ORDER BY clause, returns the columns for a SELECT DISTINCT.
-
# Both PostgreSQL and Oracle overrides this for custom DISTINCT syntax - they
-
# require the order columns appear in the SELECT.
-
#
-
# columns_for_distinct("posts.id", ["posts.created_at desc"])
-
1
def columns_for_distinct(columns, orders) #:nodoc:
-
columns
-
end
-
-
1
include TimestampDefaultDeprecation
-
# Adds timestamps (+created_at+ and +updated_at+) columns to +table_name+.
-
# Additional options (like <tt>null: false</tt>) are forwarded to #add_column.
-
#
-
# add_timestamps(:suppliers, null: false)
-
#
-
1
def add_timestamps(table_name, options = {})
-
emit_warning_if_null_unspecified(:add_timestamps, options)
-
add_column table_name, :created_at, :datetime, options
-
add_column table_name, :updated_at, :datetime, options
-
end
-
-
# Removes the timestamp columns (+created_at+ and +updated_at+) from the table definition.
-
#
-
# remove_timestamps(:suppliers)
-
#
-
1
def remove_timestamps(table_name, options = {})
-
remove_column table_name, :updated_at
-
remove_column table_name, :created_at
-
end
-
-
1
def update_table_definition(table_name, base) #:nodoc:
-
Table.new(table_name, base)
-
end
-
-
1
def add_index_options(table_name, column_name, options = {}) #:nodoc:
-
column_names = Array(column_name)
-
index_name = index_name(table_name, column: column_names)
-
-
options.assert_valid_keys(:unique, :order, :name, :where, :length, :internal, :using, :algorithm, :type)
-
-
index_type = options[:unique] ? "UNIQUE" : ""
-
index_type = options[:type].to_s if options.key?(:type)
-
index_name = options[:name].to_s if options.key?(:name)
-
max_index_length = options.fetch(:internal, false) ? index_name_length : allowed_index_name_length
-
-
if options.key?(:algorithm)
-
algorithm = index_algorithms.fetch(options[:algorithm]) {
-
raise ArgumentError.new("Algorithm must be one of the following: #{index_algorithms.keys.map(&:inspect).join(', ')}")
-
}
-
end
-
-
using = "USING #{options[:using]}" if options[:using].present?
-
-
if supports_partial_index?
-
index_options = options[:where] ? " WHERE #{options[:where]}" : ""
-
end
-
-
if index_name.length > max_index_length
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{max_index_length} characters"
-
end
-
if table_exists?(table_name) && index_name_exists?(table_name, index_name, false)
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
-
end
-
index_columns = quoted_columns_for_index(column_names, options).join(", ")
-
-
[index_name, index_type, index_columns, index_options, algorithm, using]
-
end
-
-
1
protected
-
1
def add_index_sort_order(option_strings, column_names, options = {})
-
if options.is_a?(Hash) && order = options[:order]
-
case order
-
when Hash
-
column_names.each {|name| option_strings[name] += " #{order[name].upcase}" if order.has_key?(name)}
-
when String
-
column_names.each {|name| option_strings[name] += " #{order.upcase}"}
-
end
-
end
-
-
return option_strings
-
end
-
-
# Overridden by the MySQL adapter for supporting index lengths
-
1
def quoted_columns_for_index(column_names, options = {})
-
option_strings = Hash[column_names.map {|name| [name, '']}]
-
-
# add index sort order if supported
-
if supports_index_sort_order?
-
option_strings = add_index_sort_order(option_strings, column_names, options)
-
end
-
-
column_names.map {|name| quote_column_name(name) + option_strings[name]}
-
end
-
-
1
def options_include_default?(options)
-
options.include?(:default) && !(options[:null] == false && options[:default].nil?)
-
end
-
-
1
def index_name_for_remove(table_name, options = {})
-
index_name = index_name(table_name, options)
-
-
unless index_name_exists?(table_name, index_name, true)
-
if options.is_a?(Hash) && options.has_key?(:name)
-
options_without_column = options.dup
-
options_without_column.delete :column
-
index_name_without_column = index_name(table_name, options_without_column)
-
-
return index_name_without_column if index_name_exists?(table_name, index_name_without_column, false)
-
end
-
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
-
end
-
-
index_name
-
end
-
-
1
def rename_table_indexes(table_name, new_name)
-
indexes(new_name).each do |index|
-
generated_index_name = index_name(table_name, column: index.columns)
-
if generated_index_name == index.name
-
rename_index new_name, generated_index_name, index_name(new_name, column: index.columns)
-
end
-
end
-
end
-
-
1
def rename_column_indexes(table_name, column_name, new_column_name)
-
column_name, new_column_name = column_name.to_s, new_column_name.to_s
-
indexes(table_name).each do |index|
-
next unless index.columns.include?(new_column_name)
-
old_columns = index.columns.dup
-
old_columns[old_columns.index(new_column_name)] = column_name
-
generated_index_name = index_name(table_name, column: old_columns)
-
if generated_index_name == index.name
-
rename_index table_name, generated_index_name, index_name(table_name, column: index.columns)
-
end
-
end
-
end
-
-
1
private
-
1
def create_table_definition(name, temporary, options, as = nil)
-
TableDefinition.new native_database_types, name, temporary, options, as
-
end
-
-
1
def create_alter_table(name)
-
AlterTable.new create_table_definition(name, false, {})
-
end
-
-
1
def foreign_key_name(table_name, options) # :nodoc:
-
identifier = "#{table_name}_#{options.fetch(:column)}_fk"
-
hashed_identifier = Digest::SHA256.hexdigest(identifier).first(10)
-
options.fetch(:name) do
-
"fk_rails_#{hashed_identifier}"
-
end
-
end
-
-
1
def validate_index_length!(table_name, new_name)
-
if new_name.length > allowed_index_name_length
-
raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters"
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class TransactionState
-
1
attr_reader :parent
-
-
1
VALID_STATES = Set.new([:committed, :rolledback, nil])
-
-
1
def initialize(state = nil)
-
68
@state = state
-
68
@parent = nil
-
end
-
-
1
def finalized?
-
89
@state
-
end
-
-
1
def committed?
-
36
@state == :committed
-
end
-
-
1
def rolledback?
-
14
@state == :rolledback
-
end
-
-
1
def completed?
-
committed? || rolledback?
-
end
-
-
1
def set_state(state)
-
68
if !VALID_STATES.include?(state)
-
raise ArgumentError, "Invalid transaction state: #{state}"
-
end
-
68
@state = state
-
end
-
end
-
-
1
class NullTransaction #:nodoc:
-
1
def initialize; end
-
1
def closed?; true; end
-
1
def open?; false; end
-
19
def joinable?; false; end
-
1
def add_record(record); end
-
end
-
-
1
class Transaction #:nodoc:
-
-
1
attr_reader :connection, :state, :records, :savepoint_name
-
1
attr_writer :joinable
-
-
1
def initialize(connection, options)
-
68
@connection = connection
-
68
@state = TransactionState.new
-
68
@records = []
-
68
@joinable = options.fetch(:joinable, true)
-
end
-
-
1
def add_record(record)
-
6
records << record
-
end
-
-
1
def rollback
-
18
@state.set_state(:rolledback)
-
end
-
-
1
def rollback_records
-
18
ite = records.uniq
-
18
while record = ite.shift
-
3
begin
-
3
record.rolledback! full_rollback?
-
rescue => e
-
raise if ActiveRecord::Base.raise_in_transactional_callbacks
-
record.logger.error(e) if record.respond_to?(:logger) && record.logger
-
end
-
end
-
ensure
-
18
ite.each do |i|
-
i.rolledback!(full_rollback?, false)
-
end
-
end
-
-
1
def commit
-
50
@state.set_state(:committed)
-
end
-
-
1
def commit_records
-
18
ite = records.uniq
-
18
while record = ite.shift
-
begin
-
record.committed!
-
rescue => e
-
raise if ActiveRecord::Base.raise_in_transactional_callbacks
-
record.logger.error(e) if record.respond_to?(:logger) && record.logger
-
end
-
end
-
ensure
-
18
ite.each do |i|
-
i.committed!(false)
-
end
-
end
-
-
4
def full_rollback?; true; end
-
37
def joinable?; @joinable; end
-
1
def closed?; false; end
-
1
def open?; !closed?; end
-
end
-
-
1
class SavepointTransaction < Transaction
-
-
1
def initialize(connection, savepoint_name, options)
-
32
super(connection, options)
-
32
if options[:isolation]
-
raise ActiveRecord::TransactionIsolationError, "cannot set transaction isolation in a nested transaction"
-
end
-
32
connection.create_savepoint(@savepoint_name = savepoint_name)
-
end
-
-
1
def rollback
-
connection.rollback_to_savepoint(savepoint_name)
-
super
-
rollback_records
-
end
-
-
1
def commit
-
32
connection.release_savepoint(savepoint_name)
-
32
super
-
32
parent = connection.transaction_manager.current_transaction
-
35
records.each { |r| parent.add_record(r) }
-
end
-
-
1
def full_rollback?; false; end
-
end
-
-
1
class RealTransaction < Transaction
-
-
1
def initialize(connection, options)
-
36
super
-
36
if options[:isolation]
-
connection.begin_isolated_db_transaction(options[:isolation])
-
else
-
36
connection.begin_db_transaction
-
end
-
end
-
-
1
def rollback
-
18
connection.rollback_db_transaction
-
18
super
-
18
rollback_records
-
end
-
-
1
def commit
-
18
connection.commit_db_transaction
-
18
super
-
18
commit_records
-
end
-
end
-
-
1
class TransactionManager #:nodoc:
-
1
def initialize(connection)
-
1
@stack = []
-
1
@connection = connection
-
end
-
-
1
def begin_transaction(options = {})
-
68
transaction =
-
if @stack.empty?
-
36
RealTransaction.new(@connection, options)
-
else
-
32
SavepointTransaction.new(@connection, "active_record_#{@stack.size}", options)
-
end
-
68
@stack.push(transaction)
-
68
transaction
-
end
-
-
1
def commit_transaction
-
50
@stack.pop.commit
-
end
-
-
1
def rollback_transaction
-
18
@stack.pop.rollback
-
end
-
-
1
def within_new_transaction(options = {})
-
50
transaction = begin_transaction options
-
50
yield
-
rescue Exception => error
-
rollback_transaction if transaction
-
raise
-
ensure
-
50
unless error
-
50
if Thread.current.status == 'aborting'
-
rollback_transaction if transaction
-
else
-
50
begin
-
50
commit_transaction
-
rescue Exception
-
transaction.rollback unless transaction.state.completed?
-
raise
-
end
-
end
-
end
-
end
-
-
1
def open_transactions
-
18
@stack.size
-
end
-
-
1
def current_transaction
-
125
@stack.last || NULL_TRANSACTION
-
end
-
-
1
private
-
1
NULL_TRANSACTION = NullTransaction.new
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'bigdecimal'
-
1
require 'bigdecimal/util'
-
1
require 'active_record/type'
-
1
require 'active_support/core_ext/benchmark'
-
1
require 'active_record/connection_adapters/schema_cache'
-
1
require 'active_record/connection_adapters/abstract/schema_dumper'
-
1
require 'active_record/connection_adapters/abstract/schema_creation'
-
1
require 'monitor'
-
1
require 'arel/collectors/bind'
-
1
require 'arel/collectors/sql_string'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Column
-
1
autoload :ConnectionSpecification
-
-
1
autoload_at 'active_record/connection_adapters/abstract/schema_definitions' do
-
1
autoload :IndexDefinition
-
1
autoload :ColumnDefinition
-
1
autoload :ChangeColumnDefinition
-
1
autoload :TableDefinition
-
1
autoload :Table
-
1
autoload :AlterTable
-
1
autoload :TimestampDefaultDeprecation
-
end
-
-
1
autoload_at 'active_record/connection_adapters/abstract/connection_pool' do
-
1
autoload :ConnectionHandler
-
1
autoload :ConnectionManagement
-
end
-
-
1
autoload_under 'abstract' do
-
1
autoload :SchemaStatements
-
1
autoload :DatabaseStatements
-
1
autoload :DatabaseLimits
-
1
autoload :Quoting
-
1
autoload :ConnectionPool
-
1
autoload :QueryCache
-
1
autoload :Savepoints
-
end
-
-
1
autoload_at 'active_record/connection_adapters/abstract/transaction' do
-
1
autoload :TransactionManager
-
1
autoload :NullTransaction
-
1
autoload :RealTransaction
-
1
autoload :SavepointTransaction
-
1
autoload :TransactionState
-
end
-
-
# Active Record supports multiple database systems. AbstractAdapter and
-
# related classes form the abstraction layer which makes this possible.
-
# An AbstractAdapter represents a connection to a database, and provides an
-
# abstract interface for database-specific functionality such as establishing
-
# a connection, escaping values, building the right SQL fragments for ':offset'
-
# and ':limit' options, etc.
-
#
-
# All the concrete database adapters follow the interface laid down in this class.
-
# ActiveRecord::Base.connection returns an AbstractAdapter object, which
-
# you can use.
-
#
-
# Most of the methods in the adapter are useful during migrations. Most
-
# notably, the instance methods provided by SchemaStatement are very useful.
-
1
class AbstractAdapter
-
1
ADAPTER_NAME = 'Abstract'.freeze
-
1
include Quoting, DatabaseStatements, SchemaStatements
-
1
include DatabaseLimits
-
1
include QueryCache
-
1
include ActiveSupport::Callbacks
-
1
include MonitorMixin
-
1
include ColumnDumper
-
-
1
SIMPLE_INT = /\A\d+\z/
-
-
1
define_callbacks :checkout, :checkin
-
-
1
attr_accessor :visitor, :pool
-
1
attr_reader :schema_cache, :owner, :logger
-
1
alias :in_use? :owner
-
-
1
def self.type_cast_config_to_integer(config)
-
2
if config =~ SIMPLE_INT
-
config.to_i
-
else
-
2
config
-
end
-
end
-
-
1
def self.type_cast_config_to_boolean(config)
-
1
if config == "false"
-
false
-
else
-
1
config
-
end
-
end
-
-
1
attr_reader :prepared_statements
-
-
1
def initialize(connection, logger = nil, pool = nil) #:nodoc:
-
1
super()
-
-
1
@connection = connection
-
1
@owner = nil
-
1
@instrumenter = ActiveSupport::Notifications.instrumenter
-
1
@logger = logger
-
1
@pool = pool
-
1
@schema_cache = SchemaCache.new self
-
1
@visitor = nil
-
1
@prepared_statements = false
-
end
-
-
1
class BindCollector < Arel::Collectors::Bind
-
1
def compile(bvs, conn)
-
super(bvs.map { |bv| conn.quote(*bv.reverse) })
-
end
-
end
-
-
1
class SQLString < Arel::Collectors::SQLString
-
1
def compile(bvs, conn)
-
56
super(bvs)
-
end
-
end
-
-
1
def collector
-
56
if prepared_statements
-
56
SQLString.new
-
else
-
BindCollector.new
-
end
-
end
-
-
1
def valid_type?(type)
-
true
-
end
-
-
1
def schema_creation
-
SchemaCreation.new self
-
end
-
-
1
def lease
-
1
synchronize do
-
1
unless in_use?
-
1
@owner = Thread.current
-
end
-
end
-
end
-
-
1
def schema_cache=(cache)
-
cache.connection = self
-
@schema_cache = cache
-
end
-
-
1
def expire
-
@owner = nil
-
end
-
-
1
def unprepared_statement
-
old_prepared_statements, @prepared_statements = @prepared_statements, false
-
yield
-
ensure
-
@prepared_statements = old_prepared_statements
-
end
-
-
# Returns the human-readable name of the adapter. Use mixed case - one
-
# can always use downcase if needed.
-
1
def adapter_name
-
self.class::ADAPTER_NAME
-
end
-
-
# Does this adapter support migrations?
-
1
def supports_migrations?
-
false
-
end
-
-
# Can this adapter determine the primary key for tables not attached
-
# to an Active Record class, such as join tables?
-
1
def supports_primary_key?
-
false
-
end
-
-
# Does this adapter support DDL rollbacks in transactions? That is, would
-
# CREATE TABLE or ALTER TABLE get rolled back by a transaction?
-
1
def supports_ddl_transactions?
-
false
-
end
-
-
1
def supports_bulk_alter?
-
false
-
end
-
-
# Does this adapter support savepoints?
-
1
def supports_savepoints?
-
false
-
end
-
-
# Should primary key values be selected from their corresponding
-
# sequence before the insert statement? If true, next_sequence_value
-
# is called before each insert to set the record's primary key.
-
1
def prefetch_primary_key?(table_name = nil)
-
25
false
-
end
-
-
# Does this adapter support index sort order?
-
1
def supports_index_sort_order?
-
false
-
end
-
-
# Does this adapter support partial indices?
-
1
def supports_partial_index?
-
false
-
end
-
-
# Does this adapter support explain?
-
1
def supports_explain?
-
false
-
end
-
-
# Does this adapter support setting the isolation level for a transaction?
-
1
def supports_transaction_isolation?
-
false
-
end
-
-
# Does this adapter support database extensions?
-
1
def supports_extensions?
-
false
-
end
-
-
# Does this adapter support creating indexes in the same statement as
-
# creating the table?
-
1
def supports_indexes_in_create?
-
false
-
end
-
-
# Does this adapter support creating foreign key constraints?
-
1
def supports_foreign_keys?
-
false
-
end
-
-
# Does this adapter support views?
-
1
def supports_views?
-
false
-
end
-
-
# This is meant to be implemented by the adapters that support extensions
-
1
def disable_extension(name)
-
end
-
-
# This is meant to be implemented by the adapters that support extensions
-
1
def enable_extension(name)
-
end
-
-
# A list of extensions, to be filled in by adapters that support them.
-
1
def extensions
-
[]
-
end
-
-
# A list of index algorithms, to be filled by adapters that support them.
-
1
def index_algorithms
-
{}
-
end
-
-
# QUOTING ==================================================
-
-
# Returns a bind substitution value given a bind +column+
-
# NOTE: The column param is currently being used by the sqlserver-adapter
-
1
def substitute_at(column, _unused = 0)
-
150
Arel::Nodes::BindParam.new
-
end
-
-
# REFERENTIAL INTEGRITY ====================================
-
-
# Override to turn off referential integrity while executing <tt>&block</tt>.
-
1
def disable_referential_integrity
-
yield
-
end
-
-
# CONNECTION MANAGEMENT ====================================
-
-
# Checks whether the connection to the database is still active. This includes
-
# checking whether the database is actually capable of responding, i.e. whether
-
# the connection isn't stale.
-
1
def active?
-
end
-
-
# Disconnects from the database if already connected, and establishes a
-
# new connection with the database. Implementors should call super if they
-
# override the default implementation.
-
1
def reconnect!
-
clear_cache!
-
reset_transaction
-
end
-
-
# Disconnects from the database if already connected. Otherwise, this
-
# method does nothing.
-
1
def disconnect!
-
clear_cache!
-
reset_transaction
-
end
-
-
# Reset the state of this connection, directing the DBMS to clear
-
# transactions and other connection-related server-side state. Usually a
-
# database-dependent operation.
-
#
-
# The default implementation does nothing; the implementation should be
-
# overridden by concrete adapters.
-
1
def reset!
-
# this should be overridden by concrete adapters
-
end
-
-
###
-
# Clear any caching the database adapter may be doing, for example
-
# clearing the prepared statement cache. This is database specific.
-
1
def clear_cache!
-
# this should be overridden by concrete adapters
-
end
-
-
# Returns true if its required to reload the connection between requests for development mode.
-
1
def requires_reloading?
-
false
-
end
-
-
# Checks whether the connection to the database is still active (i.e. not stale).
-
# This is done under the hood by calling <tt>active?</tt>. If the connection
-
# is no longer active, then this method will reconnect to the database.
-
1
def verify!(*ignored)
-
1
reconnect! unless active?
-
end
-
-
# Provides access to the underlying database driver for this adapter. For
-
# example, this method returns a Mysql object in case of MysqlAdapter,
-
# and a PGconn object in case of PostgreSQLAdapter.
-
#
-
# This is useful for when you need to call a proprietary method such as
-
# PostgreSQL's lo_* methods.
-
1
def raw_connection
-
@connection
-
end
-
-
1
def create_savepoint(name = nil)
-
end
-
-
1
def release_savepoint(name = nil)
-
end
-
-
1
def case_sensitive_modifier(node, table_attribute)
-
node
-
end
-
-
1
def case_sensitive_comparison(table, attribute, column, value)
-
table_attr = table[attribute]
-
value = case_sensitive_modifier(value, table_attr) unless value.nil?
-
table_attr.eq(value)
-
end
-
-
1
def case_insensitive_comparison(table, attribute, column, value)
-
table[attribute].lower.eq(table.lower(value))
-
end
-
-
1
def current_savepoint_name
-
current_transaction.savepoint_name
-
end
-
-
# Check the connection back in to the connection pool
-
1
def close
-
pool.checkin self
-
end
-
-
1
def type_map # :nodoc:
-
@type_map ||= Type::TypeMap.new.tap do |mapping|
-
1
initialize_type_map(mapping)
-
28
end
-
end
-
-
1
def new_column(name, default, cast_type, sql_type = nil, null = true)
-
28
Column.new(name, default, cast_type, sql_type, null)
-
end
-
-
1
def lookup_cast_type(sql_type) # :nodoc:
-
28
type_map.lookup(sql_type)
-
end
-
-
1
def column_name_for_operation(operation, node) # :nodoc:
-
visitor.accept(node, collector).value
-
end
-
-
1
protected
-
-
1
def initialize_type_map(m) # :nodoc:
-
1
register_class_with_limit m, %r(boolean)i, Type::Boolean
-
1
register_class_with_limit m, %r(char)i, Type::String
-
1
register_class_with_limit m, %r(binary)i, Type::Binary
-
1
register_class_with_limit m, %r(text)i, Type::Text
-
1
register_class_with_limit m, %r(date)i, Type::Date
-
1
register_class_with_limit m, %r(time)i, Type::Time
-
1
register_class_with_limit m, %r(datetime)i, Type::DateTime
-
1
register_class_with_limit m, %r(float)i, Type::Float
-
1
register_class_with_limit m, %r(int)i, Type::Integer
-
-
1
m.alias_type %r(blob)i, 'binary'
-
1
m.alias_type %r(clob)i, 'text'
-
1
m.alias_type %r(timestamp)i, 'datetime'
-
1
m.alias_type %r(numeric)i, 'decimal'
-
1
m.alias_type %r(number)i, 'decimal'
-
1
m.alias_type %r(double)i, 'float'
-
-
1
m.register_type(%r(decimal)i) do |sql_type|
-
scale = extract_scale(sql_type)
-
precision = extract_precision(sql_type)
-
-
if scale == 0
-
# FIXME: Remove this class as well
-
Type::DecimalWithoutScale.new(precision: precision)
-
else
-
Type::Decimal.new(precision: precision, scale: scale)
-
end
-
end
-
end
-
-
1
def reload_type_map # :nodoc:
-
type_map.clear
-
initialize_type_map(type_map)
-
end
-
-
1
def register_class_with_limit(mapping, key, klass) # :nodoc:
-
9
mapping.register_type(key) do |*args|
-
5
limit = extract_limit(args.last)
-
5
klass.new(limit: limit)
-
end
-
end
-
-
1
def extract_scale(sql_type) # :nodoc:
-
case sql_type
-
when /\((\d+)\)/ then 0
-
when /\((\d+)(,(\d+))\)/ then $3.to_i
-
end
-
end
-
-
1
def extract_precision(sql_type) # :nodoc:
-
$1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/
-
end
-
-
1
def extract_limit(sql_type) # :nodoc:
-
5
case sql_type
-
when /^bigint/i
-
8
-
when /\((.*)\)/
-
$1.to_i
-
end
-
end
-
-
1
def translate_exception_class(e, sql)
-
begin
-
message = "#{e.class.name}: #{e.message}: #{sql}"
-
rescue Encoding::CompatibilityError
-
message = "#{e.class.name}: #{e.message.force_encoding sql.encoding}: #{sql}"
-
end
-
-
exception = translate_exception(e, message)
-
exception.set_backtrace e.backtrace
-
exception
-
end
-
-
1
def log(sql, name = "SQL", binds = [], statement_name = nil)
-
@instrumenter.instrument(
-
"sql.active_record",
-
:sql => sql,
-
:name => name,
-
:connection_id => object_id,
-
:statement_name => statement_name,
-
450
:binds => binds) { yield }
-
rescue => e
-
raise translate_exception_class(e, sql)
-
end
-
-
1
def translate_exception(exception, message)
-
# override in derived class
-
ActiveRecord::StatementInvalid.new(message, exception)
-
end
-
-
1
def without_prepared_statement?(binds)
-
89
!prepared_statements || binds.empty?
-
end
-
-
1
def column_for(table_name, column_name) # :nodoc:
-
column_name = column_name.to_s
-
columns(table_name).detect { |c| c.name == column_name } ||
-
raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}")
-
end
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module ActiveRecord
-
# :stopdoc:
-
1
module ConnectionAdapters
-
# An abstract definition of a column in a table.
-
1
class Column
-
1
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON'].to_set
-
1
FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE', 'off', 'OFF'].to_set
-
-
1
module Format
-
1
ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
-
1
ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
-
end
-
-
1
attr_reader :name, :cast_type, :null, :sql_type, :default, :default_function
-
-
1
delegate :type, :precision, :scale, :limit, :klass, :accessor,
-
:text?, :number?, :binary?, :changed?,
-
:type_cast_from_user, :type_cast_from_database, :type_cast_for_database,
-
:type_cast_for_schema,
-
to: :cast_type
-
-
# Instantiates a new column in the table.
-
#
-
# +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
-
# +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
-
# +cast_type+ is the object used for type casting and type information.
-
# +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
-
# <tt>company_name varchar(60)</tt>.
-
# It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
-
# +null+ determines if this column allows +NULL+ values.
-
1
def initialize(name, default, cast_type, sql_type = nil, null = true)
-
28
@name = name.freeze
-
28
@cast_type = cast_type
-
28
@sql_type = sql_type
-
28
@null = null
-
28
@default = default
-
28
@default_function = nil
-
end
-
-
1
def has_default?
-
!default.nil?
-
end
-
-
# Returns the human name of the column name.
-
#
-
# ===== Examples
-
# Column.new('sales_stage', ...).human_name # => 'Sales stage'
-
1
def human_name
-
Base.human_attribute_name(@name)
-
end
-
-
1
def with_type(type)
-
28
dup.tap do |clone|
-
28
clone.instance_variable_set('@cast_type', type)
-
end
-
end
-
-
1
def ==(other)
-
other.name == name &&
-
other.default == default &&
-
other.cast_type == cast_type &&
-
other.sql_type == sql_type &&
-
other.null == null &&
-
other.default_function == default_function
-
end
-
1
alias :eql? :==
-
-
1
def hash
-
22
attributes_for_hash.hash
-
end
-
-
1
private
-
-
1
def attributes_for_hash
-
22
[self.class, name, default, cast_type, sql_type, null, default_function]
-
end
-
end
-
end
-
# :startdoc:
-
end
-
1
require 'uri'
-
1
require 'active_support/core_ext/string/filters'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class ConnectionSpecification #:nodoc:
-
1
attr_reader :config, :adapter_method
-
-
1
def initialize(config, adapter_method)
-
1
@config, @adapter_method = config, adapter_method
-
end
-
-
1
def initialize_dup(original)
-
@config = original.config.dup
-
end
-
-
# Expands a connection string into a hash.
-
1
class ConnectionUrlResolver # :nodoc:
-
-
# == Example
-
#
-
# url = "postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000"
-
# ConnectionUrlResolver.new(url).to_hash
-
# # => {
-
# "adapter" => "postgresql",
-
# "host" => "localhost",
-
# "port" => 9000,
-
# "database" => "foo_test",
-
# "username" => "foo",
-
# "password" => "bar",
-
# "pool" => "5",
-
# "timeout" => "3000"
-
# }
-
1
def initialize(url)
-
raise "Database URL cannot be empty" if url.blank?
-
@uri = uri_parser.parse(url)
-
@adapter = @uri.scheme.tr('-', '_')
-
@adapter = "postgresql" if @adapter == "postgres"
-
-
if @uri.opaque
-
@uri.opaque, @query = @uri.opaque.split('?', 2)
-
else
-
@query = @uri.query
-
end
-
end
-
-
# Converts the given URL to a full connection hash.
-
1
def to_hash
-
config = raw_config.reject { |_,value| value.blank? }
-
config.map { |key,value| config[key] = uri_parser.unescape(value) if value.is_a? String }
-
config
-
end
-
-
1
private
-
-
1
def uri
-
@uri
-
end
-
-
1
def uri_parser
-
@uri_parser ||= URI::Parser.new
-
end
-
-
# Converts the query parameters of the URI into a hash.
-
#
-
# "localhost?pool=5&reaping_frequency=2"
-
# # => { "pool" => "5", "reaping_frequency" => "2" }
-
#
-
# returns empty hash if no query present.
-
#
-
# "localhost"
-
# # => {}
-
1
def query_hash
-
Hash[(@query || '').split("&").map { |pair| pair.split("=") }]
-
end
-
-
1
def raw_config
-
if uri.opaque
-
query_hash.merge({
-
"adapter" => @adapter,
-
"database" => uri.opaque })
-
else
-
query_hash.merge({
-
"adapter" => @adapter,
-
"username" => uri.user,
-
"password" => uri.password,
-
"port" => uri.port,
-
"database" => database_from_path,
-
"host" => uri.hostname })
-
end
-
end
-
-
# Returns name of the database.
-
1
def database_from_path
-
if @adapter == 'sqlite3'
-
# 'sqlite3:/foo' is absolute, because that makes sense. The
-
# corresponding relative version, 'sqlite3:foo', is handled
-
# elsewhere, as an "opaque".
-
-
uri.path
-
else
-
# Only SQLite uses a filename as the "database" name; for
-
# anything else, a leading slash would be silly.
-
-
uri.path.sub(%r{^/}, "")
-
end
-
end
-
end
-
-
##
-
# Builds a ConnectionSpecification from user input.
-
1
class Resolver # :nodoc:
-
1
attr_reader :configurations
-
-
# Accepts a hash two layers deep, keys on the first layer represent
-
# environments such as "production". Keys must be strings.
-
1
def initialize(configurations)
-
3
@configurations = configurations
-
end
-
-
# Returns a hash with database connection information.
-
#
-
# == Examples
-
#
-
# Full hash Configuration.
-
#
-
# configurations = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } }
-
# Resolver.new(configurations).resolve(:production)
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3"}
-
#
-
# Initialized with URL configuration strings.
-
#
-
# configurations = { "production" => "postgresql://localhost/foo" }
-
# Resolver.new(configurations).resolve(:production)
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" }
-
#
-
1
def resolve(config)
-
6
if config
-
6
resolve_connection config
-
elsif env = ActiveRecord::ConnectionHandling::RAILS_ENV.call
-
resolve_symbol_connection env.to_sym
-
else
-
raise AdapterNotSpecified
-
end
-
end
-
-
# Expands each key in @configurations hash into fully resolved hash
-
1
def resolve_all
-
2
config = configurations.dup
-
2
config.each do |key, value|
-
5
config[key] = resolve(value) if value
-
end
-
2
config
-
end
-
-
# Returns an instance of ConnectionSpecification for a given adapter.
-
# Accepts a hash one layer deep that contains all connection information.
-
#
-
# == Example
-
#
-
# config = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } }
-
# spec = Resolver.new(config).spec(:production)
-
# spec.adapter_method
-
# # => "sqlite3_connection"
-
# spec.config
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" }
-
#
-
1
def spec(config)
-
1
spec = resolve(config).symbolize_keys
-
-
1
raise(AdapterNotSpecified, "database configuration does not specify adapter") unless spec.key?(:adapter)
-
-
1
path_to_adapter = "active_record/connection_adapters/#{spec[:adapter]}_adapter"
-
1
begin
-
1
require path_to_adapter
-
rescue Gem::LoadError => e
-
raise Gem::LoadError, "Specified '#{spec[:adapter]}' for database adapter, but the gem is not loaded. Add `gem '#{e.name}'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord)."
-
rescue LoadError => e
-
raise LoadError, "Could not load '#{path_to_adapter}'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.", e.backtrace
-
end
-
-
1
adapter_method = "#{spec[:adapter]}_connection"
-
1
ConnectionSpecification.new(spec, adapter_method)
-
end
-
-
1
private
-
-
# Returns fully resolved connection, accepts hash, string or symbol.
-
# Always returns a hash.
-
#
-
# == Examples
-
#
-
# Symbol representing current environment.
-
#
-
# Resolver.new("production" => {}).resolve_connection(:production)
-
# # => {}
-
#
-
# One layer deep hash of connection values.
-
#
-
# Resolver.new({}).resolve_connection("adapter" => "sqlite3")
-
# # => { "adapter" => "sqlite3" }
-
#
-
# Connection URL.
-
#
-
# Resolver.new({}).resolve_connection("postgresql://localhost/foo")
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" }
-
#
-
1
def resolve_connection(spec)
-
7
case spec
-
when Symbol
-
1
resolve_symbol_connection spec
-
when String
-
resolve_string_connection spec
-
when Hash
-
6
resolve_hash_connection spec
-
end
-
end
-
-
1
def resolve_string_connection(spec)
-
# Rails has historically accepted a string to mean either
-
# an environment key or a URL spec, so we have deprecated
-
# this ambiguous behaviour and in the future this function
-
# can be removed in favor of resolve_url_connection.
-
if configurations.key?(spec) || spec !~ /:/
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
Passing a string to ActiveRecord::Base.establish_connection for a
-
configuration lookup is deprecated, please pass a symbol
-
(#{spec.to_sym.inspect}) instead.
-
MSG
-
-
resolve_symbol_connection(spec)
-
else
-
resolve_url_connection(spec)
-
end
-
end
-
-
# Takes the environment such as +:production+ or +:development+.
-
# This requires that the @configurations was initialized with a key that
-
# matches.
-
#
-
# Resolver.new("production" => {}).resolve_symbol_connection(:production)
-
# # => {}
-
#
-
1
def resolve_symbol_connection(spec)
-
1
if config = configurations[spec.to_s]
-
1
resolve_connection(config)
-
else
-
raise(AdapterNotSpecified, "'#{spec}' database is not configured. Available: #{configurations.keys.inspect}")
-
end
-
end
-
-
# Accepts a hash. Expands the "url" key that contains a
-
# URL database connection to a full connection
-
# hash and merges with the rest of the hash.
-
# Connection details inside of the "url" key win any merge conflicts
-
1
def resolve_hash_connection(spec)
-
6
if spec["url"] && spec["url"] !~ /^jdbc:/
-
connection_hash = resolve_url_connection(spec.delete("url"))
-
spec.merge!(connection_hash)
-
end
-
6
spec
-
end
-
-
# Takes a connection URL.
-
#
-
# Resolver.new({}).resolve_url_connection("postgresql://localhost/foo")
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" }
-
#
-
1
def resolve_url_connection(url)
-
ConnectionUrlResolver.new(url).to_hash
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class SchemaCache
-
1
attr_reader :version
-
1
attr_accessor :connection
-
-
1
def initialize(conn)
-
1
@connection = conn
-
-
1
@columns = {}
-
1
@columns_hash = {}
-
1
@primary_keys = {}
-
1
@tables = {}
-
end
-
-
1
def primary_keys(table_name)
-
4
@primary_keys[table_name] ||= table_exists?(table_name) ? connection.primary_key(table_name) : nil
-
end
-
-
# A cached lookup for table existence.
-
1
def table_exists?(name)
-
12
prepare_tables if @tables.empty?
-
12
return @tables[name] if @tables.key? name
-
-
@tables[name] = connection.table_exists?(name)
-
end
-
-
# Add internal cache for table with +table_name+.
-
1
def add(table_name)
-
if table_exists?(table_name)
-
primary_keys(table_name)
-
columns(table_name)
-
columns_hash(table_name)
-
end
-
end
-
-
1
def tables(name)
-
@tables[name]
-
end
-
-
# Get the columns for a table
-
1
def columns(table_name)
-
9
@columns[table_name] ||= connection.columns(table_name)
-
end
-
-
# Get the columns for a table as a hash, key is the column name
-
# value is the column object.
-
1
def columns_hash(table_name)
-
4
@columns_hash[table_name] ||= Hash[columns(table_name).map { |col|
-
27
[col.name, col]
-
}]
-
end
-
-
# Clears out internal caches
-
1
def clear!
-
@columns.clear
-
@columns_hash.clear
-
@primary_keys.clear
-
@tables.clear
-
@version = nil
-
end
-
-
1
def size
-
[@columns, @columns_hash, @primary_keys, @tables].map { |x|
-
x.size
-
}.inject :+
-
end
-
-
# Clear out internal caches for table with +table_name+.
-
1
def clear_table_cache!(table_name)
-
@columns.delete table_name
-
@columns_hash.delete table_name
-
@primary_keys.delete table_name
-
@tables.delete table_name
-
end
-
-
1
def marshal_dump
-
# if we get current version during initialization, it happens stack over flow.
-
@version = ActiveRecord::Migrator.current_version
-
[@version, @columns, @columns_hash, @primary_keys, @tables]
-
end
-
-
1
def marshal_load(array)
-
@version, @columns, @columns_hash, @primary_keys, @tables = array
-
end
-
-
1
private
-
-
1
def prepare_tables
-
6
connection.tables.each { |table| @tables[table] = true }
-
end
-
end
-
end
-
end
-
1
require 'active_record/connection_adapters/abstract_adapter'
-
1
require 'active_record/connection_adapters/statement_pool'
-
1
require 'arel/visitors/bind_visitor'
-
-
1
gem 'sqlite3', '~> 1.3.6'
-
1
require 'sqlite3'
-
-
1
module ActiveRecord
-
1
module ConnectionHandling # :nodoc:
-
# sqlite3 adapter reuses sqlite_connection.
-
1
def sqlite3_connection(config)
-
# Require database.
-
1
unless config[:database]
-
raise ArgumentError, "No database file specified. Missing argument: database"
-
end
-
-
# Allow database path relative to Rails.root, but only if the database
-
# path is not the special path that tells sqlite to build a database only
-
# in memory.
-
1
if ':memory:' != config[:database]
-
1
config[:database] = File.expand_path(config[:database], Rails.root) if defined?(Rails.root)
-
1
dirname = File.dirname(config[:database])
-
1
Dir.mkdir(dirname) unless File.directory?(dirname)
-
end
-
-
1
db = SQLite3::Database.new(
-
config[:database].to_s,
-
:results_as_hash => true
-
)
-
-
1
db.busy_timeout(ConnectionAdapters::SQLite3Adapter.type_cast_config_to_integer(config[:timeout])) if config[:timeout]
-
-
1
ConnectionAdapters::SQLite3Adapter.new(db, logger, nil, config)
-
rescue Errno::ENOENT => error
-
if error.message.include?("No such file or directory")
-
raise ActiveRecord::NoDatabaseError.new(error.message, error)
-
else
-
raise
-
end
-
end
-
end
-
-
1
module ConnectionAdapters #:nodoc:
-
1
class SQLite3Binary < Type::Binary # :nodoc:
-
1
def cast_value(value)
-
if value.encoding != Encoding::ASCII_8BIT
-
value = value.force_encoding(Encoding::ASCII_8BIT)
-
end
-
value
-
end
-
end
-
-
# The SQLite3 adapter works SQLite 3.6.16 or newer
-
# with the sqlite3-ruby drivers (available as gem from https://rubygems.org/gems/sqlite3).
-
#
-
# Options:
-
#
-
# * <tt>:database</tt> - Path to the database file.
-
1
class SQLite3Adapter < AbstractAdapter
-
1
ADAPTER_NAME = 'SQLite'.freeze
-
1
include Savepoints
-
-
1
NATIVE_DATABASE_TYPES = {
-
primary_key: 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL',
-
string: { name: "varchar" },
-
text: { name: "text" },
-
integer: { name: "integer" },
-
float: { name: "float" },
-
decimal: { name: "decimal" },
-
datetime: { name: "datetime" },
-
time: { name: "time" },
-
date: { name: "date" },
-
binary: { name: "blob" },
-
boolean: { name: "boolean" }
-
}
-
-
1
class Version
-
1
include Comparable
-
-
1
def initialize(version_string)
-
@version = version_string.split('.').map { |v| v.to_i }
-
end
-
-
1
def <=>(version_string)
-
@version <=> version_string.split('.').map { |v| v.to_i }
-
end
-
end
-
-
1
class StatementPool < ConnectionAdapters::StatementPool
-
1
def initialize(connection, max)
-
1
super
-
2
@cache = Hash.new { |h,pid| h[pid] = {} }
-
end
-
-
1
def each(&block); cache.each(&block); end
-
1
def key?(key); cache.key?(key); end
-
55
def [](key); cache[key]; end
-
1
def length; cache.length; end
-
-
1
def []=(sql, key)
-
16
while @max <= cache.size
-
dealloc(cache.shift.last[:stmt])
-
end
-
16
cache[sql] = key
-
end
-
-
1
def clear
-
cache.each_value do |hash|
-
dealloc hash[:stmt]
-
end
-
cache.clear
-
end
-
-
1
private
-
1
def cache
-
86
@cache[$$]
-
end
-
-
1
def dealloc(stmt)
-
stmt.close unless stmt.closed?
-
end
-
end
-
-
1
def initialize(connection, logger, connection_options, config)
-
1
super(connection, logger)
-
-
1
@active = nil
-
1
@statements = StatementPool.new(@connection,
-
1
self.class.type_cast_config_to_integer(config.fetch(:statement_limit) { 1000 }))
-
1
@config = config
-
-
1
@visitor = Arel::Visitors::SQLite.new self
-
-
2
if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
-
1
@prepared_statements = true
-
else
-
@prepared_statements = false
-
end
-
end
-
-
1
def supports_ddl_transactions?
-
true
-
end
-
-
1
def supports_savepoints?
-
true
-
end
-
-
1
def supports_partial_index?
-
sqlite_version >= '3.8.0'
-
end
-
-
# Returns true, since this connection adapter supports prepared statement
-
# caching.
-
1
def supports_statement_cache?
-
true
-
end
-
-
# Returns true, since this connection adapter supports migrations.
-
1
def supports_migrations? #:nodoc:
-
true
-
end
-
-
1
def supports_primary_key? #:nodoc:
-
true
-
end
-
-
1
def requires_reloading?
-
true
-
end
-
-
1
def supports_views?
-
true
-
end
-
-
1
def active?
-
1
@active != false
-
end
-
-
# Disconnects from the database if already connected. Otherwise, this
-
# method does nothing.
-
1
def disconnect!
-
super
-
@active = false
-
@connection.close rescue nil
-
end
-
-
# Clears the prepared statements cache.
-
1
def clear_cache!
-
@statements.clear
-
end
-
-
1
def supports_index_sort_order?
-
true
-
end
-
-
# Returns 62. SQLite supports index names up to 64
-
# characters. The rest is used by rails internally to perform
-
# temporary rename operations
-
1
def allowed_index_name_length
-
index_name_length - 2
-
end
-
-
1
def native_database_types #:nodoc:
-
NATIVE_DATABASE_TYPES
-
end
-
-
# Returns the current database encoding format as a string, eg: 'UTF-8'
-
1
def encoding
-
@connection.encoding.to_s
-
end
-
-
1
def supports_explain?
-
true
-
end
-
-
# QUOTING ==================================================
-
-
1
def _quote(value) # :nodoc:
-
case value
-
when Type::Binary::Data
-
"x'#{value.hex}'"
-
else
-
super
-
end
-
end
-
-
1
def _type_cast(value) # :nodoc:
-
168
case value
-
when BigDecimal
-
value.to_f
-
when String
-
67
if value.encoding == Encoding::ASCII_8BIT
-
super(value.encode(Encoding::UTF_8))
-
else
-
67
super
-
end
-
else
-
101
super
-
end
-
end
-
-
1
def quote_string(s) #:nodoc:
-
@connection.class.quote(s)
-
end
-
-
1
def quote_table_name_for_assignment(table, attr)
-
quote_column_name(attr)
-
end
-
-
1
def quote_column_name(name) #:nodoc:
-
259
%Q("#{name.to_s.gsub('"', '""')}")
-
end
-
-
# Quote date/time values for use in SQL input. Includes microseconds
-
# if the value is a Time responding to usec.
-
1
def quoted_date(value) #:nodoc:
-
60
if value.respond_to?(:usec)
-
54
"#{super}.#{sprintf("%06d", value.usec)}"
-
else
-
6
super
-
end
-
end
-
-
#--
-
# DATABASE STATEMENTS ======================================
-
#++
-
-
1
def explain(arel, binds = [])
-
sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}"
-
ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', []))
-
end
-
-
1
class ExplainPrettyPrinter
-
# Pretty prints the result of a EXPLAIN QUERY PLAN in a way that resembles
-
# the output of the SQLite shell:
-
#
-
# 0|0|0|SEARCH TABLE users USING INTEGER PRIMARY KEY (rowid=?) (~1 rows)
-
# 0|1|1|SCAN TABLE posts (~100000 rows)
-
#
-
1
def pp(result) # :nodoc:
-
result.rows.map do |row|
-
row.join('|')
-
end.join("\n") + "\n"
-
end
-
end
-
-
1
def exec_query(sql, name = nil, binds = [])
-
89
type_casted_binds = binds.map { |col, val|
-
168
[col, type_cast(val, col)]
-
}
-
-
89
log(sql, name, type_casted_binds) do
-
# Don't cache statements if they are not prepared
-
89
if without_prepared_statement?(binds)
-
35
stmt = @connection.prepare(sql)
-
35
begin
-
35
cols = stmt.columns
-
35
records = stmt.to_a
-
ensure
-
35
stmt.close
-
end
-
35
stmt = records
-
else
-
54
cache = @statements[sql] ||= {
-
:stmt => @connection.prepare(sql)
-
}
-
54
stmt = cache[:stmt]
-
54
cols = cache[:cols] ||= stmt.columns
-
54
stmt.reset!
-
222
stmt.bind_params type_casted_binds.map { |_, val| val }
-
end
-
-
89
ActiveRecord::Result.new(cols, stmt.to_a)
-
end
-
end
-
-
1
def exec_delete(sql, name = 'SQL', binds = [])
-
7
exec_query(sql, name, binds)
-
7
@connection.changes
-
end
-
1
alias :exec_update :exec_delete
-
-
1
def last_inserted_id(result)
-
25
@connection.last_insert_row_id
-
end
-
-
1
def execute(sql, name = nil) #:nodoc:
-
128
log(sql, name) { @connection.execute(sql) }
-
end
-
-
1
def update_sql(sql, name = nil) #:nodoc:
-
super
-
@connection.changes
-
end
-
-
1
def delete_sql(sql, name = nil) #:nodoc:
-
sql += " WHERE 1=1" unless sql =~ /WHERE/i
-
super sql, name
-
end
-
-
1
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
-
super
-
id_value || @connection.last_insert_row_id
-
end
-
1
alias :create :insert_sql
-
-
1
def select_rows(sql, name = nil, binds = [])
-
exec_query(sql, name, binds).rows
-
end
-
-
1
def begin_db_transaction #:nodoc:
-
72
log('begin transaction',nil) { @connection.transaction }
-
end
-
-
1
def commit_db_transaction #:nodoc:
-
36
log('commit transaction',nil) { @connection.commit }
-
end
-
-
1
def exec_rollback_db_transaction #:nodoc:
-
36
log('rollback transaction',nil) { @connection.rollback }
-
end
-
-
# SCHEMA STATEMENTS ========================================
-
-
1
def tables(name = nil, table_name = nil) #:nodoc:
-
2
sql = <<-SQL
-
SELECT name
-
FROM sqlite_master
-
WHERE (type = 'table' OR type = 'view') AND NOT name = 'sqlite_sequence'
-
SQL
-
2
sql << " AND name = #{quote_table_name(table_name)}" if table_name
-
-
2
exec_query(sql, 'SCHEMA').map do |row|
-
6
row['name']
-
end
-
end
-
-
1
def table_exists?(table_name)
-
1
table_name && tables(nil, table_name).any?
-
end
-
-
# Returns an array of +Column+ objects for the table specified by +table_name+.
-
1
def columns(table_name) #:nodoc:
-
5
table_structure(table_name).map do |field|
-
28
case field["dflt_value"]
-
when /^null$/i
-
field["dflt_value"] = nil
-
when /^'(.*)'$/m
-
field["dflt_value"] = $1.gsub("''", "'")
-
when /^"(.*)"$/m
-
field["dflt_value"] = $1.gsub('""', '"')
-
end
-
-
28
sql_type = field['type']
-
28
cast_type = lookup_cast_type(sql_type)
-
28
new_column(field['name'], field['dflt_value'], cast_type, sql_type, field['notnull'].to_i == 0)
-
end
-
end
-
-
# Returns an array of indexes for the given table.
-
1
def indexes(table_name, name = nil) #:nodoc:
-
exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", 'SCHEMA').map do |row|
-
sql = <<-SQL
-
SELECT sql
-
FROM sqlite_master
-
WHERE name=#{quote(row['name'])} AND type='index'
-
UNION ALL
-
SELECT sql
-
FROM sqlite_temp_master
-
WHERE name=#{quote(row['name'])} AND type='index'
-
SQL
-
index_sql = exec_query(sql).first['sql']
-
match = /\sWHERE\s+(.+)$/i.match(index_sql)
-
where = match[1] if match
-
IndexDefinition.new(
-
table_name,
-
row['name'],
-
row['unique'] != 0,
-
exec_query("PRAGMA index_info('#{row['name']}')", "SCHEMA").map { |col|
-
col['name']
-
}, nil, nil, where)
-
end
-
end
-
-
1
def primary_key(table_name) #:nodoc:
-
31
pks = table_structure(table_name).select { |f| f['pk'] > 0 }
-
4
return nil unless pks.count == 1
-
4
pks[0]['name']
-
end
-
-
1
def remove_index!(table_name, index_name) #:nodoc:
-
exec_query "DROP INDEX #{quote_column_name(index_name)}"
-
end
-
-
# Renames a table.
-
#
-
# Example:
-
# rename_table('octopuses', 'octopi')
-
1
def rename_table(table_name, new_name)
-
exec_query "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
-
rename_table_indexes(table_name, new_name)
-
end
-
-
# See: http://www.sqlite.org/lang_altertable.html
-
# SQLite has an additional restriction on the ALTER TABLE statement
-
1
def valid_alter_table_type?(type)
-
type.to_sym != :primary_key
-
end
-
-
1
def add_column(table_name, column_name, type, options = {}) #:nodoc:
-
if valid_alter_table_type?(type)
-
super(table_name, column_name, type, options)
-
else
-
alter_table(table_name) do |definition|
-
definition.column(column_name, type, options)
-
end
-
end
-
end
-
-
1
def remove_column(table_name, column_name, type = nil, options = {}) #:nodoc:
-
alter_table(table_name) do |definition|
-
definition.remove_column column_name
-
end
-
end
-
-
1
def change_column_default(table_name, column_name, default) #:nodoc:
-
alter_table(table_name) do |definition|
-
definition[column_name].default = default
-
end
-
end
-
-
1
def change_column_null(table_name, column_name, null, default = nil)
-
unless null || default.nil?
-
exec_query("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
-
end
-
alter_table(table_name) do |definition|
-
definition[column_name].null = null
-
end
-
end
-
-
1
def change_column(table_name, column_name, type, options = {}) #:nodoc:
-
alter_table(table_name) do |definition|
-
include_default = options_include_default?(options)
-
definition[column_name].instance_eval do
-
self.type = type
-
self.limit = options[:limit] if options.include?(:limit)
-
self.default = options[:default] if include_default
-
self.null = options[:null] if options.include?(:null)
-
self.precision = options[:precision] if options.include?(:precision)
-
self.scale = options[:scale] if options.include?(:scale)
-
end
-
end
-
end
-
-
1
def rename_column(table_name, column_name, new_column_name) #:nodoc:
-
column = column_for(table_name, column_name)
-
alter_table(table_name, rename: {column.name => new_column_name.to_s})
-
rename_column_indexes(table_name, column.name, new_column_name)
-
end
-
-
1
protected
-
-
1
def initialize_type_map(m)
-
1
super
-
1
m.register_type(/binary/i, SQLite3Binary.new)
-
end
-
-
1
def table_structure(table_name)
-
9
structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA').to_hash
-
9
raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
-
9
structure
-
end
-
-
1
def alter_table(table_name, options = {}) #:nodoc:
-
altered_table_name = "a#{table_name}"
-
caller = lambda {|definition| yield definition if block_given?}
-
-
transaction do
-
move_table(table_name, altered_table_name,
-
options.merge(:temporary => true))
-
move_table(altered_table_name, table_name, &caller)
-
end
-
end
-
-
1
def move_table(from, to, options = {}, &block) #:nodoc:
-
copy_table(from, to, options, &block)
-
drop_table(from)
-
end
-
-
1
def copy_table(from, to, options = {}) #:nodoc:
-
from_primary_key = primary_key(from)
-
options[:id] = false
-
create_table(to, options) do |definition|
-
@definition = definition
-
@definition.primary_key(from_primary_key) if from_primary_key.present?
-
columns(from).each do |column|
-
column_name = options[:rename] ?
-
(options[:rename][column.name] ||
-
options[:rename][column.name.to_sym] ||
-
column.name) : column.name
-
next if column_name == from_primary_key
-
-
@definition.column(column_name, column.type,
-
:limit => column.limit, :default => column.default,
-
:precision => column.precision, :scale => column.scale,
-
:null => column.null)
-
end
-
yield @definition if block_given?
-
end
-
copy_table_indexes(from, to, options[:rename] || {})
-
copy_table_contents(from, to,
-
@definition.columns.map {|column| column.name},
-
options[:rename] || {})
-
end
-
-
1
def copy_table_indexes(from, to, rename = {}) #:nodoc:
-
indexes(from).each do |index|
-
name = index.name
-
if to == "a#{from}"
-
name = "t#{name}"
-
elsif from == "a#{to}"
-
name = name[1..-1]
-
end
-
-
to_column_names = columns(to).map { |c| c.name }
-
columns = index.columns.map {|c| rename[c] || c }.select do |column|
-
to_column_names.include?(column)
-
end
-
-
unless columns.empty?
-
# index name can't be the same
-
opts = { name: name.gsub(/(^|_)(#{from})_/, "\\1#{to}_"), internal: true }
-
opts[:unique] = true if index.unique
-
add_index(to, columns, opts)
-
end
-
end
-
end
-
-
1
def copy_table_contents(from, to, columns, rename = {}) #:nodoc:
-
column_mappings = Hash[columns.map {|name| [name, name]}]
-
rename.each { |a| column_mappings[a.last] = a.first }
-
from_columns = columns(from).collect {|col| col.name}
-
columns = columns.find_all{|col| from_columns.include?(column_mappings[col])}
-
quoted_columns = columns.map { |col| quote_column_name(col) } * ','
-
-
quoted_to = quote_table_name(to)
-
-
raw_column_mappings = Hash[columns(from).map { |c| [c.name, c] }]
-
-
exec_query("SELECT * FROM #{quote_table_name(from)}").each do |row|
-
sql = "INSERT INTO #{quoted_to} (#{quoted_columns}) VALUES ("
-
-
column_values = columns.map do |col|
-
quote(row[column_mappings[col]], raw_column_mappings[col])
-
end
-
-
sql << column_values * ', '
-
sql << ')'
-
exec_query sql
-
end
-
end
-
-
1
def sqlite_version
-
@sqlite_version ||= SQLite3Adapter::Version.new(select_value('select sqlite_version(*)'))
-
end
-
-
1
def translate_exception(exception, message)
-
case exception.message
-
# SQLite 3.8.2 returns a newly formatted error message:
-
# UNIQUE constraint failed: *table_name*.*column_name*
-
# Older versions of SQLite return:
-
# column *column_name* is not unique
-
when /column(s)? .* (is|are) not unique/, /UNIQUE constraint failed: .*/
-
RecordNotUnique.new(message, exception)
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class StatementPool
-
1
include Enumerable
-
-
1
def initialize(connection, max = 1000)
-
1
@connection = connection
-
1
@max = max
-
end
-
-
1
def each
-
raise NotImplementedError
-
end
-
-
1
def key?(key)
-
raise NotImplementedError
-
end
-
-
1
def [](key)
-
raise NotImplementedError
-
end
-
-
1
def length
-
raise NotImplementedError
-
end
-
-
1
def []=(sql, key)
-
raise NotImplementedError
-
end
-
-
1
def clear
-
raise NotImplementedError
-
end
-
-
1
def delete(key)
-
raise NotImplementedError
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionHandling
-
4
RAILS_ENV = -> { (Rails.env if defined?(Rails.env)) || ENV["RAILS_ENV"] || ENV["RACK_ENV"] }
-
4
DEFAULT_ENV = -> { RAILS_ENV.call || "default_env" }
-
-
# Establishes the connection to the database. Accepts a hash as input where
-
# the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
-
# example for regular databases (MySQL, Postgresql, etc):
-
#
-
# ActiveRecord::Base.establish_connection(
-
# adapter: "mysql",
-
# host: "localhost",
-
# username: "myuser",
-
# password: "mypass",
-
# database: "somedatabase"
-
# )
-
#
-
# Example for SQLite database:
-
#
-
# ActiveRecord::Base.establish_connection(
-
# adapter: "sqlite3",
-
# database: "path/to/dbfile"
-
# )
-
#
-
# Also accepts keys as strings (for parsing from YAML for example):
-
#
-
# ActiveRecord::Base.establish_connection(
-
# "adapter" => "sqlite3",
-
# "database" => "path/to/dbfile"
-
# )
-
#
-
# Or a URL:
-
#
-
# ActiveRecord::Base.establish_connection(
-
# "postgres://myuser:mypass@localhost/somedatabase"
-
# )
-
#
-
# In case <tt>ActiveRecord::Base.configurations</tt> is set (Rails
-
# automatically loads the contents of config/database.yml into it),
-
# a symbol can also be given as argument, representing a key in the
-
# configuration hash:
-
#
-
# ActiveRecord::Base.establish_connection(:production)
-
#
-
# The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError
-
# may be returned on an error.
-
1
def establish_connection(spec = nil)
-
1
spec ||= DEFAULT_ENV.call.to_sym
-
1
resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new configurations
-
1
spec = resolver.spec(spec)
-
-
1
unless respond_to?(spec.adapter_method)
-
raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter"
-
end
-
-
1
remove_connection
-
1
connection_handler.establish_connection self, spec
-
end
-
-
1
class MergeAndResolveDefaultUrlConfig # :nodoc:
-
1
def initialize(raw_configurations)
-
2
@raw_config = raw_configurations.dup
-
2
@env = DEFAULT_ENV.call.to_s
-
end
-
-
# Returns fully resolved connection hashes.
-
# Merges connection information from `ENV['DATABASE_URL']` if available.
-
1
def resolve
-
2
ConnectionAdapters::ConnectionSpecification::Resolver.new(config).resolve_all
-
end
-
-
1
private
-
1
def config
-
2
@raw_config.dup.tap do |cfg|
-
2
if url = ENV['DATABASE_URL']
-
cfg[@env] ||= {}
-
cfg[@env]["url"] ||= url
-
end
-
end
-
end
-
end
-
-
# Returns the connection currently associated with the class. This can
-
# also be used to "borrow" the connection to do database work unrelated
-
# to any of the specific Active Records.
-
1
def connection
-
3
retrieve_connection
-
end
-
-
1
def connection_id
-
771
ActiveRecord::RuntimeRegistry.connection_id
-
end
-
-
1
def connection_id=(connection_id)
-
67
ActiveRecord::RuntimeRegistry.connection_id = connection_id
-
end
-
-
# Returns the configuration of the associated connection as a hash:
-
#
-
# ActiveRecord::Base.connection_config
-
# # => {pool: 5, timeout: 5000, database: "db/development.sqlite3", adapter: "sqlite3"}
-
#
-
# Please use only for reading.
-
1
def connection_config
-
connection_pool.spec.config
-
end
-
-
1
def connection_pool
-
connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished
-
end
-
-
1
def retrieve_connection
-
704
connection_handler.retrieve_connection(self)
-
end
-
-
# Returns +true+ if Active Record is connected.
-
1
def connected?
-
121
connection_handler.connected?(self)
-
end
-
-
1
def remove_connection(klass = self)
-
1
connection_handler.remove_connection(klass)
-
end
-
-
1
def clear_cache! # :nodoc:
-
connection.schema_cache.clear!
-
end
-
-
1
delegate :clear_active_connections!, :clear_reloadable_connections!,
-
:clear_all_connections!, :to => :connection_handler
-
end
-
end
-
1
require 'thread'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'active_support/core_ext/string/filters'
-
-
1
module ActiveRecord
-
1
module Core
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
##
-
# :singleton-method:
-
#
-
# Accepts a logger conforming to the interface of Log4r which is then
-
# passed on to any new database connections made and which can be
-
# retrieved on both a class and instance level by calling +logger+.
-
1
mattr_accessor :logger, instance_writer: false
-
-
##
-
# Contains the database configuration - as is typically stored in config/database.yml -
-
# as a Hash.
-
#
-
# For example, the following database.yml...
-
#
-
# development:
-
# adapter: sqlite3
-
# database: db/development.sqlite3
-
#
-
# production:
-
# adapter: sqlite3
-
# database: db/production.sqlite3
-
#
-
# ...would result in ActiveRecord::Base.configurations to look like this:
-
#
-
# {
-
# 'development' => {
-
# 'adapter' => 'sqlite3',
-
# 'database' => 'db/development.sqlite3'
-
# },
-
# 'production' => {
-
# 'adapter' => 'sqlite3',
-
# 'database' => 'db/production.sqlite3'
-
# }
-
# }
-
1
def self.configurations=(config)
-
2
@@configurations = ActiveRecord::ConnectionHandling::MergeAndResolveDefaultUrlConfig.new(config).resolve
-
end
-
1
self.configurations = {}
-
-
# Returns fully resolved configurations hash
-
1
def self.configurations
-
1
@@configurations
-
end
-
-
##
-
# :singleton-method:
-
# Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
-
# dates and times from the database. This is set to :utc by default.
-
1
mattr_accessor :default_timezone, instance_writer: false
-
1
self.default_timezone = :utc
-
-
##
-
# :singleton-method:
-
# Specifies the format to use when dumping the database schema with Rails'
-
# Rakefile. If :sql, the schema is dumped as (potentially database-
-
# specific) SQL statements. If :ruby, the schema is dumped as an
-
# ActiveRecord::Schema file which can be loaded into any database that
-
# supports migrations. Use :ruby if you want to have different database
-
# adapters for, e.g., your development and test environments.
-
1
mattr_accessor :schema_format, instance_writer: false
-
1
self.schema_format = :ruby
-
-
##
-
# :singleton-method:
-
# Specify whether or not to use timestamps for migration versions
-
1
mattr_accessor :timestamped_migrations, instance_writer: false
-
1
self.timestamped_migrations = true
-
-
##
-
# :singleton-method:
-
# Specify whether schema dump should happen at the end of the
-
# db:migrate rake task. This is true by default, which is useful for the
-
# development environment. This should ideally be false in the production
-
# environment where dumping schema is rarely needed.
-
1
mattr_accessor :dump_schema_after_migration, instance_writer: false
-
1
self.dump_schema_after_migration = true
-
-
1
mattr_accessor :maintain_test_schema, instance_accessor: false
-
-
1
def self.disable_implicit_join_references=(value)
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
Implicit join references were removed with Rails 4.1.
-
Make sure to remove this configuration because it does nothing.
-
MSG
-
end
-
-
1
class_attribute :default_connection_handler, instance_writer: false
-
1
class_attribute :find_by_statement_cache
-
-
1
def self.connection_handler
-
832
ActiveRecord::RuntimeRegistry.connection_handler || default_connection_handler
-
end
-
-
1
def self.connection_handler=(handler)
-
ActiveRecord::RuntimeRegistry.connection_handler = handler
-
end
-
-
1
self.default_connection_handler = ConnectionAdapters::ConnectionHandler.new
-
end
-
-
1
module ClassMethods
-
1
def allocate
-
54
define_attribute_methods
-
54
super
-
end
-
-
1
def initialize_find_by_cache # :nodoc:
-
5
self.find_by_statement_cache = {}.extend(Mutex_m)
-
end
-
-
1
def inherited(child_class) # :nodoc:
-
5
child_class.initialize_find_by_cache
-
5
super
-
end
-
-
1
def find(*ids) # :nodoc:
-
# We don't have cache keys for this stuff yet
-
22
return super unless ids.length == 1
-
# Allow symbols to super to maintain compatibility for deprecated finders until Rails 5
-
22
return super if ids.first.kind_of?(Symbol)
-
return super if block_given? ||
-
22
primary_key.nil? ||
-
default_scopes.any? ||
-
current_scope ||
-
columns_hash.include?(inheritance_column) ||
-
ids.first.kind_of?(Array)
-
-
22
id = ids.first
-
22
if ActiveRecord::Base === id
-
id = id.id
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
You are passing an instance of ActiveRecord::Base to `find`.
-
Please pass the id of the object by calling `.id`
-
MSG
-
end
-
22
key = primary_key
-
-
22
s = find_by_statement_cache[key] || find_by_statement_cache.synchronize {
-
4
find_by_statement_cache[key] ||= StatementCache.create(connection) { |params|
-
4
where(key => params.bind).limit(1)
-
}
-
}
-
22
record = s.execute([id], self, connection).first
-
22
unless record
-
raise RecordNotFound, "Couldn't find #{name} with '#{primary_key}'=#{id}"
-
end
-
22
record
-
rescue RangeError
-
raise RecordNotFound, "Couldn't find #{name} with an out of range value for '#{primary_key}'"
-
end
-
-
1
def find_by(*args) # :nodoc:
-
return super if current_scope || !(Hash === args.first) || reflect_on_all_aggregations.any?
-
return super if default_scopes.any?
-
-
hash = args.first
-
-
return super if hash.values.any? { |v|
-
v.nil? || Array === v || Hash === v
-
}
-
-
# We can't cache Post.find_by(author: david) ...yet
-
return super unless hash.keys.all? { |k| columns_hash.has_key?(k.to_s) }
-
-
key = hash.keys
-
-
klass = self
-
s = find_by_statement_cache[key] || find_by_statement_cache.synchronize {
-
find_by_statement_cache[key] ||= StatementCache.create(connection) { |params|
-
wheres = key.each_with_object({}) { |param,o|
-
o[param] = params.bind
-
}
-
klass.where(wheres).limit(1)
-
}
-
}
-
begin
-
s.execute(hash.values, self, connection).first
-
rescue TypeError => e
-
raise ActiveRecord::StatementInvalid.new(e.message, e)
-
rescue RangeError
-
nil
-
end
-
end
-
-
1
def find_by!(*args) # :nodoc:
-
find_by(*args) or raise RecordNotFound.new("Couldn't find #{name}")
-
end
-
-
1
def initialize_generated_modules # :nodoc:
-
6
generated_association_methods
-
end
-
-
1
def generated_association_methods
-
@generated_association_methods ||= begin
-
6
mod = const_set(:GeneratedAssociationMethods, Module.new)
-
6
include mod
-
6
mod
-
13
end
-
end
-
-
# Returns a string like 'Post(id:integer, title:string, body:text)'
-
1
def inspect
-
if self == Base
-
super
-
elsif abstract_class?
-
"#{super}(abstract)"
-
elsif !connected?
-
"#{super} (call '#{super}.connection' to establish a connection)"
-
elsif table_exists?
-
attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
-
"#{super}(#{attr_list})"
-
else
-
"#{super}(Table doesn't exist)"
-
end
-
end
-
-
# Overwrite the default class equality method to provide support for association proxies.
-
1
def ===(object)
-
38
object.is_a?(self)
-
end
-
-
# Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
-
#
-
# class Post < ActiveRecord::Base
-
# scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) }
-
# end
-
1
def arel_table # :nodoc:
-
188
@arel_table ||= Arel::Table.new(table_name, arel_engine)
-
end
-
-
# Returns the Arel engine.
-
1
def arel_engine # :nodoc:
-
@arel_engine ||=
-
if Base == self || connection_handler.retrieve_connection_pool(self)
-
5
self
-
else
-
superclass.arel_engine
-
5
end
-
end
-
-
1
private
-
-
1
def relation #:nodoc:
-
92
relation = Relation.create(self, arel_table)
-
-
92
if finder_needs_type_condition?
-
relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
-
else
-
92
relation
-
end
-
end
-
end
-
-
# New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
-
# attributes but not yet saved (pass a hash with key names matching the associated table column names).
-
# In both instances, valid attribute keys are determined by the column names of the associated table --
-
# hence you can't have attributes that aren't part of the table columns.
-
#
-
# ==== Example:
-
# # Instantiates a single new object
-
# User.new(first_name: 'Jamie')
-
1
def initialize(attributes = nil, options = {})
-
29
@attributes = self.class._default_attributes.dup
-
29
self.class.define_attribute_methods
-
-
29
init_internals
-
29
initialize_internals_callback
-
-
# +options+ argument is only needed to make protected_attributes gem easier to hook.
-
# Remove it when we drop support to this gem.
-
29
init_attributes(attributes, options) if attributes
-
-
29
yield self if block_given?
-
29
_run_initialize_callbacks
-
end
-
-
# Initialize an empty model object from +coder+. +coder+ should be
-
# the result of previously encoding an Active Record model, using
-
# `encode_with`
-
#
-
# class Post < ActiveRecord::Base
-
# end
-
#
-
# old_post = Post.new(title: "hello world")
-
# coder = {}
-
# old_post.encode_with(coder)
-
#
-
# post = Post.allocate
-
# post.init_with(coder)
-
# post.title # => 'hello world'
-
1
def init_with(coder)
-
54
coder = LegacyYamlAdapter.convert(self.class, coder)
-
54
@attributes = coder['attributes']
-
-
54
init_internals
-
-
54
@new_record = coder['new_record']
-
-
54
self.class.define_attribute_methods
-
-
54
_run_find_callbacks
-
54
_run_initialize_callbacks
-
-
54
self
-
end
-
-
##
-
# :method: clone
-
# Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied.
-
# That means that modifying attributes of the clone will modify the original, since they will both point to the
-
# same attributes hash. If you need a copy of your attributes hash, please use the #dup method.
-
#
-
# user = User.first
-
# new_user = user.clone
-
# user.name # => "Bob"
-
# new_user.name = "Joe"
-
# user.name # => "Joe"
-
#
-
# user.object_id == new_user.object_id # => false
-
# user.name.object_id == new_user.name.object_id # => true
-
#
-
# user.name.object_id == user.dup.name.object_id # => false
-
-
##
-
# :method: dup
-
# Duped objects have no id assigned and are treated as new records. Note
-
# that this is a "shallow" copy as it copies the object's attributes
-
# only, not its associations. The extent of a "deep" copy is application
-
# specific and is therefore left to the application to implement according
-
# to its need.
-
# The dup method does not preserve the timestamps (created|updated)_(at|on).
-
-
##
-
1
def initialize_dup(other) # :nodoc:
-
@attributes = @attributes.dup
-
@attributes.reset(self.class.primary_key)
-
-
_run_initialize_callbacks
-
-
@aggregation_cache = {}
-
@association_cache = {}
-
-
@new_record = true
-
@destroyed = false
-
-
super
-
end
-
-
# Populate +coder+ with attributes about this record that should be
-
# serialized. The structure of +coder+ defined in this method is
-
# guaranteed to match the structure of +coder+ passed to the +init_with+
-
# method.
-
#
-
# Example:
-
#
-
# class Post < ActiveRecord::Base
-
# end
-
# coder = {}
-
# Post.new.encode_with(coder)
-
# coder # => {"attributes" => {"id" => nil, ... }}
-
1
def encode_with(coder)
-
# FIXME: Remove this when we better serialize attributes
-
coder['raw_attributes'] = attributes_before_type_cast
-
coder['attributes'] = @attributes
-
coder['new_record'] = new_record?
-
coder['active_record_yaml_version'] = 0
-
end
-
-
# Returns true if +comparison_object+ is the same exact object, or +comparison_object+
-
# is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
-
#
-
# Note that new records are different from any other record by definition, unless the
-
# other record is the receiver itself. Besides, if you fetch existing records with
-
# +select+ and leave the ID out, you're on your own, this predicate will return false.
-
#
-
# Note also that destroying a record preserves its ID in the model instance, so deleted
-
# models are still comparable.
-
1
def ==(comparison_object)
-
super ||
-
comparison_object.instance_of?(self.class) &&
-
!id.nil? &&
-
comparison_object.id == id
-
end
-
1
alias :eql? :==
-
-
# Delegates to id in order to allow two records of the same type and id to work with something like:
-
# [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
-
1
def hash
-
if id
-
id.hash
-
else
-
super
-
end
-
end
-
-
# Clone and freeze the attributes hash such that associations are still
-
# accessible, even on destroyed records, but cloned models will not be
-
# frozen.
-
1
def freeze
-
3
@attributes = @attributes.clone.freeze
-
3
self
-
end
-
-
# Returns +true+ if the attributes hash has been frozen.
-
1
def frozen?
-
42
@attributes.frozen?
-
end
-
-
# Allows sort on objects
-
1
def <=>(other_object)
-
if other_object.is_a?(self.class)
-
self.to_key <=> other_object.to_key
-
else
-
super
-
end
-
end
-
-
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
-
# attributes will be marked as read only since they cannot be saved.
-
1
def readonly?
-
32
@readonly
-
end
-
-
# Marks this record as read only.
-
1
def readonly!
-
@readonly = true
-
end
-
-
1
def connection_handler
-
self.class.connection_handler
-
end
-
-
# Returns the contents of the record as a nicely formatted string.
-
1
def inspect
-
# We check defined?(@attributes) not to issue warnings if the object is
-
# allocated but not initialized.
-
inspection = if defined?(@attributes) && @attributes
-
self.class.column_names.collect { |name|
-
if has_attribute?(name)
-
"#{name}: #{attribute_for_inspect(name)}"
-
end
-
}.compact.join(", ")
-
else
-
"not initialized"
-
end
-
"#<#{self.class} #{inspection}>"
-
end
-
-
# Takes a PP and prettily prints this record to it, allowing you to get a nice result from `pp record`
-
# when pp is required.
-
1
def pretty_print(pp)
-
return super if custom_inspect_method_defined?
-
pp.object_address_group(self) do
-
if defined?(@attributes) && @attributes
-
column_names = self.class.column_names.select { |name| has_attribute?(name) || new_record? }
-
pp.seplist(column_names, proc { pp.text ',' }) do |column_name|
-
column_value = read_attribute(column_name)
-
pp.breakable ' '
-
pp.group(1) do
-
pp.text column_name
-
pp.text ':'
-
pp.breakable
-
pp.pp column_value
-
end
-
end
-
else
-
pp.breakable ' '
-
pp.text 'not initialized'
-
end
-
end
-
end
-
-
# Returns a hash of the given methods with their names as keys and returned values as values.
-
1
def slice(*methods)
-
Hash[methods.map! { |method| [method, public_send(method)] }].with_indifferent_access
-
end
-
-
1
private
-
-
1
def set_transaction_state(state) # :nodoc:
-
36
@transaction_state = state
-
end
-
-
1
def has_transactional_callbacks? # :nodoc:
-
50
!_rollback_callbacks.empty? || !_commit_callbacks.empty?
-
end
-
-
# Updates the attributes on this particular ActiveRecord object so that
-
# if it is associated with a transaction, then the state of the AR object
-
# will be updated to reflect the current state of the transaction
-
#
-
# The @transaction_state variable stores the states of the associated
-
# transaction. This relies on the fact that a transaction can only be in
-
# one rollback or commit (otherwise a list of states would be required)
-
# Each AR object inside of a transaction carries that transaction's
-
# TransactionState.
-
#
-
# This method checks to see if the ActiveRecord object's state reflects
-
# the TransactionState, and rolls back or commits the ActiveRecord object
-
# as appropriate.
-
#
-
# Since ActiveRecord objects can be inside multiple transactions, this
-
# method recursively goes through the parent of the TransactionState and
-
# checks if the ActiveRecord object reflects the state of the object.
-
1
def sync_with_transaction_state
-
184
update_attributes_from_transaction_state(@transaction_state, 0)
-
end
-
-
1
def update_attributes_from_transaction_state(transaction_state, depth)
-
184
@reflects_state = [false] if depth == 0
-
-
184
if transaction_state && transaction_state.finalized? && !has_transactional_callbacks?
-
14
unless @reflects_state[depth]
-
14
restore_transaction_record_state if transaction_state.rolledback?
-
14
clear_transaction_record_state
-
14
@reflects_state[depth] = true
-
end
-
-
14
if transaction_state.parent && !@reflects_state[depth+1]
-
update_attributes_from_transaction_state(transaction_state.parent, depth+1)
-
end
-
end
-
end
-
-
# Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
-
# of the array, and then rescues from the possible NoMethodError. If those elements are
-
# ActiveRecord::Base's, then this triggers the various method_missing's that we have,
-
# which significantly impacts upon performance.
-
#
-
# So we can avoid the method_missing hit by explicitly defining #to_ary as nil here.
-
#
-
# See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
-
1
def to_ary # :nodoc:
-
nil
-
end
-
-
1
def init_internals
-
83
@aggregation_cache = {}
-
83
@association_cache = {}
-
83
@readonly = false
-
83
@destroyed = false
-
83
@marked_for_destruction = false
-
83
@destroyed_by_association = nil
-
83
@new_record = true
-
83
@txn = nil
-
83
@_start_transaction_state = {}
-
83
@transaction_state = nil
-
end
-
-
1
def initialize_internals_callback
-
end
-
-
# This method is needed to make protected_attributes gem easier to hook.
-
# Remove it when we drop support to this gem.
-
1
def init_attributes(attributes, options)
-
25
assign_attributes(attributes)
-
end
-
-
1
def thaw
-
if frozen?
-
@attributes = @attributes.dup
-
end
-
end
-
-
1
def custom_inspect_method_defined?
-
self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Counter Cache
-
1
module CounterCache
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Resets one or more counter caches to their correct value using an SQL
-
# count query. This is useful when adding new counter caches, or if the
-
# counter has been corrupted or modified directly by SQL.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - The id of the object you wish to reset a counter on.
-
# * +counters+ - One or more association counters to reset. Association name or counter name can be given.
-
#
-
# ==== Examples
-
#
-
# # For Post with id #1 records reset the comments_count
-
# Post.reset_counters(1, :comments)
-
1
def reset_counters(id, *counters)
-
object = find(id)
-
counters.each do |counter_association|
-
has_many_association = _reflect_on_association(counter_association)
-
unless has_many_association
-
has_many = reflect_on_all_associations(:has_many)
-
has_many_association = has_many.find { |association| association.counter_cache_column && association.counter_cache_column.to_sym == counter_association.to_sym }
-
counter_association = has_many_association.plural_name if has_many_association
-
end
-
raise ArgumentError, "'#{self.name}' has no association called '#{counter_association}'" unless has_many_association
-
-
if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
-
has_many_association = has_many_association.through_reflection
-
end
-
-
foreign_key = has_many_association.foreign_key.to_s
-
child_class = has_many_association.klass
-
reflection = child_class._reflections.values.find { |e| e.belongs_to? && e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
-
counter_name = reflection.counter_cache_column
-
-
stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
-
arel_table[counter_name] => object.send(counter_association).count(:all)
-
}, primary_key)
-
connection.update stmt
-
end
-
return true
-
end
-
-
# A generic "counter updater" implementation, intended primarily to be
-
# used by increment_counter and decrement_counter, but which may also
-
# be useful on its own. It simply does a direct SQL update for the record
-
# with the given ID, altering the given hash of counters by the amount
-
# given by the corresponding value:
-
#
-
# ==== Parameters
-
#
-
# * +id+ - The id of the object you wish to update a counter on or an Array of ids.
-
# * +counters+ - A Hash containing the names of the fields
-
# to update as keys and the amount to update the field by as values.
-
#
-
# ==== Examples
-
#
-
# # For the Post with id of 5, decrement the comment_count by 1, and
-
# # increment the action_count by 1
-
# Post.update_counters 5, comment_count: -1, action_count: 1
-
# # Executes the following SQL:
-
# # UPDATE posts
-
# # SET comment_count = COALESCE(comment_count, 0) - 1,
-
# # action_count = COALESCE(action_count, 0) + 1
-
# # WHERE id = 5
-
#
-
# # For the Posts with id of 10 and 15, increment the comment_count by 1
-
# Post.update_counters [10, 15], comment_count: 1
-
# # Executes the following SQL:
-
# # UPDATE posts
-
# # SET comment_count = COALESCE(comment_count, 0) + 1
-
# # WHERE id IN (10, 15)
-
1
def update_counters(id, counters)
-
updates = counters.map do |counter_name, value|
-
operator = value < 0 ? '-' : '+'
-
quoted_column = connection.quote_column_name(counter_name)
-
"#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
-
end
-
-
unscoped.where(primary_key => id).update_all updates.join(', ')
-
end
-
-
# Increment a numeric field by one, via a direct SQL update.
-
#
-
# This method is used primarily for maintaining counter_cache columns that are
-
# used to store aggregate values. For example, a DiscussionBoard may cache
-
# posts_count and comments_count to avoid running an SQL query to calculate the
-
# number of posts and comments there are, each time it is displayed.
-
#
-
# ==== Parameters
-
#
-
# * +counter_name+ - The name of the field that should be incremented.
-
# * +id+ - The id of the object that should be incremented or an Array of ids.
-
#
-
# ==== Examples
-
#
-
# # Increment the post_count column for the record with an id of 5
-
# DiscussionBoard.increment_counter(:post_count, 5)
-
1
def increment_counter(counter_name, id)
-
update_counters(id, counter_name => 1)
-
end
-
-
# Decrement a numeric field by one, via a direct SQL update.
-
#
-
# This works the same as increment_counter but reduces the column value by
-
# 1 instead of increasing it.
-
#
-
# ==== Parameters
-
#
-
# * +counter_name+ - The name of the field that should be decremented.
-
# * +id+ - The id of the object that should be decremented or an Array of ids.
-
#
-
# ==== Examples
-
#
-
# # Decrement the post_count column for the record with an id of 5
-
# DiscussionBoard.decrement_counter(:post_count, 5)
-
1
def decrement_counter(counter_name, id)
-
update_counters(id, counter_name => -1)
-
end
-
end
-
-
1
protected
-
-
1
def actually_destroyed?
-
@_actually_destroyed
-
end
-
-
1
def clear_destroy_state
-
@_actually_destroyed = nil
-
end
-
-
1
private
-
-
1
def _create_record(*)
-
25
id = super
-
-
25
each_counter_cached_associations do |association|
-
if send(association.reflection.name)
-
association.increment_counters
-
@_after_create_counter_called = true
-
end
-
end
-
-
25
id
-
end
-
-
1
def destroy_row
-
3
affected_rows = super
-
-
3
if affected_rows > 0
-
3
each_counter_cached_associations do |association|
-
foreign_key = association.reflection.foreign_key.to_sym
-
unless destroyed_by_association && destroyed_by_association.foreign_key.to_sym == foreign_key
-
if send(association.reflection.name)
-
association.decrement_counters
-
end
-
end
-
end
-
end
-
-
3
affected_rows
-
end
-
-
1
def each_counter_cached_associations
-
28
_reflections.each do |name, reflection|
-
21
yield association(name.to_sym) if reflection.belongs_to? && reflection.counter_cache_column
-
end
-
end
-
-
end
-
end
-
1
module ActiveRecord
-
1
module DynamicMatchers #:nodoc:
-
# This code in this file seems to have a lot of indirection, but the indirection
-
# is there to provide extension points for the activerecord-deprecated_finders
-
# gem. When we stop supporting activerecord-deprecated_finders (from Rails 5),
-
# then we can remove the indirection.
-
-
1
def respond_to?(name, include_private = false)
-
323
if self == Base
-
1
super
-
else
-
322
match = Method.match(self, name)
-
322
match && match.valid? || super
-
end
-
end
-
-
1
private
-
-
1
def method_missing(name, *arguments, &block)
-
match = Method.match(self, name)
-
-
if match && match.valid?
-
match.define
-
send(name, *arguments, &block)
-
else
-
super
-
end
-
end
-
-
1
class Method
-
1
@matchers = []
-
-
1
class << self
-
1
attr_reader :matchers
-
-
1
def match(model, name)
-
966
klass = matchers.find { |k| name =~ k.pattern }
-
322
klass.new(model, name) if klass
-
end
-
-
1
def pattern
-
644
@pattern ||= /\A#{prefix}_([_a-zA-Z]\w*)#{suffix}\Z/
-
end
-
-
1
def prefix
-
raise NotImplementedError
-
end
-
-
1
def suffix
-
1
''
-
end
-
end
-
-
1
attr_reader :model, :name, :attribute_names
-
-
1
def initialize(model, name)
-
@model = model
-
@name = name.to_s
-
@attribute_names = @name.match(self.class.pattern)[1].split('_and_')
-
@attribute_names.map! { |n| @model.attribute_aliases[n] || n }
-
end
-
-
1
def valid?
-
attribute_names.all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) }
-
end
-
-
1
def define
-
model.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def self.#{name}(#{signature})
-
#{body}
-
end
-
CODE
-
end
-
-
1
def body
-
raise NotImplementedError
-
end
-
end
-
-
1
module Finder
-
# Extended in activerecord-deprecated_finders
-
1
def body
-
result
-
end
-
-
# Extended in activerecord-deprecated_finders
-
1
def result
-
"#{finder}(#{attributes_hash})"
-
end
-
-
# The parameters in the signature may have reserved Ruby words, in order
-
# to prevent errors, we start each param name with `_`.
-
#
-
# Extended in activerecord-deprecated_finders
-
1
def signature
-
attribute_names.map { |name| "_#{name}" }.join(', ')
-
end
-
-
# Given that the parameters starts with `_`, the finder needs to use the
-
# same parameter name.
-
1
def attributes_hash
-
"{" + attribute_names.map { |name| ":#{name} => _#{name}" }.join(',') + "}"
-
end
-
-
1
def finder
-
raise NotImplementedError
-
end
-
end
-
-
1
class FindBy < Method
-
1
Method.matchers << self
-
1
include Finder
-
-
1
def self.prefix
-
1
"find_by"
-
end
-
-
1
def finder
-
"find_by"
-
end
-
end
-
-
1
class FindByBang < Method
-
1
Method.matchers << self
-
1
include Finder
-
-
1
def self.prefix
-
1
"find_by"
-
end
-
-
1
def self.suffix
-
1
"!"
-
end
-
-
1
def finder
-
"find_by!"
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/deep_dup'
-
-
1
module ActiveRecord
-
# Declare an enum attribute where the values map to integers in the database,
-
# but can be queried by name. Example:
-
#
-
# class Conversation < ActiveRecord::Base
-
# enum status: [ :active, :archived ]
-
# end
-
#
-
# # conversation.update! status: 0
-
# conversation.active!
-
# conversation.active? # => true
-
# conversation.status # => "active"
-
#
-
# # conversation.update! status: 1
-
# conversation.archived!
-
# conversation.archived? # => true
-
# conversation.status # => "archived"
-
#
-
# # conversation.status = 1
-
# conversation.status = "archived"
-
#
-
# conversation.status = nil
-
# conversation.status.nil? # => true
-
# conversation.status # => nil
-
#
-
# Scopes based on the allowed values of the enum field will be provided
-
# as well. With the above example:
-
#
-
# Conversation.active
-
# Conversation.archived
-
#
-
# You can set the default value from the database declaration, like:
-
#
-
# create_table :conversations do |t|
-
# t.column :status, :integer, default: 0
-
# end
-
#
-
# Good practice is to let the first declared status be the default.
-
#
-
# Finally, it's also possible to explicitly map the relation between attribute and
-
# database integer with a +Hash+:
-
#
-
# class Conversation < ActiveRecord::Base
-
# enum status: { active: 0, archived: 1 }
-
# end
-
#
-
# Note that when an +Array+ is used, the implicit mapping from the values to database
-
# integers is derived from the order the values appear in the array. In the example,
-
# <tt>:active</tt> is mapped to +0+ as it's the first element, and <tt>:archived</tt>
-
# is mapped to +1+. In general, the +i+-th element is mapped to <tt>i-1</tt> in the
-
# database.
-
#
-
# Therefore, once a value is added to the enum array, its position in the array must
-
# be maintained, and new values should only be added to the end of the array. To
-
# remove unused values, the explicit +Hash+ syntax should be used.
-
#
-
# In rare circumstances you might need to access the mapping directly.
-
# The mappings are exposed through a class method with the pluralized attribute
-
# name:
-
#
-
# Conversation.statuses # => { "active" => 0, "archived" => 1 }
-
#
-
# Use that class method when you need to know the ordinal value of an enum:
-
#
-
# Conversation.where("status <> ?", Conversation.statuses[:archived])
-
#
-
# Where conditions on an enum attribute must use the ordinal value of an enum.
-
1
module Enum
-
1
def self.extended(base) # :nodoc:
-
1
base.class_attribute(:defined_enums)
-
1
base.defined_enums = {}
-
end
-
-
1
def inherited(base) # :nodoc:
-
5
base.defined_enums = defined_enums.deep_dup
-
5
super
-
end
-
-
1
def enum(definitions)
-
klass = self
-
definitions.each do |name, values|
-
# statuses = { }
-
enum_values = ActiveSupport::HashWithIndifferentAccess.new
-
name = name.to_sym
-
-
# def self.statuses statuses end
-
detect_enum_conflict!(name, name.to_s.pluralize, true)
-
klass.singleton_class.send(:define_method, name.to_s.pluralize) { enum_values }
-
-
_enum_methods_module.module_eval do
-
# def status=(value) self[:status] = statuses[value] end
-
klass.send(:detect_enum_conflict!, name, "#{name}=")
-
define_method("#{name}=") { |value|
-
if enum_values.has_key?(value) || value.blank?
-
self[name] = enum_values[value]
-
elsif enum_values.has_value?(value)
-
# Assigning a value directly is not a end-user feature, hence it's not documented.
-
# This is used internally to make building objects from the generated scopes work
-
# as expected, i.e. +Conversation.archived.build.archived?+ should be true.
-
self[name] = value
-
else
-
raise ArgumentError, "'#{value}' is not a valid #{name}"
-
end
-
}
-
-
# def status() statuses.key self[:status] end
-
klass.send(:detect_enum_conflict!, name, name)
-
define_method(name) { enum_values.key self[name] }
-
-
# def status_before_type_cast() statuses.key self[:status] end
-
klass.send(:detect_enum_conflict!, name, "#{name}_before_type_cast")
-
define_method("#{name}_before_type_cast") { enum_values.key self[name] }
-
-
pairs = values.respond_to?(:each_pair) ? values.each_pair : values.each_with_index
-
pairs.each do |value, i|
-
enum_values[value] = i
-
-
# def active?() status == 0 end
-
klass.send(:detect_enum_conflict!, name, "#{value}?")
-
define_method("#{value}?") { self[name] == i }
-
-
# def active!() update! status: :active end
-
klass.send(:detect_enum_conflict!, name, "#{value}!")
-
define_method("#{value}!") { update! name => value }
-
-
# scope :active, -> { where status: 0 }
-
klass.send(:detect_enum_conflict!, name, value, true)
-
klass.scope value, -> { klass.where name => i }
-
end
-
end
-
defined_enums[name.to_s] = enum_values
-
end
-
end
-
-
1
private
-
1
def _enum_methods_module
-
@_enum_methods_module ||= begin
-
mod = Module.new do
-
private
-
def save_changed_attribute(attr_name, old)
-
if (mapping = self.class.defined_enums[attr_name.to_s])
-
value = _read_attribute(attr_name)
-
if attribute_changed?(attr_name)
-
if mapping[old] == value
-
clear_attribute_changes([attr_name])
-
end
-
else
-
if old != value
-
set_attribute_was(attr_name, mapping.key(old))
-
end
-
end
-
else
-
super
-
end
-
end
-
end
-
include mod
-
mod
-
end
-
end
-
-
1
ENUM_CONFLICT_MESSAGE = \
-
"You tried to define an enum named \"%{enum}\" on the model \"%{klass}\", but " \
-
"this will generate a %{type} method \"%{method}\", which is already defined " \
-
"by %{source}."
-
-
1
def detect_enum_conflict!(enum_name, method_name, klass_method = false)
-
if klass_method && dangerous_class_method?(method_name)
-
raise ArgumentError, ENUM_CONFLICT_MESSAGE % {
-
enum: enum_name,
-
klass: self.name,
-
type: 'class',
-
method: method_name,
-
source: 'Active Record'
-
}
-
elsif !klass_method && dangerous_attribute_method?(method_name)
-
raise ArgumentError, ENUM_CONFLICT_MESSAGE % {
-
enum: enum_name,
-
klass: self.name,
-
type: 'instance',
-
method: method_name,
-
source: 'Active Record'
-
}
-
elsif !klass_method && method_defined_within?(method_name, _enum_methods_module, Module)
-
raise ArgumentError, ENUM_CONFLICT_MESSAGE % {
-
enum: enum_name,
-
klass: self.name,
-
type: 'instance',
-
method: method_name,
-
source: 'another enum'
-
}
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
-
# = Active Record Errors
-
#
-
# Generic Active Record exception class.
-
1
class ActiveRecordError < StandardError
-
end
-
-
# Raised when the single-table inheritance mechanism fails to locate the subclass
-
# (for example due to improper usage of column that +inheritance_column+ points to).
-
1
class SubclassNotFound < ActiveRecordError #:nodoc:
-
end
-
-
# Raised when an object assigned to an association has an incorrect type.
-
#
-
# class Ticket < ActiveRecord::Base
-
# has_many :patches
-
# end
-
#
-
# class Patch < ActiveRecord::Base
-
# belongs_to :ticket
-
# end
-
#
-
# # Comments are not patches, this assignment raises AssociationTypeMismatch.
-
# @ticket.patches << Comment.new(content: "Please attach tests to your patch.")
-
1
class AssociationTypeMismatch < ActiveRecordError
-
end
-
-
# Raised when unserialized object's type mismatches one specified for serializable field.
-
1
class SerializationTypeMismatch < ActiveRecordError
-
end
-
-
# Raised when adapter not specified on connection (or configuration file
-
# +config/database.yml+ misses adapter field).
-
1
class AdapterNotSpecified < ActiveRecordError
-
end
-
-
# Raised when Active Record cannot find database adapter specified in
-
# +config/database.yml+ or programmatically.
-
1
class AdapterNotFound < ActiveRecordError
-
end
-
-
# Raised when connection to the database could not been established (for
-
# example when +connection=+ is given a nil object).
-
1
class ConnectionNotEstablished < ActiveRecordError
-
end
-
-
# Raised when Active Record cannot find record by given id or set of ids.
-
1
class RecordNotFound < ActiveRecordError
-
end
-
-
# Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
-
# saved because record is invalid.
-
1
class RecordNotSaved < ActiveRecordError
-
1
attr_reader :record
-
-
1
def initialize(message, record = nil)
-
@record = record
-
super(message)
-
end
-
end
-
-
# Raised by ActiveRecord::Base.destroy! when a call to destroy would return false.
-
#
-
# begin
-
# complex_operation_that_internally_calls_destroy!
-
# rescue ActiveRecord::RecordNotDestroyed => invalid
-
# puts invalid.record.errors
-
# end
-
#
-
1
class RecordNotDestroyed < ActiveRecordError
-
1
attr_reader :record
-
-
1
def initialize(message, record = nil)
-
@record = record
-
super(message)
-
end
-
end
-
-
# Superclass for all database execution errors.
-
#
-
# Wraps the underlying database error as +original_exception+.
-
1
class StatementInvalid < ActiveRecordError
-
1
attr_reader :original_exception
-
-
1
def initialize(message, original_exception = nil)
-
super(message)
-
@original_exception = original_exception
-
end
-
end
-
-
# Defunct wrapper class kept for compatibility.
-
# +StatementInvalid+ wraps the original exception now.
-
1
class WrappedDatabaseException < StatementInvalid
-
end
-
-
# Raised when a record cannot be inserted because it would violate a uniqueness constraint.
-
1
class RecordNotUnique < WrappedDatabaseException
-
end
-
-
# Raised when a record cannot be inserted or updated because it references a non-existent record.
-
1
class InvalidForeignKey < WrappedDatabaseException
-
end
-
-
# Raised when number of bind variables in statement given to +:condition+ key
-
# (for example, when using +find+ method) does not match number of expected
-
# values supplied.
-
#
-
# For example, when there are two placeholders with only one value supplied:
-
#
-
# Location.where("lat = ? AND lng = ?", 53.7362)
-
1
class PreparedStatementInvalid < ActiveRecordError
-
end
-
-
# Raised when a given database does not exist.
-
1
class NoDatabaseError < StatementInvalid
-
end
-
-
# Raised on attempt to save stale record. Record is stale when it's being saved in another query after
-
# instantiation, for example, when two users edit the same wiki page and one starts editing and saves
-
# the page before the other.
-
#
-
# Read more about optimistic locking in ActiveRecord::Locking module
-
# documentation.
-
1
class StaleObjectError < ActiveRecordError
-
1
attr_reader :record, :attempted_action
-
-
1
def initialize(record, attempted_action)
-
super("Attempted to #{attempted_action} a stale object: #{record.class.name}")
-
@record = record
-
@attempted_action = attempted_action
-
end
-
-
end
-
-
# Raised when association is being configured improperly or user tries to use
-
# offset and limit together with +has_many+ or +has_and_belongs_to_many+
-
# associations.
-
1
class ConfigurationError < ActiveRecordError
-
end
-
-
# Raised on attempt to update record that is instantiated as read only.
-
1
class ReadOnlyRecord < ActiveRecordError
-
end
-
-
# ActiveRecord::Transactions::ClassMethods.transaction uses this exception
-
# to distinguish a deliberate rollback from other exceptional situations.
-
# Normally, raising an exception will cause the +transaction+ method to rollback
-
# the database transaction *and* pass on the exception. But if you raise an
-
# ActiveRecord::Rollback exception, then the database transaction will be rolled back,
-
# without passing on the exception.
-
#
-
# For example, you could do this in your controller to rollback a transaction:
-
#
-
# class BooksController < ActionController::Base
-
# def create
-
# Book.transaction do
-
# book = Book.new(params[:book])
-
# book.save!
-
# if today_is_friday?
-
# # The system must fail on Friday so that our support department
-
# # won't be out of job. We silently rollback this transaction
-
# # without telling the user.
-
# raise ActiveRecord::Rollback, "Call tech support!"
-
# end
-
# end
-
# # ActiveRecord::Rollback is the only exception that won't be passed on
-
# # by ActiveRecord::Base.transaction, so this line will still be reached
-
# # even on Friday.
-
# redirect_to root_url
-
# end
-
# end
-
1
class Rollback < ActiveRecordError
-
end
-
-
# Raised when attribute has a name reserved by Active Record (when attribute
-
# has name of one of Active Record instance methods).
-
1
class DangerousAttributeError < ActiveRecordError
-
end
-
-
# Raised when unknown attributes are supplied via mass assignment.
-
1
class UnknownAttributeError < NoMethodError
-
-
1
attr_reader :record, :attribute
-
-
1
def initialize(record, attribute)
-
@record = record
-
@attribute = attribute.to_s
-
super("unknown attribute '#{attribute}' for #{@record.class}.")
-
end
-
-
end
-
-
# Raised when an error occurred while doing a mass assignment to an attribute through the
-
# +attributes=+ method. The exception has an +attribute+ property that is the name of the
-
# offending attribute.
-
1
class AttributeAssignmentError < ActiveRecordError
-
1
attr_reader :exception, :attribute
-
-
1
def initialize(message, exception, attribute)
-
super(message)
-
@exception = exception
-
@attribute = attribute
-
end
-
end
-
-
# Raised when there are multiple errors while doing a mass assignment through the +attributes+
-
# method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
-
# objects, each corresponding to the error while assigning to an attribute.
-
1
class MultiparameterAssignmentErrors < ActiveRecordError
-
1
attr_reader :errors
-
-
1
def initialize(errors)
-
@errors = errors
-
end
-
end
-
-
# Raised when a primary key is needed, but not specified in the schema or model.
-
1
class UnknownPrimaryKey < ActiveRecordError
-
1
attr_reader :model
-
-
1
def initialize(model, description = nil)
-
message = "Unknown primary key for table #{model.table_name} in model #{model}."
-
message += "\n#{description}" if description
-
super(message)
-
@model = model
-
end
-
end
-
-
# Raised when a relation cannot be mutated because it's already loaded.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# relation = Task.all
-
# relation.loaded? # => true
-
#
-
# # Methods which try to mutate a loaded relation fail.
-
# relation.where!(title: 'TODO') # => ActiveRecord::ImmutableRelation
-
# relation.limit!(5) # => ActiveRecord::ImmutableRelation
-
1
class ImmutableRelation < ActiveRecordError
-
end
-
-
# TransactionIsolationError will be raised under the following conditions:
-
#
-
# * The adapter does not support setting the isolation level
-
# * You are joining an existing open transaction
-
# * You are creating a nested (savepoint) transaction
-
#
-
# The mysql, mysql2 and postgresql adapters support setting the transaction isolation level.
-
1
class TransactionIsolationError < ActiveRecordError
-
end
-
end
-
1
require 'active_support/lazy_load_hooks'
-
1
require 'active_record/explain_registry'
-
-
1
module ActiveRecord
-
1
module Explain
-
# Executes the block with the collect flag enabled. Queries are collected
-
# asynchronously by the subscriber and returned.
-
1
def collecting_queries_for_explain # :nodoc:
-
ExplainRegistry.collect = true
-
yield
-
ExplainRegistry.queries
-
ensure
-
ExplainRegistry.reset
-
end
-
-
# Makes the adapter execute EXPLAIN for the tuples of queries and bindings.
-
# Returns a formatted string ready to be logged.
-
1
def exec_explain(queries) # :nodoc:
-
str = queries.map do |sql, bind|
-
[].tap do |msg|
-
msg << "EXPLAIN for: #{sql}"
-
unless bind.empty?
-
bind_msg = bind.map {|col, val| [col.name, val]}.inspect
-
msg.last << " #{bind_msg}"
-
end
-
msg << connection.explain(sql, bind)
-
end.join("\n")
-
end.join("\n")
-
-
# Overriding inspect to be more human readable, especially in the console.
-
def str.inspect
-
self
-
end
-
-
str
-
end
-
end
-
end
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveRecord
-
# This is a thread locals registry for EXPLAIN. For example
-
#
-
# ActiveRecord::ExplainRegistry.queries
-
#
-
# returns the collected queries local to the current thread.
-
#
-
# See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
-
# for further details.
-
1
class ExplainRegistry # :nodoc:
-
1
extend ActiveSupport::PerThreadRegistry
-
-
1
attr_accessor :queries, :collect
-
-
1
def initialize
-
1
reset
-
end
-
-
1
def collect?
-
225
@collect
-
end
-
-
1
def reset
-
1
@collect = false
-
1
@queries = []
-
end
-
end
-
end
-
1
require 'active_support/notifications'
-
1
require 'active_record/explain_registry'
-
-
1
module ActiveRecord
-
1
class ExplainSubscriber # :nodoc:
-
1
def start(name, id, payload)
-
# unused
-
end
-
-
1
def finish(name, id, payload)
-
225
if ExplainRegistry.collect? && !ignore_payload?(payload)
-
ExplainRegistry.queries << payload.values_at(:sql, :binds)
-
end
-
end
-
-
# SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on
-
# our own EXPLAINs now matter how loopingly beautiful that would be.
-
#
-
# On the other hand, we want to monitor the performance of our real database
-
# queries, not the performance of the access to the query cache.
-
1
IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN CACHE)
-
1
EXPLAINED_SQLS = /\A\s*(with|select|update|delete|insert)\b/i
-
1
def ignore_payload?(payload)
-
payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name]) || payload[:sql] !~ EXPLAINED_SQLS
-
end
-
-
1
ActiveSupport::Notifications.subscribe("sql.active_record", new)
-
end
-
end
-
1
require 'erb'
-
1
require 'yaml'
-
-
1
module ActiveRecord
-
1
class FixtureSet
-
1
class File # :nodoc:
-
1
include Enumerable
-
-
##
-
# Open a fixture file named +file+. When called with a block, the block
-
# is called with the filehandle and the filehandle is automatically closed
-
# when the block finishes.
-
1
def self.open(file)
-
x = new file
-
block_given? ? yield(x) : x
-
end
-
-
1
def initialize(file)
-
@file = file
-
@rows = nil
-
end
-
-
1
def each(&block)
-
rows.each(&block)
-
end
-
-
-
1
private
-
1
def rows
-
return @rows if @rows
-
-
begin
-
data = YAML.load(render(IO.read(@file)))
-
rescue ArgumentError, Psych::SyntaxError => error
-
raise Fixture::FormatError, "a YAML error occurred parsing #{@file}. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html\nThe exact error was:\n #{error.class}: #{error}", error.backtrace
-
end
-
@rows = data ? validate(data).to_a : []
-
end
-
-
1
def render(content)
-
context = ActiveRecord::FixtureSet::RenderContext.create_subclass.new
-
ERB.new(content).result(context.get_binding)
-
end
-
-
# Validate our unmarshalled data.
-
1
def validate(data)
-
unless Hash === data || YAML::Omap === data
-
raise Fixture::FormatError, 'fixture is not a hash'
-
end
-
-
raise Fixture::FormatError unless data.all? { |name, row| Hash === row }
-
data
-
end
-
end
-
end
-
end
-
1
require 'erb'
-
1
require 'yaml'
-
1
require 'zlib'
-
1
require 'active_support/dependencies'
-
1
require 'active_support/core_ext/digest/uuid'
-
1
require 'active_record/fixture_set/file'
-
1
require 'active_record/errors'
-
-
1
module ActiveRecord
-
1
class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
-
end
-
-
# \Fixtures are a way of organizing data that you want to test against; in short, sample data.
-
#
-
# They are stored in YAML files, one file per model, which are placed in the directory
-
# appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically
-
# configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
-
# The fixture file ends with the +.yml+ file extension, for example:
-
# <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>).
-
#
-
# The format of a fixture file looks like this:
-
#
-
# rubyonrails:
-
# id: 1
-
# name: Ruby on Rails
-
# url: http://www.rubyonrails.org
-
#
-
# google:
-
# id: 2
-
# name: Google
-
# url: http://www.google.com
-
#
-
# This fixture file includes two fixtures. Each YAML fixture (ie. record) is given a name and
-
# is followed by an indented list of key/value pairs in the "key: value" format. Records are
-
# separated by a blank line for your viewing pleasure.
-
#
-
# Note: Fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
-
# See http://yaml.org/type/omap.html
-
# for the specification. You will need ordered fixtures when you have foreign key constraints
-
# on keys in the same table. This is commonly needed for tree structures. Example:
-
#
-
# --- !omap
-
# - parent:
-
# id: 1
-
# parent_id: NULL
-
# title: Parent
-
# - child:
-
# id: 2
-
# parent_id: 1
-
# title: Child
-
#
-
# = Using Fixtures in Test Cases
-
#
-
# Since fixtures are a testing construct, we use them in our unit and functional tests. There
-
# are two ways to use the fixtures, but first let's take a look at a sample unit test:
-
#
-
# require 'test_helper'
-
#
-
# class WebSiteTest < ActiveSupport::TestCase
-
# test "web_site_count" do
-
# assert_equal 2, WebSite.count
-
# end
-
# end
-
#
-
# By default, +test_helper.rb+ will load all of your fixtures into your test
-
# database, so this test will succeed.
-
#
-
# The testing environment will automatically load the all fixtures into the database before each
-
# test. To ensure consistent data, the environment deletes the fixtures before running the load.
-
#
-
# In addition to being available in the database, the fixture's data may also be accessed by
-
# using a special dynamic method, which has the same name as the model, and accepts the
-
# name of the fixture to instantiate:
-
#
-
# test "find" do
-
# assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
-
# end
-
#
-
# Alternatively, you may enable auto-instantiation of the fixture data. For instance, take the
-
# following tests:
-
#
-
# test "find_alt_method_1" do
-
# assert_equal "Ruby on Rails", @web_sites['rubyonrails']['name']
-
# end
-
#
-
# test "find_alt_method_2" do
-
# assert_equal "Ruby on Rails", @rubyonrails.name
-
# end
-
#
-
# In order to use these methods to access fixtured data within your testcases, you must specify one of the
-
# following in your <tt>ActiveSupport::TestCase</tt>-derived class:
-
#
-
# - to fully enable instantiated fixtures (enable alternate methods #1 and #2 above)
-
# self.use_instantiated_fixtures = true
-
#
-
# - create only the hash for the fixtures, do not 'find' each instance (enable alternate method #1 only)
-
# self.use_instantiated_fixtures = :no_instances
-
#
-
# Using either of these alternate methods incurs a performance hit, as the fixtured data must be fully
-
# traversed in the database to create the fixture hash and/or instance variables. This is expensive for
-
# large sets of fixtured data.
-
#
-
# = Dynamic fixtures with ERB
-
#
-
# Some times you don't care about the content of the fixtures as much as you care about the volume.
-
# In these cases, you can mix ERB in with your YAML fixtures to create a bunch of fixtures for load
-
# testing, like:
-
#
-
# <% 1.upto(1000) do |i| %>
-
# fix_<%= i %>:
-
# id: <%= i %>
-
# name: guy_<%= 1 %>
-
# <% end %>
-
#
-
# This will create 1000 very simple fixtures.
-
#
-
# Using ERB, you can also inject dynamic values into your fixtures with inserts like
-
# <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>.
-
# This is however a feature to be used with some caution. The point of fixtures are that they're
-
# stable units of predictable sample data. If you feel that you need to inject dynamic values, then
-
# perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
-
# in fixtures are to be considered a code smell.
-
#
-
# Helper methods defined in a fixture will not be available in other fixtures, to prevent against
-
# unwanted inter-test dependencies. Methods used by multiple fixtures should be defined in a module
-
# that is included in <tt>ActiveRecord::FixtureSet.context_class</tt>.
-
#
-
# - define a helper method in `test_helper.rb`
-
# module FixtureFileHelpers
-
# def file_sha(path)
-
# Digest::SHA2.hexdigest(File.read(Rails.root.join('test/fixtures', path)))
-
# end
-
# end
-
# ActiveRecord::FixtureSet.context_class.send :include, FixtureFileHelpers
-
#
-
# - use the helper method in a fixture
-
# photo:
-
# name: kitten.png
-
# sha: <%= file_sha 'files/kitten.png' %>
-
#
-
# = Transactional Fixtures
-
#
-
# Test cases can use begin+rollback to isolate their changes to the database instead of having to
-
# delete+insert for every test case.
-
#
-
# class FooTest < ActiveSupport::TestCase
-
# self.use_transactional_fixtures = true
-
#
-
# test "godzilla" do
-
# assert !Foo.all.empty?
-
# Foo.destroy_all
-
# assert Foo.all.empty?
-
# end
-
#
-
# test "godzilla aftermath" do
-
# assert !Foo.all.empty?
-
# end
-
# end
-
#
-
# If you preload your test database with all fixture data (probably in the rake task) and use
-
# transactional fixtures, then you may omit all fixtures declarations in your test cases since
-
# all the data's already there and every case rolls back its changes.
-
#
-
# In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to
-
# true. This will provide access to fixture data for every table that has been loaded through
-
# fixtures (depending on the value of +use_instantiated_fixtures+).
-
#
-
# When *not* to use transactional fixtures:
-
#
-
# 1. You're testing whether a transaction works correctly. Nested transactions don't commit until
-
# all parent transactions commit, particularly, the fixtures transaction which is begun in setup
-
# and rolled back in teardown. Thus, you won't be able to verify
-
# the results of your transaction until Active Record supports nested transactions or savepoints (in progress).
-
# 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM.
-
# Use InnoDB, MaxDB, or NDB instead.
-
#
-
# = Advanced Fixtures
-
#
-
# Fixtures that don't specify an ID get some extra features:
-
#
-
# * Stable, autogenerated IDs
-
# * Label references for associations (belongs_to, has_one, has_many)
-
# * HABTM associations as inline lists
-
#
-
# There are some more advanced features available even if the id is specified:
-
#
-
# * Autofilled timestamp columns
-
# * Fixture label interpolation
-
# * Support for YAML defaults
-
#
-
# == Stable, Autogenerated IDs
-
#
-
# Here, have a monkey fixture:
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
#
-
# reginald:
-
# id: 2
-
# name: Reginald the Pirate
-
#
-
# Each of these fixtures has two unique identifiers: one for the database
-
# and one for the humans. Why don't we generate the primary key instead?
-
# Hashing each fixture's label yields a consistent ID:
-
#
-
# george: # generated id: 503576764
-
# name: George the Monkey
-
#
-
# reginald: # generated id: 324201669
-
# name: Reginald the Pirate
-
#
-
# Active Record looks at the fixture's model class, discovers the correct
-
# primary key, and generates it right before inserting the fixture
-
# into the database.
-
#
-
# The generated ID for a given label is constant, so we can discover
-
# any fixture's ID without loading anything, as long as we know the label.
-
#
-
# == Label references for associations (belongs_to, has_one, has_many)
-
#
-
# Specifying foreign keys in fixtures can be very fragile, not to
-
# mention difficult to read. Since Active Record can figure out the ID of
-
# any fixture from its label, you can specify FK's by label instead of ID.
-
#
-
# === belongs_to
-
#
-
# Let's break out some more monkeys and pirates.
-
#
-
# ### in pirates.yml
-
#
-
# reginald:
-
# id: 1
-
# name: Reginald the Pirate
-
# monkey_id: 1
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
# pirate_id: 1
-
#
-
# Add a few more monkeys and pirates and break this into multiple files,
-
# and it gets pretty hard to keep track of what's going on. Let's
-
# use labels instead of IDs:
-
#
-
# ### in pirates.yml
-
#
-
# reginald:
-
# name: Reginald the Pirate
-
# monkey: george
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# name: George the Monkey
-
# pirate: reginald
-
#
-
# Pow! All is made clear. Active Record reflects on the fixture's model class,
-
# finds all the +belongs_to+ associations, and allows you to specify
-
# a target *label* for the *association* (monkey: george) rather than
-
# a target *id* for the *FK* (<tt>monkey_id: 1</tt>).
-
#
-
# ==== Polymorphic belongs_to
-
#
-
# Supporting polymorphic relationships is a little bit more complicated, since
-
# Active Record needs to know what type your association is pointing at. Something
-
# like this should look familiar:
-
#
-
# ### in fruit.rb
-
#
-
# belongs_to :eater, polymorphic: true
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# id: 1
-
# name: apple
-
# eater_id: 1
-
# eater_type: Monkey
-
#
-
# Can we do better? You bet!
-
#
-
# apple:
-
# eater: george (Monkey)
-
#
-
# Just provide the polymorphic target type and Active Record will take care of the rest.
-
#
-
# === has_and_belongs_to_many
-
#
-
# Time to give our monkey some fruit.
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# id: 1
-
# name: apple
-
#
-
# orange:
-
# id: 2
-
# name: orange
-
#
-
# grape:
-
# id: 3
-
# name: grape
-
#
-
# ### in fruits_monkeys.yml
-
#
-
# apple_george:
-
# fruit_id: 1
-
# monkey_id: 1
-
#
-
# orange_george:
-
# fruit_id: 2
-
# monkey_id: 1
-
#
-
# grape_george:
-
# fruit_id: 3
-
# monkey_id: 1
-
#
-
# Let's make the HABTM fixture go away.
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
# fruits: apple, orange, grape
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# name: apple
-
#
-
# orange:
-
# name: orange
-
#
-
# grape:
-
# name: grape
-
#
-
# Zap! No more fruits_monkeys.yml file. We've specified the list of fruits
-
# on George's fixture, but we could've just as easily specified a list
-
# of monkeys on each fruit. As with +belongs_to+, Active Record reflects on
-
# the fixture's model class and discovers the +has_and_belongs_to_many+
-
# associations.
-
#
-
# == Autofilled Timestamp Columns
-
#
-
# If your table/model specifies any of Active Record's
-
# standard timestamp columns (+created_at+, +created_on+, +updated_at+, +updated_on+),
-
# they will automatically be set to <tt>Time.now</tt>.
-
#
-
# If you've set specific values, they'll be left alone.
-
#
-
# == Fixture label interpolation
-
#
-
# The label of the current fixture is always available as a column value:
-
#
-
# geeksomnia:
-
# name: Geeksomnia's Account
-
# subdomain: $LABEL
-
# email: $LABEL@email.com
-
#
-
# Also, sometimes (like when porting older join table fixtures) you'll need
-
# to be able to get a hold of the identifier for a given label. ERB
-
# to the rescue:
-
#
-
# george_reginald:
-
# monkey_id: <%= ActiveRecord::FixtureSet.identify(:reginald) %>
-
# pirate_id: <%= ActiveRecord::FixtureSet.identify(:george) %>
-
#
-
# == Support for YAML defaults
-
#
-
# You can set and reuse defaults in your fixtures YAML file.
-
# This is the same technique used in the +database.yml+ file to specify
-
# defaults:
-
#
-
# DEFAULTS: &DEFAULTS
-
# created_on: <%= 3.weeks.ago.to_s(:db) %>
-
#
-
# first:
-
# name: Smurf
-
# <<: *DEFAULTS
-
#
-
# second:
-
# name: Fraggle
-
# <<: *DEFAULTS
-
#
-
# Any fixture labeled "DEFAULTS" is safely ignored.
-
1
class FixtureSet
-
#--
-
# An instance of FixtureSet is normally stored in a single YAML file and
-
# possibly in a folder with the same name.
-
#++
-
-
1
MAX_ID = 2 ** 30 - 1
-
-
1
@@all_cached_fixtures = Hash.new { |h,k| h[k] = {} }
-
-
1
def self.default_fixture_model_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc:
-
config.pluralize_table_names ?
-
fixture_set_name.singularize.camelize :
-
fixture_set_name.camelize
-
end
-
-
1
def self.default_fixture_table_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc:
-
"#{ config.table_name_prefix }"\
-
"#{ fixture_set_name.tr('/', '_') }"\
-
"#{ config.table_name_suffix }".to_sym
-
end
-
-
1
def self.reset_cache
-
@@all_cached_fixtures.clear
-
end
-
-
1
def self.cache_for_connection(connection)
-
@@all_cached_fixtures[connection]
-
end
-
-
1
def self.fixture_is_cached?(connection, table_name)
-
cache_for_connection(connection)[table_name]
-
end
-
-
1
def self.cached_fixtures(connection, keys_to_fetch = nil)
-
if keys_to_fetch
-
cache_for_connection(connection).values_at(*keys_to_fetch)
-
else
-
cache_for_connection(connection).values
-
end
-
end
-
-
1
def self.cache_fixtures(connection, fixtures_map)
-
cache_for_connection(connection).update(fixtures_map)
-
end
-
-
1
def self.instantiate_fixtures(object, fixture_set, load_instances = true)
-
if load_instances
-
fixture_set.each do |fixture_name, fixture|
-
begin
-
object.instance_variable_set "@#{fixture_name}", fixture.find
-
rescue FixtureClassNotFound
-
nil
-
end
-
end
-
end
-
end
-
-
1
def self.instantiate_all_loaded_fixtures(object, load_instances = true)
-
all_loaded_fixtures.each_value do |fixture_set|
-
instantiate_fixtures(object, fixture_set, load_instances)
-
end
-
end
-
-
1
cattr_accessor :all_loaded_fixtures
-
1
self.all_loaded_fixtures = {}
-
-
1
class ClassCache
-
1
def initialize(class_names, config)
-
@class_names = class_names.stringify_keys
-
@config = config
-
-
# Remove string values that aren't constants or subclasses of AR
-
@class_names.delete_if { |klass_name, klass| !insert_class(@class_names, klass_name, klass) }
-
end
-
-
1
def [](fs_name)
-
@class_names.fetch(fs_name) {
-
klass = default_fixture_model(fs_name, @config).safe_constantize
-
insert_class(@class_names, fs_name, klass)
-
}
-
end
-
-
1
private
-
-
1
def insert_class(class_names, name, klass)
-
# We only want to deal with AR objects.
-
if klass && klass < ActiveRecord::Base
-
class_names[name] = klass
-
else
-
class_names[name] = nil
-
end
-
end
-
-
1
def default_fixture_model(fs_name, config)
-
ActiveRecord::FixtureSet.default_fixture_model_name(fs_name, config)
-
end
-
end
-
-
1
def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {}, config = ActiveRecord::Base)
-
fixture_set_names = Array(fixture_set_names).map(&:to_s)
-
class_names = ClassCache.new class_names, config
-
-
# FIXME: Apparently JK uses this.
-
connection = block_given? ? yield : ActiveRecord::Base.connection
-
-
files_to_read = fixture_set_names.reject { |fs_name|
-
fixture_is_cached?(connection, fs_name)
-
}
-
-
unless files_to_read.empty?
-
connection.disable_referential_integrity do
-
fixtures_map = {}
-
-
fixture_sets = files_to_read.map do |fs_name|
-
klass = class_names[fs_name]
-
conn = klass ? klass.connection : connection
-
fixtures_map[fs_name] = new( # ActiveRecord::FixtureSet.new
-
conn,
-
fs_name,
-
klass,
-
::File.join(fixtures_directory, fs_name))
-
end
-
-
update_all_loaded_fixtures fixtures_map
-
-
connection.transaction(:requires_new => true) do
-
fixture_sets.each do |fs|
-
conn = fs.model_class.respond_to?(:connection) ? fs.model_class.connection : connection
-
table_rows = fs.table_rows
-
-
table_rows.each_key do |table|
-
conn.delete "DELETE FROM #{conn.quote_table_name(table)}", 'Fixture Delete'
-
end
-
-
table_rows.each do |fixture_set_name, rows|
-
rows.each do |row|
-
conn.insert_fixture(row, fixture_set_name)
-
end
-
end
-
-
# Cap primary key sequences to max(pk).
-
if conn.respond_to?(:reset_pk_sequence!)
-
conn.reset_pk_sequence!(fs.table_name)
-
end
-
end
-
end
-
-
cache_fixtures(connection, fixtures_map)
-
end
-
end
-
cached_fixtures(connection, fixture_set_names)
-
end
-
-
# Returns a consistent, platform-independent identifier for +label+.
-
# Integer identifiers are values less than 2^30. UUIDs are RFC 4122 version 5 SHA-1 hashes.
-
1
def self.identify(label, column_type = :integer)
-
if column_type == :uuid
-
Digest::UUID.uuid_v5(Digest::UUID::OID_NAMESPACE, label.to_s)
-
else
-
Zlib.crc32(label.to_s) % MAX_ID
-
end
-
end
-
-
# Superclass for the evaluation contexts used by ERB fixtures.
-
1
def self.context_class
-
@context_class ||= Class.new
-
end
-
-
1
def self.update_all_loaded_fixtures(fixtures_map) # :nodoc:
-
all_loaded_fixtures.update(fixtures_map)
-
end
-
-
1
attr_reader :table_name, :name, :fixtures, :model_class, :config
-
-
1
def initialize(connection, name, class_name, path, config = ActiveRecord::Base)
-
@name = name
-
@path = path
-
@config = config
-
@model_class = nil
-
-
if class_name.is_a?(Class) # TODO: Should be an AR::Base type class, or any?
-
@model_class = class_name
-
else
-
@model_class = class_name.safe_constantize if class_name
-
end
-
-
@connection = connection
-
-
@table_name = ( model_class.respond_to?(:table_name) ?
-
model_class.table_name :
-
self.class.default_fixture_table_name(name, config) )
-
-
@fixtures = read_fixture_files path, @model_class
-
end
-
-
1
def [](x)
-
fixtures[x]
-
end
-
-
1
def []=(k,v)
-
fixtures[k] = v
-
end
-
-
1
def each(&block)
-
fixtures.each(&block)
-
end
-
-
1
def size
-
fixtures.size
-
end
-
-
# Returns a hash of rows to be inserted. The key is the table, the value is
-
# a list of rows to insert to that table.
-
1
def table_rows
-
now = config.default_timezone == :utc ? Time.now.utc : Time.now
-
now = now.to_s(:db)
-
-
# allow a standard key to be used for doing defaults in YAML
-
fixtures.delete('DEFAULTS')
-
-
# track any join tables we need to insert later
-
rows = Hash.new { |h,table| h[table] = [] }
-
-
rows[table_name] = fixtures.map do |label, fixture|
-
row = fixture.to_hash
-
-
if model_class
-
# fill in timestamp columns if they aren't specified and the model is set to record_timestamps
-
if model_class.record_timestamps
-
timestamp_column_names.each do |c_name|
-
row[c_name] = now unless row.key?(c_name)
-
end
-
end
-
-
# interpolate the fixture label
-
row.each do |key, value|
-
row[key] = value.gsub("$LABEL", label.to_s) if value.is_a?(String)
-
end
-
-
# generate a primary key if necessary
-
if has_primary_key_column? && !row.include?(primary_key_name)
-
row[primary_key_name] = ActiveRecord::FixtureSet.identify(label, primary_key_type)
-
end
-
-
# If STI is used, find the correct subclass for association reflection
-
reflection_class =
-
if row.include?(inheritance_column_name)
-
row[inheritance_column_name].constantize rescue model_class
-
else
-
model_class
-
end
-
-
reflection_class._reflections.each_value do |association|
-
case association.macro
-
when :belongs_to
-
# Do not replace association name with association foreign key if they are named the same
-
fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
-
-
if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
-
if association.polymorphic? && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
-
# support polymorphic belongs_to as "label (Type)"
-
row[association.foreign_type] = $1
-
end
-
-
fk_type = reflection_class.columns_hash[fk_name].type
-
row[fk_name] = ActiveRecord::FixtureSet.identify(value, fk_type)
-
end
-
when :has_many
-
if association.options[:through]
-
add_join_records(rows, row, HasManyThroughProxy.new(association))
-
end
-
end
-
end
-
end
-
-
row
-
end
-
rows
-
end
-
-
1
class ReflectionProxy # :nodoc:
-
1
def initialize(association)
-
@association = association
-
end
-
-
1
def join_table
-
@association.join_table
-
end
-
-
1
def name
-
@association.name
-
end
-
-
1
def primary_key_type
-
@association.klass.column_types[@association.klass.primary_key].type
-
end
-
end
-
-
1
class HasManyThroughProxy < ReflectionProxy # :nodoc:
-
1
def rhs_key
-
@association.foreign_key
-
end
-
-
1
def lhs_key
-
@association.through_reflection.foreign_key
-
end
-
-
1
def join_table
-
@association.through_reflection.table_name
-
end
-
end
-
-
1
private
-
1
def primary_key_name
-
@primary_key_name ||= model_class && model_class.primary_key
-
end
-
-
1
def primary_key_type
-
@primary_key_type ||= model_class && model_class.column_types[model_class.primary_key].type
-
end
-
-
1
def add_join_records(rows, row, association)
-
# This is the case when the join table has no fixtures file
-
if (targets = row.delete(association.name.to_s))
-
table_name = association.join_table
-
column_type = association.primary_key_type
-
lhs_key = association.lhs_key
-
rhs_key = association.rhs_key
-
-
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
-
rows[table_name].concat targets.map { |target|
-
{ lhs_key => row[primary_key_name],
-
rhs_key => ActiveRecord::FixtureSet.identify(target, column_type) }
-
}
-
end
-
end
-
-
1
def has_primary_key_column?
-
@has_primary_key_column ||= primary_key_name &&
-
model_class.columns.any? { |c| c.name == primary_key_name }
-
end
-
-
1
def timestamp_column_names
-
@timestamp_column_names ||=
-
%w(created_at created_on updated_at updated_on) & column_names
-
end
-
-
1
def inheritance_column_name
-
@inheritance_column_name ||= model_class && model_class.inheritance_column
-
end
-
-
1
def column_names
-
@column_names ||= @connection.columns(@table_name).collect { |c| c.name }
-
end
-
-
1
def read_fixture_files(path, model_class)
-
yaml_files = Dir["#{path}/{**,*}/*.yml"].select { |f|
-
::File.file?(f)
-
} + [yaml_file_path(path)]
-
-
yaml_files.each_with_object({}) do |file, fixtures|
-
FixtureSet::File.open(file) do |fh|
-
fh.each do |fixture_name, row|
-
fixtures[fixture_name] = ActiveRecord::Fixture.new(row, model_class)
-
end
-
end
-
end
-
end
-
-
1
def yaml_file_path(path)
-
"#{path}.yml"
-
end
-
-
end
-
-
#--
-
# Deprecate 'Fixtures' in favor of 'FixtureSet'.
-
#++
-
# :nodoc:
-
1
Fixtures = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('ActiveRecord::Fixtures', 'ActiveRecord::FixtureSet')
-
-
1
class Fixture #:nodoc:
-
1
include Enumerable
-
-
1
class FixtureError < StandardError #:nodoc:
-
end
-
-
1
class FormatError < FixtureError #:nodoc:
-
end
-
-
1
attr_reader :model_class, :fixture
-
-
1
def initialize(fixture, model_class)
-
@fixture = fixture
-
@model_class = model_class
-
end
-
-
1
def class_name
-
model_class.name if model_class
-
end
-
-
1
def each
-
fixture.each { |item| yield item }
-
end
-
-
1
def [](key)
-
fixture[key]
-
end
-
-
1
alias :to_hash :fixture
-
-
1
def find
-
if model_class
-
model_class.unscoped do
-
model_class.find(fixture[model_class.primary_key])
-
end
-
else
-
raise FixtureClassNotFound, "No class attached to find."
-
end
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
1
module TestFixtures
-
1
extend ActiveSupport::Concern
-
-
1
def before_setup
-
setup_fixtures
-
super
-
end
-
-
1
def after_teardown
-
super
-
teardown_fixtures
-
end
-
-
1
included do
-
1
class_attribute :fixture_path, :instance_writer => false
-
1
class_attribute :fixture_table_names
-
1
class_attribute :fixture_class_names
-
1
class_attribute :use_transactional_fixtures
-
1
class_attribute :use_instantiated_fixtures # true, false, or :no_instances
-
1
class_attribute :pre_loaded_fixtures
-
1
class_attribute :config
-
-
1
self.fixture_table_names = []
-
1
self.use_transactional_fixtures = true
-
1
self.use_instantiated_fixtures = false
-
1
self.pre_loaded_fixtures = false
-
1
self.config = ActiveRecord::Base
-
-
1
self.fixture_class_names = Hash.new do |h, fixture_set_name|
-
h[fixture_set_name] = ActiveRecord::FixtureSet.default_fixture_model_name(fixture_set_name, self.config)
-
end
-
end
-
-
1
module ClassMethods
-
# Sets the model class for a fixture when the class name cannot be inferred from the fixture name.
-
#
-
# Examples:
-
#
-
# set_fixture_class some_fixture: SomeModel,
-
# 'namespaced/fixture' => Another::Model
-
#
-
# The keys must be the fixture names, that coincide with the short paths to the fixture files.
-
1
def set_fixture_class(class_names = {})
-
self.fixture_class_names = self.fixture_class_names.merge(class_names.stringify_keys)
-
end
-
-
1
def fixtures(*fixture_set_names)
-
if fixture_set_names.first == :all
-
fixture_set_names = Dir["#{fixture_path}/{**,*}/*.{yml}"]
-
fixture_set_names.map! { |f| f[(fixture_path.to_s.size + 1)..-5] }
-
else
-
fixture_set_names = fixture_set_names.flatten.map { |n| n.to_s }
-
end
-
-
self.fixture_table_names |= fixture_set_names
-
setup_fixture_accessors(fixture_set_names)
-
end
-
-
1
def setup_fixture_accessors(fixture_set_names = nil)
-
fixture_set_names = Array(fixture_set_names || fixture_table_names)
-
methods = Module.new do
-
fixture_set_names.each do |fs_name|
-
fs_name = fs_name.to_s
-
accessor_name = fs_name.tr('/', '_').to_sym
-
-
define_method(accessor_name) do |*fixture_names|
-
force_reload = fixture_names.pop if fixture_names.last == true || fixture_names.last == :reload
-
-
@fixture_cache[fs_name] ||= {}
-
-
instances = fixture_names.map do |f_name|
-
f_name = f_name.to_s
-
@fixture_cache[fs_name].delete(f_name) if force_reload
-
-
if @loaded_fixtures[fs_name][f_name]
-
@fixture_cache[fs_name][f_name] ||= @loaded_fixtures[fs_name][f_name].find
-
else
-
raise StandardError, "No fixture named '#{f_name}' found for fixture set '#{fs_name}'"
-
end
-
end
-
-
instances.size == 1 ? instances.first : instances
-
end
-
private accessor_name
-
end
-
end
-
include methods
-
end
-
-
1
def uses_transaction(*methods)
-
@uses_transaction = [] unless defined?(@uses_transaction)
-
@uses_transaction.concat methods.map { |m| m.to_s }
-
end
-
-
1
def uses_transaction?(method)
-
@uses_transaction = [] unless defined?(@uses_transaction)
-
@uses_transaction.include?(method.to_s)
-
end
-
end
-
-
1
def run_in_transaction?
-
use_transactional_fixtures &&
-
!self.class.uses_transaction?(method_name)
-
end
-
-
1
def setup_fixtures(config = ActiveRecord::Base)
-
if pre_loaded_fixtures && !use_transactional_fixtures
-
raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures'
-
end
-
-
@fixture_cache = {}
-
@fixture_connections = []
-
@@already_loaded_fixtures ||= {}
-
-
# Load fixtures once and begin transaction.
-
if run_in_transaction?
-
if @@already_loaded_fixtures[self.class]
-
@loaded_fixtures = @@already_loaded_fixtures[self.class]
-
else
-
@loaded_fixtures = load_fixtures(config)
-
@@already_loaded_fixtures[self.class] = @loaded_fixtures
-
end
-
@fixture_connections = enlist_fixture_connections
-
@fixture_connections.each do |connection|
-
connection.begin_transaction joinable: false
-
end
-
# Load fixtures for every test.
-
else
-
ActiveRecord::FixtureSet.reset_cache
-
@@already_loaded_fixtures[self.class] = nil
-
@loaded_fixtures = load_fixtures(config)
-
end
-
-
# Instantiate fixtures for every test if requested.
-
instantiate_fixtures if use_instantiated_fixtures
-
end
-
-
1
def teardown_fixtures
-
# Rollback changes if a transaction is active.
-
if run_in_transaction?
-
@fixture_connections.each do |connection|
-
connection.rollback_transaction if connection.transaction_open?
-
end
-
@fixture_connections.clear
-
else
-
ActiveRecord::FixtureSet.reset_cache
-
end
-
-
ActiveRecord::Base.clear_active_connections!
-
end
-
-
1
def enlist_fixture_connections
-
ActiveRecord::Base.connection_handler.connection_pool_list.map(&:connection)
-
end
-
-
1
private
-
1
def load_fixtures(config)
-
fixtures = ActiveRecord::FixtureSet.create_fixtures(fixture_path, fixture_table_names, fixture_class_names, config)
-
Hash[fixtures.map { |f| [f.name, f] }]
-
end
-
-
1
def instantiate_fixtures
-
if pre_loaded_fixtures
-
raise RuntimeError, 'Load fixtures before instantiating them.' if ActiveRecord::FixtureSet.all_loaded_fixtures.empty?
-
ActiveRecord::FixtureSet.instantiate_all_loaded_fixtures(self, load_instances?)
-
else
-
raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil?
-
@loaded_fixtures.each_value do |fixture_set|
-
ActiveRecord::FixtureSet.instantiate_fixtures(self, fixture_set, load_instances?)
-
end
-
end
-
end
-
-
1
def load_instances?
-
use_instantiated_fixtures != :no_instances
-
end
-
end
-
end
-
-
1
class ActiveRecord::FixtureSet::RenderContext # :nodoc:
-
1
def self.create_subclass
-
Class.new ActiveRecord::FixtureSet.context_class do
-
def get_binding
-
binding()
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# Returns the version of the currently loaded Active Record as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 2
-
1
TINY = 5
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActiveRecord
-
# == Single table inheritance
-
#
-
# Active Record allows inheritance by storing the name of the class in a column that by
-
# default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>).
-
# This means that an inheritance looking like this:
-
#
-
# class Company < ActiveRecord::Base; end
-
# class Firm < Company; end
-
# class Client < Company; end
-
# class PriorityClient < Client; end
-
#
-
# When you do <tt>Firm.create(name: "37signals")</tt>, this record will be saved in
-
# the companies table with type = "Firm". You can then fetch this row again using
-
# <tt>Company.where(name: '37signals').first</tt> and it will return a Firm object.
-
#
-
# Be aware that because the type column is an attribute on the record every new
-
# subclass will instantly be marked as dirty and the type column will be included
-
# in the list of changed attributes on the record. This is different from non
-
# STI classes:
-
#
-
# Company.new.changed? # => false
-
# Firm.new.changed? # => true
-
# Firm.new.changes # => {"type"=>["","Firm"]}
-
#
-
# If you don't have a type column defined in your table, single-table inheritance won't
-
# be triggered. In that case, it'll work just like normal subclasses with no special magic
-
# for differentiating between them or reloading the right type with find.
-
#
-
# Note, all the attributes for all the cases are kept in the same table. Read more:
-
# http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
-
#
-
1
module Inheritance
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
# Determines whether to store the full constant name including namespace when using STI.
-
1
class_attribute :store_full_sti_class, instance_writer: false
-
1
self.store_full_sti_class = true
-
end
-
-
1
module ClassMethods
-
# Determines if one of the attributes passed in is the inheritance column,
-
# and if the inheritance column is attr accessible, it initializes an
-
# instance of the given subclass instead of the base class.
-
1
def new(*args, &block)
-
29
if abstract_class? || self == Base
-
raise NotImplementedError, "#{self} is an abstract class and cannot be instantiated."
-
end
-
-
29
attrs = args.first
-
29
if subclass_from_attributes?(attrs)
-
subclass = subclass_from_attributes(attrs)
-
end
-
-
29
if subclass
-
subclass.new(*args, &block)
-
else
-
29
super
-
end
-
end
-
-
# Returns +true+ if this does not need STI type condition. Returns
-
# +false+ if STI type condition needs to be applied.
-
1
def descends_from_active_record?
-
5
if self == Base
-
false
-
5
elsif superclass.abstract_class?
-
superclass.descends_from_active_record?
-
else
-
5
superclass == Base || !columns_hash.include?(inheritance_column)
-
end
-
end
-
-
1
def finder_needs_type_condition? #:nodoc:
-
# This is like this because benchmarking justifies the strange :false stuff
-
125
:true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
-
end
-
-
1
def symbolized_base_class
-
ActiveSupport::Deprecation.warn('`ActiveRecord::Base.symbolized_base_class` is deprecated and will be removed without replacement.')
-
@symbolized_base_class ||= base_class.to_s.to_sym
-
end
-
-
1
def symbolized_sti_name
-
ActiveSupport::Deprecation.warn('`ActiveRecord::Base.symbolized_sti_name` is deprecated and will be removed without replacement.')
-
@symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class
-
end
-
-
# Returns the class descending directly from ActiveRecord::Base, or
-
# an abstract class, if any, in the inheritance hierarchy.
-
#
-
# If A extends AR::Base, A.base_class will return A. If B descends from A
-
# through some arbitrarily deep hierarchy, B.base_class will return A.
-
#
-
# If B < A and C < B and if A is an abstract_class then both B.base_class
-
# and C.base_class would return B as the answer since A is an abstract_class.
-
1
def base_class
-
104
unless self < Base
-
raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
-
end
-
-
104
if superclass == Base || superclass.abstract_class?
-
104
self
-
else
-
superclass.base_class
-
end
-
end
-
-
# Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
-
# If you are using inheritance with ActiveRecord and don't want child classes
-
# to utilize the implied STI table name of the parent class, this will need to be true.
-
# For example, given the following:
-
#
-
# class SuperClass < ActiveRecord::Base
-
# self.abstract_class = true
-
# end
-
# class Child < SuperClass
-
# self.table_name = 'the_table_i_really_want'
-
# end
-
#
-
#
-
# <tt>self.abstract_class = true</tt> is required to make <tt>Child<.find,.create, or any Arel method></tt> use <tt>the_table_i_really_want</tt> instead of a table called <tt>super_classes</tt>
-
#
-
1
attr_accessor :abstract_class
-
-
# Returns whether this class is an abstract class or not.
-
1
def abstract_class?
-
74
defined?(@abstract_class) && @abstract_class == true
-
end
-
-
1
def sti_name
-
store_full_sti_class ? name : name.demodulize
-
end
-
-
1
protected
-
-
# Returns the class type of the record using the current module as a prefix. So descendants of
-
# MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
-
1
def compute_type(type_name)
-
if type_name.match(/^::/)
-
# If the type is prefixed with a scope operator then we assume that
-
# the type_name is an absolute reference.
-
ActiveSupport::Dependencies.constantize(type_name)
-
else
-
# Build a list of candidates to search for
-
candidates = []
-
name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
-
candidates << type_name
-
-
candidates.each do |candidate|
-
constant = ActiveSupport::Dependencies.safe_constantize(candidate)
-
return constant if candidate == constant.to_s
-
end
-
-
raise NameError.new("uninitialized constant #{candidates.first}", candidates.first)
-
end
-
end
-
-
1
private
-
-
# Called by +instantiate+ to decide which class to use for a new
-
# record instance. For single-table inheritance, we check the record
-
# for a +type+ column and return the corresponding class.
-
1
def discriminate_class_for_record(record)
-
54
if using_single_table_inheritance?(record)
-
find_sti_class(record[inheritance_column])
-
else
-
54
super
-
end
-
end
-
-
1
def using_single_table_inheritance?(record)
-
54
record[inheritance_column].present? && columns_hash.include?(inheritance_column)
-
end
-
-
1
def find_sti_class(type_name)
-
if store_full_sti_class
-
ActiveSupport::Dependencies.constantize(type_name)
-
else
-
compute_type(type_name)
-
end
-
rescue NameError
-
raise SubclassNotFound,
-
"The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " +
-
"This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
-
"Please rename this column if you didn't intend it to be used for storing the inheritance class " +
-
"or overwrite #{name}.inheritance_column to use another column for that information."
-
end
-
-
1
def type_condition(table = arel_table)
-
sti_column = table[inheritance_column]
-
sti_names = ([self] + descendants).map { |model| model.sti_name }
-
-
sti_column.in(sti_names)
-
end
-
-
# Detect the subclass from the inheritance column of attrs. If the inheritance column value
-
# is not self or a valid subclass, raises ActiveRecord::SubclassNotFound
-
# If this is a StrongParameters hash, and access to inheritance_column is not permitted,
-
# this will ignore the inheritance column and return nil
-
1
def subclass_from_attributes?(attrs)
-
29
columns_hash.include?(inheritance_column) && attrs.is_a?(Hash)
-
end
-
-
1
def subclass_from_attributes(attrs)
-
subclass_name = attrs.with_indifferent_access[inheritance_column]
-
-
if subclass_name.present? && subclass_name != self.name
-
subclass = subclass_name.safe_constantize
-
-
unless descendants.include?(subclass)
-
raise ActiveRecord::SubclassNotFound.new("Invalid single-table inheritance type: #{subclass_name} is not a subclass of #{name}")
-
end
-
-
subclass
-
end
-
end
-
end
-
-
1
def initialize_dup(other)
-
super
-
ensure_proper_type
-
end
-
-
1
private
-
-
1
def initialize_internals_callback
-
29
super
-
29
ensure_proper_type
-
end
-
-
# Sets the attribute used for single table inheritance to this class name if this is not the
-
# ActiveRecord::Base descendant.
-
# Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to
-
# do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself.
-
# No such attribute would be set for objects of the Message class in that example.
-
1
def ensure_proper_type
-
29
klass = self.class
-
29
if klass.finder_needs_type_condition?
-
write_attribute(klass.inheritance_column, klass.sti_name)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/filters'
-
-
1
module ActiveRecord
-
1
module Integration
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
##
-
# :singleton-method:
-
# Indicates the format used to generate the timestamp in the cache key.
-
# Accepts any of the symbols in <tt>Time::DATE_FORMATS</tt>.
-
#
-
# This is +:nsec+, by default.
-
1
class_attribute :cache_timestamp_format, :instance_writer => false
-
1
self.cache_timestamp_format = :nsec
-
end
-
-
# Returns a String, which Action Pack uses for constructing an URL to this
-
# object. The default implementation returns this record's id as a String,
-
# or nil if this record's unsaved.
-
#
-
# For example, suppose that you have a User model, and that you have a
-
# <tt>resources :users</tt> route. Normally, +user_path+ will
-
# construct a path with the user object's 'id' in it:
-
#
-
# user = User.find_by(name: 'Phusion')
-
# user_path(user) # => "/users/1"
-
#
-
# You can override +to_param+ in your model to make +user_path+ construct
-
# a path using the user's name instead of the user's id:
-
#
-
# class User < ActiveRecord::Base
-
# def to_param # overridden
-
# name
-
# end
-
# end
-
#
-
# user = User.find_by(name: 'Phusion')
-
# user_path(user) # => "/users/Phusion"
-
1
def to_param
-
# We can't use alias_method here, because method 'id' optimizes itself on the fly.
-
78
id && id.to_s # Be sure to stringify the id for routes
-
end
-
-
# Returns a cache key that can be used to identify this record.
-
#
-
# Product.new.cache_key # => "products/new"
-
# Product.find(5).cache_key # => "products/5" (updated_at not available)
-
# Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
-
#
-
# You can also pass a list of named timestamps, and the newest in the list will be
-
# used to generate the key:
-
#
-
# Person.find(5).cache_key(:updated_at, :last_reviewed_at)
-
1
def cache_key(*timestamp_names)
-
case
-
when new_record?
-
"#{model_name.cache_key}/new"
-
when timestamp_names.any?
-
timestamp = max_updated_column_timestamp(timestamp_names)
-
timestamp = timestamp.utc.to_s(cache_timestamp_format)
-
"#{model_name.cache_key}/#{id}-#{timestamp}"
-
when timestamp = max_updated_column_timestamp
-
timestamp = timestamp.utc.to_s(cache_timestamp_format)
-
"#{model_name.cache_key}/#{id}-#{timestamp}"
-
else
-
"#{model_name.cache_key}/#{id}"
-
end
-
end
-
-
1
module ClassMethods
-
# Defines your model's +to_param+ method to generate "pretty" URLs
-
# using +method_name+, which can be any attribute or method that
-
# responds to +to_s+.
-
#
-
# class User < ActiveRecord::Base
-
# to_param :name
-
# end
-
#
-
# user = User.find_by(name: 'Fancy Pants')
-
# user.id # => 123
-
# user_path(user) # => "/users/123-fancy-pants"
-
#
-
# Values longer than 20 characters will be truncated. The value
-
# is truncated word by word.
-
#
-
# user = User.find_by(name: 'David HeinemeierHansson')
-
# user.id # => 125
-
# user_path(user) # => "/users/125-david"
-
#
-
# Because the generated param begins with the record's +id+, it is
-
# suitable for passing to +find+. In a controller, for example:
-
#
-
# params[:id] # => "123-fancy-pants"
-
# User.find(params[:id]).id # => 123
-
1
def to_param(method_name = nil)
-
if method_name.nil?
-
super()
-
else
-
define_method :to_param do
-
if (default = super()) &&
-
(result = send(method_name).to_s).present? &&
-
(param = result.squish.truncate(20, separator: /\s/, omission: nil).parameterize).present?
-
"#{default}-#{param}"
-
else
-
default
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module LegacyYamlAdapter
-
1
def self.convert(klass, coder)
-
54
return coder unless coder.is_a?(Psych::Coder)
-
-
case coder["active_record_yaml_version"]
-
when 0 then coder
-
else
-
if coder["attributes"].is_a?(AttributeSet)
-
coder
-
else
-
Rails41.convert(klass, coder)
-
end
-
end
-
end
-
-
1
module Rails41
-
1
def self.convert(klass, coder)
-
attributes = klass.attributes_builder
-
.build_from_database(coder["attributes"])
-
new_record = coder["attributes"][klass.primary_key].blank?
-
-
{
-
"attributes" => attributes,
-
"new_record" => new_record,
-
}
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Locking
-
# == What is Optimistic Locking
-
#
-
# Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of
-
# conflicts with the data. It does this by checking whether another process has made changes to a record since
-
# it was opened, an <tt>ActiveRecord::StaleObjectError</tt> exception is thrown if that has occurred
-
# and the update is ignored.
-
#
-
# Check out <tt>ActiveRecord::Locking::Pessimistic</tt> for an alternative.
-
#
-
# == Usage
-
#
-
# Active Records support optimistic locking if the field +lock_version+ is present. Each update to the
-
# record increments the +lock_version+ column and the locking facilities ensure that records instantiated twice
-
# will let the last one saved raise a +StaleObjectError+ if the first was also updated. Example:
-
#
-
# p1 = Person.find(1)
-
# p2 = Person.find(1)
-
#
-
# p1.first_name = "Michael"
-
# p1.save
-
#
-
# p2.first_name = "should fail"
-
# p2.save # Raises a ActiveRecord::StaleObjectError
-
#
-
# Optimistic locking will also check for stale data when objects are destroyed. Example:
-
#
-
# p1 = Person.find(1)
-
# p2 = Person.find(1)
-
#
-
# p1.first_name = "Michael"
-
# p1.save
-
#
-
# p2.destroy # Raises a ActiveRecord::StaleObjectError
-
#
-
# You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
-
# or otherwise apply the business logic needed to resolve the conflict.
-
#
-
# This locking mechanism will function inside a single Ruby process. To make it work across all
-
# web requests, the recommended approach is to add +lock_version+ as a hidden field to your form.
-
#
-
# This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
-
# To override the name of the +lock_version+ column, set the <tt>locking_column</tt> class attribute:
-
#
-
# class Person < ActiveRecord::Base
-
# self.locking_column = :lock_person
-
# end
-
#
-
1
module Optimistic
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :lock_optimistically, instance_writer: false
-
1
self.lock_optimistically = true
-
end
-
-
1
def locking_enabled? #:nodoc:
-
35
self.class.locking_enabled?
-
end
-
-
1
private
-
1
def increment_lock
-
lock_col = self.class.locking_column
-
previous_lock_value = send(lock_col).to_i
-
send(lock_col + '=', previous_lock_value + 1)
-
end
-
-
1
def _create_record(attribute_names = self.attribute_names, *) # :nodoc:
-
25
if locking_enabled?
-
# We always want to persist the locking version, even if we don't detect
-
# a change from the default, since the database might have no default
-
attribute_names |= [self.class.locking_column]
-
end
-
25
super
-
end
-
-
1
def _update_record(attribute_names = self.attribute_names) #:nodoc:
-
4
return super unless locking_enabled?
-
return 0 if attribute_names.empty?
-
-
lock_col = self.class.locking_column
-
previous_lock_value = send(lock_col).to_i
-
increment_lock
-
-
attribute_names += [lock_col]
-
attribute_names.uniq!
-
-
begin
-
relation = self.class.unscoped
-
-
affected_rows = relation.where(
-
self.class.primary_key => id,
-
lock_col => previous_lock_value,
-
).update_all(
-
Hash[attributes_for_update(attribute_names).map do |name|
-
[name, _read_attribute(name)]
-
end]
-
)
-
-
unless affected_rows == 1
-
raise ActiveRecord::StaleObjectError.new(self, "update")
-
end
-
-
affected_rows
-
-
# If something went wrong, revert the version.
-
rescue Exception
-
send(lock_col + '=', previous_lock_value)
-
raise
-
end
-
end
-
-
1
def destroy_row
-
3
affected_rows = super
-
-
3
if locking_enabled? && affected_rows != 1
-
raise ActiveRecord::StaleObjectError.new(self, "destroy")
-
end
-
-
3
affected_rows
-
end
-
-
1
def relation_for_destroy
-
3
relation = super
-
-
3
if locking_enabled?
-
column_name = self.class.locking_column
-
column = self.class.columns_hash[column_name]
-
substitute = self.class.connection.substitute_at(column)
-
-
relation = relation.where(self.class.arel_table[column_name].eq(substitute))
-
relation.bind_values << [column, self[column_name].to_i]
-
end
-
-
3
relation
-
end
-
-
1
module ClassMethods
-
1
DEFAULT_LOCKING_COLUMN = 'lock_version'
-
-
# Returns true if the +lock_optimistically+ flag is set to true
-
# (which it is, by default) and the table includes the
-
# +locking_column+ column (defaults to +lock_version+).
-
1
def locking_enabled?
-
35
lock_optimistically && columns_hash[locking_column]
-
end
-
-
# Set the column to use for optimistic locking. Defaults to +lock_version+.
-
1
def locking_column=(value)
-
5
clear_caches_calculated_from_columns
-
5
@locking_column = value.to_s
-
end
-
-
# The version column used for optimistic locking. Defaults to +lock_version+.
-
1
def locking_column
-
63
reset_locking_column unless defined?(@locking_column)
-
63
@locking_column
-
end
-
-
# Reset the column used for optimistic locking back to the +lock_version+ default.
-
1
def reset_locking_column
-
5
self.locking_column = DEFAULT_LOCKING_COLUMN
-
end
-
-
# Make sure the lock version column gets updated when counters are
-
# updated.
-
1
def update_counters(id, counters)
-
counters = counters.merge(locking_column => 1) if locking_enabled?
-
super
-
end
-
-
1
private
-
-
# We need to apply this decorator here, rather than on module inclusion. The closure
-
# created by the matcher would otherwise evaluate for `ActiveRecord::Base`, not the
-
# sub class being decorated. As such, changes to `lock_optimistically`, or
-
# `locking_column` would not be picked up.
-
1
def inherited(subclass)
-
5
subclass.class_eval do
-
33
is_lock_column = ->(name, _) { lock_optimistically && name == locking_column }
-
5
decorate_matching_attribute_types(is_lock_column, :_optimistic_locking) do |type|
-
LockingType.new(type)
-
end
-
end
-
5
super
-
end
-
end
-
end
-
-
1
class LockingType < SimpleDelegator # :nodoc:
-
1
def type_cast_from_database(value)
-
# `nil` *should* be changed to 0
-
super.to_i
-
end
-
-
1
def init_with(coder)
-
__setobj__(coder['subtype'])
-
end
-
-
1
def encode_with(coder)
-
coder['subtype'] = __getobj__
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Locking
-
# Locking::Pessimistic provides support for row-level locking using
-
# SELECT ... FOR UPDATE and other lock types.
-
#
-
# Chain <tt>ActiveRecord::Base#find</tt> to <tt>ActiveRecord::QueryMethods#lock</tt> to obtain an exclusive
-
# lock on the selected rows:
-
# # select * from accounts where id=1 for update
-
# Account.lock.find(1)
-
#
-
# Call <tt>lock('some locking clause')</tt> to use a database-specific locking clause
-
# of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'. Example:
-
#
-
# Account.transaction do
-
# # select * from accounts where name = 'shugo' limit 1 for update
-
# shugo = Account.where("name = 'shugo'").lock(true).first
-
# yuko = Account.where("name = 'yuko'").lock(true).first
-
# shugo.balance -= 100
-
# shugo.save!
-
# yuko.balance += 100
-
# yuko.save!
-
# end
-
#
-
# You can also use <tt>ActiveRecord::Base#lock!</tt> method to lock one record by id.
-
# This may be better if you don't need to lock every row. Example:
-
#
-
# Account.transaction do
-
# # select * from accounts where ...
-
# accounts = Account.where(...)
-
# account1 = accounts.detect { |account| ... }
-
# account2 = accounts.detect { |account| ... }
-
# # select * from accounts where id=? for update
-
# account1.lock!
-
# account2.lock!
-
# account1.balance -= 100
-
# account1.save!
-
# account2.balance += 100
-
# account2.save!
-
# end
-
#
-
# You can start a transaction and acquire the lock in one go by calling
-
# <tt>with_lock</tt> with a block. The block is called from within
-
# a transaction, the object is already locked. Example:
-
#
-
# account = Account.first
-
# account.with_lock do
-
# # This block is called within a transaction,
-
# # account is already locked.
-
# account.balance -= 100
-
# account.save!
-
# end
-
#
-
# Database-specific information on row locking:
-
# MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
-
# PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
-
1
module Pessimistic
-
# Obtain a row lock on this record. Reloads the record to obtain the requested
-
# lock. Pass an SQL locking clause to append the end of the SELECT statement
-
# or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
-
# the locked record.
-
1
def lock!(lock = true)
-
reload(:lock => lock) if persisted?
-
self
-
end
-
-
# Wraps the passed block in a transaction, locking the object
-
# before yielding. You can pass the SQL locking clause
-
# as argument (see <tt>lock!</tt>).
-
1
def with_lock(lock = true)
-
transaction do
-
lock!(lock)
-
yield
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class LogSubscriber < ActiveSupport::LogSubscriber
-
1
IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"]
-
-
1
def self.runtime=(value)
-
467
ActiveRecord::RuntimeRegistry.sql_runtime = value
-
end
-
-
1
def self.runtime
-
467
ActiveRecord::RuntimeRegistry.sql_runtime ||= 0
-
end
-
-
1
def self.reset_runtime
-
242
rt, self.runtime = runtime, 0
-
242
rt
-
end
-
-
1
def initialize
-
1
super
-
1
@odd = false
-
end
-
-
1
def render_bind(column, value)
-
168
if column
-
168
if column.binary?
-
# This specifically deals with the PG adapter that casts bytea columns into a Hash.
-
value = value[:value] if value.is_a?(Hash)
-
value = value ? "<#{value.bytesize} bytes of binary data>" : "<NULL binary data>"
-
end
-
-
168
[column.name, value]
-
else
-
[nil, value]
-
end
-
end
-
-
1
def sql(event)
-
225
self.class.runtime += event.duration
-
225
return unless logger.debug?
-
-
225
payload = event.payload
-
-
225
return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])
-
-
214
name = "#{payload[:name]} (#{event.duration.round(1)}ms)"
-
214
sql = payload[:sql]
-
214
binds = nil
-
-
214
unless (payload[:binds] || []).empty?
-
54
binds = " " + payload[:binds].map { |col,v|
-
168
render_bind(col, v)
-
}.inspect
-
end
-
-
214
if odd?
-
107
name = color(name, CYAN, true)
-
107
sql = color(sql, nil, true)
-
else
-
107
name = color(name, MAGENTA, true)
-
end
-
-
214
debug " #{name} #{sql}#{binds}"
-
end
-
-
1
def odd?
-
214
@odd = !@odd
-
end
-
-
1
def logger
-
1103
ActiveRecord::Base.logger
-
end
-
end
-
end
-
-
1
ActiveRecord::LogSubscriber.attach_to :active_record
-
1
require "active_support/core_ext/module/attribute_accessors"
-
1
require 'set'
-
-
1
module ActiveRecord
-
1
class MigrationError < ActiveRecordError#:nodoc:
-
1
def initialize(message = nil)
-
message = "\n\n#{message}\n\n" if message
-
super
-
end
-
end
-
-
# Exception that can be raised to stop migrations from going backwards.
-
1
class IrreversibleMigration < MigrationError
-
end
-
-
1
class DuplicateMigrationVersionError < MigrationError#:nodoc:
-
1
def initialize(version)
-
super("Multiple migrations have the version number #{version}")
-
end
-
end
-
-
1
class DuplicateMigrationNameError < MigrationError#:nodoc:
-
1
def initialize(name)
-
super("Multiple migrations have the name #{name}")
-
end
-
end
-
-
1
class UnknownMigrationVersionError < MigrationError #:nodoc:
-
1
def initialize(version)
-
super("No migration with version number #{version}")
-
end
-
end
-
-
1
class IllegalMigrationNameError < MigrationError#:nodoc:
-
1
def initialize(name)
-
super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed)")
-
end
-
end
-
-
1
class PendingMigrationError < MigrationError#:nodoc:
-
1
def initialize
-
if defined?(Rails.env)
-
super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rake db:migrate RAILS_ENV=#{::Rails.env}")
-
else
-
super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rake db:migrate")
-
end
-
end
-
end
-
-
# = Active Record Migrations
-
#
-
# Migrations can manage the evolution of a schema used by several physical
-
# databases. It's a solution to the common problem of adding a field to make
-
# a new feature work in your local database, but being unsure of how to
-
# push that change to other developers and to the production server. With
-
# migrations, you can describe the transformations in self-contained classes
-
# that can be checked into version control systems and executed against
-
# another database that might be one, two, or five versions behind.
-
#
-
# Example of a simple migration:
-
#
-
# class AddSsl < ActiveRecord::Migration
-
# def up
-
# add_column :accounts, :ssl_enabled, :boolean, default: true
-
# end
-
#
-
# def down
-
# remove_column :accounts, :ssl_enabled
-
# end
-
# end
-
#
-
# This migration will add a boolean flag to the accounts table and remove it
-
# if you're backing out of the migration. It shows how all migrations have
-
# two methods +up+ and +down+ that describes the transformations
-
# required to implement or remove the migration. These methods can consist
-
# of both the migration specific methods like +add_column+ and +remove_column+,
-
# but may also contain regular Ruby code for generating data needed for the
-
# transformations.
-
#
-
# Example of a more complex migration that also needs to initialize data:
-
#
-
# class AddSystemSettings < ActiveRecord::Migration
-
# def up
-
# create_table :system_settings do |t|
-
# t.string :name
-
# t.string :label
-
# t.text :value
-
# t.string :type
-
# t.integer :position
-
# end
-
#
-
# SystemSetting.create name: 'notice',
-
# label: 'Use notice?',
-
# value: 1
-
# end
-
#
-
# def down
-
# drop_table :system_settings
-
# end
-
# end
-
#
-
# This migration first adds the +system_settings+ table, then creates the very
-
# first row in it using the Active Record model that relies on the table. It
-
# also uses the more advanced +create_table+ syntax where you can specify a
-
# complete table schema in one block call.
-
#
-
# == Available transformations
-
#
-
# * <tt>create_table(name, options)</tt>: Creates a table called +name+ and
-
# makes the table object available to a block that can then add columns to it,
-
# following the same format as +add_column+. See example above. The options hash
-
# is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create
-
# table definition.
-
# * <tt>drop_table(name)</tt>: Drops the table called +name+.
-
# * <tt>change_table(name, options)</tt>: Allows to make column alterations to
-
# the table called +name+. It makes the table object available to a block that
-
# can then add/remove columns, indexes or foreign keys to it.
-
# * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+
-
# to +new_name+.
-
# * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column
-
# to the table called +table_name+
-
# named +column_name+ specified to be one of the following types:
-
# <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>,
-
# <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
-
# <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. A default value can be
-
# specified by passing an +options+ hash like <tt>{ default: 11 }</tt>.
-
# Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g.
-
# <tt>{ limit: 50, null: false }</tt>) -- see
-
# ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
-
# * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames
-
# a column but keeps the type and content.
-
# * <tt>change_column(table_name, column_name, type, options)</tt>: Changes
-
# the column to a different type using the same parameters as add_column.
-
# * <tt>remove_column(table_name, column_name, type, options)</tt>: Removes the column
-
# named +column_name+ from the table called +table_name+.
-
# * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index
-
# with the name of the column. Other options include
-
# <tt>:name</tt>, <tt>:unique</tt> (e.g.
-
# <tt>{ name: 'users_name_index', unique: true }</tt>) and <tt>:order</tt>
-
# (e.g. <tt>{ order: { name: :desc } }</tt>).
-
# * <tt>remove_index(table_name, column: column_name)</tt>: Removes the index
-
# specified by +column_name+.
-
# * <tt>remove_index(table_name, name: index_name)</tt>: Removes the index
-
# specified by +index_name+.
-
#
-
# == Irreversible transformations
-
#
-
# Some transformations are destructive in a manner that cannot be reversed.
-
# Migrations of that kind should raise an <tt>ActiveRecord::IrreversibleMigration</tt>
-
# exception in their +down+ method.
-
#
-
# == Running migrations from within Rails
-
#
-
# The Rails package has several tools to help create and apply migrations.
-
#
-
# To generate a new migration, you can use
-
# rails generate migration MyNewMigration
-
#
-
# where MyNewMigration is the name of your migration. The generator will
-
# create an empty migration file <tt>timestamp_my_new_migration.rb</tt>
-
# in the <tt>db/migrate/</tt> directory where <tt>timestamp</tt> is the
-
# UTC formatted date and time that the migration was generated.
-
#
-
# There is a special syntactic shortcut to generate migrations that add fields to a table.
-
#
-
# rails generate migration add_fieldname_to_tablename fieldname:string
-
#
-
# This will generate the file <tt>timestamp_add_fieldname_to_tablename</tt>, which will look like this:
-
# class AddFieldnameToTablename < ActiveRecord::Migration
-
# def change
-
# add_column :tablenames, :field, :string
-
# end
-
# end
-
#
-
# To run migrations against the currently configured database, use
-
# <tt>rake db:migrate</tt>. This will update the database by running all of the
-
# pending migrations, creating the <tt>schema_migrations</tt> table
-
# (see "About the schema_migrations table" section below) if missing. It will also
-
# invoke the db:schema:dump task, which will update your db/schema.rb file
-
# to match the structure of your database.
-
#
-
# To roll the database back to a previous migration version, use
-
# <tt>rake db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which
-
# you wish to downgrade. Alternatively, you can also use the STEP option if you
-
# wish to rollback last few migrations. <tt>rake db:migrate STEP=2</tt> will rollback
-
# the latest two migrations.
-
#
-
# If any of the migrations throw an <tt>ActiveRecord::IrreversibleMigration</tt> exception,
-
# that step will fail and you'll have some manual work to do.
-
#
-
# == Database support
-
#
-
# Migrations are currently supported in MySQL, PostgreSQL, SQLite,
-
# SQL Server, and Oracle (all supported databases except DB2).
-
#
-
# == More examples
-
#
-
# Not all migrations change the schema. Some just fix the data:
-
#
-
# class RemoveEmptyTags < ActiveRecord::Migration
-
# def up
-
# Tag.all.each { |tag| tag.destroy if tag.pages.empty? }
-
# end
-
#
-
# def down
-
# # not much we can do to restore deleted data
-
# raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags"
-
# end
-
# end
-
#
-
# Others remove columns when they migrate up instead of down:
-
#
-
# class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
-
# def up
-
# remove_column :items, :incomplete_items_count
-
# remove_column :items, :completed_items_count
-
# end
-
#
-
# def down
-
# add_column :items, :incomplete_items_count
-
# add_column :items, :completed_items_count
-
# end
-
# end
-
#
-
# And sometimes you need to do something in SQL not abstracted directly by migrations:
-
#
-
# class MakeJoinUnique < ActiveRecord::Migration
-
# def up
-
# execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
-
# end
-
#
-
# def down
-
# execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
-
# end
-
# end
-
#
-
# == Using a model after changing its table
-
#
-
# Sometimes you'll want to add a column in a migration and populate it
-
# immediately after. In that case, you'll need to make a call to
-
# <tt>Base#reset_column_information</tt> in order to ensure that the model has the
-
# latest column data from after the new column was added. Example:
-
#
-
# class AddPeopleSalary < ActiveRecord::Migration
-
# def up
-
# add_column :people, :salary, :integer
-
# Person.reset_column_information
-
# Person.all.each do |p|
-
# p.update_attribute :salary, SalaryCalculator.compute(p)
-
# end
-
# end
-
# end
-
#
-
# == Controlling verbosity
-
#
-
# By default, migrations will describe the actions they are taking, writing
-
# them to the console as they happen, along with benchmarks describing how
-
# long each step took.
-
#
-
# You can quiet them down by setting ActiveRecord::Migration.verbose = false.
-
#
-
# You can also insert your own messages and benchmarks by using the +say_with_time+
-
# method:
-
#
-
# def up
-
# ...
-
# say_with_time "Updating salaries..." do
-
# Person.all.each do |p|
-
# p.update_attribute :salary, SalaryCalculator.compute(p)
-
# end
-
# end
-
# ...
-
# end
-
#
-
# The phrase "Updating salaries..." would then be printed, along with the
-
# benchmark for the block when the block completes.
-
#
-
# == About the schema_migrations table
-
#
-
# Rails versions 2.0 and prior used to create a table called
-
# <tt>schema_info</tt> when using migrations. This table contained the
-
# version of the schema as of the last applied migration.
-
#
-
# Starting with Rails 2.1, the <tt>schema_info</tt> table is
-
# (automatically) replaced by the <tt>schema_migrations</tt> table, which
-
# contains the version numbers of all the migrations applied.
-
#
-
# As a result, it is now possible to add migration files that are numbered
-
# lower than the current schema version: when migrating up, those
-
# never-applied "interleaved" migrations will be automatically applied, and
-
# when migrating down, never-applied "interleaved" migrations will be skipped.
-
#
-
# == Timestamped Migrations
-
#
-
# By default, Rails generates migrations that look like:
-
#
-
# 20080717013526_your_migration_name.rb
-
#
-
# The prefix is a generation timestamp (in UTC).
-
#
-
# If you'd prefer to use numeric prefixes, you can turn timestamped migrations
-
# off by setting:
-
#
-
# config.active_record.timestamped_migrations = false
-
#
-
# In application.rb.
-
#
-
# == Reversible Migrations
-
#
-
# Reversible migrations are migrations that know how to go +down+ for you.
-
# You simply supply the +up+ logic, and the Migration system figures out
-
# how to execute the down commands for you.
-
#
-
# To define a reversible migration, define the +change+ method in your
-
# migration like this:
-
#
-
# class TenderloveMigration < ActiveRecord::Migration
-
# def change
-
# create_table(:horses) do |t|
-
# t.column :content, :text
-
# t.column :remind_at, :datetime
-
# end
-
# end
-
# end
-
#
-
# This migration will create the horses table for you on the way up, and
-
# automatically figure out how to drop the table on the way down.
-
#
-
# Some commands like +remove_column+ cannot be reversed. If you care to
-
# define how to move up and down in these cases, you should define the +up+
-
# and +down+ methods as before.
-
#
-
# If a command cannot be reversed, an
-
# <tt>ActiveRecord::IrreversibleMigration</tt> exception will be raised when
-
# the migration is moving down.
-
#
-
# For a list of commands that are reversible, please see
-
# <tt>ActiveRecord::Migration::CommandRecorder</tt>.
-
#
-
# == Transactional Migrations
-
#
-
# If the database adapter supports DDL transactions, all migrations will
-
# automatically be wrapped in a transaction. There are queries that you
-
# can't execute inside a transaction though, and for these situations
-
# you can turn the automatic transactions off.
-
#
-
# class ChangeEnum < ActiveRecord::Migration
-
# disable_ddl_transaction!
-
#
-
# def up
-
# execute "ALTER TYPE model_size ADD VALUE 'new_value'"
-
# end
-
# end
-
#
-
# Remember that you can still open your own transactions, even if you
-
# are in a Migration with <tt>self.disable_ddl_transaction!</tt>.
-
1
class Migration
-
1
autoload :CommandRecorder, 'active_record/migration/command_recorder'
-
-
-
# This class is used to verify that all migrations have been run before
-
# loading a web page if config.active_record.migration_error is set to :page_load
-
1
class CheckPending
-
1
def initialize(app)
-
@app = app
-
@last_check = 0
-
end
-
-
1
def call(env)
-
if connection.supports_migrations?
-
mtime = ActiveRecord::Migrator.last_migration.mtime.to_i
-
if @last_check < mtime
-
ActiveRecord::Migration.check_pending!(connection)
-
@last_check = mtime
-
end
-
end
-
@app.call(env)
-
end
-
-
1
private
-
-
1
def connection
-
ActiveRecord::Base.connection
-
end
-
end
-
-
1
class << self
-
1
attr_accessor :delegate # :nodoc:
-
1
attr_accessor :disable_ddl_transaction # :nodoc:
-
-
1
def check_pending!(connection = Base.connection)
-
raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection)
-
end
-
-
1
def load_schema_if_pending!
-
1
if ActiveRecord::Migrator.needs_migration? || !ActiveRecord::Migrator.any_migrations?
-
# Roundrip to Rake to allow plugins to hook into database initialization.
-
FileUtils.cd Rails.root do
-
current_config = Base.connection_config
-
Base.clear_all_connections!
-
system("bin/rake db:test:prepare")
-
# Establish a new connection, the old database may be gone (db:test:prepare uses purge)
-
Base.establish_connection(current_config)
-
end
-
check_pending!
-
end
-
end
-
-
1
def maintain_test_schema! # :nodoc:
-
1
if ActiveRecord::Base.maintain_test_schema
-
2
suppress_messages { load_schema_if_pending! }
-
end
-
end
-
-
1
def method_missing(name, *args, &block) # :nodoc:
-
1
(delegate || superclass.delegate).send(name, *args, &block)
-
end
-
-
1
def migrate(direction)
-
new.migrate direction
-
end
-
-
# Disable the transaction wrapping this migration.
-
# You can still create your own transactions even after calling #disable_ddl_transaction!
-
#
-
# For more details read the {"Transactional Migrations" section above}[rdoc-ref:Migration].
-
1
def disable_ddl_transaction!
-
@disable_ddl_transaction = true
-
end
-
end
-
-
1
def disable_ddl_transaction # :nodoc:
-
self.class.disable_ddl_transaction
-
end
-
-
1
cattr_accessor :verbose
-
1
attr_accessor :name, :version
-
-
1
def initialize(name = self.class.name, version = nil)
-
1
@name = name
-
1
@version = version
-
1
@connection = nil
-
end
-
-
1
self.verbose = true
-
# instantiate the delegate object after initialize is defined
-
1
self.delegate = new
-
-
# Reverses the migration commands for the given block and
-
# the given migrations.
-
#
-
# The following migration will remove the table 'horses'
-
# and create the table 'apples' on the way up, and the reverse
-
# on the way down.
-
#
-
# class FixTLMigration < ActiveRecord::Migration
-
# def change
-
# revert do
-
# create_table(:horses) do |t|
-
# t.text :content
-
# t.datetime :remind_at
-
# end
-
# end
-
# create_table(:apples) do |t|
-
# t.string :variety
-
# end
-
# end
-
# end
-
#
-
# Or equivalently, if +TenderloveMigration+ is defined as in the
-
# documentation for Migration:
-
#
-
# require_relative '2012121212_tenderlove_migration'
-
#
-
# class FixupTLMigration < ActiveRecord::Migration
-
# def change
-
# revert TenderloveMigration
-
#
-
# create_table(:apples) do |t|
-
# t.string :variety
-
# end
-
# end
-
# end
-
#
-
# This command can be nested.
-
1
def revert(*migration_classes)
-
run(*migration_classes.reverse, revert: true) unless migration_classes.empty?
-
if block_given?
-
if @connection.respond_to? :revert
-
@connection.revert { yield }
-
else
-
recorder = CommandRecorder.new(@connection)
-
@connection = recorder
-
suppress_messages do
-
@connection.revert { yield }
-
end
-
@connection = recorder.delegate
-
recorder.commands.each do |cmd, args, block|
-
send(cmd, *args, &block)
-
end
-
end
-
end
-
end
-
-
1
def reverting?
-
@connection.respond_to?(:reverting) && @connection.reverting
-
end
-
-
1
class ReversibleBlockHelper < Struct.new(:reverting) # :nodoc:
-
1
def up
-
yield unless reverting
-
end
-
-
1
def down
-
yield if reverting
-
end
-
end
-
-
# Used to specify an operation that can be run in one direction or another.
-
# Call the methods +up+ and +down+ of the yielded object to run a block
-
# only in one given direction.
-
# The whole block will be called in the right order within the migration.
-
#
-
# In the following example, the looping on users will always be done
-
# when the three columns 'first_name', 'last_name' and 'full_name' exist,
-
# even when migrating down:
-
#
-
# class SplitNameMigration < ActiveRecord::Migration
-
# def change
-
# add_column :users, :first_name, :string
-
# add_column :users, :last_name, :string
-
#
-
# reversible do |dir|
-
# User.reset_column_information
-
# User.all.each do |u|
-
# dir.up { u.first_name, u.last_name = u.full_name.split(' ') }
-
# dir.down { u.full_name = "#{u.first_name} #{u.last_name}" }
-
# u.save
-
# end
-
# end
-
#
-
# revert { add_column :users, :full_name, :string }
-
# end
-
# end
-
1
def reversible
-
helper = ReversibleBlockHelper.new(reverting?)
-
execute_block{ yield helper }
-
end
-
-
# Runs the given migration classes.
-
# Last argument can specify options:
-
# - :direction (default is :up)
-
# - :revert (default is false)
-
1
def run(*migration_classes)
-
opts = migration_classes.extract_options!
-
dir = opts[:direction] || :up
-
dir = (dir == :down ? :up : :down) if opts[:revert]
-
if reverting?
-
# If in revert and going :up, say, we want to execute :down without reverting, so
-
revert { run(*migration_classes, direction: dir, revert: true) }
-
else
-
migration_classes.each do |migration_class|
-
migration_class.new.exec_migration(@connection, dir)
-
end
-
end
-
end
-
-
1
def up
-
self.class.delegate = self
-
return unless self.class.respond_to?(:up)
-
self.class.up
-
end
-
-
1
def down
-
self.class.delegate = self
-
return unless self.class.respond_to?(:down)
-
self.class.down
-
end
-
-
# Execute this migration in the named direction
-
1
def migrate(direction)
-
return unless respond_to?(direction)
-
-
case direction
-
when :up then announce "migrating"
-
when :down then announce "reverting"
-
end
-
-
time = nil
-
ActiveRecord::Base.connection_pool.with_connection do |conn|
-
time = Benchmark.measure do
-
exec_migration(conn, direction)
-
end
-
end
-
-
case direction
-
when :up then announce "migrated (%.4fs)" % time.real; write
-
when :down then announce "reverted (%.4fs)" % time.real; write
-
end
-
end
-
-
1
def exec_migration(conn, direction)
-
@connection = conn
-
if respond_to?(:change)
-
if direction == :down
-
revert { change }
-
else
-
change
-
end
-
else
-
send(direction)
-
end
-
ensure
-
@connection = nil
-
end
-
-
1
def write(text="")
-
puts(text) if verbose
-
end
-
-
1
def announce(message)
-
text = "#{version} #{name}: #{message}"
-
length = [0, 75 - text.length].max
-
write "== %s %s" % [text, "=" * length]
-
end
-
-
1
def say(message, subitem=false)
-
write "#{subitem ? " ->" : "--"} #{message}"
-
end
-
-
1
def say_with_time(message)
-
say(message)
-
result = nil
-
time = Benchmark.measure { result = yield }
-
say "%.4fs" % time.real, :subitem
-
say("#{result} rows", :subitem) if result.is_a?(Integer)
-
result
-
end
-
-
1
def suppress_messages
-
1
save, self.verbose = verbose, false
-
1
yield
-
ensure
-
1
self.verbose = save
-
end
-
-
1
def connection
-
@connection || ActiveRecord::Base.connection
-
end
-
-
1
def method_missing(method, *arguments, &block)
-
arg_list = arguments.map{ |a| a.inspect } * ', '
-
-
say_with_time "#{method}(#{arg_list})" do
-
unless @connection.respond_to? :revert
-
unless arguments.empty? || [:execute, :enable_extension, :disable_extension].include?(method)
-
arguments[0] = proper_table_name(arguments.first, table_name_options)
-
if [:rename_table, :add_foreign_key].include?(method) ||
-
(method == :remove_foreign_key && !arguments.second.is_a?(Hash))
-
arguments[1] = proper_table_name(arguments.second, table_name_options)
-
end
-
end
-
end
-
return super unless connection.respond_to?(method)
-
connection.send(method, *arguments, &block)
-
end
-
end
-
-
1
def copy(destination, sources, options = {})
-
copied = []
-
-
FileUtils.mkdir_p(destination) unless File.exist?(destination)
-
-
destination_migrations = ActiveRecord::Migrator.migrations(destination)
-
last = destination_migrations.last
-
sources.each do |scope, path|
-
source_migrations = ActiveRecord::Migrator.migrations(path)
-
-
source_migrations.each do |migration|
-
source = File.binread(migration.filename)
-
inserted_comment = "# This migration comes from #{scope} (originally #{migration.version})\n"
-
if /\A#.*\b(?:en)?coding:\s*\S+/ =~ source
-
# If we have a magic comment in the original migration,
-
# insert our comment after the first newline(end of the magic comment line)
-
# so the magic keep working.
-
# Note that magic comments must be at the first line(except sh-bang).
-
source[/\n/] = "\n#{inserted_comment}"
-
else
-
source = "#{inserted_comment}#{source}"
-
end
-
-
if duplicate = destination_migrations.detect { |m| m.name == migration.name }
-
if options[:on_skip] && duplicate.scope != scope.to_s
-
options[:on_skip].call(scope, migration)
-
end
-
next
-
end
-
-
migration.version = next_migration_number(last ? last.version + 1 : 0).to_i
-
new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb")
-
old_path, migration.filename = migration.filename, new_path
-
last = migration
-
-
File.binwrite(migration.filename, source)
-
copied << migration
-
options[:on_copy].call(scope, migration, old_path) if options[:on_copy]
-
destination_migrations << migration
-
end
-
end
-
-
copied
-
end
-
-
# Finds the correct table name given an Active Record object.
-
# Uses the Active Record object's own table_name, or pre/suffix from the
-
# options passed in.
-
1
def proper_table_name(name, options = {})
-
if name.respond_to? :table_name
-
name.table_name
-
else
-
"#{options[:table_name_prefix]}#{name}#{options[:table_name_suffix]}"
-
end
-
end
-
-
# Determines the version number of the next migration.
-
1
def next_migration_number(number)
-
if ActiveRecord::Base.timestamped_migrations
-
[Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % number].max
-
else
-
SchemaMigration.normalize_migration_number(number)
-
end
-
end
-
-
1
def table_name_options(config = ActiveRecord::Base)
-
{
-
table_name_prefix: config.table_name_prefix,
-
table_name_suffix: config.table_name_suffix
-
}
-
end
-
-
1
private
-
1
def execute_block
-
if connection.respond_to? :execute_block
-
super # use normal delegation to record the block
-
else
-
yield
-
end
-
end
-
end
-
-
# MigrationProxy is used to defer loading of the actual migration classes
-
# until they are needed
-
1
class MigrationProxy < Struct.new(:name, :version, :filename, :scope)
-
-
1
def initialize(name, version, filename, scope)
-
12
super
-
12
@migration = nil
-
end
-
-
1
def basename
-
File.basename(filename)
-
end
-
-
1
def mtime
-
File.mtime filename
-
end
-
-
1
delegate :migrate, :announce, :write, :disable_ddl_transaction, to: :migration
-
-
1
private
-
-
1
def migration
-
@migration ||= load_migration
-
end
-
-
1
def load_migration
-
require(File.expand_path(filename))
-
name.constantize.new(name, version)
-
end
-
-
end
-
-
1
class NullMigration < MigrationProxy #:nodoc:
-
1
def initialize
-
super(nil, 0, nil, nil)
-
end
-
-
1
def mtime
-
0
-
end
-
end
-
-
1
class Migrator#:nodoc:
-
1
class << self
-
1
attr_writer :migrations_paths
-
1
alias :migrations_path= :migrations_paths=
-
-
1
def migrate(migrations_paths, target_version = nil, &block)
-
case
-
when target_version.nil?
-
up(migrations_paths, target_version, &block)
-
when current_version == 0 && target_version == 0
-
[]
-
when current_version > target_version
-
down(migrations_paths, target_version, &block)
-
else
-
up(migrations_paths, target_version, &block)
-
end
-
end
-
-
1
def rollback(migrations_paths, steps=1)
-
move(:down, migrations_paths, steps)
-
end
-
-
1
def forward(migrations_paths, steps=1)
-
move(:up, migrations_paths, steps)
-
end
-
-
1
def up(migrations_paths, target_version = nil)
-
migrations = migrations(migrations_paths)
-
migrations.select! { |m| yield m } if block_given?
-
-
new(:up, migrations, target_version).migrate
-
end
-
-
1
def down(migrations_paths, target_version = nil, &block)
-
migrations = migrations(migrations_paths)
-
migrations.select! { |m| yield m } if block_given?
-
-
new(:down, migrations, target_version).migrate
-
end
-
-
1
def run(direction, migrations_paths, target_version)
-
new(direction, migrations(migrations_paths), target_version).run
-
end
-
-
1
def open(migrations_paths)
-
new(:up, migrations(migrations_paths), nil)
-
end
-
-
1
def schema_migrations_table_name
-
1
SchemaMigration.table_name
-
end
-
-
1
def get_all_versions(connection = Base.connection)
-
1
if connection.table_exists?(schema_migrations_table_name)
-
7
SchemaMigration.all.map { |x| x.version.to_i }.sort
-
else
-
[]
-
end
-
end
-
-
1
def current_version(connection = Base.connection)
-
get_all_versions(connection).max || 0
-
end
-
-
1
def needs_migration?(connection = Base.connection)
-
1
(migrations(migrations_paths).collect(&:version) - get_all_versions(connection)).size > 0
-
end
-
-
1
def any_migrations?
-
1
migrations(migrations_paths).any?
-
end
-
-
1
def last_version
-
last_migration.version
-
end
-
-
1
def last_migration #:nodoc:
-
migrations(migrations_paths).last || NullMigration.new
-
end
-
-
1
def migrations_paths
-
2
@migrations_paths ||= ['db/migrate']
-
# just to not break things if someone uses: migration_path = some_string
-
2
Array(@migrations_paths)
-
end
-
-
1
def migrations_path
-
migrations_paths.first
-
end
-
-
1
def migrations(paths)
-
2
paths = Array(paths)
-
-
4
files = Dir[*paths.map { |p| "#{p}/**/[0-9]*_*.rb" }]
-
-
2
migrations = files.map do |file|
-
12
version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/).first
-
-
12
raise IllegalMigrationNameError.new(file) unless version
-
12
version = version.to_i
-
12
name = name.camelize
-
-
12
MigrationProxy.new(name, version, file, scope)
-
end
-
-
2
migrations.sort_by(&:version)
-
end
-
-
1
private
-
-
1
def move(direction, migrations_paths, steps)
-
migrator = new(direction, migrations(migrations_paths))
-
start_index = migrator.migrations.index(migrator.current_migration)
-
-
if start_index
-
finish = migrator.migrations[start_index + steps]
-
version = finish ? finish.version : 0
-
send(direction, migrations_paths, version)
-
end
-
end
-
end
-
-
1
def initialize(direction, migrations, target_version = nil)
-
raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations?
-
-
@direction = direction
-
@target_version = target_version
-
@migrated_versions = nil
-
@migrations = migrations
-
-
validate(@migrations)
-
-
Base.connection.initialize_schema_migrations_table
-
end
-
-
1
def current_version
-
migrated.max || 0
-
end
-
-
1
def current_migration
-
migrations.detect { |m| m.version == current_version }
-
end
-
1
alias :current :current_migration
-
-
1
def run
-
migration = migrations.detect { |m| m.version == @target_version }
-
raise UnknownMigrationVersionError.new(@target_version) if migration.nil?
-
unless (up? && migrated.include?(migration.version.to_i)) || (down? && !migrated.include?(migration.version.to_i))
-
begin
-
execute_migration_in_transaction(migration, @direction)
-
rescue => e
-
canceled_msg = use_transaction?(migration) ? ", this migration was canceled" : ""
-
raise StandardError, "An error has occurred#{canceled_msg}:\n\n#{e}", e.backtrace
-
end
-
end
-
end
-
-
1
def migrate
-
if !target && @target_version && @target_version > 0
-
raise UnknownMigrationVersionError.new(@target_version)
-
end
-
-
runnable.each do |migration|
-
Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger
-
-
begin
-
execute_migration_in_transaction(migration, @direction)
-
rescue => e
-
canceled_msg = use_transaction?(migration) ? "this and " : ""
-
raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace
-
end
-
end
-
end
-
-
1
def runnable
-
runnable = migrations[start..finish]
-
if up?
-
runnable.reject { |m| ran?(m) }
-
else
-
# skip the last migration if we're headed down, but not ALL the way down
-
runnable.pop if target
-
runnable.find_all { |m| ran?(m) }
-
end
-
end
-
-
1
def migrations
-
down? ? @migrations.reverse : @migrations.sort_by(&:version)
-
end
-
-
1
def pending_migrations
-
already_migrated = migrated
-
migrations.reject { |m| already_migrated.include?(m.version) }
-
end
-
-
1
def migrated
-
@migrated_versions ||= Set.new(self.class.get_all_versions)
-
end
-
-
1
private
-
1
def ran?(migration)
-
migrated.include?(migration.version.to_i)
-
end
-
-
1
def execute_migration_in_transaction(migration, direction)
-
ddl_transaction(migration) do
-
migration.migrate(direction)
-
record_version_state_after_migrating(migration.version)
-
end
-
end
-
-
1
def target
-
migrations.detect { |m| m.version == @target_version }
-
end
-
-
1
def finish
-
migrations.index(target) || migrations.size - 1
-
end
-
-
1
def start
-
up? ? 0 : (migrations.index(current) || 0)
-
end
-
-
1
def validate(migrations)
-
name ,= migrations.group_by(&:name).find { |_,v| v.length > 1 }
-
raise DuplicateMigrationNameError.new(name) if name
-
-
version ,= migrations.group_by(&:version).find { |_,v| v.length > 1 }
-
raise DuplicateMigrationVersionError.new(version) if version
-
end
-
-
1
def record_version_state_after_migrating(version)
-
if down?
-
migrated.delete(version)
-
ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all
-
else
-
migrated << version
-
ActiveRecord::SchemaMigration.create!(:version => version.to_s)
-
end
-
end
-
-
1
def up?
-
@direction == :up
-
end
-
-
1
def down?
-
@direction == :down
-
end
-
-
# Wrap the migration in a transaction only if supported by the adapter.
-
1
def ddl_transaction(migration)
-
if use_transaction?(migration)
-
Base.transaction { yield }
-
else
-
yield
-
end
-
end
-
-
1
def use_transaction?(migration)
-
!migration.disable_ddl_transaction && Base.connection.supports_ddl_transactions?
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class Migration
-
1
module JoinTable #:nodoc:
-
1
private
-
-
1
def find_join_table_name(table_1, table_2, options = {})
-
options.delete(:table_name) || join_table_name(table_1, table_2)
-
end
-
-
1
def join_table_name(table_1, table_2)
-
ModelSchema.derive_join_table_name(table_1, table_2).to_sym
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ModelSchema
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
##
-
# :singleton-method:
-
# Accessor for the prefix type that will be prepended to every primary key column name.
-
# The options are :table_name and :table_name_with_underscore. If the first is specified,
-
# the Product class will look for "productid" instead of "id" as the primary column. If the
-
# latter is specified, the Product class will look for "product_id" instead of "id". Remember
-
# that this is a global setting for all Active Records.
-
1
mattr_accessor :primary_key_prefix_type, instance_writer: false
-
-
##
-
# :singleton-method:
-
# Accessor for the name of the prefix string to prepend to every table name. So if set
-
# to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people",
-
# etc. This is a convenient way of creating a namespace for tables in a shared database.
-
# By default, the prefix is the empty string.
-
#
-
# If you are organising your models within modules you can add a prefix to the models within
-
# a namespace by defining a singleton method in the parent module called table_name_prefix which
-
# returns your chosen prefix.
-
1
class_attribute :table_name_prefix, instance_writer: false
-
1
self.table_name_prefix = ""
-
-
##
-
# :singleton-method:
-
# Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
-
# "people_basecamp"). By default, the suffix is the empty string.
-
#
-
# If you are organising your models within modules, you can add a suffix to the models within
-
# a namespace by defining a singleton method in the parent module called table_name_suffix which
-
# returns your chosen suffix.
-
1
class_attribute :table_name_suffix, instance_writer: false
-
1
self.table_name_suffix = ""
-
-
##
-
# :singleton-method:
-
# Accessor for the name of the schema migrations table. By default, the value is "schema_migrations"
-
1
class_attribute :schema_migrations_table_name, instance_accessor: false
-
1
self.schema_migrations_table_name = "schema_migrations"
-
-
##
-
# :singleton-method:
-
# Indicates whether table names should be the pluralized versions of the corresponding class names.
-
# If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
-
# See table_name for the full rules on table/class naming. This is true, by default.
-
1
class_attribute :pluralize_table_names, instance_writer: false
-
1
self.pluralize_table_names = true
-
-
1
self.inheritance_column = 'type'
-
-
1
delegate :type_for_attribute, to: :class
-
end
-
-
# Derives the join table name for +first_table+ and +second_table+. The
-
# table names appear in alphabetical order. A common prefix is removed
-
# (useful for namespaced models like Music::Artist and Music::Record):
-
#
-
# artists, records => artists_records
-
# records, artists => artists_records
-
# music_artists, music_records => music_artists_records
-
1
def self.derive_join_table_name(first_table, second_table) # :nodoc:
-
[first_table.to_s, second_table.to_s].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').tr("\0", "_")
-
end
-
-
1
module ClassMethods
-
# Guesses the table name (in forced lower-case) based on the name of the class in the
-
# inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy
-
# looks like: Reply < Message < ActiveRecord::Base, then Message is used
-
# to guess the table name even when called on Reply. The rules used to do the guess
-
# are handled by the Inflector class in Active Support, which knows almost all common
-
# English inflections. You can add new inflections in config/initializers/inflections.rb.
-
#
-
# Nested classes are given table names prefixed by the singular form of
-
# the parent's table name. Enclosing modules are not considered.
-
#
-
# ==== Examples
-
#
-
# class Invoice < ActiveRecord::Base
-
# end
-
#
-
# file class table_name
-
# invoice.rb Invoice invoices
-
#
-
# class Invoice < ActiveRecord::Base
-
# class Lineitem < ActiveRecord::Base
-
# end
-
# end
-
#
-
# file class table_name
-
# invoice.rb Invoice::Lineitem invoice_lineitems
-
#
-
# module Invoice
-
# class Lineitem < ActiveRecord::Base
-
# end
-
# end
-
#
-
# file class table_name
-
# invoice/lineitem.rb Invoice::Lineitem lineitems
-
#
-
# Additionally, the class-level +table_name_prefix+ is prepended and the
-
# +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
-
# the table name guess for an Invoice class becomes "myapp_invoices".
-
# Invoice::Lineitem becomes "myapp_invoice_lineitems".
-
#
-
# You can also set your own table name explicitly:
-
#
-
# class Mouse < ActiveRecord::Base
-
# self.table_name = "mice"
-
# end
-
#
-
# Alternatively, you can override the table_name method to define your
-
# own computation. (Possibly using <tt>super</tt> to manipulate the default
-
# table name.) Example:
-
#
-
# class Post < ActiveRecord::Base
-
# def self.table_name
-
# "special_" + super
-
# end
-
# end
-
# Post.table_name # => "special_posts"
-
1
def table_name
-
94
reset_table_name unless defined?(@table_name)
-
94
@table_name
-
end
-
-
# Sets the table name explicitly. Example:
-
#
-
# class Project < ActiveRecord::Base
-
# self.table_name = "project"
-
# end
-
#
-
# You can also just define your own <tt>self.table_name</tt> method; see
-
# the documentation for ActiveRecord::Base#table_name.
-
1
def table_name=(value)
-
4
value = value && value.to_s
-
-
4
if defined?(@table_name)
-
return if value == @table_name
-
reset_column_information if connected?
-
end
-
-
4
@table_name = value
-
4
@quoted_table_name = nil
-
4
@arel_table = nil
-
4
@sequence_name = nil unless defined?(@explicit_sequence_name) && @explicit_sequence_name
-
4
@relation = Relation.create(self, arel_table)
-
end
-
-
# Returns a quoted version of the table name, used to construct SQL statements.
-
1
def quoted_table_name
-
@quoted_table_name ||= connection.quote_table_name(table_name)
-
end
-
-
# Computes the table name, (re)sets it internally, and returns it.
-
1
def reset_table_name #:nodoc:
-
4
self.table_name = if abstract_class?
-
superclass == Base ? nil : superclass.table_name
-
elsif superclass.abstract_class?
-
superclass.table_name || compute_table_name
-
else
-
4
compute_table_name
-
end
-
end
-
-
1
def full_table_name_prefix #:nodoc:
-
8
(parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
-
end
-
-
1
def full_table_name_suffix #:nodoc:
-
8
(parents.detect {|p| p.respond_to?(:table_name_suffix) } || self).table_name_suffix
-
end
-
-
# Defines the name of the table column which will store the class name on single-table
-
# inheritance situations.
-
#
-
# The default inheritance column name is +type+, which means it's a
-
# reserved word inside Active Record. To be able to use single-table
-
# inheritance with another column name, or to use the column +type+ in
-
# your own model for something else, you can set +inheritance_column+:
-
#
-
# self.inheritance_column = 'zoink'
-
1
def inheritance_column
-
210
(@inheritance_column ||= nil) || superclass.inheritance_column
-
end
-
-
# Sets the value of inheritance_column
-
1
def inheritance_column=(value)
-
1
@inheritance_column = value.to_s
-
1
@explicit_inheritance_column = true
-
end
-
-
1
def sequence_name
-
if base_class == self
-
@sequence_name ||= reset_sequence_name
-
else
-
(@sequence_name ||= nil) || base_class.sequence_name
-
end
-
end
-
-
1
def reset_sequence_name #:nodoc:
-
@explicit_sequence_name = false
-
@sequence_name = connection.default_sequence_name(table_name, primary_key)
-
end
-
-
# Sets the name of the sequence to use when generating ids to the given
-
# value, or (if the value is nil or false) to the value returned by the
-
# given block. This is required for Oracle and is useful for any
-
# database which relies on sequences for primary key generation.
-
#
-
# If a sequence name is not explicitly set when using Oracle,
-
# it will default to the commonly used pattern of: #{table_name}_seq
-
#
-
# If a sequence name is not explicitly set when using PostgreSQL, it
-
# will discover the sequence corresponding to your primary key for you.
-
#
-
# class Project < ActiveRecord::Base
-
# self.sequence_name = "projectseq" # default would have been "project_seq"
-
# end
-
1
def sequence_name=(value)
-
@sequence_name = value.to_s
-
@explicit_sequence_name = true
-
end
-
-
# Indicates whether the table associated with this class exists
-
1
def table_exists?
-
8
connection.schema_cache.table_exists?(table_name)
-
end
-
-
1
def attributes_builder # :nodoc:
-
58
@attributes_builder ||= AttributeSet::Builder.new(column_types, primary_key)
-
end
-
-
1
def column_types # :nodoc:
-
@column_types ||= columns_hash.transform_values(&:cast_type).tap do |h|
-
5
h.default = Type::Value.new
-
7
end
-
end
-
-
1
def type_for_attribute(attr_name) # :nodoc:
-
2
column_types[attr_name]
-
end
-
-
# Returns a hash where the keys are column names and the values are
-
# default values when instantiating the AR object for this table.
-
1
def column_defaults
-
_default_attributes.to_hash
-
end
-
-
1
def _default_attributes # :nodoc:
-
@default_attributes ||= attributes_builder.build_from_database(
-
29
raw_default_values)
-
end
-
-
# Returns an array of column names as strings.
-
1
def column_names
-
276
@column_names ||= columns.map { |column| column.name }
-
end
-
-
# Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
-
# and columns used for single table inheritance have been removed.
-
1
def content_columns
-
@content_columns ||= columns.reject { |c| c.name == primary_key || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
-
end
-
-
# Resets all the cached information about columns, which will cause them
-
# to be reloaded on the next request.
-
#
-
# The most common usage pattern for this method is probably in a migration,
-
# when just after creating a table you want to populate it with some default
-
# values, eg:
-
#
-
# class CreateJobLevels < ActiveRecord::Migration
-
# def up
-
# create_table :job_levels do |t|
-
# t.integer :id
-
# t.string :name
-
#
-
# t.timestamps
-
# end
-
#
-
# JobLevel.reset_column_information
-
# %w{assistant executive manager director}.each do |type|
-
# JobLevel.create(name: type)
-
# end
-
# end
-
#
-
# def down
-
# drop_table :job_levels
-
# end
-
# end
-
1
def reset_column_information
-
connection.clear_cache!
-
undefine_attribute_methods
-
connection.schema_cache.clear_table_cache!(table_name)
-
-
@arel_engine = nil
-
@column_names = nil
-
@column_types = nil
-
@content_columns = nil
-
@default_attributes = nil
-
@inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
-
@relation = nil
-
end
-
-
1
private
-
-
# Guesses the table name, but does not decorate it with prefix and suffix information.
-
1
def undecorated_table_name(class_name = base_class.name)
-
4
table_name = class_name.to_s.demodulize.underscore
-
4
pluralize_table_names ? table_name.pluralize : table_name
-
end
-
-
# Computes and returns a table name according to default conventions.
-
1
def compute_table_name
-
4
base = base_class
-
4
if self == base
-
# Nested classes are prefixed with singular parent table name.
-
4
if parent < Base && !parent.abstract_class?
-
contained = parent.table_name
-
contained = contained.singularize if parent.pluralize_table_names
-
contained += '_'
-
end
-
-
4
"#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{full_table_name_suffix}"
-
else
-
# STI subclasses always use their superclass' table.
-
base.table_name
-
end
-
end
-
-
1
def raw_default_values
-
4
columns_hash.transform_values(&:default)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActiveRecord
-
1
module NestedAttributes #:nodoc:
-
1
class TooManyRecords < ActiveRecordError
-
end
-
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :nested_attributes_options, instance_writer: false
-
1
self.nested_attributes_options = {}
-
end
-
-
# = Active Record Nested Attributes
-
#
-
# Nested attributes allow you to save attributes on associated records
-
# through the parent. By default nested attribute updating is turned off
-
# and you can enable it using the accepts_nested_attributes_for class
-
# method. When you enable nested attributes an attribute writer is
-
# defined on the model.
-
#
-
# The attribute writer is named after the association, which means that
-
# in the following example, two new methods are added to your model:
-
#
-
# <tt>author_attributes=(attributes)</tt> and
-
# <tt>pages_attributes=(attributes)</tt>.
-
#
-
# class Book < ActiveRecord::Base
-
# has_one :author
-
# has_many :pages
-
#
-
# accepts_nested_attributes_for :author, :pages
-
# end
-
#
-
# Note that the <tt>:autosave</tt> option is automatically enabled on every
-
# association that accepts_nested_attributes_for is used for.
-
#
-
# === One-to-one
-
#
-
# Consider a Member model that has one Avatar:
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar
-
# end
-
#
-
# Enabling nested attributes on a one-to-one association allows you to
-
# create the member and avatar in one go:
-
#
-
# params = { member: { name: 'Jack', avatar_attributes: { icon: 'smiling' } } }
-
# member = Member.create(params[:member])
-
# member.avatar.id # => 2
-
# member.avatar.icon # => 'smiling'
-
#
-
# It also allows you to update the avatar through the member:
-
#
-
# params = { member: { avatar_attributes: { id: '2', icon: 'sad' } } }
-
# member.update params[:member]
-
# member.avatar.icon # => 'sad'
-
#
-
# By default you will only be able to set and update attributes on the
-
# associated model. If you want to destroy the associated model through the
-
# attributes hash, you have to enable it first using the
-
# <tt>:allow_destroy</tt> option.
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar, allow_destroy: true
-
# end
-
#
-
# Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
-
# value that evaluates to +true+, you will destroy the associated model:
-
#
-
# member.avatar_attributes = { id: '2', _destroy: '1' }
-
# member.avatar.marked_for_destruction? # => true
-
# member.save
-
# member.reload.avatar # => nil
-
#
-
# Note that the model will _not_ be destroyed until the parent is saved.
-
#
-
# === One-to-many
-
#
-
# Consider a member that has a number of posts:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts
-
# end
-
#
-
# You can now set or update attributes on the associated posts through
-
# an attribute hash for a member: include the key +:posts_attributes+
-
# with an array of hashes of post attributes as a value.
-
#
-
# For each hash that does _not_ have an <tt>id</tt> key a new record will
-
# be instantiated, unless the hash also contains a <tt>_destroy</tt> key
-
# that evaluates to +true+.
-
#
-
# params = { member: {
-
# name: 'joe', posts_attributes: [
-
# { title: 'Kari, the awesome Ruby documentation browser!' },
-
# { title: 'The egalitarian assumption of the modern citizen' },
-
# { title: '', _destroy: '1' } # this will be ignored
-
# ]
-
# }}
-
#
-
# member = Member.create(params[:member])
-
# member.posts.length # => 2
-
# member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
-
# member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
-
#
-
# You may also set a :reject_if proc to silently ignore any new record
-
# hashes if they fail to pass your criteria. For example, the previous
-
# example could be rewritten as:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, reject_if: proc { |attributes| attributes['title'].blank? }
-
# end
-
#
-
# params = { member: {
-
# name: 'joe', posts_attributes: [
-
# { title: 'Kari, the awesome Ruby documentation browser!' },
-
# { title: 'The egalitarian assumption of the modern citizen' },
-
# { title: '' } # this will be ignored because of the :reject_if proc
-
# ]
-
# }}
-
#
-
# member = Member.create(params[:member])
-
# member.posts.length # => 2
-
# member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
-
# member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
-
#
-
# Alternatively, :reject_if also accepts a symbol for using methods:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, reject_if: :new_record?
-
# end
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, reject_if: :reject_posts
-
#
-
# def reject_posts(attributed)
-
# attributed['title'].blank?
-
# end
-
# end
-
#
-
# If the hash contains an <tt>id</tt> key that matches an already
-
# associated record, the matching record will be modified:
-
#
-
# member.attributes = {
-
# name: 'Joe',
-
# posts_attributes: [
-
# { id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
-
# { id: 2, title: '[UPDATED] other post' }
-
# ]
-
# }
-
#
-
# member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
-
# member.posts.second.title # => '[UPDATED] other post'
-
#
-
# By default the associated records are protected from being destroyed. If
-
# you want to destroy any of the associated records through the attributes
-
# hash, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option. This will allow you to also use the <tt>_destroy</tt> key to
-
# destroy existing records:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, allow_destroy: true
-
# end
-
#
-
# params = { member: {
-
# posts_attributes: [{ id: '2', _destroy: '1' }]
-
# }}
-
#
-
# member.attributes = params[:member]
-
# member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
-
# member.posts.length # => 2
-
# member.save
-
# member.reload.posts.length # => 1
-
#
-
# Nested attributes for an associated collection can also be passed in
-
# the form of a hash of hashes instead of an array of hashes:
-
#
-
# Member.create(name: 'joe',
-
# posts_attributes: { first: { title: 'Foo' },
-
# second: { title: 'Bar' } })
-
#
-
# has the same effect as
-
#
-
# Member.create(name: 'joe',
-
# posts_attributes: [ { title: 'Foo' },
-
# { title: 'Bar' } ])
-
#
-
# The keys of the hash which is the value for +:posts_attributes+ are
-
# ignored in this case.
-
# However, it is not allowed to use +'id'+ or +:id+ for one of
-
# such keys, otherwise the hash will be wrapped in an array and
-
# interpreted as an attribute hash for a single post.
-
#
-
# Passing attributes for an associated collection in the form of a hash
-
# of hashes can be used with hashes generated from HTTP/HTML parameters,
-
# where there maybe no natural way to submit an array of hashes.
-
#
-
# === Saving
-
#
-
# All changes to models, including the destruction of those marked for
-
# destruction, are saved and destroyed automatically and atomically when
-
# the parent model is saved. This happens inside the transaction initiated
-
# by the parents save method. See ActiveRecord::AutosaveAssociation.
-
#
-
# === Validating the presence of a parent model
-
#
-
# If you want to validate that a child record is associated with a parent
-
# record, you can use <tt>validates_presence_of</tt> and
-
# <tt>inverse_of</tt> as this example illustrates:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts, inverse_of: :member
-
# accepts_nested_attributes_for :posts
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :member, inverse_of: :posts
-
# validates_presence_of :member
-
# end
-
#
-
# Note that if you do not specify the <tt>inverse_of</tt> option, then
-
# Active Record will try to automatically guess the inverse association
-
# based on heuristics.
-
#
-
# For one-to-one nested associations, if you build the new (in-memory)
-
# child object yourself before assignment, then this module will not
-
# overwrite it, e.g.:
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar
-
#
-
# def avatar
-
# super || build_avatar(width: 200)
-
# end
-
# end
-
#
-
# member = Member.new
-
# member.avatar_attributes = {icon: 'sad'}
-
# member.avatar.width # => 200
-
1
module ClassMethods
-
1
REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
-
-
# Defines an attributes writer for the specified association(s).
-
#
-
# Supported options:
-
# [:allow_destroy]
-
# If true, destroys any members from the attributes hash with a
-
# <tt>_destroy</tt> key and a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'). This option is off by default.
-
# [:reject_if]
-
# Allows you to specify a Proc or a Symbol pointing to a method
-
# that checks whether a record should be built for a certain attribute
-
# hash. The hash is passed to the supplied Proc or the method
-
# and it should return either +true+ or +false+. When no :reject_if
-
# is specified, a record will be built for all attribute hashes that
-
# do not have a <tt>_destroy</tt> value that evaluates to true.
-
# Passing <tt>:all_blank</tt> instead of a Proc will create a proc
-
# that will reject a record where all the attributes are blank excluding
-
# any value for _destroy.
-
# [:limit]
-
# Allows you to specify the maximum number of the associated records that
-
# can be processed with the nested attributes. Limit also can be specified as a
-
# Proc or a Symbol pointing to a method that should return number. If the size of the
-
# nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
-
# exception is raised. If omitted, any number associations can be processed.
-
# Note that the :limit option is only applicable to one-to-many associations.
-
# [:update_only]
-
# For a one-to-one association, this option allows you to specify how
-
# nested attributes are to be used when an associated record already
-
# exists. In general, an existing record may either be updated with the
-
# new set of attribute values or be replaced by a wholly new record
-
# containing those values. By default the :update_only option is +false+
-
# and the nested attributes are used to update the existing record only
-
# if they include the record's <tt>:id</tt> value. Otherwise a new
-
# record will be instantiated and used to replace the existing one.
-
# However if the :update_only option is +true+, the nested attributes
-
# are used to update the record's attributes always, regardless of
-
# whether the <tt>:id</tt> is present. The option is ignored for collection
-
# associations.
-
#
-
# Examples:
-
# # creates avatar_attributes=
-
# accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
-
# # creates avatar_attributes=
-
# accepts_nested_attributes_for :avatar, reject_if: :all_blank
-
# # creates avatar_attributes= and posts_attributes=
-
# accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
-
1
def accepts_nested_attributes_for(*attr_names)
-
options = { :allow_destroy => false, :update_only => false }
-
options.update(attr_names.extract_options!)
-
options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
-
options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
-
-
attr_names.each do |association_name|
-
if reflection = _reflect_on_association(association_name)
-
reflection.autosave = true
-
define_autosave_validation_callbacks(reflection)
-
-
nested_attributes_options = self.nested_attributes_options.dup
-
nested_attributes_options[association_name.to_sym] = options
-
self.nested_attributes_options = nested_attributes_options
-
-
type = (reflection.collection? ? :collection : :one_to_one)
-
generate_association_writer(association_name, type)
-
else
-
raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
-
end
-
end
-
end
-
-
1
private
-
-
# Generates a writer method for this association. Serves as a point for
-
# accessing the objects in the association. For example, this method
-
# could generate the following:
-
#
-
# def pirate_attributes=(attributes)
-
# assign_nested_attributes_for_one_to_one_association(:pirate, attributes)
-
# end
-
#
-
# This redirects the attempts to write objects in an association through
-
# the helper methods defined below. Makes it seem like the nested
-
# associations are just regular associations.
-
1
def generate_association_writer(association_name, type)
-
generated_association_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1
-
if method_defined?(:#{association_name}_attributes=)
-
remove_method(:#{association_name}_attributes=)
-
end
-
def #{association_name}_attributes=(attributes)
-
assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
-
end
-
eoruby
-
end
-
end
-
-
# Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
-
# used in conjunction with fields_for to build a form element for the
-
# destruction of this association.
-
#
-
# See ActionView::Helpers::FormHelper::fields_for for more info.
-
1
def _destroy
-
marked_for_destruction?
-
end
-
-
1
private
-
-
# Attribute hash keys that should not be assigned as normal attributes.
-
# These hash keys are nested attributes implementation details.
-
1
UNASSIGNABLE_KEYS = %w( id _destroy )
-
-
# Assigns the given attributes to the association.
-
#
-
# If an associated record does not yet exist, one will be instantiated. If
-
# an associated record already exists, the method's behavior depends on
-
# the value of the update_only option. If update_only is +false+ and the
-
# given attributes include an <tt>:id</tt> that matches the existing record's
-
# id, then the existing record will be modified. If no <tt>:id</tt> is provided
-
# it will be replaced with a new record. If update_only is +true+ the existing
-
# record will be modified regardless of whether an <tt>:id</tt> is provided.
-
#
-
# If the given attributes include a matching <tt>:id</tt> attribute, or
-
# update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
-
# then the existing record will be marked for destruction.
-
1
def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
-
options = self.nested_attributes_options[association_name]
-
attributes = attributes.with_indifferent_access
-
existing_record = send(association_name)
-
-
if (options[:update_only] || !attributes['id'].blank?) && existing_record &&
-
(options[:update_only] || existing_record.id.to_s == attributes['id'].to_s)
-
assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
-
-
elsif attributes['id'].present?
-
raise_nested_attributes_record_not_found!(association_name, attributes['id'])
-
-
elsif !reject_new_record?(association_name, attributes)
-
assignable_attributes = attributes.except(*UNASSIGNABLE_KEYS)
-
-
if existing_record && existing_record.new_record?
-
existing_record.assign_attributes(assignable_attributes)
-
association(association_name).initialize_attributes(existing_record)
-
else
-
method = "build_#{association_name}"
-
if respond_to?(method)
-
send(method, assignable_attributes)
-
else
-
raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?"
-
end
-
end
-
end
-
end
-
-
# Assigns the given attributes to the collection association.
-
#
-
# Hashes with an <tt>:id</tt> value matching an existing associated record
-
# will update that record. Hashes without an <tt>:id</tt> value will build
-
# a new record for the association. Hashes with a matching <tt>:id</tt>
-
# value and a <tt>:_destroy</tt> key set to a truthy value will mark the
-
# matched record for destruction.
-
#
-
# For example:
-
#
-
# assign_nested_attributes_for_collection_association(:people, {
-
# '1' => { id: '1', name: 'Peter' },
-
# '2' => { name: 'John' },
-
# '3' => { id: '2', _destroy: true }
-
# })
-
#
-
# Will update the name of the Person with ID 1, build a new associated
-
# person with the name 'John', and mark the associated Person with ID 2
-
# for destruction.
-
#
-
# Also accepts an Array of attribute hashes:
-
#
-
# assign_nested_attributes_for_collection_association(:people, [
-
# { id: '1', name: 'Peter' },
-
# { name: 'John' },
-
# { id: '2', _destroy: true }
-
# ])
-
1
def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
-
options = self.nested_attributes_options[association_name]
-
-
unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
-
raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
-
end
-
-
check_record_limit!(options[:limit], attributes_collection)
-
-
if attributes_collection.is_a? Hash
-
keys = attributes_collection.keys
-
attributes_collection = if keys.include?('id') || keys.include?(:id)
-
[attributes_collection]
-
else
-
attributes_collection.values
-
end
-
end
-
-
association = association(association_name)
-
-
existing_records = if association.loaded?
-
association.target
-
else
-
attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
-
attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids)
-
end
-
-
attributes_collection.each do |attributes|
-
attributes = attributes.with_indifferent_access
-
-
if attributes['id'].blank?
-
unless reject_new_record?(association_name, attributes)
-
association.build(attributes.except(*UNASSIGNABLE_KEYS))
-
end
-
elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
-
unless call_reject_if(association_name, attributes)
-
# Make sure we are operating on the actual object which is in the association's
-
# proxy_target array (either by finding it, or adding it if not found)
-
# Take into account that the proxy_target may have changed due to callbacks
-
target_record = association.target.detect { |record| record.id.to_s == attributes['id'].to_s }
-
if target_record
-
existing_record = target_record
-
else
-
association.add_to_target(existing_record, :skip_callbacks)
-
end
-
-
assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
-
end
-
else
-
raise_nested_attributes_record_not_found!(association_name, attributes['id'])
-
end
-
end
-
end
-
-
# Takes in a limit and checks if the attributes_collection has too many
-
# records. It accepts limit in the form of symbol, proc, or
-
# number-like object (anything that can be compared with an integer).
-
#
-
# Raises TooManyRecords error if the attributes_collection is
-
# larger than the limit.
-
1
def check_record_limit!(limit, attributes_collection)
-
if limit
-
limit = case limit
-
when Symbol
-
send(limit)
-
when Proc
-
limit.call
-
else
-
limit
-
end
-
-
if limit && attributes_collection.size > limit
-
raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead."
-
end
-
end
-
end
-
-
# Updates a record with the +attributes+ or marks it for destruction if
-
# +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
-
1
def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
-
record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
-
record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
-
end
-
-
# Determines if a hash contains a truthy _destroy key.
-
1
def has_destroy_flag?(hash)
-
Type::Boolean.new.type_cast_from_user(hash['_destroy'])
-
end
-
-
# Determines if a new record should be rejected by checking
-
# has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
-
# association and evaluates to +true+.
-
1
def reject_new_record?(association_name, attributes)
-
has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
-
end
-
-
# Determines if a record with the particular +attributes+ should be
-
# rejected by calling the reject_if Symbol or Proc (if defined).
-
# The reject_if option is defined by +accepts_nested_attributes_for+.
-
#
-
# Returns false if there is a +destroy_flag+ on the attributes.
-
1
def call_reject_if(association_name, attributes)
-
return false if has_destroy_flag?(attributes)
-
case callback = self.nested_attributes_options[association_name][:reject_if]
-
when Symbol
-
method(callback).arity == 0 ? send(callback) : send(callback, attributes)
-
when Proc
-
callback.call(attributes)
-
end
-
end
-
-
1
def raise_nested_attributes_record_not_found!(association_name, record_id)
-
raise RecordNotFound, "Couldn't find #{self.class._reflect_on_association(association_name).klass.name} with ID=#{record_id} for #{self.class.name} with ID=#{id}"
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record No Touching
-
1
module NoTouching
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Lets you selectively disable calls to `touch` for the
-
# duration of a block.
-
#
-
# ==== Examples
-
# ActiveRecord::Base.no_touching do
-
# Project.first.touch # does nothing
-
# Message.first.touch # does nothing
-
# end
-
#
-
# Project.no_touching do
-
# Project.first.touch # does nothing
-
# Message.first.touch # works, but does not touch the associated project
-
# end
-
#
-
1
def no_touching(&block)
-
NoTouching.apply_to(self, &block)
-
end
-
end
-
-
1
class << self
-
1
def apply_to(klass) #:nodoc:
-
klasses.push(klass)
-
yield
-
ensure
-
klasses.pop
-
end
-
-
1
def applied_to?(klass) #:nodoc:
-
klasses.any? { |k| k >= klass }
-
end
-
-
1
private
-
1
def klasses
-
Thread.current[:no_touching_classes] ||= []
-
end
-
end
-
-
1
def no_touching?
-
NoTouching.applied_to?(self.class)
-
end
-
-
1
def touch(*) # :nodoc:
-
super unless no_touching?
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Persistence
-
1
module Persistence
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Creates an object (or multiple objects) and saves it to the database, if validations pass.
-
# The resulting object is returned whether the object was saved successfully to the database or not.
-
#
-
# The +attributes+ parameter can be either a Hash or an Array of Hashes. These Hashes describe the
-
# attributes on the objects that are to be created.
-
#
-
# ==== Examples
-
# # Create a single new object
-
# User.create(first_name: 'Jamie')
-
#
-
# # Create an Array of new objects
-
# User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])
-
#
-
# # Create a single object and pass it into a block to set other attributes.
-
# User.create(first_name: 'Jamie') do |u|
-
# u.is_admin = false
-
# end
-
#
-
# # Creating an Array of new objects using a block, where the block is executed for each object:
-
# User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
-
# u.is_admin = false
-
# end
-
1
def create(attributes = nil, &block)
-
if attributes.is_a?(Array)
-
attributes.collect { |attr| create(attr, &block) }
-
else
-
object = new(attributes, &block)
-
object.save
-
object
-
end
-
end
-
-
# Creates an object (or multiple objects) and saves it to the database,
-
# if validations pass. Raises a RecordInvalid error if validations fail,
-
# unlike Base#create.
-
#
-
# The +attributes+ parameter can be either a Hash or an Array of Hashes.
-
# These describe which attributes to be created on the object, or
-
# multiple objects when given an Array of Hashes.
-
1
def create!(attributes = nil, &block)
-
22
if attributes.is_a?(Array)
-
attributes.collect { |attr| create!(attr, &block) }
-
else
-
22
object = new(attributes, &block)
-
22
object.save!
-
22
object
-
end
-
end
-
-
# Given an attributes hash, +instantiate+ returns a new instance of
-
# the appropriate class. Accepts only keys as strings.
-
#
-
# For example, +Post.all+ may return Comments, Messages, and Emails
-
# by storing the record's subclass in a +type+ attribute. By calling
-
# +instantiate+ instead of +new+, finder methods ensure they get new
-
# instances of the appropriate class for each record.
-
#
-
# See +ActiveRecord::Inheritance#discriminate_class_for_record+ to see
-
# how this "single-table" inheritance mapping is implemented.
-
1
def instantiate(attributes, column_types = {})
-
54
klass = discriminate_class_for_record(attributes)
-
54
attributes = klass.attributes_builder.build_from_database(attributes, column_types)
-
54
klass.allocate.init_with('attributes' => attributes, 'new_record' => false)
-
end
-
-
1
private
-
# Called by +instantiate+ to decide which class to use for a new
-
# record instance.
-
#
-
# See +ActiveRecord::Inheritance#discriminate_class_for_record+ for
-
# the single-table inheritance discriminator.
-
1
def discriminate_class_for_record(record)
-
54
self
-
end
-
end
-
-
# Returns true if this object hasn't been saved yet -- that is, a record
-
# for the object doesn't exist in the database yet; otherwise, returns false.
-
1
def new_record?
-
108
sync_with_transaction_state
-
108
@new_record
-
end
-
-
# Returns true if this object has been destroyed, otherwise returns false.
-
1
def destroyed?
-
32
sync_with_transaction_state
-
32
@destroyed
-
end
-
-
# Returns true if the record is persisted, i.e. it's not a new record and it was
-
# not destroyed, otherwise returns false.
-
1
def persisted?
-
43
!(new_record? || destroyed?)
-
end
-
-
# Saves the model.
-
#
-
# If the model is new a record gets created in the database, otherwise
-
# the existing record gets updated.
-
#
-
# By default, save always run validations. If any of them fail the action
-
# is cancelled and +save+ returns +false+. However, if you supply
-
# validate: false, validations are bypassed altogether. See
-
# ActiveRecord::Validations for more information.
-
#
-
# There's a series of callbacks associated with +save+. If any of the
-
# <tt>before_*</tt> callbacks return +false+ the action is cancelled and
-
# +save+ returns +false+. See ActiveRecord::Callbacks for further
-
# details.
-
#
-
# Attributes marked as readonly are silently ignored if the record is
-
# being updated.
-
1
def save(*)
-
6
create_or_update
-
rescue ActiveRecord::RecordInvalid
-
false
-
end
-
-
# Saves the model.
-
#
-
# If the model is new a record gets created in the database, otherwise
-
# the existing record gets updated.
-
#
-
# With <tt>save!</tt> validations always run. If any of them fail
-
# ActiveRecord::RecordInvalid gets raised. See ActiveRecord::Validations
-
# for more information.
-
#
-
# There's a series of callbacks associated with <tt>save!</tt>. If any of
-
# the <tt>before_*</tt> callbacks return +false+ the action is cancelled
-
# and <tt>save!</tt> raises ActiveRecord::RecordNotSaved. See
-
# ActiveRecord::Callbacks for further details.
-
#
-
# Attributes marked as readonly are silently ignored if the record is
-
# being updated.
-
1
def save!(*)
-
23
create_or_update || raise(RecordNotSaved.new("Failed to save the record", self))
-
end
-
-
# Deletes the record in the database and freezes this instance to
-
# reflect that no changes should be made (since they can't be
-
# persisted). Returns the frozen instance.
-
#
-
# The row is simply removed with an SQL +DELETE+ statement on the
-
# record's primary key, and no callbacks are executed.
-
#
-
# To enforce the object's +before_destroy+ and +after_destroy+
-
# callbacks or any <tt>:dependent</tt> association
-
# options, use <tt>#destroy</tt>.
-
1
def delete
-
self.class.delete(id) if persisted?
-
@destroyed = true
-
freeze
-
end
-
-
# Deletes the record in the database and freezes this instance to reflect
-
# that no changes should be made (since they can't be persisted).
-
#
-
# There's a series of callbacks associated with <tt>destroy</tt>. If
-
# the <tt>before_destroy</tt> callback return +false+ the action is cancelled
-
# and <tt>destroy</tt> returns +false+. See
-
# ActiveRecord::Callbacks for further details.
-
1
def destroy
-
3
raise ReadOnlyRecord, "#{self.class} is marked as readonly" if readonly?
-
3
destroy_associations
-
3
self.class.connection.add_transaction_record(self)
-
3
destroy_row if persisted?
-
3
@destroyed = true
-
3
freeze
-
end
-
-
# Deletes the record in the database and freezes this instance to reflect
-
# that no changes should be made (since they can't be persisted).
-
#
-
# There's a series of callbacks associated with <tt>destroy!</tt>. If
-
# the <tt>before_destroy</tt> callback return +false+ the action is cancelled
-
# and <tt>destroy!</tt> raises ActiveRecord::RecordNotDestroyed. See
-
# ActiveRecord::Callbacks for further details.
-
1
def destroy!
-
destroy || raise(RecordNotDestroyed.new("Failed to destroy the record", self))
-
end
-
-
# Returns an instance of the specified +klass+ with the attributes of the
-
# current record. This is mostly useful in relation to single-table
-
# inheritance structures where you want a subclass to appear as the
-
# superclass. This can be used along with record identification in
-
# Action Pack to allow, say, <tt>Client < Company</tt> to do something
-
# like render <tt>partial: @client.becomes(Company)</tt> to render that
-
# instance using the companies/company partial instead of clients/client.
-
#
-
# Note: The new instance will share a link to the same attributes as the original class.
-
# So any change to the attributes in either instance will affect the other.
-
1
def becomes(klass)
-
became = klass.new
-
became.instance_variable_set("@attributes", @attributes)
-
changed_attributes = @changed_attributes if defined?(@changed_attributes)
-
became.instance_variable_set("@changed_attributes", changed_attributes || {})
-
became.instance_variable_set("@new_record", new_record?)
-
became.instance_variable_set("@destroyed", destroyed?)
-
became.instance_variable_set("@errors", errors)
-
became
-
end
-
-
# Wrapper around +becomes+ that also changes the instance's sti column value.
-
# This is especially useful if you want to persist the changed class in your
-
# database.
-
#
-
# Note: The old instance's sti column value will be changed too, as both objects
-
# share the same set of attributes.
-
1
def becomes!(klass)
-
became = becomes(klass)
-
sti_type = nil
-
if !klass.descends_from_active_record?
-
sti_type = klass.sti_name
-
end
-
became.public_send("#{klass.inheritance_column}=", sti_type)
-
became
-
end
-
-
# Updates a single attribute and saves the record.
-
# This is especially useful for boolean flags on existing records. Also note that
-
#
-
# * Validation is skipped.
-
# * Callbacks are invoked.
-
# * updated_at/updated_on column is updated if that column is available.
-
# * Updates all the attributes that are dirty in this object.
-
#
-
# This method raises an +ActiveRecord::ActiveRecordError+ if the
-
# attribute is marked as readonly.
-
#
-
# See also +update_column+.
-
1
def update_attribute(name, value)
-
name = name.to_s
-
verify_readonly_attribute(name)
-
send("#{name}=", value)
-
save(validate: false)
-
end
-
-
# Updates the attributes of the model from the passed-in hash and saves the
-
# record, all wrapped in a transaction. If the object is invalid, the saving
-
# will fail and false will be returned.
-
1
def update(attributes)
-
# The following transaction covers any possible database side-effects of the
-
# attributes assignment. For example, setting the IDs of a child collection.
-
3
with_transaction_returning_status do
-
3
assign_attributes(attributes)
-
3
save
-
end
-
end
-
-
1
alias update_attributes update
-
-
# Updates its receiver just like +update+ but calls <tt>save!</tt> instead
-
# of +save+, so an exception is raised if the record is invalid.
-
1
def update!(attributes)
-
# The following transaction covers any possible database side-effects of the
-
# attributes assignment. For example, setting the IDs of a child collection.
-
1
with_transaction_returning_status do
-
1
assign_attributes(attributes)
-
1
save!
-
end
-
end
-
-
1
alias update_attributes! update!
-
-
# Equivalent to <code>update_columns(name => value)</code>.
-
1
def update_column(name, value)
-
update_columns(name => value)
-
end
-
-
# Updates the attributes directly in the database issuing an UPDATE SQL
-
# statement and sets them in the receiver:
-
#
-
# user.update_columns(last_request_at: Time.current)
-
#
-
# This is the fastest way to update attributes because it goes straight to
-
# the database, but take into account that in consequence the regular update
-
# procedures are totally bypassed. In particular:
-
#
-
# * Validations are skipped.
-
# * Callbacks are skipped.
-
# * +updated_at+/+updated_on+ are not updated.
-
#
-
# This method raises an +ActiveRecord::ActiveRecordError+ when called on new
-
# objects, or when at least one of the attributes is marked as readonly.
-
1
def update_columns(attributes)
-
raise ActiveRecordError, "cannot update a new record" if new_record?
-
raise ActiveRecordError, "cannot update a destroyed record" if destroyed?
-
-
attributes.each_key do |key|
-
verify_readonly_attribute(key.to_s)
-
end
-
-
updated_count = self.class.unscoped.where(self.class.primary_key => id).update_all(attributes)
-
-
attributes.each do |k, v|
-
raw_write_attribute(k, v)
-
end
-
-
updated_count == 1
-
end
-
-
# Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1).
-
# The increment is performed directly on the underlying attribute, no setter is invoked.
-
# Only makes sense for number-based attributes. Returns +self+.
-
1
def increment(attribute, by = 1)
-
self[attribute] ||= 0
-
self[attribute] += by
-
self
-
end
-
-
# Wrapper around +increment+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
1
def increment!(attribute, by = 1)
-
increment(attribute, by).update_attribute(attribute, self[attribute])
-
end
-
-
# Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1).
-
# The decrement is performed directly on the underlying attribute, no setter is invoked.
-
# Only makes sense for number-based attributes. Returns +self+.
-
1
def decrement(attribute, by = 1)
-
self[attribute] ||= 0
-
self[attribute] -= by
-
self
-
end
-
-
# Wrapper around +decrement+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
1
def decrement!(attribute, by = 1)
-
decrement(attribute, by).update_attribute(attribute, self[attribute])
-
end
-
-
# Assigns to +attribute+ the boolean opposite of <tt>attribute?</tt>. So
-
# if the predicate returns +true+ the attribute will become +false+. This
-
# method toggles directly the underlying value without calling any setter.
-
# Returns +self+.
-
1
def toggle(attribute)
-
self[attribute] = !send("#{attribute}?")
-
self
-
end
-
-
# Wrapper around +toggle+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
1
def toggle!(attribute)
-
toggle(attribute).update_attribute(attribute, self[attribute])
-
end
-
-
# Reloads the record from the database.
-
#
-
# This method finds record by its primary key (which could be assigned manually) and
-
# modifies the receiver in-place:
-
#
-
# account = Account.new
-
# # => #<Account id: nil, email: nil>
-
# account.id = 1
-
# account.reload
-
# # Account Load (1.2ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT 1 [["id", 1]]
-
# # => #<Account id: 1, email: 'account@example.com'>
-
#
-
# Attributes are reloaded from the database, and caches busted, in
-
# particular the associations cache and the QueryCache.
-
#
-
# If the record no longer exists in the database <tt>ActiveRecord::RecordNotFound</tt>
-
# is raised. Otherwise, in addition to the in-place modification the method
-
# returns +self+ for convenience.
-
#
-
# The optional <tt>:lock</tt> flag option allows you to lock the reloaded record:
-
#
-
# reload(lock: true) # reload with pessimistic locking
-
#
-
# Reloading is commonly used in test suites to test something is actually
-
# written to the database, or when some action modifies the corresponding
-
# row in the database but not the object in memory:
-
#
-
# assert account.deposit!(25)
-
# assert_equal 25, account.credit # check it is updated in memory
-
# assert_equal 25, account.reload.credit # check it is also persisted
-
#
-
# Another common use case is optimistic locking handling:
-
#
-
# def with_optimistic_retry
-
# begin
-
# yield
-
# rescue ActiveRecord::StaleObjectError
-
# begin
-
# # Reload lock_version in particular.
-
# reload
-
# rescue ActiveRecord::RecordNotFound
-
# # If the record is gone there is nothing to do.
-
# else
-
# retry
-
# end
-
# end
-
# end
-
#
-
1
def reload(options = nil)
-
clear_aggregation_cache
-
clear_association_cache
-
self.class.connection.clear_query_cache
-
-
fresh_object =
-
if options && options[:lock]
-
self.class.unscoped { self.class.lock(options[:lock]).find(id) }
-
else
-
self.class.unscoped { self.class.find(id) }
-
end
-
-
@attributes = fresh_object.instance_variable_get('@attributes')
-
@new_record = false
-
self
-
end
-
-
# Saves the record with the updated_at/on attributes set to the current time.
-
# Please note that no validation is performed and only the +after_touch+,
-
# +after_commit+ and +after_rollback+ callbacks are executed.
-
#
-
# If attribute names are passed, they are updated along with updated_at/on
-
# attributes.
-
#
-
# product.touch # updates updated_at/on
-
# product.touch(:designed_at) # updates the designed_at attribute and updated_at/on
-
# product.touch(:started_at, :ended_at) # updates started_at, ended_at and updated_at/on attributes
-
#
-
# If used along with +belongs_to+ then +touch+ will invoke +touch+ method on
-
# associated object.
-
#
-
# class Brake < ActiveRecord::Base
-
# belongs_to :car, touch: true
-
# end
-
#
-
# class Car < ActiveRecord::Base
-
# belongs_to :corporation, touch: true
-
# end
-
#
-
# # triggers @brake.car.touch and @brake.car.corporation.touch
-
# @brake.touch
-
#
-
# Note that +touch+ must be used on a persisted object, or else an
-
# ActiveRecordError will be thrown. For example:
-
#
-
# ball = Ball.new
-
# ball.touch(:updated_at) # => raises ActiveRecordError
-
#
-
1
def touch(*names)
-
raise ActiveRecordError, "cannot touch on a new record object" unless persisted?
-
-
attributes = timestamp_attributes_for_update_in_model
-
attributes.concat(names)
-
-
unless attributes.empty?
-
current_time = current_time_from_proper_timezone
-
changes = {}
-
-
attributes.each do |column|
-
column = column.to_s
-
changes[column] = write_attribute(column, current_time)
-
end
-
-
changes[self.class.locking_column] = increment_lock if locking_enabled?
-
-
clear_attribute_changes(changes.keys)
-
primary_key = self.class.primary_key
-
self.class.unscoped.where(primary_key => self[primary_key]).update_all(changes) == 1
-
else
-
true
-
end
-
end
-
-
1
private
-
-
# A hook to be overridden by association modules.
-
1
def destroy_associations
-
end
-
-
1
def destroy_row
-
3
relation_for_destroy.delete_all
-
end
-
-
1
def relation_for_destroy
-
3
pk = self.class.primary_key
-
3
column = self.class.columns_hash[pk]
-
3
substitute = self.class.connection.substitute_at(column)
-
-
3
relation = self.class.unscoped.where(
-
self.class.arel_table[pk].eq(substitute))
-
-
3
relation.bind_values = [[column, id]]
-
3
relation
-
end
-
-
1
def create_or_update
-
29
raise ReadOnlyRecord, "#{self.class} is marked as readonly" if readonly?
-
29
result = new_record? ? _create_record : _update_record
-
29
result != false
-
end
-
-
# Updates the associated record with values matching those of the instance attributes.
-
# Returns the number of affected rows.
-
1
def _update_record(attribute_names = self.attribute_names)
-
4
attributes_values = arel_attributes_with_values_for_update(attribute_names)
-
4
if attributes_values.empty?
-
0
-
else
-
4
self.class.unscoped._update_record attributes_values, id, id_was
-
end
-
end
-
-
# Creates a record with values matching those of the instance attributes
-
# and returns its id.
-
1
def _create_record(attribute_names = self.attribute_names)
-
25
attributes_values = arel_attributes_with_values_for_create(attribute_names)
-
-
25
new_id = self.class.unscoped.insert attributes_values
-
25
self.id ||= new_id if self.class.primary_key
-
-
25
@new_record = false
-
25
id
-
end
-
-
1
def verify_readonly_attribute(name)
-
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Query Cache
-
1
class QueryCache
-
1
module ClassMethods
-
# Enable the query cache within the block if Active Record is configured.
-
# If it's not, it will execute the given block.
-
1
def cache(&block)
-
if ActiveRecord::Base.connected?
-
connection.cache(&block)
-
else
-
yield
-
end
-
end
-
-
# Disable the query cache within the block if Active Record is configured.
-
# If it's not, it will execute the given block.
-
1
def uncached(&block)
-
if ActiveRecord::Base.connected?
-
connection.uncached(&block)
-
else
-
yield
-
end
-
end
-
end
-
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
66
connection = ActiveRecord::Base.connection
-
66
enabled = connection.query_cache_enabled
-
66
connection_id = ActiveRecord::Base.connection_id
-
66
connection.enable_query_cache!
-
-
66
response = @app.call(env)
-
66
response[2] = Rack::BodyProxy.new(response[2]) do
-
66
restore_query_cache_settings(connection_id, enabled)
-
end
-
-
66
response
-
rescue Exception => e
-
restore_query_cache_settings(connection_id, enabled)
-
raise e
-
end
-
-
1
private
-
-
1
def restore_query_cache_settings(connection_id, enabled)
-
66
ActiveRecord::Base.connection_id = connection_id
-
66
ActiveRecord::Base.connection.clear_query_cache
-
66
ActiveRecord::Base.connection.disable_query_cache! unless enabled
-
end
-
-
end
-
end
-
1
module ActiveRecord
-
1
module Querying
-
1
delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, to: :all
-
1
delegate :second, :second!, :third, :third!, :fourth, :fourth!, :fifth, :fifth!, :forty_two, :forty_two!, to: :all
-
1
delegate :first_or_create, :first_or_create!, :first_or_initialize, to: :all
-
1
delegate :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, to: :all
-
1
delegate :find_by, :find_by!, to: :all
-
1
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, to: :all
-
1
delegate :find_each, :find_in_batches, to: :all
-
1
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
-
:where, :rewhere, :preload, :eager_load, :includes, :from, :lock, :readonly,
-
:having, :create_with, :uniq, :distinct, :references, :none, :unscope, to: :all
-
1
delegate :count, :average, :minimum, :maximum, :sum, :calculate, to: :all
-
1
delegate :pluck, :ids, to: :all
-
-
# Executes a custom SQL query against your database and returns all the results. The results will
-
# be returned as an array with columns requested encapsulated as attributes of the model you call
-
# this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
-
# a +Product+ object with the attributes you specified in the SQL query.
-
#
-
# If you call a complicated SQL query which spans multiple tables the columns specified by the
-
# SELECT will be attributes of the model, whether or not they are columns of the corresponding
-
# table.
-
#
-
# The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
-
# no database agnostic conversions performed. This should be a last resort because using, for example,
-
# MySQL specific terms will lock you to using that particular database engine or require you to
-
# change your call if you switch engines.
-
#
-
# # A simple SQL query spanning multiple tables
-
# Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
-
# # => [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
-
#
-
# You can use the same string replacement techniques as you can with <tt>ActiveRecord::QueryMethods#where</tt>:
-
#
-
# Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
-
# Post.find_by_sql ["SELECT body FROM comments WHERE author = :user_id OR approved_by = :user_id", { :user_id => user_id }]
-
1
def find_by_sql(sql, binds = [])
-
46
result_set = connection.select_all(sanitize_sql(sql), "#{name} Load", binds)
-
46
column_types = result_set.column_types.dup
-
356
columns_hash.each_key { |k| column_types.delete k }
-
46
message_bus = ActiveSupport::Notifications.instrumenter
-
-
46
payload = {
-
record_count: result_set.length,
-
class_name: name
-
}
-
-
46
message_bus.instrument('instantiation.active_record', payload) do
-
100
result_set.map { |record| instantiate(record, column_types) }
-
end
-
end
-
-
# Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
-
# The use of this method should be restricted to complicated SQL queries that can't be executed
-
# using the ActiveRecord::Calculations class methods. Look into those before using this.
-
#
-
# ==== Parameters
-
#
-
# * +sql+ - An SQL statement which should return a count query from the database, see the example below.
-
#
-
# Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
-
1
def count_by_sql(sql)
-
sql = sanitize_conditions(sql)
-
connection.select_value(sql, "#{name} Count").to_i
-
end
-
end
-
end
-
1
require "active_record"
-
1
require "rails"
-
1
require "active_model/railtie"
-
-
# For now, action_controller must always be present with
-
# rails, so let's make sure that it gets required before
-
# here. This is needed for correctly setting up the middleware.
-
# In the future, this might become an optional require.
-
1
require "action_controller/railtie"
-
-
1
module ActiveRecord
-
# = Active Record Railtie
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.active_record = ActiveSupport::OrderedOptions.new
-
-
1
config.app_generators.orm :active_record, :migration => true,
-
:timestamps => true
-
-
1
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::QueryCache"
-
-
1
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::ConnectionAdapters::ConnectionManagement"
-
-
1
config.action_dispatch.rescue_responses.merge!(
-
'ActiveRecord::RecordNotFound' => :not_found,
-
'ActiveRecord::StaleObjectError' => :conflict,
-
'ActiveRecord::RecordInvalid' => :unprocessable_entity,
-
'ActiveRecord::RecordNotSaved' => :unprocessable_entity
-
)
-
-
-
1
config.active_record.use_schema_cache_dump = true
-
1
config.active_record.maintain_test_schema = true
-
-
1
config.eager_load_namespaces << ActiveRecord
-
-
1
rake_tasks do
-
namespace :db do
-
task :load_config do
-
ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration
-
-
if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
-
if engine.paths['db/migrate'].existent
-
ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths['db/migrate'].to_a
-
end
-
end
-
end
-
end
-
-
load "active_record/railties/databases.rake"
-
end
-
-
# When loading console, force ActiveRecord::Base to be loaded
-
# to avoid cross references when loading a constant for the
-
# first time. Also, make it output to STDERR.
-
1
console do |app|
-
require "active_record/railties/console_sandbox" if app.sandbox?
-
require "active_record/base"
-
console = ActiveSupport::Logger.new(STDERR)
-
Rails.logger.extend ActiveSupport::Logger.broadcast console
-
end
-
-
1
runner do
-
require "active_record/base"
-
end
-
-
1
initializer "active_record.initialize_timezone" do
-
1
ActiveSupport.on_load(:active_record) do
-
1
self.time_zone_aware_attributes = true
-
1
self.default_timezone = :utc
-
end
-
end
-
-
1
initializer "active_record.logger" do
-
2
ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
-
end
-
-
1
initializer "active_record.migration_error" do
-
1
if config.active_record.delete(:migration_error) == :page_load
-
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::Migration::CheckPending"
-
end
-
end
-
-
1
initializer "active_record.check_schema_cache_dump" do
-
1
if config.active_record.delete(:use_schema_cache_dump)
-
1
config.after_initialize do |app|
-
1
ActiveSupport.on_load(:active_record) do
-
1
filename = File.join(app.config.paths["db"].first, "schema_cache.dump")
-
-
1
if File.file?(filename)
-
cache = Marshal.load File.binread filename
-
if cache.version == ActiveRecord::Migrator.current_version
-
self.connection.schema_cache = cache
-
else
-
warn "Ignoring db/schema_cache.dump because it has expired. The current schema version is #{ActiveRecord::Migrator.current_version}, but the one in the cache is #{cache.version}."
-
end
-
end
-
end
-
end
-
end
-
end
-
-
1
initializer "active_record.set_configs" do |app|
-
1
ActiveSupport.on_load(:active_record) do
-
1
app.config.active_record.each do |k,v|
-
2
send "#{k}=", v
-
end
-
end
-
end
-
-
# This sets the database configuration from Configuration#database_configuration
-
# and then establishes the connection.
-
1
initializer "active_record.initialize_database" do |app|
-
1
ActiveSupport.on_load(:active_record) do
-
1
self.configurations = Rails.application.config.database_configuration
-
-
1
begin
-
1
establish_connection
-
rescue ActiveRecord::NoDatabaseError
-
warn <<-end_warning
-
Oops - You have a database configured, but it doesn't exist yet!
-
-
Here's how to get started:
-
-
1. Configure your database in config/database.yml.
-
2. Run `bin/rake db:create` to create the database.
-
3. Run `bin/rake db:setup` to load your database schema.
-
end_warning
-
raise
-
end
-
end
-
end
-
-
# Expose database runtime to controller for logging.
-
1
initializer "active_record.log_runtime" do
-
1
require "active_record/railties/controller_runtime"
-
1
ActiveSupport.on_load(:action_controller) do
-
1
include ActiveRecord::Railties::ControllerRuntime
-
end
-
end
-
-
1
initializer "active_record.set_reloader_hooks" do |app|
-
1
hook = app.config.reload_classes_only_on_change ? :to_prepare : :to_cleanup
-
-
1
ActiveSupport.on_load(:active_record) do
-
1
ActionDispatch::Reloader.send(hook) do
-
if ActiveRecord::Base.connected?
-
ActiveRecord::Base.clear_cache!
-
ActiveRecord::Base.clear_reloadable_connections!
-
end
-
end
-
end
-
end
-
-
1
initializer "active_record.add_watchable_files" do |app|
-
1
path = app.paths["db"].first
-
1
config.watchable_files.concat ["#{path}/schema.rb", "#{path}/structure.sql"]
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_record/log_subscriber'
-
-
1
module ActiveRecord
-
1
module Railties # :nodoc:
-
1
module ControllerRuntime #:nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
protected
-
-
1
attr_internal :db_runtime
-
-
1
def process_action(action, *args)
-
# We also need to reset the runtime before each action
-
# because of queries in middleware or in cases we are streaming
-
# and it won't be cleaned up by the method below.
-
66
ActiveRecord::LogSubscriber.reset_runtime
-
66
super
-
end
-
-
1
def cleanup_view_runtime
-
55
if ActiveRecord::Base.connected?
-
55
db_rt_before_render = ActiveRecord::LogSubscriber.reset_runtime
-
55
self.db_runtime = (db_runtime || 0) + db_rt_before_render
-
55
runtime = super
-
55
db_rt_after_render = ActiveRecord::LogSubscriber.reset_runtime
-
55
self.db_runtime += db_rt_after_render
-
55
runtime - db_rt_after_render
-
else
-
super
-
end
-
end
-
-
1
def append_info_to_payload(payload)
-
66
super
-
66
if ActiveRecord::Base.connected?
-
66
payload[:db_runtime] = (db_runtime || 0) + ActiveRecord::LogSubscriber.reset_runtime
-
end
-
end
-
-
1
module ClassMethods # :nodoc:
-
1
def log_process_action(payload)
-
66
messages, db_runtime = super, payload[:db_runtime]
-
66
messages << ("ActiveRecord: %.1fms" % db_runtime.to_f) if db_runtime
-
66
messages
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ReadonlyAttributes
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :_attr_readonly, instance_accessor: false
-
1
self._attr_readonly = []
-
end
-
-
1
module ClassMethods
-
# Attributes listed as readonly will be used to create a new record but update operations will
-
# ignore these fields.
-
1
def attr_readonly(*attributes)
-
self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || [])
-
end
-
-
# Returns an array of all the attributes that have been specified as readonly.
-
1
def readonly_attributes
-
9
self._attr_readonly
-
end
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'active_support/core_ext/string/filters'
-
-
1
module ActiveRecord
-
# = Active Record Reflection
-
1
module Reflection # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :_reflections
-
1
class_attribute :aggregate_reflections
-
1
self._reflections = {}
-
1
self.aggregate_reflections = {}
-
end
-
-
1
def self.create(macro, name, scope, options, ar)
-
4
klass = case macro
-
when :composed_of
-
AggregateReflection
-
when :has_many
-
1
HasManyReflection
-
when :has_one
-
HasOneReflection
-
when :belongs_to
-
3
BelongsToReflection
-
else
-
raise "Unsupported Macro: #{macro}"
-
end
-
-
4
reflection = klass.new(name, scope, options, ar)
-
4
options[:through] ? ThroughReflection.new(reflection) : reflection
-
end
-
-
1
def self.add_reflection(ar, name, reflection)
-
4
ar.clear_reflections_cache
-
4
ar._reflections = ar._reflections.merge(name.to_s => reflection)
-
end
-
-
1
def self.add_aggregate_reflection(ar, name, reflection)
-
ar.aggregate_reflections = ar.aggregate_reflections.merge(name.to_s => reflection)
-
end
-
-
# \Reflection enables interrogating of Active Record classes and objects
-
# about their associations and aggregations. This information can,
-
# for example, be used in a form builder that takes an Active Record object
-
# and creates input fields for all of the attributes depending on their type
-
# and displays the associations to other objects.
-
#
-
# MacroReflection class has info for AggregateReflection and AssociationReflection
-
# classes.
-
1
module ClassMethods
-
# Returns an array of AggregateReflection objects for all the aggregations in the class.
-
1
def reflect_on_all_aggregations
-
aggregate_reflections.values
-
end
-
-
# Returns the AggregateReflection object for the named +aggregation+ (use the symbol).
-
#
-
# Account.reflect_on_aggregation(:balance) # => the balance AggregateReflection
-
#
-
1
def reflect_on_aggregation(aggregation)
-
16
aggregate_reflections[aggregation.to_s]
-
end
-
-
# Returns a Hash of name of the reflection as the key and a AssociationReflection as the value.
-
#
-
# Account.reflections # => {"balance" => AggregateReflection}
-
#
-
# @api public
-
1
def reflections
-
@__reflections ||= begin
-
ref = {}
-
-
_reflections.each do |name, reflection|
-
parent_name, parent_reflection = reflection.parent_reflection
-
-
if parent_name
-
ref[parent_name] = parent_reflection
-
else
-
ref[name] = reflection
-
end
-
end
-
-
ref
-
end
-
end
-
-
# Returns an array of AssociationReflection objects for all the
-
# associations in the class. If you only want to reflect on a certain
-
# association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>,
-
# <tt>:belongs_to</tt>) as the first parameter.
-
#
-
# Example:
-
#
-
# Account.reflect_on_all_associations # returns an array of all associations
-
# Account.reflect_on_all_associations(:has_many) # returns an array of all has_many associations
-
#
-
# @api public
-
1
def reflect_on_all_associations(macro = nil)
-
association_reflections = reflections.values
-
macro ? association_reflections.select { |reflection| reflection.macro == macro } : association_reflections
-
end
-
-
# Returns the AssociationReflection object for the +association+ (use the symbol).
-
#
-
# Account.reflect_on_association(:owner) # returns the owner AssociationReflection
-
# Invoice.reflect_on_association(:line_items).macro # returns :has_many
-
#
-
# @api public
-
1
def reflect_on_association(association)
-
reflections[association.to_s]
-
end
-
-
# @api private
-
1
def _reflect_on_association(association) #:nodoc:
-
101
_reflections[association.to_s]
-
end
-
-
# Returns an array of AssociationReflection objects for all associations which have <tt>:autosave</tt> enabled.
-
#
-
# @api public
-
1
def reflect_on_all_autosave_associations
-
reflections.values.select { |reflection| reflection.options[:autosave] }
-
end
-
-
1
def clear_reflections_cache #:nodoc:
-
4
@__reflections = nil
-
end
-
end
-
-
# Holds all the methods that are shared between MacroReflection, AssociationReflection
-
# and ThroughReflection
-
1
class AbstractReflection # :nodoc:
-
1
def table_name
-
klass.table_name
-
end
-
-
# Returns a new, unsaved instance of the associated class. +attributes+ will
-
# be passed to the class's constructor.
-
1
def build_association(attributes, &block)
-
klass.new(attributes, &block)
-
end
-
-
1
def quoted_table_name
-
klass.quoted_table_name
-
end
-
-
1
def primary_key_type
-
klass.type_for_attribute(klass.primary_key)
-
end
-
-
# Returns the class name for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>'Money'</tt>
-
# <tt>has_many :clients</tt> returns <tt>'Client'</tt>
-
1
def class_name
-
@class_name ||= (options[:class_name] || derive_class_name).to_s
-
end
-
-
1
JoinKeys = Struct.new(:key, :foreign_key) # :nodoc:
-
-
1
def join_keys(assoc_klass)
-
JoinKeys.new(foreign_key, active_record_primary_key)
-
end
-
-
1
def source_macro
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
ActiveRecord::Base.source_macro is deprecated and will be removed
-
without replacement.
-
MSG
-
-
macro
-
end
-
-
1
def inverse_of
-
return unless inverse_name
-
-
@inverse_of ||= klass._reflect_on_association inverse_name
-
end
-
-
1
def check_validity_of_inverse!
-
unless polymorphic?
-
if has_inverse? && inverse_of.nil?
-
raise InverseOfAssociationNotFoundError.new(self)
-
end
-
end
-
end
-
end
-
# Base class for AggregateReflection and AssociationReflection. Objects of
-
# AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
-
#
-
# MacroReflection
-
# AssociationReflection
-
# AggregateReflection
-
# HasManyReflection
-
# HasOneReflection
-
# BelongsToReflection
-
# ThroughReflection
-
1
class MacroReflection < AbstractReflection
-
# Returns the name of the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>:balance</tt>
-
# <tt>has_many :clients</tt> returns <tt>:clients</tt>
-
1
attr_reader :name
-
-
1
attr_reader :scope
-
-
# Returns the hash of options used for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>{ class_name: "Money" }</tt>
-
# <tt>has_many :clients</tt> returns <tt>{}</tt>
-
1
attr_reader :options
-
-
1
attr_reader :active_record
-
-
1
attr_reader :plural_name # :nodoc:
-
-
1
def initialize(name, scope, options, active_record)
-
4
@name = name
-
4
@scope = scope
-
4
@options = options
-
4
@active_record = active_record
-
4
@klass = options[:anonymous_class]
-
4
@plural_name = active_record.pluralize_table_names ?
-
name.to_s.pluralize : name.to_s
-
end
-
-
1
def autosave=(autosave)
-
@automatic_inverse_of = false
-
@options[:autosave] = autosave
-
_, parent_reflection = self.parent_reflection
-
if parent_reflection
-
parent_reflection.autosave = autosave
-
end
-
end
-
-
# Returns the class for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns the Money class
-
# <tt>has_many :clients</tt> returns the Client class
-
1
def klass
-
@klass ||= compute_class(class_name)
-
end
-
-
1
def compute_class(name)
-
name.constantize
-
end
-
-
# Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
-
# and +other_aggregation+ has an options hash assigned to it.
-
1
def ==(other_aggregation)
-
super ||
-
other_aggregation.kind_of?(self.class) &&
-
name == other_aggregation.name &&
-
!other_aggregation.options.nil? &&
-
active_record == other_aggregation.active_record
-
end
-
-
1
private
-
1
def derive_class_name
-
name.to_s.camelize
-
end
-
end
-
-
-
# Holds all the meta-data about an aggregation as it was specified in the
-
# Active Record class.
-
1
class AggregateReflection < MacroReflection #:nodoc:
-
1
def mapping
-
mapping = options[:mapping] || [name, name]
-
mapping.first.is_a?(Array) ? mapping : [mapping]
-
end
-
end
-
-
# Holds all the meta-data about an association as it was specified in the
-
# Active Record class.
-
1
class AssociationReflection < MacroReflection #:nodoc:
-
# Returns the target association's class.
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :books
-
# end
-
#
-
# Author.reflect_on_association(:books).klass
-
# # => Book
-
#
-
# <b>Note:</b> Do not call +klass.new+ or +klass.create+ to instantiate
-
# a new association object. Use +build_association+ or +create_association+
-
# instead. This allows plugins to hook into association object creation.
-
1
def klass
-
@klass ||= compute_class(class_name)
-
end
-
-
1
def compute_class(name)
-
active_record.send(:compute_type, name)
-
end
-
-
1
attr_reader :type, :foreign_type
-
1
attr_accessor :parent_reflection # [:name, Reflection]
-
-
1
def initialize(name, scope, options, active_record)
-
4
super
-
4
@automatic_inverse_of = nil
-
4
@type = options[:as] && (options[:foreign_type] || "#{options[:as]}_type")
-
4
@foreign_type = options[:foreign_type] || "#{name}_type"
-
4
@constructable = calculate_constructable(macro, options)
-
4
@association_scope_cache = {}
-
4
@scope_lock = Mutex.new
-
end
-
-
1
def association_scope_cache(conn, owner)
-
key = conn.prepared_statements
-
if polymorphic?
-
key = [key, owner._read_attribute(@foreign_type)]
-
end
-
@association_scope_cache[key] ||= @scope_lock.synchronize {
-
@association_scope_cache[key] ||= yield
-
}
-
end
-
-
1
def constructable? # :nodoc:
-
3
@constructable
-
end
-
-
1
def join_table
-
@join_table ||= options[:join_table] || derive_join_table
-
end
-
-
1
def foreign_key
-
@foreign_key ||= options[:foreign_key] || derive_foreign_key
-
end
-
-
1
def association_foreign_key
-
@association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key
-
end
-
-
# klass option is necessary to support loading polymorphic associations
-
1
def association_primary_key(klass = nil)
-
options[:primary_key] || primary_key(klass || self.klass)
-
end
-
-
1
def active_record_primary_key
-
@active_record_primary_key ||= options[:primary_key] || primary_key(active_record)
-
end
-
-
1
def counter_cache_column
-
21
if options[:counter_cache] == true
-
"#{active_record.name.demodulize.underscore.pluralize}_count"
-
21
elsif options[:counter_cache]
-
options[:counter_cache].to_s
-
end
-
end
-
-
1
def check_validity!
-
check_validity_of_inverse!
-
end
-
-
1
def check_preloadable!
-
return unless scope
-
-
if scope.arity > 0
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
The association scope '#{name}' is instance dependent (the scope
-
block takes an argument). Preloading happens before the individual
-
instances are created. This means that there is no instance being
-
passed to the association scope. This will most likely result in
-
broken or incorrect behavior. Joining, Preloading and eager loading
-
of these associations is deprecated and will be removed in the future.
-
MSG
-
end
-
end
-
1
alias :check_eager_loadable! :check_preloadable!
-
-
1
def join_id_for(owner) # :nodoc:
-
owner[active_record_primary_key]
-
end
-
-
1
def through_reflection
-
nil
-
end
-
-
1
def source_reflection
-
self
-
end
-
-
# A chain of reflections from this one back to the owner. For more see the explanation in
-
# ThroughReflection.
-
1
def chain
-
[self]
-
end
-
-
1
def nested?
-
false
-
end
-
-
# An array of arrays of scopes. Each item in the outside array corresponds to a reflection
-
# in the #chain.
-
1
def scope_chain
-
scope ? [[scope]] : [[]]
-
end
-
-
1
def has_inverse?
-
inverse_name
-
end
-
-
1
def polymorphic_inverse_of(associated_class)
-
if has_inverse?
-
if inverse_relationship = associated_class._reflect_on_association(options[:inverse_of])
-
inverse_relationship
-
else
-
raise InverseOfAssociationNotFoundError.new(self, associated_class)
-
end
-
end
-
end
-
-
# Returns the macro type.
-
#
-
# <tt>has_many :clients</tt> returns <tt>:has_many</tt>
-
1
def macro; raise NotImplementedError; end
-
-
# Returns whether or not this association reflection is for a collection
-
# association. Returns +true+ if the +macro+ is either +has_many+ or
-
# +has_and_belongs_to_many+, +false+ otherwise.
-
1
def collection?
-
6
false
-
end
-
-
# Returns whether or not the association should be validated as part of
-
# the parent's validation.
-
#
-
# Unless you explicitly disable validation with
-
# <tt>validate: false</tt>, validation will take place when:
-
#
-
# * you explicitly enable validation; <tt>validate: true</tt>
-
# * you use autosave; <tt>autosave: true</tt>
-
# * the association is a +has_many+ association
-
1
def validate?
-
4
!options[:validate].nil? ? options[:validate] : (options[:autosave] == true || collection?)
-
end
-
-
# Returns +true+ if +self+ is a +belongs_to+ reflection.
-
1
def belongs_to?; false; end
-
-
# Returns +true+ if +self+ is a +has_one+ reflection.
-
4
def has_one?; false; end
-
-
1
def association_class
-
case macro
-
when :belongs_to
-
if polymorphic?
-
Associations::BelongsToPolymorphicAssociation
-
else
-
Associations::BelongsToAssociation
-
end
-
when :has_many
-
if options[:through]
-
Associations::HasManyThroughAssociation
-
else
-
Associations::HasManyAssociation
-
end
-
when :has_one
-
if options[:through]
-
Associations::HasOneThroughAssociation
-
else
-
Associations::HasOneAssociation
-
end
-
end
-
end
-
-
1
def polymorphic?
-
3
options[:polymorphic]
-
end
-
-
1
VALID_AUTOMATIC_INVERSE_MACROS = [:has_many, :has_one, :belongs_to]
-
1
INVALID_AUTOMATIC_INVERSE_OPTIONS = [:conditions, :through, :polymorphic, :foreign_key]
-
-
1
protected
-
-
1
def actual_source_reflection # FIXME: this is a horrible name
-
self
-
end
-
-
1
private
-
-
1
def calculate_constructable(macro, options)
-
4
case macro
-
when :belongs_to
-
3
!polymorphic?
-
when :has_one
-
!options[:through]
-
else
-
1
true
-
end
-
end
-
-
# Attempts to find the inverse association name automatically.
-
# If it cannot find a suitable inverse association name, it returns
-
# nil.
-
1
def inverse_name
-
options.fetch(:inverse_of) do
-
if @automatic_inverse_of == false
-
nil
-
else
-
@automatic_inverse_of ||= automatic_inverse_of
-
end
-
end
-
end
-
-
# returns either nil or the inverse association name that it finds.
-
1
def automatic_inverse_of
-
if can_find_inverse_of_automatically?(self)
-
inverse_name = ActiveSupport::Inflector.underscore(options[:as] || active_record.name.demodulize).to_sym
-
-
begin
-
reflection = klass._reflect_on_association(inverse_name)
-
rescue NameError
-
# Give up: we couldn't compute the klass type so we won't be able
-
# to find any associations either.
-
reflection = false
-
end
-
-
if valid_inverse_reflection?(reflection)
-
return inverse_name
-
end
-
end
-
-
false
-
end
-
-
# Checks if the inverse reflection that is returned from the
-
# +automatic_inverse_of+ method is a valid reflection. We must
-
# make sure that the reflection's active_record name matches up
-
# with the current reflection's klass name.
-
#
-
# Note: klass will always be valid because when there's a NameError
-
# from calling +klass+, +reflection+ will already be set to false.
-
1
def valid_inverse_reflection?(reflection)
-
reflection &&
-
klass.name == reflection.active_record.name &&
-
can_find_inverse_of_automatically?(reflection)
-
end
-
-
# Checks to see if the reflection doesn't have any options that prevent
-
# us from being able to guess the inverse automatically. First, the
-
# <tt>inverse_of</tt> option cannot be set to false. Second, we must
-
# have <tt>has_many</tt>, <tt>has_one</tt>, <tt>belongs_to</tt> associations.
-
# Third, we must not have options such as <tt>:polymorphic</tt> or
-
# <tt>:foreign_key</tt> which prevent us from correctly guessing the
-
# inverse association.
-
#
-
# Anything with a scope can additionally ruin our attempt at finding an
-
# inverse, so we exclude reflections with scopes.
-
1
def can_find_inverse_of_automatically?(reflection)
-
reflection.options[:inverse_of] != false &&
-
VALID_AUTOMATIC_INVERSE_MACROS.include?(reflection.macro) &&
-
!INVALID_AUTOMATIC_INVERSE_OPTIONS.any? { |opt| reflection.options[opt] } &&
-
!reflection.scope
-
end
-
-
1
def derive_class_name
-
class_name = name.to_s
-
class_name = class_name.singularize if collection?
-
class_name.camelize
-
end
-
-
1
def derive_foreign_key
-
if belongs_to?
-
"#{name}_id"
-
elsif options[:as]
-
"#{options[:as]}_id"
-
else
-
active_record.name.foreign_key
-
end
-
end
-
-
1
def derive_join_table
-
ModelSchema.derive_join_table_name active_record.table_name, klass.table_name
-
end
-
-
1
def primary_key(klass)
-
klass.primary_key || raise(UnknownPrimaryKey.new(klass))
-
end
-
end
-
-
1
class HasManyReflection < AssociationReflection # :nodoc:
-
1
def initialize(name, scope, options, active_record)
-
1
super(name, scope, options, active_record)
-
end
-
-
2
def macro; :has_many; end
-
-
4
def collection?; true; end
-
end
-
-
1
class HasOneReflection < AssociationReflection # :nodoc:
-
1
def initialize(name, scope, options, active_record)
-
super(name, scope, options, active_record)
-
end
-
-
1
def macro; :has_one; end
-
-
1
def has_one?; true; end
-
end
-
-
1
class BelongsToReflection < AssociationReflection # :nodoc:
-
1
def initialize(name, scope, options, active_record)
-
3
super(name, scope, options, active_record)
-
end
-
-
4
def macro; :belongs_to; end
-
-
22
def belongs_to?; true; end
-
-
1
def join_keys(assoc_klass)
-
key = polymorphic? ? association_primary_key(assoc_klass) : association_primary_key
-
JoinKeys.new(key, foreign_key)
-
end
-
-
1
def join_id_for(owner) # :nodoc:
-
owner[foreign_key]
-
end
-
end
-
-
1
class HasAndBelongsToManyReflection < AssociationReflection # :nodoc:
-
1
def initialize(name, scope, options, active_record)
-
super
-
end
-
-
1
def macro; :has_and_belongs_to_many; end
-
-
1
def collection?
-
true
-
end
-
end
-
-
# Holds all the meta-data about a :through association as it was specified
-
# in the Active Record class.
-
1
class ThroughReflection < AbstractReflection #:nodoc:
-
1
attr_reader :delegate_reflection
-
1
delegate :foreign_key, :foreign_type, :association_foreign_key,
-
:active_record_primary_key, :type, :to => :source_reflection
-
-
1
def initialize(delegate_reflection)
-
@delegate_reflection = delegate_reflection
-
@klass = delegate_reflection.options[:anonymous_class]
-
@source_reflection_name = delegate_reflection.options[:source]
-
end
-
-
1
def klass
-
@klass ||= delegate_reflection.compute_class(class_name)
-
end
-
-
# Returns the source of the through reflection. It checks both a singularized
-
# and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# class Tagging < ActiveRecord::Base
-
# belongs_to :post
-
# belongs_to :tag
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.source_reflection
-
# # => <ActiveRecord::Reflection::BelongsToReflection: @name=:tag, @active_record=Tagging, @plural_name="tags">
-
#
-
1
def source_reflection
-
through_reflection.klass._reflect_on_association(source_reflection_name)
-
end
-
-
# Returns the AssociationReflection object specified in the <tt>:through</tt> option
-
# of a HasManyThrough or HasOneThrough association.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.through_reflection
-
# # => <ActiveRecord::Reflection::HasManyReflection: @name=:taggings, @active_record=Post, @plural_name="taggings">
-
#
-
1
def through_reflection
-
active_record._reflect_on_association(options[:through])
-
end
-
-
# Returns an array of reflections which are involved in this association. Each item in the
-
# array corresponds to a table which will be part of the query for this association.
-
#
-
# The chain is built by recursively calling #chain on the source reflection and the through
-
# reflection. The base case for the recursion is a normal association, which just returns
-
# [self] as its #chain.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.chain
-
# # => [<ActiveRecord::Reflection::ThroughReflection: @delegate_reflection=#<ActiveRecord::Reflection::HasManyReflection: @name=:tags...>,
-
# <ActiveRecord::Reflection::HasManyReflection: @name=:taggings, @options={}, @active_record=Post>]
-
#
-
1
def chain
-
@chain ||= begin
-
a = source_reflection.chain
-
b = through_reflection.chain
-
chain = a + b
-
chain[0] = self # Use self so we don't lose the information from :source_type
-
chain
-
end
-
end
-
-
# Consider the following example:
-
#
-
# class Person
-
# has_many :articles
-
# has_many :comment_tags, through: :articles
-
# end
-
#
-
# class Article
-
# has_many :comments
-
# has_many :comment_tags, through: :comments, source: :tags
-
# end
-
#
-
# class Comment
-
# has_many :tags
-
# end
-
#
-
# There may be scopes on Person.comment_tags, Article.comment_tags and/or Comment.tags,
-
# but only Comment.tags will be represented in the #chain. So this method creates an array
-
# of scopes corresponding to the chain.
-
1
def scope_chain
-
@scope_chain ||= begin
-
scope_chain = source_reflection.scope_chain.map(&:dup)
-
-
# Add to it the scope from this reflection (if any)
-
scope_chain.first << scope if scope
-
-
through_scope_chain = through_reflection.scope_chain.map(&:dup)
-
-
if options[:source_type]
-
type = foreign_type
-
source_type = options[:source_type]
-
through_scope_chain.first << lambda { |object|
-
where(type => source_type)
-
}
-
end
-
-
# Recursively fill out the rest of the array from the through reflection
-
scope_chain + through_scope_chain
-
end
-
end
-
-
1
def join_keys(assoc_klass)
-
source_reflection.join_keys(assoc_klass)
-
end
-
-
# The macro used by the source association
-
1
def source_macro
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
ActiveRecord::Base.source_macro is deprecated and will be removed
-
without replacement.
-
MSG
-
-
source_reflection.source_macro
-
end
-
-
# A through association is nested if there would be more than one join table
-
1
def nested?
-
chain.length > 2
-
end
-
-
# We want to use the klass from this reflection, rather than just delegate straight to
-
# the source_reflection, because the source_reflection may be polymorphic. We still
-
# need to respect the source_reflection's :primary_key option, though.
-
1
def association_primary_key(klass = nil)
-
# Get the "actual" source reflection if the immediate source reflection has a
-
# source reflection itself
-
actual_source_reflection.options[:primary_key] || primary_key(klass || self.klass)
-
end
-
-
# Gets an array of possible <tt>:through</tt> source reflection names in both singular and plural form.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.source_reflection_names
-
# # => [:tag, :tags]
-
#
-
1
def source_reflection_names
-
options[:source] ? [options[:source]] : [name.to_s.singularize, name].uniq
-
end
-
-
1
def source_reflection_name # :nodoc:
-
return @source_reflection_name if @source_reflection_name
-
-
names = [name.to_s.singularize, name].collect { |n| n.to_sym }.uniq
-
names = names.find_all { |n|
-
through_reflection.klass._reflect_on_association(n)
-
}
-
-
if names.length > 1
-
example_options = options.dup
-
example_options[:source] = source_reflection_names.first
-
ActiveSupport::Deprecation.warn \
-
"Ambiguous source reflection for through association. Please " \
-
"specify a :source directive on your declaration like:\n" \
-
"\n" \
-
" class #{active_record.name} < ActiveRecord::Base\n" \
-
" #{macro} :#{name}, #{example_options}\n" \
-
" end"
-
end
-
-
@source_reflection_name = names.first
-
end
-
-
1
def source_options
-
source_reflection.options
-
end
-
-
1
def through_options
-
through_reflection.options
-
end
-
-
1
def join_id_for(owner) # :nodoc:
-
source_reflection.join_id_for(owner)
-
end
-
-
1
def check_validity!
-
if through_reflection.nil?
-
raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
-
end
-
-
if through_reflection.polymorphic?
-
if has_one?
-
raise HasOneAssociationPolymorphicThroughError.new(active_record.name, self)
-
else
-
raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self)
-
end
-
end
-
-
if source_reflection.nil?
-
raise HasManyThroughSourceAssociationNotFoundError.new(self)
-
end
-
-
if options[:source_type] && !source_reflection.polymorphic?
-
raise HasManyThroughAssociationPointlessSourceTypeError.new(active_record.name, self, source_reflection)
-
end
-
-
if source_reflection.polymorphic? && options[:source_type].nil?
-
raise HasManyThroughAssociationPolymorphicSourceError.new(active_record.name, self, source_reflection)
-
end
-
-
if has_one? && through_reflection.collection?
-
raise HasOneThroughCantAssociateThroughCollection.new(active_record.name, self, through_reflection)
-
end
-
-
check_validity_of_inverse!
-
end
-
-
1
protected
-
-
1
def actual_source_reflection # FIXME: this is a horrible name
-
source_reflection.send(:actual_source_reflection)
-
end
-
-
1
def primary_key(klass)
-
klass.primary_key || raise(UnknownPrimaryKey.new(klass))
-
end
-
-
1
def inverse_name; delegate_reflection.send(:inverse_name); end
-
-
1
private
-
1
def derive_class_name
-
# get the class_name of the belongs_to association of the through reflection
-
options[:source_type] || source_reflection.class_name
-
end
-
-
1
delegate_methods = AssociationReflection.public_instance_methods -
-
public_instance_methods
-
-
1
delegate(*delegate_methods, to: :delegate_reflection)
-
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
1
require 'arel/collectors/bind'
-
-
1
module ActiveRecord
-
# = Active Record Relation
-
1
class Relation
-
1
MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
-
:order, :joins, :where, :having, :bind, :references,
-
:extending, :unscope]
-
-
1
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering,
-
:reverse_order, :distinct, :create_with, :uniq]
-
1
INVALID_METHODS_FOR_DELETE_ALL = [:limit, :distinct, :offset, :group, :having]
-
-
1
VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS
-
-
1
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
-
-
1
attr_reader :table, :klass, :loaded
-
1
alias :model :klass
-
1
alias :loaded? :loaded
-
-
1
def initialize(klass, table, values = {})
-
96
@klass = klass
-
96
@table = table
-
96
@values = values
-
96
@offsets = {}
-
96
@loaded = false
-
end
-
-
1
def initialize_copy(other)
-
# This method is a hot spot, so for now, use Hash[] to dup the hash.
-
# https://bugs.ruby-lang.org/issues/7166
-
32
@values = Hash[@values]
-
32
@values[:bind] = @values[:bind].dup if @values.key? :bind
-
32
reset
-
end
-
-
1
def insert(values) # :nodoc:
-
25
primary_key_value = nil
-
-
25
if primary_key && Hash === values
-
25
primary_key_value = values[values.keys.find { |k|
-
130
k.name == primary_key
-
}]
-
-
25
if !primary_key_value && connection.prefetch_primary_key?(klass.table_name)
-
primary_key_value = connection.next_sequence_value(klass.sequence_name)
-
values[klass.arel_table[klass.primary_key]] = primary_key_value
-
end
-
end
-
-
25
im = arel.create_insert
-
25
im.into @table
-
-
25
substitutes, binds = substitute_values values
-
-
25
if values.empty? # empty insert
-
im.values = Arel.sql(connection.empty_insert_statement_value)
-
else
-
25
im.insert substitutes
-
end
-
-
25
@klass.connection.insert(
-
im,
-
'SQL',
-
primary_key,
-
primary_key_value,
-
nil,
-
binds)
-
end
-
-
1
def _update_record(values, id, id_was) # :nodoc:
-
4
substitutes, binds = substitute_values values
-
-
4
scope = @klass.unscoped
-
-
4
if @klass.finder_needs_type_condition?
-
scope.unscope!(where: @klass.inheritance_column)
-
end
-
-
4
relation = scope.where(@klass.primary_key => (id_was || id))
-
4
bvs = binds + relation.bind_values
-
4
um = relation
-
.arel
-
.compile_update(substitutes, @klass.primary_key)
-
-
4
@klass.connection.update(
-
um,
-
'SQL',
-
bvs,
-
)
-
end
-
-
1
def substitute_values(values) # :nodoc:
-
29
binds = values.map do |arel_attr, value|
-
139
[@klass.columns_hash[arel_attr.name], value]
-
end
-
-
29
substitutes = values.each_with_index.map do |(arel_attr, _), i|
-
139
[arel_attr, @klass.connection.substitute_at(binds[i][0])]
-
end
-
-
29
[substitutes, binds]
-
end
-
-
# Initializes new record from relation while maintaining the current
-
# scope.
-
#
-
# Expects arguments in the same format as +Base.new+.
-
#
-
# users = User.where(name: 'DHH')
-
# user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
-
#
-
# You can also pass a block to new with the new record as argument:
-
#
-
# user = users.new { |user| user.name = 'Oscar' }
-
# user.name # => Oscar
-
1
def new(*args, &block)
-
scoping { @klass.new(*args, &block) }
-
end
-
-
1
alias build new
-
-
# Tries to create a new record with the same scoped attributes
-
# defined in the relation. Returns the initialized object if validation fails.
-
#
-
# Expects arguments in the same format as +Base.create+.
-
#
-
# ==== Examples
-
# users = User.where(name: 'Oscar')
-
# users.create # #<User id: 3, name: "oscar", ...>
-
#
-
# users.create(name: 'fxn')
-
# users.create # #<User id: 4, name: "fxn", ...>
-
#
-
# users.create { |user| user.name = 'tenderlove' }
-
# # #<User id: 5, name: "tenderlove", ...>
-
#
-
# users.create(name: nil) # validation on name
-
# # #<User id: nil, name: nil, ...>
-
1
def create(*args, &block)
-
scoping { @klass.create(*args, &block) }
-
end
-
-
# Similar to #create, but calls +create!+ on the base class. Raises
-
# an exception if a validation error occurs.
-
#
-
# Expects arguments in the same format as <tt>Base.create!</tt>.
-
1
def create!(*args, &block)
-
scoping { @klass.create!(*args, &block) }
-
end
-
-
1
def first_or_create(attributes = nil, &block) # :nodoc:
-
first || create(attributes, &block)
-
end
-
-
1
def first_or_create!(attributes = nil, &block) # :nodoc:
-
first || create!(attributes, &block)
-
end
-
-
1
def first_or_initialize(attributes = nil, &block) # :nodoc:
-
first || new(attributes, &block)
-
end
-
-
# Finds the first record with the given attributes, or creates a record
-
# with the attributes if one is not found:
-
#
-
# # Find the first user named "Penélope" or create a new one.
-
# User.find_or_create_by(first_name: 'Penélope')
-
# # => #<User id: 1, first_name: "Penélope", last_name: nil>
-
#
-
# # Find the first user named "Penélope" or create a new one.
-
# # We already have one so the existing record will be returned.
-
# User.find_or_create_by(first_name: 'Penélope')
-
# # => #<User id: 1, first_name: "Penélope", last_name: nil>
-
#
-
# # Find the first user named "Scarlett" or create a new one with
-
# # a particular last name.
-
# User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
-
# # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
-
#
-
# This method accepts a block, which is passed down to +create+. The last example
-
# above can be alternatively written this way:
-
#
-
# # Find the first user named "Scarlett" or create a new one with a
-
# # different last name.
-
# User.find_or_create_by(first_name: 'Scarlett') do |user|
-
# user.last_name = 'Johansson'
-
# end
-
# # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
-
#
-
# This method always returns a record, but if creation was attempted and
-
# failed due to validation errors it won't be persisted, you get what
-
# +create+ returns in such situation.
-
#
-
# Please note *this method is not atomic*, it runs first a SELECT, and if
-
# there are no results an INSERT is attempted. If there are other threads
-
# or processes there is a race condition between both calls and it could
-
# be the case that you end up with two similar records.
-
#
-
# Whether that is a problem or not depends on the logic of the
-
# application, but in the particular case in which rows have a UNIQUE
-
# constraint an exception may be raised, just retry:
-
#
-
# begin
-
# CreditAccount.find_or_create_by(user_id: user.id)
-
# rescue ActiveRecord::RecordNotUnique
-
# retry
-
# end
-
#
-
1
def find_or_create_by(attributes, &block)
-
find_by(attributes) || create(attributes, &block)
-
end
-
-
# Like <tt>find_or_create_by</tt>, but calls <tt>create!</tt> so an exception
-
# is raised if the created record is invalid.
-
1
def find_or_create_by!(attributes, &block)
-
find_by(attributes) || create!(attributes, &block)
-
end
-
-
# Like <tt>find_or_create_by</tt>, but calls <tt>new</tt> instead of <tt>create</tt>.
-
1
def find_or_initialize_by(attributes, &block)
-
find_by(attributes) || new(attributes, &block)
-
end
-
-
# Runs EXPLAIN on the query or queries triggered by this relation and
-
# returns the result as a string. The string is formatted imitating the
-
# ones printed by the database shell.
-
#
-
# Note that this method actually runs the queries, since the results of some
-
# are needed by the next ones when eager loading is going on.
-
#
-
# Please see further details in the
-
# {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
-
1
def explain
-
#TODO: Fix for binds.
-
exec_explain(collecting_queries_for_explain { exec_queries })
-
end
-
-
# Converts relation objects to Array.
-
1
def to_a
-
24
load
-
24
@records
-
end
-
-
# Serializes the relation objects Array.
-
1
def encode_with(coder)
-
coder.represent_seq(nil, to_a)
-
end
-
-
1
def as_json(options = nil) #:nodoc:
-
to_a.as_json(options)
-
end
-
-
# Returns size of the records.
-
1
def size
-
loaded? ? @records.length : count(:all)
-
end
-
-
# Returns true if there are no records.
-
1
def empty?
-
return @records.empty? if loaded?
-
-
if limit_value == 0
-
true
-
else
-
c = count(:all)
-
c.respond_to?(:zero?) ? c.zero? : c.empty?
-
end
-
end
-
-
# Returns true if there are any records.
-
1
def any?
-
if block_given?
-
to_a.any? { |*block_args| yield(*block_args) }
-
else
-
!empty?
-
end
-
end
-
-
# Returns true if there is more than one record.
-
1
def many?
-
if block_given?
-
to_a.many? { |*block_args| yield(*block_args) }
-
else
-
limit_value ? to_a.many? : size > 1
-
end
-
end
-
-
# Scope all queries to the current scope.
-
#
-
# Comment.where(post_id: 1).scoping do
-
# Comment.first
-
# end
-
# # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1
-
#
-
# Please check unscoped if you want to remove all previous scopes (including
-
# the default_scope) during the execution of a block.
-
1
def scoping
-
previous, klass.current_scope = klass.current_scope, self
-
yield
-
ensure
-
klass.current_scope = previous
-
end
-
-
# Updates all records in the current relation with details given. This method constructs a single SQL UPDATE
-
# statement and sends it straight to the database. It does not instantiate the involved models and it does not
-
# trigger Active Record callbacks or validations. Values passed to `update_all` will not go through
-
# ActiveRecord's type-casting behavior. It should receive only values that can be passed as-is to the SQL
-
# database.
-
#
-
# ==== Parameters
-
#
-
# * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
-
#
-
# ==== Examples
-
#
-
# # Update all customers with the given attributes
-
# Customer.update_all wants_email: true
-
#
-
# # Update all books with 'Rails' in their title
-
# Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
-
#
-
# # Update all books that match conditions, but limit it to 5 ordered by date
-
# Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
-
1
def update_all(updates)
-
raise ArgumentError, "Empty list of attributes to change" if updates.blank?
-
-
stmt = Arel::UpdateManager.new(arel.engine)
-
-
stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
-
stmt.table(table)
-
stmt.key = table[primary_key]
-
-
if joins_values.any?
-
@klass.connection.join_to_update(stmt, arel)
-
else
-
stmt.take(arel.limit)
-
stmt.order(*arel.orders)
-
stmt.wheres = arel.constraints
-
end
-
-
bvs = arel.bind_values + bind_values
-
@klass.connection.update stmt, 'SQL', bvs
-
end
-
-
# Updates an object (or multiple objects) and saves it to the database, if validations pass.
-
# The resulting object is returned whether the object was saved successfully to the database or not.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - This should be the id or an array of ids to be updated.
-
# * +attributes+ - This should be a hash of attributes or an array of hashes.
-
#
-
# ==== Examples
-
#
-
# # Updates one record
-
# Person.update(15, user_name: 'Samuel', group: 'expert')
-
#
-
# # Updates multiple records
-
# people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
-
# Person.update(people.keys, people.values)
-
1
def update(id, attributes)
-
if id.is_a?(Array)
-
id.map.with_index { |one_id, idx| update(one_id, attributes[idx]) }
-
else
-
object = find(id)
-
object.update(attributes)
-
object
-
end
-
end
-
-
# Destroys the records matching +conditions+ by instantiating each
-
# record and calling its +destroy+ method. Each object's callbacks are
-
# executed (including <tt>:dependent</tt> association options). Returns the
-
# collection of objects that were destroyed; each will be frozen, to
-
# reflect that no changes should be made (since they can't be persisted).
-
#
-
# Note: Instantiation, callback execution, and deletion of each
-
# record can be time consuming when you're removing many records at
-
# once. It generates at least one SQL +DELETE+ query per record (or
-
# possibly more, to enforce your callbacks). If you want to delete many
-
# rows quickly, without concern for their associations or callbacks, use
-
# +delete_all+ instead.
-
#
-
# ==== Parameters
-
#
-
# * +conditions+ - A string, array, or hash that specifies which records
-
# to destroy. If omitted, all records are destroyed. See the
-
# Conditions section in the introduction to ActiveRecord::Base for
-
# more information.
-
#
-
# ==== Examples
-
#
-
# Person.destroy_all("last_login < '2004-04-04'")
-
# Person.destroy_all(status: "inactive")
-
# Person.where(age: 0..18).destroy_all
-
1
def destroy_all(conditions = nil)
-
if conditions
-
where(conditions).destroy_all
-
else
-
to_a.each {|object| object.destroy }.tap { reset }
-
end
-
end
-
-
# Destroy an object (or multiple objects) that has the given id. The object is instantiated first,
-
# therefore all callbacks and filters are fired off before the object is deleted. This method is
-
# less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
-
#
-
# This essentially finds the object (or multiple objects) with the given id, creates a new object
-
# from the attributes, and then calls destroy on it.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - Can be either an Integer or an Array of Integers.
-
#
-
# ==== Examples
-
#
-
# # Destroy a single object
-
# Todo.destroy(1)
-
#
-
# # Destroy multiple objects
-
# todos = [1,2,3]
-
# Todo.destroy(todos)
-
1
def destroy(id)
-
if id.is_a?(Array)
-
id.map { |one_id| destroy(one_id) }
-
else
-
find(id).destroy
-
end
-
end
-
-
# Deletes the records matching +conditions+ without instantiating the records
-
# first, and hence not calling the +destroy+ method nor invoking callbacks. This
-
# is a single SQL DELETE statement that goes straight to the database, much more
-
# efficient than +destroy_all+. Be careful with relations though, in particular
-
# <tt>:dependent</tt> rules defined on associations are not honored. Returns the
-
# number of rows affected.
-
#
-
# Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
-
# Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
-
# Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
-
#
-
# Both calls delete the affected posts all at once with a single DELETE statement.
-
# If you need to destroy dependent associations or call your <tt>before_*</tt> or
-
# +after_destroy+ callbacks, use the +destroy_all+ method instead.
-
#
-
# If an invalid method is supplied, +delete_all+ raises an ActiveRecord error:
-
#
-
# Post.limit(100).delete_all
-
# # => ActiveRecord::ActiveRecordError: delete_all doesn't support limit
-
1
def delete_all(conditions = nil)
-
3
invalid_methods = INVALID_METHODS_FOR_DELETE_ALL.select { |method|
-
15
if MULTI_VALUE_METHODS.include?(method)
-
6
send("#{method}_values").any?
-
else
-
9
send("#{method}_value")
-
end
-
}
-
3
if invalid_methods.any?
-
raise ActiveRecordError.new("delete_all doesn't support #{invalid_methods.join(', ')}")
-
end
-
-
3
if conditions
-
where(conditions).delete_all
-
else
-
3
stmt = Arel::DeleteManager.new(arel.engine)
-
3
stmt.from(table)
-
-
3
if joins_values.any?
-
@klass.connection.join_to_delete(stmt, arel, table[primary_key])
-
else
-
3
stmt.wheres = arel.constraints
-
end
-
-
3
bvs = arel.bind_values + bind_values
-
3
affected = @klass.connection.delete(stmt, 'SQL', bvs)
-
-
3
reset
-
3
affected
-
end
-
end
-
-
# Deletes the row with a primary key matching the +id+ argument, using a
-
# SQL +DELETE+ statement, and returns the number of rows deleted. Active
-
# Record objects are not instantiated, so the object's callbacks are not
-
# executed, including any <tt>:dependent</tt> association options.
-
#
-
# You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
-
#
-
# Note: Although it is often much faster than the alternative,
-
# <tt>#destroy</tt>, skipping callbacks might bypass business logic in
-
# your application that ensures referential integrity or performs other
-
# essential jobs.
-
#
-
# ==== Examples
-
#
-
# # Delete a single row
-
# Todo.delete(1)
-
#
-
# # Delete multiple rows
-
# Todo.delete([2,3,4])
-
1
def delete(id_or_array)
-
where(primary_key => id_or_array).delete_all
-
end
-
-
# Causes the records to be loaded from the database if they have not
-
# been loaded already. You can use this if for some reason you need
-
# to explicitly load some records before actually using them. The
-
# return value is the relation itself, not the records.
-
#
-
# Post.where(published: true).load # => #<ActiveRecord::Relation>
-
1
def load
-
24
exec_queries unless loaded?
-
-
24
self
-
end
-
-
# Forces reloading of relation.
-
1
def reload
-
reset
-
load
-
end
-
-
1
def reset
-
35
@last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
-
35
@should_eager_load = @join_dependency = nil
-
35
@records = []
-
35
@offsets = {}
-
35
self
-
end
-
-
# Returns sql statement for the relation.
-
#
-
# User.where(name: 'Oscar').to_sql
-
# # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
-
1
def to_sql
-
@to_sql ||= begin
-
relation = self
-
connection = klass.connection
-
visitor = connection.visitor
-
-
if eager_loading?
-
find_with_associations { |rel| relation = rel }
-
end
-
-
arel = relation.arel
-
binds = (arel.bind_values + relation.bind_values).dup
-
binds.map! { |bv| connection.quote(*bv.reverse) }
-
collect = visitor.accept(arel.ast, Arel::Collectors::Bind.new)
-
collect.substitute_binds(binds).join
-
end
-
end
-
-
# Returns a hash of where conditions.
-
#
-
# User.where(name: 'Oscar').where_values_hash
-
# # => {name: "Oscar"}
-
1
def where_values_hash(relation_table_name = table_name)
-
equalities = where_values.grep(Arel::Nodes::Equality).find_all { |node|
-
node.left.relation.name == relation_table_name
-
}
-
-
binds = Hash[bind_values.find_all(&:first).map { |column, v| [column.name, v] }]
-
-
Hash[equalities.map { |where|
-
name = where.left.name
-
[name, binds.fetch(name.to_s) {
-
case where.right
-
when Array then where.right.map(&:val)
-
when Arel::Nodes::Casted
-
where.right.val
-
end
-
}]
-
}]
-
end
-
-
1
def scope_for_create
-
@scope_for_create ||= where_values_hash.merge(create_with_value)
-
end
-
-
# Returns true if relation needs eager loading.
-
1
def eager_loading?
-
@should_eager_load ||=
-
eager_load_values.any? ||
-
48
includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
-
end
-
-
# Joins that are also marked for preloading. In which case we should just eager load them.
-
# Note that this is a naive implementation because we could have strings and symbols which
-
# represent the same association, but that aren't matched by this. Also, we could have
-
# nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] }
-
1
def joined_includes_values
-
includes_values & joins_values
-
end
-
-
# +uniq+ and +uniq!+ are silently deprecated. +uniq_value+ delegates to +distinct_value+
-
# to maintain backwards compatibility. Use +distinct_value+ instead.
-
1
def uniq_value
-
distinct_value
-
end
-
-
# Compares two relations for equality.
-
1
def ==(other)
-
case other
-
when Associations::CollectionProxy, AssociationRelation
-
self == other.to_a
-
when Relation
-
other.to_sql == to_sql
-
when Array
-
to_a == other
-
end
-
end
-
-
1
def pretty_print(q)
-
q.pp(self.to_a)
-
end
-
-
# Returns true if relation is blank.
-
1
def blank?
-
to_a.blank?
-
end
-
-
1
def values
-
Hash[@values]
-
end
-
-
1
def inspect
-
entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect)
-
entries[10] = '...' if entries.size == 11
-
-
"#<#{self.class.name} [#{entries.join(', ')}]>"
-
end
-
-
1
private
-
-
1
def exec_queries
-
24
@records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, arel.bind_values + bind_values)
-
-
24
preload = preload_values
-
24
preload += includes_values unless eager_loading?
-
24
preloader = build_preloader
-
24
preload.each do |associations|
-
preloader.preload @records, associations
-
end
-
-
24
@records.each { |record| record.readonly! } if readonly_value
-
-
24
@loaded = true
-
24
@records
-
end
-
-
1
def build_preloader
-
24
ActiveRecord::Associations::Preloader.new
-
end
-
-
1
def references_eager_loaded_tables?
-
joined_tables = arel.join_sources.map do |join|
-
if join.is_a?(Arel::Nodes::StringJoin)
-
tables_in_string(join.left)
-
else
-
[join.left.table_name, join.left.table_alias]
-
end
-
end
-
-
joined_tables += [table.name, table.table_alias]
-
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
-
joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq
-
-
(references_values - joined_tables).any?
-
end
-
-
1
def tables_in_string(string)
-
return [] if string.blank?
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
-
# ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
-
string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Batches
-
# Looping through a collection of records from the database
-
# (using the +all+ method, for example) is very inefficient
-
# since it will try to instantiate all the objects at once.
-
#
-
# In that case, batch processing methods allow you to work
-
# with the records in batches, thereby greatly reducing memory consumption.
-
#
-
# The #find_each method uses #find_in_batches with a batch size of 1000 (or as
-
# specified by the +:batch_size+ option).
-
#
-
# Person.find_each do |person|
-
# person.do_awesome_stuff
-
# end
-
#
-
# Person.where("age > 21").find_each do |person|
-
# person.party_all_night!
-
# end
-
#
-
# If you do not provide a block to #find_each, it will return an Enumerator
-
# for chaining with other methods:
-
#
-
# Person.find_each.with_index do |person, index|
-
# person.award_trophy(index + 1)
-
# end
-
#
-
# ==== Options
-
# * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
-
# * <tt>:start</tt> - Specifies the starting point for the batch processing.
-
# This is especially useful if you want multiple workers dealing with
-
# the same processing queue. You can make worker 1 handle all the records
-
# between id 0 and 10,000 and worker 2 handle from 10,000 and beyond
-
# (by setting the +:start+ option on that worker).
-
#
-
# # Let's process for a batch of 2000 records, skipping the first 2000 rows
-
# Person.find_each(start: 2000, batch_size: 2000) do |person|
-
# person.party_all_night!
-
# end
-
#
-
# NOTE: It's not possible to set the order. That is automatically set to
-
# ascending on the primary key ("id ASC") to make the batch ordering
-
# work. This also means that this method only works with integer-based
-
# primary keys.
-
#
-
# NOTE: You can't set the limit either, that's used to control
-
# the batch sizes.
-
1
def find_each(options = {})
-
if block_given?
-
find_in_batches(options) do |records|
-
records.each { |record| yield record }
-
end
-
else
-
enum_for :find_each, options do
-
options[:start] ? where(table[primary_key].gteq(options[:start])).size : size
-
end
-
end
-
end
-
-
# Yields each batch of records that was found by the find +options+ as
-
# an array.
-
#
-
# Person.where("age > 21").find_in_batches do |group|
-
# sleep(50) # Make sure it doesn't get too crowded in there!
-
# group.each { |person| person.party_all_night! }
-
# end
-
#
-
# If you do not provide a block to #find_in_batches, it will return an Enumerator
-
# for chaining with other methods:
-
#
-
# Person.find_in_batches.with_index do |group, batch|
-
# puts "Processing group ##{batch}"
-
# group.each(&:recover_from_last_night!)
-
# end
-
#
-
# To be yielded each record one by one, use #find_each instead.
-
#
-
# ==== Options
-
# * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
-
# * <tt>:start</tt> - Specifies the starting point for the batch processing.
-
# This is especially useful if you want multiple workers dealing with
-
# the same processing queue. You can make worker 1 handle all the records
-
# between id 0 and 10,000 and worker 2 handle from 10,000 and beyond
-
# (by setting the +:start+ option on that worker).
-
#
-
# # Let's process the next 2000 records
-
# Person.find_in_batches(start: 2000, batch_size: 2000) do |group|
-
# group.each { |person| person.party_all_night! }
-
# end
-
#
-
# NOTE: It's not possible to set the order. That is automatically set to
-
# ascending on the primary key ("id ASC") to make the batch ordering
-
# work. This also means that this method only works with integer-based
-
# primary keys.
-
#
-
# NOTE: You can't set the limit either, that's used to control
-
# the batch sizes.
-
1
def find_in_batches(options = {})
-
options.assert_valid_keys(:start, :batch_size)
-
-
relation = self
-
start = options[:start]
-
batch_size = options[:batch_size] || 1000
-
-
unless block_given?
-
return to_enum(:find_in_batches, options) do
-
total = start ? where(table[primary_key].gteq(start)).size : size
-
(total - 1).div(batch_size) + 1
-
end
-
end
-
-
if logger && (arel.orders.present? || arel.taken.present?)
-
logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
-
end
-
-
relation = relation.reorder(batch_order).limit(batch_size)
-
records = start ? relation.where(table[primary_key].gteq(start)).to_a : relation.to_a
-
-
while records.any?
-
records_size = records.size
-
primary_key_offset = records.last.id
-
raise "Primary key not included in the custom select clause" unless primary_key_offset
-
-
yield records
-
-
break if records_size < batch_size
-
-
records = relation.where(table[primary_key].gt(primary_key_offset)).to_a
-
end
-
end
-
-
1
private
-
-
1
def batch_order
-
"#{quoted_table_name}.#{quoted_primary_key} ASC"
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Calculations
-
# Count the records.
-
#
-
# Person.count
-
# # => the total count of all people
-
#
-
# Person.count(:age)
-
# # => returns the total count of all people whose age is present in database
-
#
-
# Person.count(:all)
-
# # => performs a COUNT(*) (:all is an alias for '*')
-
#
-
# Person.distinct.count(:age)
-
# # => counts the number of different age values
-
#
-
# If +count+ is used with +group+, it returns a Hash whose keys represent the aggregated column,
-
# and the values are the respective amounts:
-
#
-
# Person.group(:city).count
-
# # => { 'Rome' => 5, 'Paris' => 3 }
-
#
-
# If +count+ is used with +group+ for multiple columns, it returns a Hash whose
-
# keys are an array containing the individual values of each column and the value
-
# of each key would be the +count+.
-
#
-
# Article.group(:status, :category).count
-
# # => {["draft", "business"]=>10, ["draft", "technology"]=>4,
-
# ["published", "business"]=>0, ["published", "technology"]=>2}
-
#
-
# If +count+ is used with +select+, it will count the selected columns:
-
#
-
# Person.select(:age).count
-
# # => counts the number of different age values
-
#
-
# Note: not all valid +select+ expressions are valid +count+ expressions. The specifics differ
-
# between databases. In invalid cases, an error from the database is thrown.
-
1
def count(column_name = nil, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
column_name, options = nil, column_name if column_name.is_a?(Hash)
-
calculate(:count, column_name, options)
-
end
-
-
# Calculates the average value on a given column. Returns +nil+ if there's
-
# no row. See +calculate+ for examples with options.
-
#
-
# Person.average(:age) # => 35.8
-
1
def average(column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
calculate(:average, column_name, options)
-
end
-
-
# Calculates the minimum value on a given column. The value is returned
-
# with the same data type of the column, or +nil+ if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.minimum(:age) # => 7
-
1
def minimum(column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
calculate(:minimum, column_name, options)
-
end
-
-
# Calculates the maximum value on a given column. The value is returned
-
# with the same data type of the column, or +nil+ if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.maximum(:age) # => 93
-
1
def maximum(column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
calculate(:maximum, column_name, options)
-
end
-
-
# Calculates the sum of values on a given column. The value is returned
-
# with the same data type of the column, 0 if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.sum(:age) # => 4562
-
1
def sum(*args)
-
calculate(:sum, *args)
-
end
-
-
# This calculates aggregate values in the given column. Methods for count, sum, average,
-
# minimum, and maximum have been added as shortcuts.
-
#
-
# There are two basic forms of output:
-
#
-
# * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
-
# for AVG, and the given column's type for everything else.
-
#
-
# * Grouped values: This returns an ordered hash of the values and groups them. It
-
# takes either a column name, or the name of a belongs_to association.
-
#
-
# values = Person.group('last_name').maximum(:age)
-
# puts values["Drake"]
-
# # => 43
-
#
-
# drake = Family.find_by(last_name: 'Drake')
-
# values = Person.group(:family).maximum(:age) # Person belongs_to :family
-
# puts values[drake]
-
# # => 43
-
#
-
# values.each do |family, max_age|
-
# ...
-
# end
-
#
-
# Person.calculate(:count, :all) # The same as Person.count
-
# Person.average(:age) # SELECT AVG(age) FROM people...
-
#
-
# # Selects the minimum age for any family without any minors
-
# Person.group(:last_name).having("min(age) > 17").minimum(:age)
-
#
-
# Person.sum("2 * age")
-
1
def calculate(operation, column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
if column_name.is_a?(Symbol) && attribute_alias?(column_name)
-
column_name = attribute_alias(column_name)
-
end
-
-
if has_include?(column_name)
-
construct_relation_for_association_calculations.calculate(operation, column_name, options)
-
else
-
perform_calculation(operation, column_name, options)
-
end
-
end
-
-
# Use <tt>pluck</tt> as a shortcut to select one or more attributes without
-
# loading a bunch of records just to grab the attributes you want.
-
#
-
# Person.pluck(:name)
-
#
-
# instead of
-
#
-
# Person.all.map(&:name)
-
#
-
# Pluck returns an <tt>Array</tt> of attribute values type-casted to match
-
# the plucked column names, if they can be deduced. Plucking an SQL fragment
-
# returns String values by default.
-
#
-
# Person.pluck(:id)
-
# # SELECT people.id FROM people
-
# # => [1, 2, 3]
-
#
-
# Person.pluck(:id, :name)
-
# # SELECT people.id, people.name FROM people
-
# # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
-
#
-
# Person.pluck('DISTINCT role')
-
# # SELECT DISTINCT role FROM people
-
# # => ['admin', 'member', 'guest']
-
#
-
# Person.where(age: 21).limit(5).pluck(:id)
-
# # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
-
# # => [2, 3]
-
#
-
# Person.pluck('DATEDIFF(updated_at, created_at)')
-
# # SELECT DATEDIFF(updated_at, created_at) FROM people
-
# # => ['0', '27761', '173']
-
#
-
1
def pluck(*column_names)
-
column_names.map! do |column_name|
-
if column_name.is_a?(Symbol) && attribute_alias?(column_name)
-
attribute_alias(column_name)
-
else
-
column_name.to_s
-
end
-
end
-
-
if has_include?(column_names.first)
-
construct_relation_for_association_calculations.pluck(*column_names)
-
else
-
relation = spawn
-
relation.select_values = column_names.map { |cn|
-
columns_hash.key?(cn) ? arel_table[cn] : cn
-
}
-
result = klass.connection.select_all(relation.arel, nil, relation.arel.bind_values + bind_values)
-
result.cast_values(klass.column_types)
-
end
-
end
-
-
# Pluck all the ID's for the relation using the table's primary key
-
#
-
# Person.ids # SELECT people.id FROM people
-
# Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.person_id = people.id
-
1
def ids
-
pluck primary_key
-
end
-
-
1
private
-
-
1
def has_include?(column_name)
-
eager_loading? || (includes_values.present? && ((column_name && column_name != :all) || references_eager_loaded_tables?))
-
end
-
-
1
def perform_calculation(operation, column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
operation = operation.to_s.downcase
-
-
# If #count is used with #distinct / #uniq it is considered distinct. (eg. relation.distinct.count)
-
distinct = self.distinct_value
-
-
if operation == "count"
-
column_name ||= select_for_count
-
-
unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
-
distinct = true
-
end
-
-
column_name = primary_key if column_name == :all && distinct
-
distinct = nil if column_name =~ /\s*DISTINCT[\s(]+/i
-
end
-
-
if group_values.any?
-
execute_grouped_calculation(operation, column_name, distinct)
-
else
-
execute_simple_calculation(operation, column_name, distinct)
-
end
-
end
-
-
1
def aggregate_column(column_name)
-
if @klass.column_names.include?(column_name.to_s)
-
Arel::Attribute.new(@klass.unscoped.table, column_name)
-
else
-
Arel.sql(column_name == :all ? "*" : column_name.to_s)
-
end
-
end
-
-
1
def operation_over_aggregate_column(column, operation, distinct)
-
operation == 'count' ? column.count(distinct) : column.send(operation)
-
end
-
-
1
def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
-
# Postgresql doesn't like ORDER BY when there are no GROUP BY
-
relation = unscope(:order)
-
-
column_alias = column_name
-
-
bind_values = nil
-
-
if operation == "count" && (relation.limit_value || relation.offset_value)
-
# Shortcut when limit is zero.
-
return 0 if relation.limit_value == 0
-
-
query_builder = build_count_subquery(relation, column_name, distinct)
-
bind_values = query_builder.bind_values + relation.bind_values
-
else
-
column = aggregate_column(column_name)
-
-
select_value = operation_over_aggregate_column(column, operation, distinct)
-
-
column_alias = select_value.alias
-
column_alias ||= @klass.connection.column_name_for_operation(operation, select_value)
-
relation.select_values = [select_value]
-
-
query_builder = relation.arel
-
bind_values = query_builder.bind_values + relation.bind_values
-
end
-
-
result = @klass.connection.select_all(query_builder, nil, bind_values)
-
row = result.first
-
value = row && row.values.first
-
column = result.column_types.fetch(column_alias) do
-
type_for(column_name)
-
end
-
-
type_cast_calculated_value(value, column, operation)
-
end
-
-
1
def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
-
group_attrs = group_values
-
-
if group_attrs.first.respond_to?(:to_sym)
-
association = @klass._reflect_on_association(group_attrs.first)
-
associated = group_attrs.size == 1 && association && association.belongs_to? # only count belongs_to associations
-
group_fields = Array(associated ? association.foreign_key : group_attrs)
-
else
-
group_fields = group_attrs
-
end
-
-
group_aliases = group_fields.map { |field|
-
column_alias_for(field)
-
}
-
group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
-
[aliaz, field]
-
}
-
-
group = group_fields
-
-
if operation == 'count' && column_name == :all
-
aggregate_alias = 'count_all'
-
else
-
aggregate_alias = column_alias_for([operation, column_name].join(' '))
-
end
-
-
select_values = [
-
operation_over_aggregate_column(
-
aggregate_column(column_name),
-
operation,
-
distinct).as(aggregate_alias)
-
]
-
select_values += select_values unless having_values.empty?
-
-
select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
-
if field.respond_to?(:as)
-
field.as(aliaz)
-
else
-
"#{field} AS #{aliaz}"
-
end
-
}
-
-
relation = except(:group)
-
relation.group_values = group
-
relation.select_values = select_values
-
-
calculated_data = @klass.connection.select_all(relation, nil, relation.arel.bind_values + bind_values)
-
-
if association
-
key_ids = calculated_data.collect { |row| row[group_aliases.first] }
-
key_records = association.klass.base_class.find(key_ids)
-
key_records = Hash[key_records.map { |r| [r.id, r] }]
-
end
-
-
Hash[calculated_data.map do |row|
-
key = group_columns.map { |aliaz, col_name|
-
column = calculated_data.column_types.fetch(aliaz) do
-
type_for(col_name)
-
end
-
type_cast_calculated_value(row[aliaz], column)
-
}
-
key = key.first if key.size == 1
-
key = key_records[key] if associated
-
-
column_type = calculated_data.column_types.fetch(aggregate_alias) { type_for(column_name) }
-
[key, type_cast_calculated_value(row[aggregate_alias], column_type, operation)]
-
end]
-
end
-
-
# Converts the given keys to the value that the database adapter returns as
-
# a usable column name:
-
#
-
# column_alias_for("users.id") # => "users_id"
-
# column_alias_for("sum(id)") # => "sum_id"
-
# column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
-
# column_alias_for("count(*)") # => "count_all"
-
# column_alias_for("count", "id") # => "count_id"
-
1
def column_alias_for(keys)
-
if keys.respond_to? :name
-
keys = "#{keys.relation.name}.#{keys.name}"
-
end
-
-
table_name = keys.to_s.downcase
-
table_name.gsub!(/\*/, 'all')
-
table_name.gsub!(/\W+/, ' ')
-
table_name.strip!
-
table_name.gsub!(/ +/, '_')
-
-
@klass.connection.table_alias_for(table_name)
-
end
-
-
1
def type_for(field)
-
field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
-
@klass.type_for_attribute(field_name)
-
end
-
-
1
def type_cast_calculated_value(value, type, operation = nil)
-
case operation
-
when 'count' then value.to_i
-
when 'sum' then type.type_cast_from_database(value || 0)
-
when 'average' then value.respond_to?(:to_d) ? value.to_d : value
-
else type.type_cast_from_database(value)
-
end
-
end
-
-
# TODO: refactor to allow non-string `select_values` (eg. Arel nodes).
-
1
def select_for_count
-
if select_values.present?
-
select_values.join(", ")
-
else
-
:all
-
end
-
end
-
-
1
def build_count_subquery(relation, column_name, distinct)
-
column_alias = Arel.sql('count_column')
-
subquery_alias = Arel.sql('subquery_for_count')
-
-
aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias)
-
relation.select_values = [aliased_column]
-
arel = relation.arel
-
subquery = arel.as(subquery_alias)
-
-
sm = Arel::SelectManager.new relation.engine
-
sm.bind_values = arel.bind_values
-
select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
-
sm.project(select_value).from(subquery)
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'active_support/concern'
-
1
require 'active_support/deprecation'
-
-
1
module ActiveRecord
-
1
module Delegation # :nodoc:
-
1
module DelegateCache
-
1
def relation_delegate_class(klass) # :nodoc:
-
96
@relation_delegate_cache[klass]
-
end
-
-
1
def initialize_relation_delegate_cache # :nodoc:
-
5
@relation_delegate_cache = cache = {}
-
[
-
ActiveRecord::Relation,
-
ActiveRecord::Associations::CollectionProxy,
-
ActiveRecord::AssociationRelation
-
5
].each do |klass|
-
15
delegate = Class.new(klass) {
-
15
include ClassSpecificRelation
-
}
-
15
const_set klass.name.gsub('::', '_'), delegate
-
15
cache[klass] = delegate
-
end
-
end
-
-
1
def inherited(child_class)
-
5
child_class.initialize_relation_delegate_cache
-
5
super
-
end
-
end
-
-
1
extend ActiveSupport::Concern
-
-
# This module creates compiled delegation methods dynamically at runtime, which makes
-
# subsequent calls to that method faster by avoiding method_missing. The delegations
-
# may vary depending on the klass of a relation, so we create a subclass of Relation
-
# for each different klass, and the delegations are compiled into that subclass only.
-
-
1
BLACKLISTED_ARRAY_METHODS = [
-
:compact!, :flatten!, :reject!, :reverse!, :rotate!, :map!,
-
:shuffle!, :slice!, :sort!, :sort_by!, :delete_if,
-
:keep_if, :pop, :shift, :delete_at, :select!
-
].to_set # :nodoc:
-
-
1
delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :join, to: :to_a
-
-
1
delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key,
-
:connection, :columns_hash, :to => :klass
-
-
1
module ClassSpecificRelation # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
15
@delegation_mutex = Mutex.new
-
end
-
-
1
module ClassMethods # :nodoc:
-
1
def name
-
superclass.name
-
end
-
-
1
def delegate_to_scoped_klass(method)
-
@delegation_mutex.synchronize do
-
return if method_defined?(method)
-
-
if method.to_s =~ /\A[a-zA-Z_]\w*[!?]?\z/
-
module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{method}(*args, &block)
-
scoping { @klass.#{method}(*args, &block) }
-
end
-
RUBY
-
else
-
define_method method do |*args, &block|
-
scoping { @klass.public_send(method, *args, &block) }
-
end
-
end
-
end
-
end
-
-
1
def delegate(method, opts = {})
-
@delegation_mutex.synchronize do
-
return if method_defined?(method)
-
super
-
end
-
end
-
end
-
-
1
protected
-
-
1
def method_missing(method, *args, &block)
-
if @klass.respond_to?(method)
-
self.class.delegate_to_scoped_klass(method)
-
scoping { @klass.public_send(method, *args, &block) }
-
elsif arel.respond_to?(method)
-
self.class.delegate method, :to => :arel
-
arel.public_send(method, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
-
1
module ClassMethods # :nodoc:
-
1
def create(klass, *args)
-
96
relation_class_for(klass).new(klass, *args)
-
end
-
-
1
private
-
-
1
def relation_class_for(klass)
-
96
klass.relation_delegate_class(self)
-
end
-
end
-
-
1
def respond_to?(method, include_private = false)
-
super || @klass.respond_to?(method, include_private) ||
-
array_delegable?(method) ||
-
arel.respond_to?(method, include_private)
-
end
-
-
1
protected
-
-
1
def array_delegable?(method)
-
Array.method_defined?(method) && BLACKLISTED_ARRAY_METHODS.exclude?(method)
-
end
-
-
1
def method_missing(method, *args, &block)
-
if @klass.respond_to?(method)
-
scoping { @klass.public_send(method, *args, &block) }
-
elsif array_delegable?(method)
-
to_a.public_send(method, *args, &block)
-
elsif arel.respond_to?(method)
-
arel.public_send(method, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
1
require 'active_support/deprecation'
-
1
require 'active_support/core_ext/string/filters'
-
-
1
module ActiveRecord
-
1
module FinderMethods
-
1
ONE_AS_ONE = '1 AS one'
-
-
# Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
-
# If no record can be found for all of the listed ids, then RecordNotFound will be raised. If the primary key
-
# is an integer, find by id coerces its arguments using +to_i+.
-
#
-
# Person.find(1) # returns the object for ID = 1
-
# Person.find("1") # returns the object for ID = 1
-
# Person.find("31-sarah") # returns the object for ID = 31
-
# Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
-
# Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
-
# Person.find([1]) # returns an array for the object with ID = 1
-
# Person.where("administrator = 1").order("created_on DESC").find(1)
-
#
-
# <tt>ActiveRecord::RecordNotFound</tt> will be raised if one or more ids are not found.
-
#
-
# NOTE: The returned records may not be in the same order as the ids you
-
# provide since database rows are unordered. You'd need to provide an explicit <tt>order</tt>
-
# option if you want the results are sorted.
-
#
-
# ==== Find with lock
-
#
-
# Example for find with a lock: Imagine two concurrent transactions:
-
# each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
-
# in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
-
# transaction has to wait until the first is finished; we get the
-
# expected <tt>person.visits == 4</tt>.
-
#
-
# Person.transaction do
-
# person = Person.lock(true).find(1)
-
# person.visits += 1
-
# person.save!
-
# end
-
#
-
# ==== Variations of +find+
-
#
-
# Person.where(name: 'Spartacus', rating: 4)
-
# # returns a chainable list (which can be empty).
-
#
-
# Person.find_by(name: 'Spartacus', rating: 4)
-
# # returns the first item or nil.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).first_or_initialize
-
# # returns the first item or returns a new instance (requires you call .save to persist against the database).
-
#
-
# Person.where(name: 'Spartacus', rating: 4).first_or_create
-
# # returns the first item or creates it and returns it, available since Rails 3.2.1.
-
#
-
# ==== Alternatives for +find+
-
#
-
# Person.where(name: 'Spartacus', rating: 4).exists?(conditions = :none)
-
# # returns a boolean indicating if any record with the given conditions exist.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).select("field1, field2, field3")
-
# # returns a chainable list of instances with only the mentioned fields.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).ids
-
# # returns an Array of ids, available since Rails 3.2.1.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2)
-
# # returns an Array of the required fields, available since Rails 3.1.
-
1
def find(*args)
-
if block_given?
-
to_a.find(*args) { |*block_args| yield(*block_args) }
-
else
-
find_with_ids(*args)
-
end
-
end
-
-
# Finds the first record matching the specified conditions. There
-
# is no implied ordering so if order matters, you should specify it
-
# yourself.
-
#
-
# If no record is found, returns <tt>nil</tt>.
-
#
-
# Post.find_by name: 'Spartacus', rating: 4
-
# Post.find_by "published_at < ?", 2.weeks.ago
-
1
def find_by(*args)
-
where(*args).take
-
rescue RangeError
-
nil
-
end
-
-
# Like <tt>find_by</tt>, except that if no record is found, raises
-
# an <tt>ActiveRecord::RecordNotFound</tt> error.
-
1
def find_by!(*args)
-
where(*args).take!
-
rescue RangeError
-
raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range value"
-
end
-
-
# Gives a record (or N records if a parameter is supplied) without any implied
-
# order. The order will depend on the database implementation.
-
# If an order is supplied it will be respected.
-
#
-
# Person.take # returns an object fetched by SELECT * FROM people LIMIT 1
-
# Person.take(5) # returns 5 objects fetched by SELECT * FROM people LIMIT 5
-
# Person.where(["name LIKE '%?'", name]).take
-
1
def take(limit = nil)
-
limit ? limit(limit).to_a : find_take
-
end
-
-
# Same as +take+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>take!</tt> accepts no arguments.
-
1
def take!
-
take or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]")
-
end
-
-
# Find the first record (or first N records if a parameter is supplied).
-
# If no order is defined it will order by primary key.
-
#
-
# Person.first # returns the first object fetched by SELECT * FROM people ORDER BY people.id LIMIT 1
-
# Person.where(["user_name = ?", user_name]).first
-
# Person.where(["user_name = :u", { u: user_name }]).first
-
# Person.order("created_on DESC").offset(5).first
-
# Person.first(3) # returns the first three objects fetched by SELECT * FROM people ORDER BY people.id LIMIT 3
-
#
-
1
def first(limit = nil)
-
if limit
-
find_nth_with_limit(offset_index, limit)
-
else
-
find_nth(0, offset_index)
-
end
-
end
-
-
# Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>first!</tt> accepts no arguments.
-
1
def first!
-
find_nth! 0
-
end
-
-
# Find the last record (or last N records if a parameter is supplied).
-
# If no order is defined it will order by primary key.
-
#
-
# Person.last # returns the last object fetched by SELECT * FROM people
-
# Person.where(["user_name = ?", user_name]).last
-
# Person.order("created_on DESC").offset(5).last
-
# Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
-
#
-
# Take note that in that last case, the results are sorted in ascending order:
-
#
-
# [#<Person id:2>, #<Person id:3>, #<Person id:4>]
-
#
-
# and not:
-
#
-
# [#<Person id:4>, #<Person id:3>, #<Person id:2>]
-
1
def last(limit = nil)
-
if limit
-
if order_values.empty? && primary_key
-
order(arel_table[primary_key].desc).limit(limit).reverse
-
else
-
to_a.last(limit)
-
end
-
else
-
find_last
-
end
-
end
-
-
# Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>last!</tt> accepts no arguments.
-
1
def last!
-
last or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]")
-
end
-
-
# Find the second record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.second # returns the second object fetched by SELECT * FROM people
-
# Person.offset(3).second # returns the second object from OFFSET 3 (which is OFFSET 4)
-
# Person.where(["user_name = :u", { u: user_name }]).second
-
1
def second
-
find_nth(1, offset_index)
-
end
-
-
# Same as +second+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
1
def second!
-
find_nth! 1
-
end
-
-
# Find the third record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.third # returns the third object fetched by SELECT * FROM people
-
# Person.offset(3).third # returns the third object from OFFSET 3 (which is OFFSET 5)
-
# Person.where(["user_name = :u", { u: user_name }]).third
-
1
def third
-
find_nth(2, offset_index)
-
end
-
-
# Same as +third+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
1
def third!
-
find_nth! 2
-
end
-
-
# Find the fourth record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.fourth # returns the fourth object fetched by SELECT * FROM people
-
# Person.offset(3).fourth # returns the fourth object from OFFSET 3 (which is OFFSET 6)
-
# Person.where(["user_name = :u", { u: user_name }]).fourth
-
1
def fourth
-
find_nth(3, offset_index)
-
end
-
-
# Same as +fourth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
1
def fourth!
-
find_nth! 3
-
end
-
-
# Find the fifth record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.fifth # returns the fifth object fetched by SELECT * FROM people
-
# Person.offset(3).fifth # returns the fifth object from OFFSET 3 (which is OFFSET 7)
-
# Person.where(["user_name = :u", { u: user_name }]).fifth
-
1
def fifth
-
find_nth(4, offset_index)
-
end
-
-
# Same as +fifth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
1
def fifth!
-
find_nth! 4
-
end
-
-
# Find the forty-second record. Also known as accessing "the reddit".
-
# If no order is defined it will order by primary key.
-
#
-
# Person.forty_two # returns the forty-second object fetched by SELECT * FROM people
-
# Person.offset(3).forty_two # returns the forty-second object from OFFSET 3 (which is OFFSET 44)
-
# Person.where(["user_name = :u", { u: user_name }]).forty_two
-
1
def forty_two
-
find_nth(41, offset_index)
-
end
-
-
# Same as +forty_two+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
1
def forty_two!
-
find_nth! 41
-
end
-
-
# Returns +true+ if a record exists in the table that matches the +id+ or
-
# conditions given, or +false+ otherwise. The argument can take six forms:
-
#
-
# * Integer - Finds the record with this primary key.
-
# * String - Finds the record with a primary key corresponding to this
-
# string (such as <tt>'5'</tt>).
-
# * Array - Finds the record that matches these +find+-style conditions
-
# (such as <tt>['name LIKE ?', "%#{query}%"]</tt>).
-
# * Hash - Finds the record that matches these +find+-style conditions
-
# (such as <tt>{name: 'David'}</tt>).
-
# * +false+ - Returns always +false+.
-
# * No args - Returns +false+ if the table is empty, +true+ otherwise.
-
#
-
# For more information about specifying conditions as a hash or array,
-
# see the Conditions section in the introduction to <tt>ActiveRecord::Base</tt>.
-
#
-
# Note: You can't pass in a condition as a string (like <tt>name =
-
# 'Jamie'</tt>), since it would be sanitized and then queried against
-
# the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
-
#
-
# Person.exists?(5)
-
# Person.exists?('5')
-
# Person.exists?(['name LIKE ?', "%#{query}%"])
-
# Person.exists?(id: [1, 4, 8])
-
# Person.exists?(name: 'David')
-
# Person.exists?(false)
-
# Person.exists?
-
1
def exists?(conditions = :none)
-
if Base === conditions
-
conditions = conditions.id
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
You are passing an instance of ActiveRecord::Base to `exists?`.
-
Please pass the id of the object by calling `.id`
-
MSG
-
end
-
-
return false if !conditions
-
-
relation = apply_join_dependency(self, construct_join_dependency)
-
return false if ActiveRecord::NullRelation === relation
-
-
relation = relation.except(:select, :order).select(ONE_AS_ONE).limit(1)
-
-
case conditions
-
when Array, Hash
-
relation = relation.where(conditions)
-
else
-
unless conditions == :none
-
relation = relation.where(primary_key => conditions)
-
end
-
end
-
-
connection.select_value(relation, "#{name} Exists", relation.arel.bind_values + relation.bind_values) ? true : false
-
end
-
-
# This method is called whenever no records are found with either a single
-
# id or multiple ids and raises a +ActiveRecord::RecordNotFound+ exception.
-
#
-
# The error message is different depending on whether a single id or
-
# multiple ids are provided. If multiple ids are provided, then the number
-
# of results obtained should be provided in the +result_size+ argument and
-
# the expected number of results should be provided in the +expected_size+
-
# argument.
-
1
def raise_record_not_found_exception!(ids, result_size, expected_size) #:nodoc:
-
conditions = arel.where_sql
-
conditions = " [#{conditions}]" if conditions
-
-
if Array(ids).size == 1
-
error = "Couldn't find #{@klass.name} with '#{primary_key}'=#{ids}#{conditions}"
-
else
-
error = "Couldn't find all #{@klass.name.pluralize} with '#{primary_key}': "
-
error << "(#{ids.join(", ")})#{conditions} (found #{result_size} results, but was looking for #{expected_size})"
-
end
-
-
raise RecordNotFound, error
-
end
-
-
1
private
-
-
1
def offset_index
-
offset_value || 0
-
end
-
-
1
def find_with_associations
-
# NOTE: the JoinDependency constructed here needs to know about
-
# any joins already present in `self`, so pass them in
-
#
-
# failing to do so means that in cases like activerecord/test/cases/associations/inner_join_association_test.rb:136
-
# incorrect SQL is generated. In that case, the join dependency for
-
# SpecialCategorizations is constructed without knowledge of the
-
# preexisting join in joins_values to categorizations (by way of
-
# the `has_many :through` for categories).
-
#
-
join_dependency = construct_join_dependency(joins_values)
-
-
aliases = join_dependency.aliases
-
relation = select aliases.columns
-
relation = apply_join_dependency(relation, join_dependency)
-
-
if block_given?
-
yield relation
-
else
-
if ActiveRecord::NullRelation === relation
-
[]
-
else
-
arel = relation.arel
-
rows = connection.select_all(arel, 'SQL', arel.bind_values + relation.bind_values)
-
join_dependency.instantiate(rows, aliases)
-
end
-
end
-
end
-
-
1
def construct_join_dependency(joins = [])
-
including = eager_load_values + includes_values
-
ActiveRecord::Associations::JoinDependency.new(@klass, including, joins)
-
end
-
-
1
def construct_relation_for_association_calculations
-
from = arel.froms.first
-
if Arel::Table === from
-
apply_join_dependency(self, construct_join_dependency(joins_values))
-
else
-
# FIXME: as far as I can tell, `from` will always be an Arel::Table.
-
# There are no tests that test this branch, but presumably it's
-
# possible for `from` to be a list?
-
apply_join_dependency(self, construct_join_dependency(from))
-
end
-
end
-
-
1
def apply_join_dependency(relation, join_dependency)
-
relation = relation.except(:includes, :eager_load, :preload)
-
relation = relation.joins join_dependency
-
-
if using_limitable_reflections?(join_dependency.reflections)
-
relation
-
else
-
if relation.limit_value
-
limited_ids = limited_ids_for(relation)
-
limited_ids.empty? ? relation.none! : relation.where!(table[primary_key].in(limited_ids))
-
end
-
relation.except(:limit, :offset)
-
end
-
end
-
-
1
def limited_ids_for(relation)
-
values = @klass.connection.columns_for_distinct(
-
"#{quoted_table_name}.#{quoted_primary_key}", relation.order_values)
-
-
relation = relation.except(:select).select(values).distinct!
-
arel = relation.arel
-
-
id_rows = @klass.connection.select_all(arel, 'SQL', arel.bind_values + relation.bind_values)
-
id_rows.map {|row| row[primary_key]}
-
end
-
-
1
def using_limitable_reflections?(reflections)
-
reflections.none? { |r| r.collection? }
-
end
-
-
1
protected
-
-
1
def find_with_ids(*ids)
-
raise UnknownPrimaryKey.new(@klass) if primary_key.nil?
-
-
expects_array = ids.first.kind_of?(Array)
-
return ids.first if expects_array && ids.first.empty?
-
-
ids = ids.flatten.compact.uniq
-
-
case ids.size
-
when 0
-
raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
-
when 1
-
result = find_one(ids.first)
-
expects_array ? [ result ] : result
-
else
-
find_some(ids)
-
end
-
rescue RangeError
-
raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range ID"
-
end
-
-
1
def find_one(id)
-
if ActiveRecord::Base === id
-
id = id.id
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
You are passing an instance of ActiveRecord::Base to `find`.
-
Please pass the id of the object by calling `.id`
-
MSG
-
end
-
-
relation = where(primary_key => id)
-
record = relation.take
-
-
raise_record_not_found_exception!(id, 0, 1) unless record
-
-
record
-
end
-
-
1
def find_some(ids)
-
result = where(primary_key => ids).to_a
-
-
expected_size =
-
if limit_value && ids.size > limit_value
-
limit_value
-
else
-
ids.size
-
end
-
-
# 11 ids with limit 3, offset 9 should give 2 results.
-
if offset_value && (ids.size - offset_value < expected_size)
-
expected_size = ids.size - offset_value
-
end
-
-
if result.size == expected_size
-
result
-
else
-
raise_record_not_found_exception!(ids, result.size, expected_size)
-
end
-
end
-
-
1
def find_take
-
if loaded?
-
@records.first
-
else
-
@take ||= limit(1).to_a.first
-
end
-
end
-
-
1
def find_nth(index, offset)
-
if loaded?
-
@records[index]
-
else
-
offset += index
-
@offsets[offset] ||= find_nth_with_limit(offset, 1).first
-
end
-
end
-
-
1
def find_nth!(index)
-
find_nth(index, offset_index) or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]")
-
end
-
-
1
def find_nth_with_limit(offset, limit)
-
relation = if order_values.empty? && primary_key
-
order(arel_table[primary_key].asc)
-
else
-
self
-
end
-
-
relation = relation.offset(offset) unless offset.zero?
-
relation.limit(limit).to_a
-
end
-
-
1
def find_last
-
if loaded?
-
@records.last
-
else
-
@last ||=
-
if limit_value
-
to_a.last
-
else
-
reverse_order.limit(1).to_a.first
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require "set"
-
-
1
module ActiveRecord
-
1
class Relation
-
1
class HashMerger # :nodoc:
-
1
attr_reader :relation, :hash
-
-
1
def initialize(relation, hash)
-
hash.assert_valid_keys(*Relation::VALUE_METHODS)
-
-
@relation = relation
-
@hash = hash
-
end
-
-
1
def merge #:nodoc:
-
Merger.new(relation, other).merge
-
end
-
-
# Applying values to a relation has some side effects. E.g.
-
# interpolation might take place for where values. So we should
-
# build a relation to merge in rather than directly merging
-
# the values.
-
1
def other
-
other = Relation.create(relation.klass, relation.table)
-
hash.each { |k, v|
-
if k == :joins
-
if Hash === v
-
other.joins!(v)
-
else
-
other.joins!(*v)
-
end
-
elsif k == :select
-
other._select!(v)
-
else
-
other.send("#{k}!", v)
-
end
-
}
-
other
-
end
-
end
-
-
1
class Merger # :nodoc:
-
1
attr_reader :relation, :values, :other
-
-
1
def initialize(relation, other)
-
@relation = relation
-
@values = other.values
-
@other = other
-
end
-
-
1
NORMAL_VALUES = Relation::SINGLE_VALUE_METHODS +
-
Relation::MULTI_VALUE_METHODS -
-
[:includes, :preload, :joins, :where, :order, :bind, :reverse_order, :lock, :create_with, :reordering, :from] # :nodoc:
-
-
-
1
def normal_values
-
NORMAL_VALUES
-
end
-
-
1
def merge
-
normal_values.each do |name|
-
value = values[name]
-
# The unless clause is here mostly for performance reasons (since the `send` call might be moderately
-
# expensive), most of the time the value is going to be `nil` or `.blank?`, the only catch is that
-
# `false.blank?` returns `true`, so there needs to be an extra check so that explicit `false` values
-
# don't fall through the cracks.
-
unless value.nil? || (value.blank? && false != value)
-
if name == :select
-
relation._select!(*value)
-
else
-
relation.send("#{name}!", *value)
-
end
-
end
-
end
-
-
merge_multi_values
-
merge_single_values
-
merge_preloads
-
merge_joins
-
-
relation
-
end
-
-
1
private
-
-
1
def merge_preloads
-
return if other.preload_values.empty? && other.includes_values.empty?
-
-
if other.klass == relation.klass
-
relation.preload!(*other.preload_values) unless other.preload_values.empty?
-
relation.includes!(other.includes_values) unless other.includes_values.empty?
-
else
-
reflection = relation.klass.reflect_on_all_associations.find do |r|
-
r.class_name == other.klass.name
-
end || return
-
-
unless other.preload_values.empty?
-
relation.preload! reflection.name => other.preload_values
-
end
-
-
unless other.includes_values.empty?
-
relation.includes! reflection.name => other.includes_values
-
end
-
end
-
end
-
-
1
def merge_joins
-
return if other.joins_values.blank?
-
-
if other.klass == relation.klass
-
relation.joins!(*other.joins_values)
-
else
-
joins_dependency, rest = other.joins_values.partition do |join|
-
case join
-
when Hash, Symbol, Array
-
true
-
else
-
false
-
end
-
end
-
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(other.klass,
-
joins_dependency,
-
[])
-
relation.joins! rest
-
-
@relation = relation.joins join_dependency
-
end
-
end
-
-
1
def merge_multi_values
-
lhs_wheres = relation.where_values
-
rhs_wheres = other.where_values
-
-
lhs_binds = relation.bind_values
-
rhs_binds = other.bind_values
-
-
removed, kept = partition_overwrites(lhs_wheres, rhs_wheres)
-
-
where_values = kept + rhs_wheres
-
bind_values = filter_binds(lhs_binds, removed) + rhs_binds
-
-
relation.where_values = where_values
-
relation.bind_values = bind_values
-
-
if other.reordering_value
-
# override any order specified in the original relation
-
relation.reorder! other.order_values
-
elsif other.order_values
-
# merge in order_values from relation
-
relation.order! other.order_values
-
end
-
-
relation.extend(*other.extending_values) unless other.extending_values.blank?
-
end
-
-
1
def merge_single_values
-
relation.from_value = other.from_value unless relation.from_value
-
relation.lock_value = other.lock_value unless relation.lock_value
-
-
unless other.create_with_value.blank?
-
relation.create_with_value = (relation.create_with_value || {}).merge(other.create_with_value)
-
end
-
end
-
-
1
def filter_binds(lhs_binds, removed_wheres)
-
return lhs_binds if removed_wheres.empty?
-
-
set = Set.new removed_wheres.map { |x| x.left.name.to_s }
-
lhs_binds.dup.delete_if { |col,_| set.include? col.name }
-
end
-
-
# Remove equalities from the existing relation with a LHS which is
-
# present in the relation being merged in.
-
# returns [things_to_remove, things_to_keep]
-
1
def partition_overwrites(lhs_wheres, rhs_wheres)
-
if lhs_wheres.empty? || rhs_wheres.empty?
-
return [[], lhs_wheres]
-
end
-
-
nodes = rhs_wheres.find_all do |w|
-
w.respond_to?(:operator) && w.operator == :==
-
end
-
seen = Set.new(nodes) { |node| node.left }
-
-
lhs_wheres.partition do |w|
-
w.respond_to?(:operator) && w.operator == :== && seen.include?(w.left)
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class PredicateBuilder # :nodoc:
-
1
@handlers = []
-
-
1
autoload :RelationHandler, 'active_record/relation/predicate_builder/relation_handler'
-
1
autoload :ArrayHandler, 'active_record/relation/predicate_builder/array_handler'
-
-
1
def self.resolve_column_aliases(klass, hash)
-
# This method is a hot spot, so for now, use Hash[] to dup the hash.
-
# https://bugs.ruby-lang.org/issues/7166
-
8
hash = Hash[hash]
-
8
hash.keys.grep(Symbol) do |key|
-
if klass.attribute_alias? key
-
hash[klass.attribute_alias(key)] = hash.delete key
-
end
-
end
-
8
hash
-
end
-
-
1
def self.build_from_hash(klass, attributes, default_table)
-
8
queries = []
-
-
8
attributes.each do |column, value|
-
8
table = default_table
-
-
8
if value.is_a?(Hash)
-
if value.empty?
-
queries << '1=0'
-
else
-
table = Arel::Table.new(column, default_table.engine)
-
association = klass._reflect_on_association(column)
-
-
value.each do |k, v|
-
queries.concat expand(association && association.klass, table, k, v)
-
end
-
end
-
else
-
8
column = column.to_s
-
-
8
if column.include?('.')
-
table_name, column = column.split('.', 2)
-
table = Arel::Table.new(table_name, default_table.engine)
-
end
-
-
8
queries.concat expand(klass, table, column, value)
-
end
-
end
-
-
8
queries
-
end
-
-
1
def self.expand(klass, table, column, value)
-
8
queries = []
-
-
# Find the foreign key when using queries such as:
-
# Post.where(author: author)
-
#
-
# For polymorphic relationships, find the foreign key and type:
-
# PriceEstimate.where(estimate_of: treasure)
-
8
if klass && reflection = klass._reflect_on_association(column)
-
base_class = polymorphic_base_class_from_value(value)
-
-
if reflection.polymorphic? && base_class
-
queries << build(table[reflection.foreign_type], base_class)
-
end
-
-
column = reflection.foreign_key
-
-
if base_class
-
primary_key = reflection.association_primary_key(base_class)
-
value = convert_value_to_association_ids(value, primary_key)
-
end
-
end
-
-
8
queries << build(table[column], value)
-
8
queries
-
end
-
-
1
def self.polymorphic_base_class_from_value(value)
-
case value
-
when Relation
-
value.klass.base_class
-
when Array
-
val = value.compact.first
-
val.class.base_class if val.is_a?(Base)
-
when Base
-
value.class.base_class
-
end
-
end
-
-
1
def self.references(attributes)
-
attributes.map do |key, value|
-
8
if value.is_a?(Hash)
-
key
-
else
-
8
key = key.to_s
-
8
key.split('.').first if key.include?('.')
-
end
-
8
end.compact
-
end
-
-
# Define how a class is converted to Arel nodes when passed to +where+.
-
# The handler can be any object that responds to +call+, and will be used
-
# for any value that +===+ the class given. For example:
-
#
-
# MyCustomDateRange = Struct.new(:start, :end)
-
# handler = proc do |column, range|
-
# Arel::Nodes::Between.new(column,
-
# Arel::Nodes::And.new([range.start, range.end])
-
# )
-
# end
-
# ActiveRecord::PredicateBuilder.register_handler(MyCustomDateRange, handler)
-
1
def self.register_handler(klass, handler)
-
6
@handlers.unshift([klass, handler])
-
end
-
-
9
BASIC_OBJECT_HANDLER = ->(attribute, value) { attribute.eq(value) } # :nodoc:
-
1
register_handler(BasicObject, BASIC_OBJECT_HANDLER)
-
# FIXME: I think we need to deprecate this behavior
-
1
register_handler(Class, ->(attribute, value) { attribute.eq(value.name) })
-
1
register_handler(Base, ->(attribute, value) { attribute.eq(value.id) })
-
1
register_handler(Range, ->(attribute, value) { attribute.between(value) })
-
1
register_handler(Relation, RelationHandler.new)
-
1
register_handler(Array, ArrayHandler.new)
-
-
1
def self.build(attribute, value)
-
8
handler_for(value).call(attribute, value)
-
end
-
1
private_class_method :build
-
-
1
def self.handler_for(object)
-
112
@handlers.detect { |klass, _| klass === object }.last
-
end
-
1
private_class_method :handler_for
-
-
1
def self.convert_value_to_association_ids(value, primary_key)
-
case value
-
when Relation
-
value.select(primary_key)
-
when Array
-
value.map { |v| convert_value_to_association_ids(v, primary_key) }
-
when Base
-
value._read_attribute(primary_key)
-
else
-
value
-
end
-
end
-
-
1
def self.can_be_bound?(value) # :nodoc:
-
!value.nil? &&
-
8
!value.is_a?(Hash) &&
-
handler_for(value) == BASIC_OBJECT_HANDLER
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/filters'
-
-
1
module ActiveRecord
-
1
class PredicateBuilder
-
1
class ArrayHandler # :nodoc:
-
1
def call(attribute, value)
-
values = value.map { |x| x.is_a?(Base) ? x.id : x }
-
nils, values = values.partition(&:nil?)
-
-
if values.any? { |val| val.is_a?(Array) }
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
Passing a nested array to Active Record finder methods is
-
deprecated and will be removed. Flatten your array before using
-
it for 'IN' conditions.
-
MSG
-
-
values = values.flatten
-
end
-
-
return attribute.in([]) if values.empty? && nils.empty?
-
-
ranges, values = values.partition { |v| v.is_a?(Range) }
-
-
values_predicate =
-
case values.length
-
when 0 then NullPredicate
-
when 1 then attribute.eq(values.first)
-
else attribute.in(values)
-
end
-
-
unless nils.empty?
-
values_predicate = values_predicate.or(attribute.eq(nil))
-
end
-
-
array_predicates = ranges.map { |range| attribute.between(range) }
-
array_predicates.unshift(values_predicate)
-
array_predicates.inject { |composite, predicate| composite.or(predicate) }
-
end
-
-
1
module NullPredicate # :nodoc:
-
1
def self.or(other)
-
other
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class PredicateBuilder
-
1
class RelationHandler # :nodoc:
-
1
def call(attribute, value)
-
if value.select_values.empty?
-
value = value.select(value.klass.arel_table[value.klass.primary_key])
-
end
-
-
attribute.in(value.arel)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'active_model/forbidden_attributes_protection'
-
-
1
module ActiveRecord
-
1
module QueryMethods
-
1
extend ActiveSupport::Concern
-
-
1
include ActiveModel::ForbiddenAttributesProtection
-
-
# WhereChain objects act as placeholder for queries in which #where does not have any parameter.
-
# In this case, #where must be chained with #not to return a new relation.
-
1
class WhereChain
-
1
def initialize(scope)
-
@scope = scope
-
end
-
-
# Returns a new relation expressing WHERE + NOT condition according to
-
# the conditions in the arguments.
-
#
-
# +not+ accepts conditions as a string, array, or hash. See #where for
-
# more details on each format.
-
#
-
# User.where.not("name = 'Jon'")
-
# # SELECT * FROM users WHERE NOT (name = 'Jon')
-
#
-
# User.where.not(["name = ?", "Jon"])
-
# # SELECT * FROM users WHERE NOT (name = 'Jon')
-
#
-
# User.where.not(name: "Jon")
-
# # SELECT * FROM users WHERE name != 'Jon'
-
#
-
# User.where.not(name: nil)
-
# # SELECT * FROM users WHERE name IS NOT NULL
-
#
-
# User.where.not(name: %w(Ko1 Nobu))
-
# # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')
-
#
-
# User.where.not(name: "Jon", role: "admin")
-
# # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
-
1
def not(opts, *rest)
-
where_value = @scope.send(:build_where, opts, rest).map do |rel|
-
case rel
-
when NilClass
-
raise ArgumentError, 'Invalid argument for .where.not(), got nil.'
-
when Arel::Nodes::In
-
Arel::Nodes::NotIn.new(rel.left, rel.right)
-
when Arel::Nodes::Equality
-
Arel::Nodes::NotEqual.new(rel.left, rel.right)
-
when String
-
Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(rel))
-
else
-
Arel::Nodes::Not.new(rel)
-
end
-
end
-
-
@scope.references!(PredicateBuilder.references(opts)) if Hash === opts
-
@scope.where_values += where_value
-
@scope
-
end
-
end
-
-
1
Relation::MULTI_VALUE_METHODS.each do |name|
-
13
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_values # def select_values
-
@values[:#{name}] || [] # @values[:select] || []
-
end # end
-
#
-
def #{name}_values=(values) # def select_values=(values)
-
raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
-
check_cached_relation
-
@values[:#{name}] = values # @values[:select] = values
-
end # end
-
CODE
-
end
-
-
1
(Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |name|
-
9
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_value # def readonly_value
-
@values[:#{name}] # @values[:readonly]
-
end # end
-
CODE
-
end
-
-
1
Relation::SINGLE_VALUE_METHODS.each do |name|
-
10
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_value=(value) # def readonly_value=(value)
-
raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
-
check_cached_relation
-
@values[:#{name}] = value # @values[:readonly] = value
-
end # end
-
CODE
-
end
-
-
1
def check_cached_relation # :nodoc:
-
51
if defined?(@arel) && @arel
-
@arel = nil
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
Modifying already cached Relation. The cache will be reset. Use a
-
cloned Relation to prevent this warning.
-
MSG
-
end
-
end
-
-
1
def create_with_value # :nodoc:
-
@values[:create_with] || {}
-
end
-
-
1
alias extensions extending_values
-
-
# Specify relationships to be included in the result set. For
-
# example:
-
#
-
# users = User.includes(:address)
-
# users.each do |user|
-
# user.address.city
-
# end
-
#
-
# allows you to access the +address+ attribute of the +User+ model without
-
# firing an additional query. This will often result in a
-
# performance improvement over a simple +join+.
-
#
-
# You can also specify multiple relationships, like this:
-
#
-
# users = User.includes(:address, :friends)
-
#
-
# Loading nested relationships is possible using a Hash:
-
#
-
# users = User.includes(:address, friends: [:address, :followers])
-
#
-
# === conditions
-
#
-
# If you want to add conditions to your included models you'll have
-
# to explicitly reference them. For example:
-
#
-
# User.includes(:posts).where('posts.name = ?', 'example')
-
#
-
# Will throw an error, but this will work:
-
#
-
# User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
-
#
-
# Note that +includes+ works with association names while +references+ needs
-
# the actual table name.
-
1
def includes(*args)
-
check_if_method_has_arguments!(:includes, args)
-
spawn.includes!(*args)
-
end
-
-
1
def includes!(*args) # :nodoc:
-
args.reject!(&:blank?)
-
args.flatten!
-
-
self.includes_values |= args
-
self
-
end
-
-
# Forces eager loading by performing a LEFT OUTER JOIN on +args+:
-
#
-
# User.eager_load(:posts)
-
# => SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
-
# FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
-
# "users"."id"
-
1
def eager_load(*args)
-
check_if_method_has_arguments!(:eager_load, args)
-
spawn.eager_load!(*args)
-
end
-
-
1
def eager_load!(*args) # :nodoc:
-
self.eager_load_values += args
-
self
-
end
-
-
# Allows preloading of +args+, in the same way that +includes+ does:
-
#
-
# User.preload(:posts)
-
# => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
-
1
def preload(*args)
-
check_if_method_has_arguments!(:preload, args)
-
spawn.preload!(*args)
-
end
-
-
1
def preload!(*args) # :nodoc:
-
self.preload_values += args
-
self
-
end
-
-
# Use to indicate that the given +table_names+ are referenced by an SQL string,
-
# and should therefore be JOINed in any query rather than loaded separately.
-
# This method only works in conjunction with +includes+.
-
# See #includes for more details.
-
#
-
# User.includes(:posts).where("posts.name = 'foo'")
-
# # => Doesn't JOIN the posts table, resulting in an error.
-
#
-
# User.includes(:posts).where("posts.name = 'foo'").references(:posts)
-
# # => Query now knows the string references posts, so adds a JOIN
-
1
def references(*table_names)
-
check_if_method_has_arguments!(:references, table_names)
-
spawn.references!(*table_names)
-
end
-
-
1
def references!(*table_names) # :nodoc:
-
8
table_names.flatten!
-
8
table_names.map!(&:to_s)
-
-
8
self.references_values |= table_names
-
8
self
-
end
-
-
# Works in two unique ways.
-
#
-
# First: takes a block so it can be used just like Array#select.
-
#
-
# Model.all.select { |m| m.field == value }
-
#
-
# This will build an array of objects from the database for the scope,
-
# converting them into an array and iterating through them using Array#select.
-
#
-
# Second: Modifies the SELECT statement for the query so that only certain
-
# fields are retrieved:
-
#
-
# Model.select(:field)
-
# # => [#<Model id: nil, field: "value">]
-
#
-
# Although in the above example it looks as though this method returns an
-
# array, it actually returns a relation object and can have other query
-
# methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
-
#
-
# The argument to the method can also be an array of fields.
-
#
-
# Model.select(:field, :other_field, :and_one_more)
-
# # => [#<Model id: nil, field: "value", other_field: "value", and_one_more: "value">]
-
#
-
# You can also use one or more strings, which will be used unchanged as SELECT fields.
-
#
-
# Model.select('field AS field_one', 'other_field AS field_two')
-
# # => [#<Model id: nil, field: "value", other_field: "value">]
-
#
-
# If an alias was specified, it will be accessible from the resulting objects:
-
#
-
# Model.select('field AS field_one').first.field_one
-
# # => "value"
-
#
-
# Accessing attributes of an object that do not have fields retrieved by a select
-
# except +id+ will throw <tt>ActiveModel::MissingAttributeError</tt>:
-
#
-
# Model.select(:field).first.other_field
-
# # => ActiveModel::MissingAttributeError: missing attribute: other_field
-
1
def select(*fields)
-
if block_given?
-
to_a.select { |*block_args| yield(*block_args) }
-
else
-
raise ArgumentError, 'Call this with at least one field' if fields.empty?
-
spawn._select!(*fields)
-
end
-
end
-
-
1
def _select!(*fields) # :nodoc:
-
fields.flatten!
-
fields.map! do |field|
-
klass.attribute_alias?(field) ? klass.attribute_alias(field).to_sym : field
-
end
-
self.select_values += fields
-
self
-
end
-
-
# Allows to specify a group attribute:
-
#
-
# User.group(:name)
-
# => SELECT "users".* FROM "users" GROUP BY name
-
#
-
# Returns an array with distinct records based on the +group+ attribute:
-
#
-
# User.select([:id, :name])
-
# => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">
-
#
-
# User.group(:name)
-
# => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
-
#
-
# User.group('name AS grouped_name, age')
-
# => [#<User id: 3, name: "Foo", age: 21, ...>, #<User id: 2, name: "Oscar", age: 21, ...>, #<User id: 5, name: "Foo", age: 23, ...>]
-
#
-
# Passing in an array of attributes to group by is also supported.
-
# User.select([:id, :first_name]).group(:id, :first_name).first(3)
-
# => [#<User id: 1, first_name: "Bill">, #<User id: 2, first_name: "Earl">, #<User id: 3, first_name: "Beto">]
-
1
def group(*args)
-
check_if_method_has_arguments!(:group, args)
-
spawn.group!(*args)
-
end
-
-
1
def group!(*args) # :nodoc:
-
args.flatten!
-
-
self.group_values += args
-
self
-
end
-
-
# Allows to specify an order attribute:
-
#
-
# User.order(:name)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
-
#
-
# User.order(email: :desc)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
-
#
-
# User.order(:name, email: :desc)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
-
#
-
# User.order('name')
-
# => SELECT "users".* FROM "users" ORDER BY name
-
#
-
# User.order('name DESC')
-
# => SELECT "users".* FROM "users" ORDER BY name DESC
-
#
-
# User.order('name DESC, email')
-
# => SELECT "users".* FROM "users" ORDER BY name DESC, email
-
1
def order(*args)
-
17
check_if_method_has_arguments!(:order, args)
-
17
spawn.order!(*args)
-
end
-
-
1
def order!(*args) # :nodoc:
-
17
preprocess_order_args(args)
-
-
17
self.order_values += args
-
17
self
-
end
-
-
# Replaces any existing order defined on the relation with the specified order.
-
#
-
# User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
-
#
-
# Subsequent calls to order on the same relation will be appended. For example:
-
#
-
# User.order('email DESC').reorder('id ASC').order('name ASC')
-
#
-
# generates a query with 'ORDER BY id ASC, name ASC'.
-
1
def reorder(*args)
-
check_if_method_has_arguments!(:reorder, args)
-
spawn.reorder!(*args)
-
end
-
-
1
def reorder!(*args) # :nodoc:
-
preprocess_order_args(args)
-
-
self.reordering_value = true
-
self.order_values = args
-
self
-
end
-
-
1
VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock,
-
:limit, :offset, :joins, :includes, :from,
-
:readonly, :having])
-
-
# Removes an unwanted relation that is already defined on a chain of relations.
-
# This is useful when passing around chains of relations and would like to
-
# modify the relations without reconstructing the entire chain.
-
#
-
# User.order('email DESC').unscope(:order) == User.all
-
#
-
# The method arguments are symbols which correspond to the names of the methods
-
# which should be unscoped. The valid arguments are given in VALID_UNSCOPING_VALUES.
-
# The method can also be called with multiple arguments. For example:
-
#
-
# User.order('email DESC').select('id').where(name: "John")
-
# .unscope(:order, :select, :where) == User.all
-
#
-
# One can additionally pass a hash as an argument to unscope specific :where values.
-
# This is done by passing a hash with a single key-value pair. The key should be
-
# :where and the value should be the where value to unscope. For example:
-
#
-
# User.where(name: "John", active: true).unscope(where: :name)
-
# == User.where(active: true)
-
#
-
# This method is similar to <tt>except</tt>, but unlike
-
# <tt>except</tt>, it persists across merges:
-
#
-
# User.order('email').merge(User.except(:order))
-
# == User.order('email')
-
#
-
# User.order('email').merge(User.unscope(:order))
-
# == User.all
-
#
-
# This means it can be used in association definitions:
-
#
-
# has_many :comments, -> { unscope where: :trashed }
-
#
-
1
def unscope(*args)
-
check_if_method_has_arguments!(:unscope, args)
-
spawn.unscope!(*args)
-
end
-
-
1
def unscope!(*args) # :nodoc:
-
args.flatten!
-
self.unscope_values += args
-
-
args.each do |scope|
-
case scope
-
when Symbol
-
symbol_unscoping(scope)
-
when Hash
-
scope.each do |key, target_value|
-
if key != :where
-
raise ArgumentError, "Hash arguments in .unscope(*args) must have :where as the key."
-
end
-
-
Array(target_value).each do |val|
-
where_unscoping(val)
-
end
-
end
-
else
-
raise ArgumentError, "Unrecognized scoping: #{args.inspect}. Use .unscope(where: :attribute_name) or .unscope(:order), for example."
-
end
-
end
-
-
self
-
end
-
-
# Performs a joins on +args+:
-
#
-
# User.joins(:posts)
-
# => SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
-
#
-
# You can use strings in order to customize your joins:
-
#
-
# User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id")
-
# => SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id
-
1
def joins(*args)
-
check_if_method_has_arguments!(:joins, args)
-
spawn.joins!(*args)
-
end
-
-
1
def joins!(*args) # :nodoc:
-
args.compact!
-
args.flatten!
-
self.joins_values += args
-
self
-
end
-
-
1
def bind(value) # :nodoc:
-
spawn.bind!(value)
-
end
-
-
1
def bind!(value) # :nodoc:
-
self.bind_values += [value]
-
self
-
end
-
-
# Returns a new relation, which is the result of filtering the current relation
-
# according to the conditions in the arguments.
-
#
-
# #where accepts conditions in one of several formats. In the examples below, the resulting
-
# SQL is given as an illustration; the actual query generated may be different depending
-
# on the database adapter.
-
#
-
# === string
-
#
-
# A single string, without additional arguments, is passed to the query
-
# constructor as an SQL fragment, and used in the where clause of the query.
-
#
-
# Client.where("orders_count = '2'")
-
# # SELECT * from clients where orders_count = '2';
-
#
-
# Note that building your own string from user input may expose your application
-
# to injection attacks if not done properly. As an alternative, it is recommended
-
# to use one of the following methods.
-
#
-
# === array
-
#
-
# If an array is passed, then the first element of the array is treated as a template, and
-
# the remaining elements are inserted into the template to generate the condition.
-
# Active Record takes care of building the query to avoid injection attacks, and will
-
# convert from the ruby type to the database type where needed. Elements are inserted
-
# into the string in the order in which they appear.
-
#
-
# User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# Alternatively, you can use named placeholders in the template, and pass a hash as the
-
# second element of the array. The names in the template are replaced with the corresponding
-
# values from the hash.
-
#
-
# User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# This can make for more readable code in complex queries.
-
#
-
# Lastly, you can use sprintf-style % escapes in the template. This works slightly differently
-
# than the previous methods; you are responsible for ensuring that the values in the template
-
# are properly quoted. The values are passed to the connector for quoting, but the caller
-
# is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting,
-
# the values are inserted using the same escapes as the Ruby core method <tt>Kernel::sprintf</tt>.
-
#
-
# User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# If #where is called with multiple arguments, these are treated as if they were passed as
-
# the elements of a single array.
-
#
-
# User.where("name = :name and email = :email", { name: "Joe", email: "joe@example.com" })
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# When using strings to specify conditions, you can use any operator available from
-
# the database. While this provides the most flexibility, you can also unintentionally introduce
-
# dependencies on the underlying database. If your code is intended for general consumption,
-
# test with multiple database backends.
-
#
-
# === hash
-
#
-
# #where will also accept a hash condition, in which the keys are fields and the values
-
# are values to be searched for.
-
#
-
# Fields can be symbols or strings. Values can be single values, arrays, or ranges.
-
#
-
# User.where({ name: "Joe", email: "joe@example.com" })
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'
-
#
-
# User.where({ name: ["Alice", "Bob"]})
-
# # SELECT * FROM users WHERE name IN ('Alice', 'Bob')
-
#
-
# User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
-
# # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
-
#
-
# In the case of a belongs_to relationship, an association key can be used
-
# to specify the model if an ActiveRecord object is used as the value.
-
#
-
# author = Author.find(1)
-
#
-
# # The following queries will be equivalent:
-
# Post.where(author: author)
-
# Post.where(author_id: author)
-
#
-
# This also works with polymorphic belongs_to relationships:
-
#
-
# treasure = Treasure.create(name: 'gold coins')
-
# treasure.price_estimates << PriceEstimate.create(price: 125)
-
#
-
# # The following queries will be equivalent:
-
# PriceEstimate.where(estimate_of: treasure)
-
# PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
-
#
-
# === Joins
-
#
-
# If the relation is the result of a join, you may create a condition which uses any of the
-
# tables in the join. For string and array conditions, use the table name in the condition.
-
#
-
# User.joins(:posts).where("posts.created_at < ?", Time.now)
-
#
-
# For hash conditions, you can either use the table name in the key, or use a sub-hash.
-
#
-
# User.joins(:posts).where({ "posts.published" => true })
-
# User.joins(:posts).where({ posts: { published: true } })
-
#
-
# === no argument
-
#
-
# If no argument is passed, #where returns a new instance of WhereChain, that
-
# can be chained with #not to return a new relation that negates the where clause.
-
#
-
# User.where.not(name: "Jon")
-
# # SELECT * FROM users WHERE name != 'Jon'
-
#
-
# See WhereChain for more details on #not.
-
#
-
# === blank condition
-
#
-
# If the condition is any blank-ish object, then #where is a no-op and returns
-
# the current relation.
-
1
def where(opts = :chain, *rest)
-
11
if opts == :chain
-
WhereChain.new(spawn)
-
11
elsif opts.blank?
-
self
-
else
-
11
spawn.where!(opts, *rest)
-
end
-
end
-
-
1
def where!(opts, *rest) # :nodoc:
-
11
if Hash === opts
-
8
opts = sanitize_forbidden_attributes(opts)
-
8
references!(PredicateBuilder.references(opts))
-
end
-
-
11
self.where_values += build_where(opts, rest)
-
11
self
-
end
-
-
# Allows you to change a previously set where condition for a given attribute, instead of appending to that condition.
-
#
-
# Post.where(trashed: true).where(trashed: false) # => WHERE `trashed` = 1 AND `trashed` = 0
-
# Post.where(trashed: true).rewhere(trashed: false) # => WHERE `trashed` = 0
-
# Post.where(active: true).where(trashed: true).rewhere(trashed: false) # => WHERE `active` = 1 AND `trashed` = 0
-
#
-
# This is short-hand for unscope(where: conditions.keys).where(conditions). Note that unlike reorder, we're only unscoping
-
# the named conditions -- not the entire where statement.
-
1
def rewhere(conditions)
-
unscope(where: conditions.keys).where(conditions)
-
end
-
-
# Allows to specify a HAVING clause. Note that you can't use HAVING
-
# without also specifying a GROUP clause.
-
#
-
# Order.having('SUM(price) > 30').group('user_id')
-
1
def having(opts, *rest)
-
opts.blank? ? self : spawn.having!(opts, *rest)
-
end
-
-
1
def having!(opts, *rest) # :nodoc:
-
references!(PredicateBuilder.references(opts)) if Hash === opts
-
-
self.having_values += build_where(opts, rest)
-
self
-
end
-
-
# Specifies a limit for the number of records to retrieve.
-
#
-
# User.limit(10) # generated SQL has 'LIMIT 10'
-
#
-
# User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
-
1
def limit(value)
-
4
spawn.limit!(value)
-
end
-
-
1
def limit!(value) # :nodoc:
-
4
self.limit_value = value
-
4
self
-
end
-
-
# Specifies the number of rows to skip before returning rows.
-
#
-
# User.offset(10) # generated SQL has "OFFSET 10"
-
#
-
# Should be used with order.
-
#
-
# User.offset(10).order("name ASC")
-
1
def offset(value)
-
spawn.offset!(value)
-
end
-
-
1
def offset!(value) # :nodoc:
-
self.offset_value = value
-
self
-
end
-
-
# Specifies locking settings (default to +true+). For more information
-
# on locking, please see +ActiveRecord::Locking+.
-
1
def lock(locks = true)
-
spawn.lock!(locks)
-
end
-
-
1
def lock!(locks = true) # :nodoc:
-
case locks
-
when String, TrueClass, NilClass
-
self.lock_value = locks || true
-
else
-
self.lock_value = false
-
end
-
-
self
-
end
-
-
# Returns a chainable relation with zero records.
-
#
-
# The returned relation implements the Null Object pattern. It is an
-
# object with defined null behavior and always returns an empty array of
-
# records without querying the database.
-
#
-
# Any subsequent condition chained to the returned relation will continue
-
# generating an empty relation and will not fire any query to the database.
-
#
-
# Used in cases where a method or scope could return zero records but the
-
# result needs to be chainable.
-
#
-
# For example:
-
#
-
# @posts = current_user.visible_posts.where(name: params[:name])
-
# # => the visible_posts method is expected to return a chainable Relation
-
#
-
# def visible_posts
-
# case role
-
# when 'Country Manager'
-
# Post.where(country: country)
-
# when 'Reviewer'
-
# Post.published
-
# when 'Bad User'
-
# Post.none # It can't be chained if [] is returned.
-
# end
-
# end
-
#
-
1
def none
-
where("1=0").extending!(NullRelation)
-
end
-
-
1
def none! # :nodoc:
-
where!("1=0").extending!(NullRelation)
-
end
-
-
# Sets readonly attributes for the returned relation. If value is
-
# true (default), attempting to update a record will result in an error.
-
#
-
# users = User.readonly
-
# users.first.save
-
# => ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord
-
1
def readonly(value = true)
-
spawn.readonly!(value)
-
end
-
-
1
def readonly!(value = true) # :nodoc:
-
self.readonly_value = value
-
self
-
end
-
-
# Sets attributes to be used when creating new records from a
-
# relation object.
-
#
-
# users = User.where(name: 'Oscar')
-
# users.new.name # => 'Oscar'
-
#
-
# users = users.create_with(name: 'DHH')
-
# users.new.name # => 'DHH'
-
#
-
# You can pass +nil+ to +create_with+ to reset attributes:
-
#
-
# users = users.create_with(nil)
-
# users.new.name # => 'Oscar'
-
1
def create_with(value)
-
spawn.create_with!(value)
-
end
-
-
1
def create_with!(value) # :nodoc:
-
if value
-
value = sanitize_forbidden_attributes(value)
-
self.create_with_value = create_with_value.merge(value)
-
else
-
self.create_with_value = {}
-
end
-
-
self
-
end
-
-
# Specifies table from which the records will be fetched. For example:
-
#
-
# Topic.select('title').from('posts')
-
# # => SELECT title FROM posts
-
#
-
# Can accept other relation objects. For example:
-
#
-
# Topic.select('title').from(Topic.approved)
-
# # => SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
-
#
-
# Topic.select('a.title').from(Topic.approved, :a)
-
# # => SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
-
#
-
1
def from(value, subquery_name = nil)
-
spawn.from!(value, subquery_name)
-
end
-
-
1
def from!(value, subquery_name = nil) # :nodoc:
-
self.from_value = [value, subquery_name]
-
if value.is_a? Relation
-
self.bind_values = value.arel.bind_values + value.bind_values + bind_values
-
end
-
self
-
end
-
-
# Specifies whether the records should be unique or not. For example:
-
#
-
# User.select(:name)
-
# # => Might return two records with the same name
-
#
-
# User.select(:name).distinct
-
# # => Returns 1 record per distinct name
-
#
-
# User.select(:name).distinct.distinct(false)
-
# # => You can also remove the uniqueness
-
1
def distinct(value = true)
-
spawn.distinct!(value)
-
end
-
1
alias uniq distinct
-
-
# Like #distinct, but modifies relation in place.
-
1
def distinct!(value = true) # :nodoc:
-
self.distinct_value = value
-
self
-
end
-
1
alias uniq! distinct!
-
-
# Used to extend a scope with additional methods, either through
-
# a module or through a block provided.
-
#
-
# The object returned is a relation, which can be further extended.
-
#
-
# === Using a module
-
#
-
# module Pagination
-
# def page(number)
-
# # pagination code goes here
-
# end
-
# end
-
#
-
# scope = Model.all.extending(Pagination)
-
# scope.page(params[:page])
-
#
-
# You can also pass a list of modules:
-
#
-
# scope = Model.all.extending(Pagination, SomethingElse)
-
#
-
# === Using a block
-
#
-
# scope = Model.all.extending do
-
# def page(number)
-
# # pagination code goes here
-
# end
-
# end
-
# scope.page(params[:page])
-
#
-
# You can also use a block and a module list:
-
#
-
# scope = Model.all.extending(Pagination) do
-
# def per_page(number)
-
# # pagination code goes here
-
# end
-
# end
-
1
def extending(*modules, &block)
-
if modules.any? || block
-
spawn.extending!(*modules, &block)
-
else
-
self
-
end
-
end
-
-
1
def extending!(*modules, &block) # :nodoc:
-
modules << Module.new(&block) if block
-
modules.flatten!
-
-
self.extending_values += modules
-
extend(*extending_values) if extending_values.any?
-
-
self
-
end
-
-
# Reverse the existing order clause on the relation.
-
#
-
# User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
-
1
def reverse_order
-
spawn.reverse_order!
-
end
-
-
1
def reverse_order! # :nodoc:
-
orders = order_values.uniq
-
orders.reject!(&:blank?)
-
self.order_values = reverse_sql_order(orders)
-
self
-
end
-
-
# Returns the Arel object associated with the relation.
-
1
def arel # :nodoc:
-
90
@arel ||= build_arel
-
end
-
-
1
private
-
-
1
def build_arel
-
60
arel = Arel::SelectManager.new(table.engine, table)
-
-
60
build_joins(arel, joins_values.flatten) unless joins_values.empty?
-
-
60
collapse_wheres(arel, (where_values - [''])) #TODO: Add uniq with real value comparison / ignore uniqs that have binds
-
-
60
arel.having(*having_values.uniq.reject(&:blank?)) unless having_values.empty?
-
-
60
arel.take(connection.sanitize_limit(limit_value)) if limit_value
-
60
arel.skip(offset_value.to_i) if offset_value
-
60
arel.group(*arel_columns(group_values.uniq.reject(&:blank?))) unless group_values.empty?
-
-
60
build_order(arel)
-
-
60
build_select(arel)
-
-
60
arel.distinct(distinct_value)
-
60
arel.from(build_from) if from_value
-
60
arel.lock(lock_value) if lock_value
-
-
60
arel
-
end
-
-
1
def symbol_unscoping(scope)
-
if !VALID_UNSCOPING_VALUES.include?(scope)
-
raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}."
-
end
-
-
single_val_method = Relation::SINGLE_VALUE_METHODS.include?(scope)
-
unscope_code = "#{scope}_value#{'s' unless single_val_method}="
-
-
case scope
-
when :order
-
result = []
-
when :where
-
self.bind_values = []
-
else
-
result = [] unless single_val_method
-
end
-
-
self.send(unscope_code, result)
-
end
-
-
1
def where_unscoping(target_value)
-
target_value = target_value.to_s
-
-
self.where_values = where_values.reject do |rel|
-
case rel
-
when Arel::Nodes::Between, Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual, Arel::Nodes::LessThan, Arel::Nodes::LessThanOrEqual, Arel::Nodes::GreaterThan, Arel::Nodes::GreaterThanOrEqual
-
subrelation = (rel.left.kind_of?(Arel::Attributes::Attribute) ? rel.left : rel.right)
-
subrelation.name == target_value
-
end
-
end
-
-
bind_values.reject! { |col,_| col.name == target_value }
-
end
-
-
1
def custom_join_ast(table, joins)
-
joins = joins.reject(&:blank?)
-
-
return [] if joins.empty?
-
-
joins.map! do |join|
-
case join
-
when Array
-
join = Arel.sql(join.join(' ')) if array_of_strings?(join)
-
when String
-
join = Arel.sql(join)
-
end
-
table.create_string_join(join)
-
end
-
end
-
-
1
def collapse_wheres(arel, wheres)
-
60
predicates = wheres.map do |where|
-
11
next where if ::Arel::Nodes::Equality === where
-
where = Arel.sql(where) if String === where
-
Arel::Nodes::Grouping.new(where)
-
end
-
-
60
arel.where(Arel::Nodes::And.new(predicates)) if predicates.present?
-
end
-
-
1
def build_where(opts, other = [])
-
11
case opts
-
when String, Array
-
[@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
-
when Hash
-
8
opts = PredicateBuilder.resolve_column_aliases(klass, opts)
-
-
8
tmp_opts, bind_values = create_binds(opts)
-
8
self.bind_values += bind_values
-
-
8
attributes = @klass.send(:expand_hash_conditions_for_aggregates, tmp_opts)
-
8
add_relations_to_bind_values(attributes)
-
-
8
PredicateBuilder.build_from_hash(klass, attributes, table)
-
else
-
3
[opts]
-
end
-
end
-
-
1
def create_binds(opts)
-
8
bindable, non_binds = opts.partition do |column, value|
-
PredicateBuilder.can_be_bound?(value) &&
-
8
@klass.columns_hash.include?(column.to_s) &&
-
!@klass.reflect_on_aggregation(column)
-
end
-
-
8
association_binds, non_binds = non_binds.partition do |column, value|
-
value.is_a?(Hash) && association_for_table(column)
-
end
-
-
8
new_opts = {}
-
8
binds = []
-
-
8
connection = self.connection
-
-
8
bindable.each do |(column,value)|
-
8
binds.push [@klass.columns_hash[column.to_s], value]
-
8
new_opts[column] = connection.substitute_at(column)
-
end
-
-
8
association_binds.each do |(column, value)|
-
association_relation = association_for_table(column).klass.send(:relation)
-
association_new_opts, association_bind = association_relation.send(:create_binds, value)
-
new_opts[column] = association_new_opts
-
binds += association_bind
-
end
-
-
8
non_binds.each { |column,value| new_opts[column] = value }
-
-
8
[new_opts, binds]
-
end
-
-
1
def association_for_table(table_name)
-
table_name = table_name.to_s
-
@klass._reflect_on_association(table_name) ||
-
@klass._reflect_on_association(table_name.singularize)
-
end
-
-
1
def build_from
-
opts, name = from_value
-
case opts
-
when Relation
-
name ||= 'subquery'
-
opts.arel.as(name.to_s)
-
else
-
opts
-
end
-
end
-
-
1
def build_joins(manager, joins)
-
buckets = joins.group_by do |join|
-
case join
-
when String
-
:string_join
-
when Hash, Symbol, Array
-
:association_join
-
when ActiveRecord::Associations::JoinDependency
-
:stashed_join
-
when Arel::Nodes::Join
-
:join_node
-
else
-
raise 'unknown class: %s' % join.class.name
-
end
-
end
-
-
association_joins = buckets[:association_join] || []
-
stashed_association_joins = buckets[:stashed_join] || []
-
join_nodes = (buckets[:join_node] || []).uniq
-
string_joins = (buckets[:string_join] || []).map(&:strip).uniq
-
-
join_list = join_nodes + custom_join_ast(manager, string_joins)
-
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(
-
@klass,
-
association_joins,
-
join_list
-
)
-
-
join_infos = join_dependency.join_constraints stashed_association_joins
-
-
join_infos.each do |info|
-
info.joins.each { |join| manager.from(join) }
-
manager.bind_values.concat info.binds
-
end
-
-
manager.join_sources.concat(join_list)
-
-
manager
-
end
-
-
1
def build_select(arel)
-
60
if select_values.any?
-
arel.project(*arel_columns(select_values.uniq))
-
else
-
60
arel.project(@klass.arel_table[Arel.star])
-
end
-
end
-
-
1
def arel_columns(columns)
-
columns.map do |field|
-
if (Symbol === field || String === field) && columns_hash.key?(field.to_s) && !from_value
-
arel_table[field]
-
elsif Symbol === field
-
connection.quote_table_name(field.to_s)
-
else
-
field
-
end
-
end
-
end
-
-
1
def reverse_sql_order(order_query)
-
order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty?
-
-
order_query.flat_map do |o|
-
case o
-
when Arel::Nodes::Ordering
-
o.reverse
-
when String
-
o.to_s.split(',').map! do |s|
-
s.strip!
-
s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
-
end
-
else
-
o
-
end
-
end
-
end
-
-
1
def array_of_strings?(o)
-
o.is_a?(Array) && o.all? { |obj| obj.is_a?(String) }
-
end
-
-
1
def build_order(arel)
-
60
orders = order_values.uniq
-
60
orders.reject!(&:blank?)
-
-
60
arel.order(*orders) unless orders.empty?
-
end
-
-
1
VALID_DIRECTIONS = [:asc, :desc, :ASC, :DESC,
-
'asc', 'desc', 'ASC', 'DESC'] # :nodoc:
-
-
1
def validate_order_args(args)
-
17
args.each do |arg|
-
17
next unless arg.is_a?(Hash)
-
arg.each do |_key, value|
-
raise ArgumentError, "Direction \"#{value}\" is invalid. Valid " \
-
"directions are: #{VALID_DIRECTIONS.inspect}" unless VALID_DIRECTIONS.include?(value)
-
end
-
end
-
end
-
-
1
def preprocess_order_args(order_args)
-
17
order_args.flatten!
-
17
validate_order_args(order_args)
-
-
17
references = order_args.grep(String)
-
34
references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
-
17
references!(references) if references.any?
-
-
# if a symbol is given we prepend the quoted table name
-
order_args.map! do |arg|
-
17
case arg
-
when Symbol
-
arg = klass.attribute_alias(arg) if klass.attribute_alias?(arg)
-
table[arg].asc
-
when Hash
-
arg.map { |field, dir|
-
field = klass.attribute_alias(field) if klass.attribute_alias?(field)
-
table[field].send(dir.downcase)
-
}
-
else
-
17
arg
-
end
-
17
end.flatten!
-
end
-
-
# Checks to make sure that the arguments are not blank. Note that if some
-
# blank-like object were initially passed into the query method, then this
-
# method will not raise an error.
-
#
-
# Example:
-
#
-
# Post.references() # => raises an error
-
# Post.references([]) # => does not raise an error
-
#
-
# This particular method should be called with a method_name and the args
-
# passed into that method as an input. For example:
-
#
-
# def references(*args)
-
# check_if_method_has_arguments!("references", args)
-
# ...
-
# end
-
1
def check_if_method_has_arguments!(method_name, args)
-
17
if args.blank?
-
raise ArgumentError, "The method .#{method_name}() must contain arguments."
-
end
-
end
-
-
1
def add_relations_to_bind_values(attributes)
-
16
if attributes.is_a?(Hash)
-
8
attributes.each_value do |value|
-
8
if value.is_a?(ActiveRecord::Relation)
-
self.bind_values += value.arel.bind_values + value.bind_values
-
else
-
8
add_relations_to_bind_values(value)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_record/relation/merger'
-
-
1
module ActiveRecord
-
1
module SpawnMethods
-
-
# This is overridden by Associations::CollectionProxy
-
1
def spawn #:nodoc:
-
32
clone
-
end
-
-
# Merges in the conditions from <tt>other</tt>, if <tt>other</tt> is an <tt>ActiveRecord::Relation</tt>.
-
# Returns an array representing the intersection of the resulting records with <tt>other</tt>, if <tt>other</tt> is an array.
-
# Post.where(published: true).joins(:comments).merge( Comment.where(spam: false) )
-
# # Performs a single join query with both where conditions.
-
#
-
# recent_posts = Post.order('created_at DESC').first(5)
-
# Post.where(published: true).merge(recent_posts)
-
# # Returns the intersection of all published posts with the 5 most recently created posts.
-
# # (This is just an example. You'd probably want to do this with a single query!)
-
#
-
# Procs will be evaluated by merge:
-
#
-
# Post.where(published: true).merge(-> { joins(:comments) })
-
# # => Post.where(published: true).joins(:comments)
-
#
-
# This is mainly intended for sharing common conditions between multiple associations.
-
1
def merge(other)
-
28
if other.is_a?(Array)
-
to_a & other
-
28
elsif other
-
spawn.merge!(other)
-
else
-
28
self
-
end
-
end
-
-
1
def merge!(other) # :nodoc:
-
if !other.is_a?(Relation) && other.respond_to?(:to_proc)
-
instance_exec(&other)
-
else
-
klass = other.is_a?(Hash) ? Relation::HashMerger : Relation::Merger
-
klass.new(self, other).merge
-
end
-
end
-
-
# Removes from the query the condition(s) specified in +skips+.
-
#
-
# Post.order('id asc').except(:order) # discards the order condition
-
# Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order
-
1
def except(*skips)
-
relation_with values.except(*skips)
-
end
-
-
# Removes any condition from the query other than the one(s) specified in +onlies+.
-
#
-
# Post.order('id asc').only(:where) # discards the order condition
-
# Post.order('id asc').only(:where, :order) # uses the specified order
-
1
def only(*onlies)
-
if onlies.any? { |o| o == :where }
-
onlies << :bind
-
end
-
relation_with values.slice(*onlies)
-
end
-
-
1
private
-
-
1
def relation_with(values) # :nodoc:
-
result = Relation.create(klass, table, values)
-
result.extend(*extending_values) if extending_values.any?
-
result
-
end
-
end
-
end
-
1
module ActiveRecord
-
###
-
# This class encapsulates a Result returned from calling +exec_query+ on any
-
# database connection adapter. For example:
-
#
-
# result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
-
# result # => #<ActiveRecord::Result:0xdeadbeef>
-
#
-
# # Get the column names of the result:
-
# result.columns
-
# # => ["id", "title", "body"]
-
#
-
# # Get the record values of the result:
-
# result.rows
-
# # => [[1, "title_1", "body_1"],
-
# [2, "title_2", "body_2"],
-
# ...
-
# ]
-
#
-
# # Get an array of hashes representing the result (column => value):
-
# result.to_hash
-
# # => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
-
# {"id" => 2, "title" => "title_2", "body" => "body_2"},
-
# ...
-
# ]
-
#
-
# # ActiveRecord::Result also includes Enumerable.
-
# result.each do |row|
-
# puts row['title'] + " " + row['body']
-
# end
-
1
class Result
-
1
include Enumerable
-
-
1
IDENTITY_TYPE = Type::Value.new # :nodoc:
-
-
1
attr_reader :columns, :rows, :column_types
-
-
1
def initialize(columns, rows, column_types = {})
-
89
@columns = columns
-
89
@rows = rows
-
89
@hash_rows = nil
-
89
@column_types = column_types
-
end
-
-
1
def length
-
46
@rows.length
-
end
-
-
1
def each
-
48
if block_given?
-
108
hash_rows.each { |row| yield row }
-
else
-
hash_rows.to_enum { @rows.size }
-
end
-
end
-
-
1
def to_hash
-
9
hash_rows
-
end
-
-
1
alias :map! :map
-
1
alias :collect! :map
-
-
# Returns true if there are no records.
-
1
def empty?
-
rows.empty?
-
end
-
-
1
def to_ary
-
hash_rows
-
end
-
-
1
def [](idx)
-
hash_rows[idx]
-
end
-
-
1
def last
-
hash_rows.last
-
end
-
-
1
def cast_values(type_overrides = {}) # :nodoc:
-
types = columns.map { |name| column_type(name, type_overrides) }
-
result = rows.map do |values|
-
types.zip(values).map { |type, value| type.type_cast_from_database(value) }
-
end
-
-
columns.one? ? result.map!(&:first) : result
-
end
-
-
1
def initialize_copy(other)
-
45
@columns = columns.dup
-
45
@rows = rows.dup
-
45
@column_types = column_types.dup
-
45
@hash_rows = nil
-
end
-
-
1
private
-
-
1
def column_type(name, type_overrides = {})
-
type_overrides.fetch(name) do
-
column_types.fetch(name, IDENTITY_TYPE)
-
end
-
end
-
-
1
def hash_rows
-
@hash_rows ||=
-
begin
-
# We freeze the strings to prevent them getting duped when
-
# used as keys in ActiveRecord::Base's @attributes hash
-
423
columns = @columns.map { |c| c.dup.freeze }
-
57
@rows.map { |row|
-
# In the past we used Hash[columns.zip(row)]
-
# though elegant, the verbose way is much more efficient
-
# both time and memory wise cause it avoids a big array allocation
-
# this method is called a lot and needs to be micro optimised
-
115
hash = {}
-
-
115
index = 0
-
115
length = columns.length
-
-
115
while index < length
-
659
hash[columns[index]] = row[index]
-
659
index += 1
-
end
-
-
115
hash
-
}
-
57
end
-
end
-
end
-
end
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveRecord
-
# This is a thread locals registry for Active Record. For example:
-
#
-
# ActiveRecord::RuntimeRegistry.connection_handler
-
#
-
# returns the connection handler local to the current thread.
-
#
-
# See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
-
# for further details.
-
1
class RuntimeRegistry # :nodoc:
-
1
extend ActiveSupport::PerThreadRegistry
-
-
1
attr_accessor :connection_handler, :sql_runtime, :connection_id
-
-
1
[:connection_handler, :sql_runtime, :connection_id].each do |val|
-
3
class_eval %{ def self.#{val}; instance.#{val}; end }, __FILE__, __LINE__
-
3
class_eval %{ def self.#{val}=(x); instance.#{val}=x; end }, __FILE__, __LINE__
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Sanitization
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
1
def quote_value(value, column) #:nodoc:
-
connection.quote(value, column)
-
end
-
-
# Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
-
1
def sanitize(object) #:nodoc:
-
connection.quote(object)
-
end
-
-
1
protected
-
-
# Accepts an array, hash, or string of SQL conditions and sanitizes
-
# them into a valid SQL fragment for a WHERE clause.
-
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
-
# { name: "foo'bar", group_id: 4 } returns "name='foo''bar' and group_id='4'"
-
# "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
-
1
def sanitize_sql_for_conditions(condition, table_name = self.table_name)
-
46
return nil if condition.blank?
-
-
46
case condition
-
when Array; sanitize_sql_array(condition)
-
when Hash; sanitize_sql_hash_for_conditions(condition, table_name)
-
46
else condition
-
end
-
end
-
1
alias_method :sanitize_sql, :sanitize_sql_for_conditions
-
1
alias_method :sanitize_conditions, :sanitize_sql
-
-
# Accepts an array, hash, or string of SQL conditions and sanitizes
-
# them into a valid SQL fragment for a SET clause.
-
# { name: nil, group_id: 4 } returns "name = NULL , group_id='4'"
-
1
def sanitize_sql_for_assignment(assignments, default_table_name = self.table_name)
-
case assignments
-
when Array; sanitize_sql_array(assignments)
-
when Hash; sanitize_sql_hash_for_assignment(assignments, default_table_name)
-
else assignments
-
end
-
end
-
-
# Accepts a hash of SQL conditions and replaces those attributes
-
# that correspond to a +composed_of+ relationship with their expanded
-
# aggregate attribute values.
-
# Given:
-
# class Person < ActiveRecord::Base
-
# composed_of :address, class_name: "Address",
-
# mapping: [%w(address_street street), %w(address_city city)]
-
# end
-
# Then:
-
# { address: Address.new("813 abc st.", "chicago") }
-
# # => { address_street: "813 abc st.", address_city: "chicago" }
-
1
def expand_hash_conditions_for_aggregates(attrs)
-
8
expanded_attrs = {}
-
8
attrs.each do |attr, value|
-
8
if aggregation = reflect_on_aggregation(attr.to_sym)
-
mapping = aggregation.mapping
-
mapping.each do |field_attr, aggregate_attr|
-
if mapping.size == 1 && !value.respond_to?(aggregate_attr)
-
expanded_attrs[field_attr] = value
-
else
-
expanded_attrs[field_attr] = value.send(aggregate_attr)
-
end
-
end
-
else
-
8
expanded_attrs[attr] = value
-
end
-
end
-
8
expanded_attrs
-
end
-
-
# Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
-
# { name: "foo'bar", group_id: 4 }
-
# # => "name='foo''bar' and group_id= 4"
-
# { status: nil, group_id: [1,2,3] }
-
# # => "status IS NULL and group_id IN (1,2,3)"
-
# { age: 13..18 }
-
# # => "age BETWEEN 13 AND 18"
-
# { 'other_records.id' => 7 }
-
# # => "`other_records`.`id` = 7"
-
# { other_records: { id: 7 } }
-
# # => "`other_records`.`id` = 7"
-
# And for value objects on a composed_of relationship:
-
# { address: Address.new("123 abc st.", "chicago") }
-
# # => "address_street='123 abc st.' and address_city='chicago'"
-
1
def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
-
ActiveSupport::Deprecation.warn(<<-EOWARN)
-
sanitize_sql_hash_for_conditions is deprecated, and will be removed in Rails 5.0
-
EOWARN
-
attrs = PredicateBuilder.resolve_column_aliases self, attrs
-
attrs = expand_hash_conditions_for_aggregates(attrs)
-
-
table = Arel::Table.new(table_name, arel_engine).alias(default_table_name)
-
PredicateBuilder.build_from_hash(self, attrs, table).map { |b|
-
connection.visitor.compile b
-
}.join(' AND ')
-
end
-
1
alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
-
-
# Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
-
# { status: nil, group_id: 1 }
-
# # => "status = NULL , group_id = 1"
-
1
def sanitize_sql_hash_for_assignment(attrs, table)
-
c = connection
-
attrs.map do |attr, value|
-
"#{c.quote_table_name_for_assignment(table, attr)} = #{quote_bound_value(value, c, columns_hash[attr.to_s])}"
-
end.join(', ')
-
end
-
-
# Sanitizes a +string+ so that it is safe to use within an SQL
-
# LIKE statement. This method uses +escape_character+ to escape all occurrences of "\", "_" and "%"
-
1
def sanitize_sql_like(string, escape_character = "\\")
-
pattern = Regexp.union(escape_character, "%", "_")
-
string.gsub(pattern) { |x| [escape_character, x].join }
-
end
-
-
# Accepts an array of conditions. The array has each value
-
# sanitized and interpolated into the SQL statement.
-
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
-
1
def sanitize_sql_array(ary)
-
statement, *values = ary
-
if values.first.is_a?(Hash) && statement =~ /:\w+/
-
replace_named_bind_variables(statement, values.first)
-
elsif statement.include?('?')
-
replace_bind_variables(statement, values)
-
elsif statement.blank?
-
statement
-
else
-
statement % values.collect { |value| connection.quote_string(value.to_s) }
-
end
-
end
-
-
1
def replace_bind_variables(statement, values) #:nodoc:
-
raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
-
bound = values.dup
-
c = connection
-
statement.gsub(/\?/) do
-
replace_bind_variable(bound.shift, c)
-
end
-
end
-
-
1
def replace_bind_variable(value, c = connection) #:nodoc:
-
if ActiveRecord::Relation === value
-
value.to_sql
-
else
-
quote_bound_value(value, c)
-
end
-
end
-
-
1
def replace_named_bind_variables(statement, bind_vars) #:nodoc:
-
statement.gsub(/(:?):([a-zA-Z]\w*)/) do
-
if $1 == ':' # skip postgresql casts
-
$& # return the whole match
-
elsif bind_vars.include?(match = $2.to_sym)
-
replace_bind_variable(bind_vars[match])
-
else
-
raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
-
end
-
end
-
end
-
-
1
def quote_bound_value(value, c = connection, column = nil) #:nodoc:
-
if column
-
c.quote(value, column)
-
elsif value.respond_to?(:map) && !value.acts_like?(:string)
-
if value.respond_to?(:empty?) && value.empty?
-
c.quote(nil)
-
else
-
value.map { |v| c.quote(v) }.join(',')
-
end
-
else
-
c.quote(value)
-
end
-
end
-
-
1
def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc:
-
unless expected == provided
-
raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
-
end
-
end
-
end
-
-
# TODO: Deprecate this
-
1
def quoted_id
-
self.class.quote_value(id, column_for_attribute(self.class.primary_key))
-
end
-
end
-
end
-
1
require 'active_record/scoping/default'
-
1
require 'active_record/scoping/named'
-
1
require 'active_record/base'
-
-
1
module ActiveRecord
-
1
class SchemaMigration < ActiveRecord::Base
-
1
class << self
-
1
def primary_key
-
nil
-
end
-
-
1
def table_name
-
4
"#{table_name_prefix}#{ActiveRecord::Base.schema_migrations_table_name}#{table_name_suffix}"
-
end
-
-
1
def index_name
-
"#{table_name_prefix}unique_#{ActiveRecord::Base.schema_migrations_table_name}#{table_name_suffix}"
-
end
-
-
1
def table_exists?
-
connection.table_exists?(table_name)
-
end
-
-
1
def create_table(limit=nil)
-
unless table_exists?
-
version_options = {null: false}
-
version_options[:limit] = limit if limit
-
-
connection.create_table(table_name, id: false) do |t|
-
t.column :version, :string, version_options
-
end
-
connection.add_index table_name, :version, unique: true, name: index_name
-
end
-
end
-
-
1
def drop_table
-
if table_exists?
-
connection.remove_index table_name, name: index_name
-
connection.drop_table(table_name)
-
end
-
end
-
-
1
def normalize_migration_number(number)
-
"%.3d" % number.to_i
-
end
-
-
1
def normalized_versions
-
pluck(:version).map { |v| normalize_migration_number v }
-
end
-
end
-
-
1
def version
-
6
super.to_i
-
end
-
end
-
end
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveRecord
-
1
module Scoping
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
include Default
-
1
include Named
-
end
-
-
1
module ClassMethods
-
1
def current_scope #:nodoc:
-
79
ScopeRegistry.value_for(:current_scope, base_class.to_s)
-
end
-
-
1
def current_scope=(scope) #:nodoc:
-
ScopeRegistry.set_value_for(:current_scope, base_class.to_s, scope)
-
end
-
end
-
-
1
def populate_with_current_scope_attributes
-
29
return unless self.class.scope_attributes?
-
-
self.class.scope_attributes.each do |att,value|
-
send("#{att}=", value) if respond_to?("#{att}=")
-
end
-
end
-
-
1
def initialize_internals_callback
-
29
super
-
29
populate_with_current_scope_attributes
-
end
-
-
# This class stores the +:current_scope+ and +:ignore_default_scope+ values
-
# for different classes. The registry is stored as a thread local, which is
-
# accessed through +ScopeRegistry.current+.
-
#
-
# This class allows you to store and get the scope values on different
-
# classes and different types of scopes. For example, if you are attempting
-
# to get the current_scope for the +Board+ model, then you would use the
-
# following code:
-
#
-
# registry = ActiveRecord::Scoping::ScopeRegistry
-
# registry.set_value_for(:current_scope, "Board", some_new_scope)
-
#
-
# Now when you run:
-
#
-
# registry.value_for(:current_scope, "Board")
-
#
-
# You will obtain whatever was defined in +some_new_scope+. The +value_for+
-
# and +set_value_for+ methods are delegated to the current +ScopeRegistry+
-
# object, so the above example code can also be called as:
-
#
-
# ActiveRecord::Scoping::ScopeRegistry.set_value_for(:current_scope,
-
# "Board", some_new_scope)
-
1
class ScopeRegistry # :nodoc:
-
1
extend ActiveSupport::PerThreadRegistry
-
-
1
VALID_SCOPE_TYPES = [:current_scope, :ignore_default_scope]
-
-
1
def initialize
-
2
@registry = Hash.new { |hash, key| hash[key] = {} }
-
end
-
-
# Obtains the value for a given +scope_name+ and +variable_name+.
-
1
def value_for(scope_type, variable_name)
-
79
raise_invalid_scope_type!(scope_type)
-
79
@registry[scope_type][variable_name]
-
end
-
-
# Sets the +value+ for a given +scope_type+ and +variable_name+.
-
1
def set_value_for(scope_type, variable_name, value)
-
raise_invalid_scope_type!(scope_type)
-
@registry[scope_type][variable_name] = value
-
end
-
-
1
private
-
-
1
def raise_invalid_scope_type!(scope_type)
-
79
if !VALID_SCOPE_TYPES.include?(scope_type)
-
raise ArgumentError, "Invalid scope type '#{scope_type}' sent to the registry. Scope types must be included in VALID_SCOPE_TYPES"
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Scoping
-
1
module Default
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
# Stores the default scope for the class.
-
1
class_attribute :default_scopes, instance_writer: false, instance_predicate: false
-
-
1
self.default_scopes = []
-
end
-
-
1
module ClassMethods
-
# Returns a scope for the model without the previously set scopes.
-
#
-
# class Post < ActiveRecord::Base
-
# def self.default_scope
-
# where published: true
-
# end
-
# end
-
#
-
# Post.all # Fires "SELECT * FROM posts WHERE published = true"
-
# Post.unscoped.all # Fires "SELECT * FROM posts"
-
# Post.where(published: false).unscoped.all # Fires "SELECT * FROM posts"
-
#
-
# This method also accepts a block. All queries inside the block will
-
# not use the previously set scopes.
-
#
-
# Post.unscoped {
-
# Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
-
# }
-
1
def unscoped
-
36
block_given? ? relation.scoping { yield } : relation
-
end
-
-
1
def before_remove_const #:nodoc:
-
self.current_scope = nil
-
end
-
-
1
protected
-
-
# Use this macro in your model to set a default scope for all operations on
-
# the model.
-
#
-
# class Article < ActiveRecord::Base
-
# default_scope { where(published: true) }
-
# end
-
#
-
# Article.all # => SELECT * FROM articles WHERE published = true
-
#
-
# The +default_scope+ is also applied while creating/building a record.
-
# It is not applied while updating a record.
-
#
-
# Article.new.published # => true
-
# Article.create.published # => true
-
#
-
# (You can also pass any object which responds to +call+ to the
-
# +default_scope+ macro, and it will be called when building the
-
# default scope.)
-
#
-
# If you use multiple +default_scope+ declarations in your model then
-
# they will be merged together:
-
#
-
# class Article < ActiveRecord::Base
-
# default_scope { where(published: true) }
-
# default_scope { where(rating: 'G') }
-
# end
-
#
-
# Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G'
-
#
-
# This is also the case with inheritance and module includes where the
-
# parent or module defines a +default_scope+ and the child or including
-
# class defines a second one.
-
#
-
# If you need to do more complex things with a default scope, you can
-
# alternatively define it as a class method:
-
#
-
# class Article < ActiveRecord::Base
-
# def self.default_scope
-
# # Should return a scope, you can call 'super' here etc.
-
# end
-
# end
-
1
def default_scope(scope = nil)
-
scope = Proc.new if block_given?
-
-
if scope.is_a?(Relation) || !scope.respond_to?(:call)
-
raise ArgumentError,
-
"Support for calling #default_scope without a block is removed. For example instead " \
-
"of `default_scope where(color: 'red')`, please use " \
-
"`default_scope { where(color: 'red') }`. (Alternatively you can just redefine " \
-
"self.default_scope.)"
-
end
-
-
self.default_scopes += [scope]
-
end
-
-
1
def build_default_scope(base_rel = relation) # :nodoc:
-
28
return if abstract_class?
-
28
if !Base.is_a?(method(:default_scope).owner)
-
# The user has defined their own default scope method, so call that
-
evaluate_default_scope { default_scope }
-
28
elsif default_scopes.any?
-
evaluate_default_scope do
-
default_scopes.inject(base_rel) do |default_scope, scope|
-
default_scope.merge(base_rel.scoping { scope.call })
-
end
-
end
-
end
-
end
-
-
1
def ignore_default_scope? # :nodoc:
-
ScopeRegistry.value_for(:ignore_default_scope, self)
-
end
-
-
1
def ignore_default_scope=(ignore) # :nodoc:
-
ScopeRegistry.set_value_for(:ignore_default_scope, self, ignore)
-
end
-
-
# The ignore_default_scope flag is used to prevent an infinite recursion
-
# situation where a default scope references a scope which has a default
-
# scope which references a scope...
-
1
def evaluate_default_scope # :nodoc:
-
return if ignore_default_scope?
-
-
begin
-
self.ignore_default_scope = true
-
yield
-
ensure
-
self.ignore_default_scope = false
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
-
1
module ActiveRecord
-
# = Active Record \Named \Scopes
-
1
module Scoping
-
1
module Named
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Returns an <tt>ActiveRecord::Relation</tt> scope object.
-
#
-
# posts = Post.all
-
# posts.size # Fires "select count(*) from posts" and returns the count
-
# posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
-
#
-
# fruits = Fruit.all
-
# fruits = fruits.where(color: 'red') if options[:red_only]
-
# fruits = fruits.limit(10) if limited?
-
#
-
# You can define a scope that applies to all finders using
-
# <tt>ActiveRecord::Base.default_scope</tt>.
-
1
def all
-
28
if current_scope
-
current_scope.clone
-
else
-
28
default_scoped
-
end
-
end
-
-
1
def default_scoped # :nodoc:
-
28
relation.merge(build_default_scope)
-
end
-
-
# Collects attributes from scopes that should be applied when creating
-
# an AR instance for the particular class this is called on.
-
1
def scope_attributes # :nodoc:
-
all.scope_for_create
-
end
-
-
# Are there default attributes associated with this scope?
-
1
def scope_attributes? # :nodoc:
-
29
current_scope || default_scopes.any?
-
end
-
-
# Adds a class method for retrieving and querying objects. A \scope
-
# represents a narrowing of a database query, such as
-
# <tt>where(color: :red).select('shirts.*').includes(:washing_instructions)</tt>.
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :red, -> { where(color: 'red') }
-
# scope :dry_clean_only, -> { joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) }
-
# end
-
#
-
# The above calls to +scope+ define class methods <tt>Shirt.red</tt> and
-
# <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>, in effect,
-
# represents the query <tt>Shirt.where(color: 'red')</tt>.
-
#
-
# You should always pass a callable object to the scopes defined
-
# with +scope+. This ensures that the scope is re-evaluated each
-
# time it is called.
-
#
-
# Note that this is simply 'syntactic sugar' for defining an actual
-
# class method:
-
#
-
# class Shirt < ActiveRecord::Base
-
# def self.red
-
# where(color: 'red')
-
# end
-
# end
-
#
-
# Unlike <tt>Shirt.find(...)</tt>, however, the object returned by
-
# <tt>Shirt.red</tt> is not an Array; it resembles the association object
-
# constructed by a +has_many+ declaration. For instance, you can invoke
-
# <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>,
-
# <tt>Shirt.red.where(size: 'small')</tt>. Also, just as with the
-
# association objects, named \scopes act like an Array, implementing
-
# Enumerable; <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>,
-
# and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if
-
# <tt>Shirt.red</tt> really was an Array.
-
#
-
# These named \scopes are composable. For instance,
-
# <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are
-
# both red and dry clean only. Nested finds and calculations also work
-
# with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
-
# returns the number of garments for which these criteria obtain.
-
# Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
-
#
-
# All scopes are available as class methods on the ActiveRecord::Base
-
# descendant upon which the \scopes were defined. But they are also
-
# available to +has_many+ associations. If,
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :shirts
-
# end
-
#
-
# then <tt>elton.shirts.red.dry_clean_only</tt> will return all of
-
# Elton's red, dry clean only shirts.
-
#
-
# \Named scopes can also have extensions, just as with +has_many+
-
# declarations:
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :red, -> { where(color: 'red') } do
-
# def dom_id
-
# 'red_shirts'
-
# end
-
# end
-
# end
-
#
-
# Scopes can also be used while creating/building a record.
-
#
-
# class Article < ActiveRecord::Base
-
# scope :published, -> { where(published: true) }
-
# end
-
#
-
# Article.published.new.published # => true
-
# Article.published.create.published # => true
-
#
-
# \Class methods on your model are automatically available
-
# on scopes. Assuming the following setup:
-
#
-
# class Article < ActiveRecord::Base
-
# scope :published, -> { where(published: true) }
-
# scope :featured, -> { where(featured: true) }
-
#
-
# def self.latest_article
-
# order('published_at desc').first
-
# end
-
#
-
# def self.titles
-
# pluck(:title)
-
# end
-
# end
-
#
-
# We are able to call the methods like this:
-
#
-
# Article.published.featured.latest_article
-
# Article.featured.titles
-
1
def scope(name, body, &block)
-
unless body.respond_to?(:call)
-
raise ArgumentError, 'The scope body needs to be callable.'
-
end
-
-
if dangerous_class_method?(name)
-
raise ArgumentError, "You tried to define a scope named \"#{name}\" " \
-
"on the model \"#{self.name}\", but Active Record already defined " \
-
"a class method with the same name."
-
end
-
-
extension = Module.new(&block) if block
-
-
singleton_class.send(:define_method, name) do |*args|
-
scope = all.scoping { body.call(*args) }
-
scope = scope.extending(extension) if extension
-
-
scope || all
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord #:nodoc:
-
# = Active Record Serialization
-
1
module Serialization
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Serializers::JSON
-
-
1
included do
-
1
self.include_root_in_json = false
-
end
-
-
1
def serializable_hash(options = nil)
-
options = options.try(:clone) || {}
-
-
options[:except] = Array(options[:except]).map { |n| n.to_s }
-
options[:except] |= Array(self.class.inheritance_column)
-
-
super(options)
-
end
-
end
-
end
-
-
1
require 'active_record/serializers/xml_serializer'
-
1
require 'active_support/core_ext/hash/conversions'
-
-
1
module ActiveRecord #:nodoc:
-
1
module Serialization
-
1
include ActiveModel::Serializers::Xml
-
-
# Builds an XML document to represent the model. Some configuration is
-
# available through +options+. However more complicated cases should
-
# override ActiveRecord::Base#to_xml.
-
#
-
# By default the generated XML document will include the processing
-
# instruction and all the object's attributes. For example:
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <topic>
-
# <title>The First Topic</title>
-
# <author-name>David</author-name>
-
# <id type="integer">1</id>
-
# <approved type="boolean">false</approved>
-
# <replies-count type="integer">0</replies-count>
-
# <bonus-time type="dateTime">2000-01-01T08:28:00+12:00</bonus-time>
-
# <written-on type="dateTime">2003-07-16T09:28:00+1200</written-on>
-
# <content>Have a nice day</content>
-
# <author-email-address>david@loudthinking.com</author-email-address>
-
# <parent-id></parent-id>
-
# <last-read type="date">2004-04-15</last-read>
-
# </topic>
-
#
-
# This behavior can be controlled with <tt>:only</tt>, <tt>:except</tt>,
-
# <tt>:skip_instruct</tt>, <tt>:skip_types</tt>, <tt>:dasherize</tt> and <tt>:camelize</tt> .
-
# The <tt>:only</tt> and <tt>:except</tt> options are the same as for the
-
# +attributes+ method. The default is to dasherize all column names, but you
-
# can disable this setting <tt>:dasherize</tt> to +false+. Setting <tt>:camelize</tt>
-
# to +true+ will camelize all column names - this also overrides <tt>:dasherize</tt>.
-
# To not have the column type included in the XML output set <tt>:skip_types</tt> to +true+.
-
#
-
# For instance:
-
#
-
# topic.to_xml(skip_instruct: true, except: [ :id, :bonus_time, :written_on, :replies_count ])
-
#
-
# <topic>
-
# <title>The First Topic</title>
-
# <author-name>David</author-name>
-
# <approved type="boolean">false</approved>
-
# <content>Have a nice day</content>
-
# <author-email-address>david@loudthinking.com</author-email-address>
-
# <parent-id></parent-id>
-
# <last-read type="date">2004-04-15</last-read>
-
# </topic>
-
#
-
# To include first level associations use <tt>:include</tt>:
-
#
-
# firm.to_xml include: [ :account, :clients ]
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <firm>
-
# <id type="integer">1</id>
-
# <rating type="integer">1</rating>
-
# <name>37signals</name>
-
# <clients type="array">
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Summit</name>
-
# </client>
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Microsoft</name>
-
# </client>
-
# </clients>
-
# <account>
-
# <id type="integer">1</id>
-
# <credit-limit type="integer">50</credit-limit>
-
# </account>
-
# </firm>
-
#
-
# Additionally, the record being serialized will be passed to a Proc's second
-
# parameter. This allows for ad hoc additions to the resultant document that
-
# incorporate the context of the record being serialized. And by leveraging the
-
# closure created by a Proc, to_xml can be used to add elements that normally fall
-
# outside of the scope of the model -- for example, generating and appending URLs
-
# associated with models.
-
#
-
# proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
-
# firm.to_xml procs: [ proc ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <name-reverse>slangis73</name-reverse>
-
# </firm>
-
#
-
# To include deeper levels of associations pass a hash like this:
-
#
-
# firm.to_xml include: {account: {}, clients: {include: :address}}
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <firm>
-
# <id type="integer">1</id>
-
# <rating type="integer">1</rating>
-
# <name>37signals</name>
-
# <clients type="array">
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Summit</name>
-
# <address>
-
# ...
-
# </address>
-
# </client>
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Microsoft</name>
-
# <address>
-
# ...
-
# </address>
-
# </client>
-
# </clients>
-
# <account>
-
# <id type="integer">1</id>
-
# <credit-limit type="integer">50</credit-limit>
-
# </account>
-
# </firm>
-
#
-
# To include any methods on the model being called use <tt>:methods</tt>:
-
#
-
# firm.to_xml methods: [ :calculated_earnings, :real_earnings ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <calculated-earnings>100000000000000000</calculated-earnings>
-
# <real-earnings>5</real-earnings>
-
# </firm>
-
#
-
# To call any additional Procs use <tt>:procs</tt>. The Procs are passed a
-
# modified version of the options hash that was given to +to_xml+:
-
#
-
# proc = Proc.new { |options| options[:builder].tag!('abc', 'def') }
-
# firm.to_xml procs: [ proc ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <abc>def</abc>
-
# </firm>
-
#
-
# Alternatively, you can yield the builder object as part of the +to_xml+ call:
-
#
-
# firm.to_xml do |xml|
-
# xml.creator do
-
# xml.first_name "David"
-
# xml.last_name "Heinemeier Hansson"
-
# end
-
# end
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <creator>
-
# <first_name>David</first_name>
-
# <last_name>Heinemeier Hansson</last_name>
-
# </creator>
-
# </firm>
-
#
-
# As noted above, you may override +to_xml+ in your ActiveRecord::Base
-
# subclasses to have complete control about what's generated. The general
-
# form of doing this is:
-
#
-
# class IHaveMyOwnXML < ActiveRecord::Base
-
# def to_xml(options = {})
-
# require 'builder'
-
# options[:indent] ||= 2
-
# xml = options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
-
# xml.instruct! unless options[:skip_instruct]
-
# xml.level_one do
-
# xml.tag!(:second_level, 'content')
-
# end
-
# end
-
# end
-
1
def to_xml(options = {}, &block)
-
XmlSerializer.new(self, options).serialize(&block)
-
end
-
end
-
-
1
class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc:
-
1
class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
-
1
def compute_type
-
klass = @serializable.class
-
column = klass.columns_hash[name] || Type::Value.new
-
-
type = ActiveSupport::XmlMini::TYPE_NAMES[value.class.name] || column.type
-
-
{ :text => :string,
-
:time => :datetime }[type] || type
-
end
-
1
protected :compute_type
-
end
-
end
-
end
-
1
module ActiveRecord
-
-
# Statement cache is used to cache a single statement in order to avoid creating the AST again.
-
# Initializing the cache is done by passing the statement in the create block:
-
#
-
# cache = StatementCache.create(Book.connection) do |params|
-
# Book.where(name: "my book").where("author_id > 3")
-
# end
-
#
-
# The cached statement is executed by using the +execute+ method:
-
#
-
# cache.execute([], Book, Book.connection)
-
#
-
# The relation returned by the block is cached, and for each +execute+ call the cached relation gets duped.
-
# Database is queried when +to_a+ is called on the relation.
-
#
-
# If you want to cache the statement without the values you can use the +bind+ method of the
-
# block parameter.
-
#
-
# cache = StatementCache.create(Book.connection) do |params|
-
# Book.where(name: params.bind)
-
# end
-
#
-
# And pass the bind values as the first argument of +execute+ call.
-
#
-
# cache.execute(["my book"], Book, Book.connection)
-
1
class StatementCache # :nodoc:
-
1
class Substitute; end # :nodoc:
-
-
1
class Query # :nodoc:
-
1
def initialize(sql)
-
4
@sql = sql
-
end
-
-
1
def sql_for(binds, connection)
-
22
@sql
-
end
-
end
-
-
1
class PartialQuery < Query # :nodoc:
-
1
def initialize values
-
@values = values
-
@indexes = values.each_with_index.find_all { |thing,i|
-
Arel::Nodes::BindParam === thing
-
}.map(&:last)
-
end
-
-
1
def sql_for(binds, connection)
-
val = @values.dup
-
binds = binds.dup
-
@indexes.each { |i| val[i] = connection.quote(*binds.shift.reverse) }
-
val.join
-
end
-
end
-
-
1
def self.query(visitor, ast)
-
4
Query.new visitor.accept(ast, Arel::Collectors::SQLString.new).value
-
end
-
-
1
def self.partial_query(visitor, ast, collector)
-
collected = visitor.accept(ast, collector).value
-
PartialQuery.new collected
-
end
-
-
1
class Params # :nodoc:
-
5
def bind; Substitute.new; end
-
end
-
-
1
class BindMap # :nodoc:
-
1
def initialize(bind_values)
-
4
@indexes = []
-
4
@bind_values = bind_values
-
-
4
bind_values.each_with_index do |(_, value), i|
-
4
if Substitute === value
-
4
@indexes << i
-
end
-
end
-
end
-
-
1
def bind(values)
-
44
bvs = @bind_values.map { |pair| pair.dup }
-
44
@indexes.each_with_index { |offset,i| bvs[offset][1] = values[i] }
-
22
bvs
-
end
-
end
-
-
1
attr_reader :bind_map, :query_builder
-
-
1
def self.create(connection, block = Proc.new)
-
4
relation = block.call Params.new
-
4
bind_map = BindMap.new relation.bind_values
-
4
query_builder = connection.cacheable_query relation.arel
-
4
new query_builder, bind_map
-
end
-
-
1
def initialize(query_builder, bind_map)
-
4
@query_builder = query_builder
-
4
@bind_map = bind_map
-
end
-
-
1
def execute(params, klass, connection)
-
22
bind_values = bind_map.bind params
-
-
22
sql = query_builder.sql_for bind_values, connection
-
-
22
klass.find_by_sql sql, bind_values
-
end
-
1
alias :call :execute
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActiveRecord
-
# Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column.
-
# It's like a simple key/value store baked into your record when you don't care about being able to
-
# query that store outside the context of a single record.
-
#
-
# You can then declare accessors to this store that are then accessible just like any other attribute
-
# of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's
-
# already built around just accessing attributes on the model.
-
#
-
# Make sure that you declare the database column used for the serialized store as a text, so there's
-
# plenty of room.
-
#
-
# You can set custom coder to encode/decode your serialized attributes to/from different formats.
-
# JSON, YAML, Marshal are supported out of the box. Generally it can be any wrapper that provides +load+ and +dump+.
-
#
-
# NOTE - If you are using PostgreSQL specific columns like +hstore+ or +json+ there is no need for
-
# the serialization provided by +store+. Simply use +store_accessor+ instead to generate
-
# the accessor methods. Be aware that these columns use a string keyed hash and do not allow access
-
# using a symbol.
-
#
-
# Examples:
-
#
-
# class User < ActiveRecord::Base
-
# store :settings, accessors: [ :color, :homepage ], coder: JSON
-
# end
-
#
-
# u = User.new(color: 'black', homepage: '37signals.com')
-
# u.color # Accessor stored attribute
-
# u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
-
#
-
# # There is no difference between strings and symbols for accessing custom attributes
-
# u.settings[:country] # => 'Denmark'
-
# u.settings['country'] # => 'Denmark'
-
#
-
# # Add additional accessors to an existing store through store_accessor
-
# class SuperUser < User
-
# store_accessor :settings, :privileges, :servants
-
# end
-
#
-
# The stored attribute names can be retrieved using +stored_attributes+.
-
#
-
# User.stored_attributes[:settings] # [:color, :homepage]
-
#
-
# == Overwriting default accessors
-
#
-
# All stored values are automatically available through accessors on the Active Record
-
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
-
# the default accessors (using the same name as the attribute) and calling <tt>super</tt>
-
# to actually change things.
-
#
-
# class Song < ActiveRecord::Base
-
# # Uses a stored integer to hold the volume adjustment of the song
-
# store :settings, accessors: [:volume_adjustment]
-
#
-
# def volume_adjustment=(decibels)
-
# super(decibels.to_i)
-
# end
-
#
-
# def volume_adjustment
-
# super.to_i
-
# end
-
# end
-
1
module Store
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class << self
-
1
attr_accessor :local_stored_attributes
-
end
-
end
-
-
1
module ClassMethods
-
1
def store(store_attribute, options = {})
-
serialize store_attribute, IndifferentCoder.new(options[:coder])
-
store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
-
end
-
-
1
def store_accessor(store_attribute, *keys)
-
keys = keys.flatten
-
-
_store_accessors_module.module_eval do
-
keys.each do |key|
-
define_method("#{key}=") do |value|
-
write_store_attribute(store_attribute, key, value)
-
end
-
-
define_method(key) do
-
read_store_attribute(store_attribute, key)
-
end
-
end
-
end
-
-
# assign new store attribute and create new hash to ensure that each class in the hierarchy
-
# has its own hash of stored attributes.
-
self.local_stored_attributes ||= {}
-
self.local_stored_attributes[store_attribute] ||= []
-
self.local_stored_attributes[store_attribute] |= keys
-
end
-
-
1
def _store_accessors_module # :nodoc:
-
@_store_accessors_module ||= begin
-
mod = Module.new
-
include mod
-
mod
-
end
-
end
-
-
1
def stored_attributes
-
parent = superclass.respond_to?(:stored_attributes) ? superclass.stored_attributes : {}
-
if self.local_stored_attributes
-
parent.merge!(self.local_stored_attributes) { |k, a, b| a | b }
-
end
-
parent
-
end
-
end
-
-
1
protected
-
1
def read_store_attribute(store_attribute, key)
-
accessor = store_accessor_for(store_attribute)
-
accessor.read(self, store_attribute, key)
-
end
-
-
1
def write_store_attribute(store_attribute, key, value)
-
accessor = store_accessor_for(store_attribute)
-
accessor.write(self, store_attribute, key, value)
-
end
-
-
1
private
-
1
def store_accessor_for(store_attribute)
-
type_for_attribute(store_attribute.to_s).accessor
-
end
-
-
1
class HashAccessor # :nodoc:
-
1
def self.read(object, attribute, key)
-
prepare(object, attribute)
-
object.public_send(attribute)[key]
-
end
-
-
1
def self.write(object, attribute, key, value)
-
prepare(object, attribute)
-
if value != read(object, attribute, key)
-
object.public_send :"#{attribute}_will_change!"
-
object.public_send(attribute)[key] = value
-
end
-
end
-
-
1
def self.prepare(object, attribute)
-
object.public_send :"#{attribute}=", {} unless object.send(attribute)
-
end
-
end
-
-
1
class StringKeyedHashAccessor < HashAccessor # :nodoc:
-
1
def self.read(object, attribute, key)
-
super object, attribute, key.to_s
-
end
-
-
1
def self.write(object, attribute, key, value)
-
super object, attribute, key.to_s, value
-
end
-
end
-
-
1
class IndifferentHashAccessor < ActiveRecord::Store::HashAccessor # :nodoc:
-
1
def self.prepare(object, store_attribute)
-
attribute = object.send(store_attribute)
-
unless attribute.is_a?(ActiveSupport::HashWithIndifferentAccess)
-
attribute = IndifferentCoder.as_indifferent_hash(attribute)
-
object.send :"#{store_attribute}=", attribute
-
end
-
attribute
-
end
-
end
-
-
1
class IndifferentCoder # :nodoc:
-
1
def initialize(coder_or_class_name)
-
@coder =
-
if coder_or_class_name.respond_to?(:load) && coder_or_class_name.respond_to?(:dump)
-
coder_or_class_name
-
else
-
ActiveRecord::Coders::YAMLColumn.new(coder_or_class_name || Object)
-
end
-
end
-
-
1
def dump(obj)
-
@coder.dump self.class.as_indifferent_hash(obj)
-
end
-
-
1
def load(yaml)
-
self.class.as_indifferent_hash(@coder.load(yaml || ''))
-
end
-
-
1
def self.as_indifferent_hash(obj)
-
case obj
-
when ActiveSupport::HashWithIndifferentAccess
-
obj
-
when Hash
-
obj.with_indifferent_access
-
else
-
ActiveSupport::HashWithIndifferentAccess.new
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# See ActiveRecord::Transactions::ClassMethods for documentation.
-
1
module Transactions
-
1
extend ActiveSupport::Concern
-
#:nodoc:
-
1
ACTIONS = [:create, :destroy, :update]
-
#:nodoc:
-
1
CALLBACK_WARN_MESSAGE = "Currently, Active Record suppresses errors raised " \
-
"within `after_rollback`/`after_commit` callbacks and only print them to " \
-
"the logs. In the next version, these errors will no longer be suppressed. " \
-
"Instead, the errors will propagate normally just like in other Active " \
-
"Record callbacks.\n" \
-
"\n" \
-
"You can opt into the new behavior and remove this warning by setting:\n" \
-
"\n" \
-
" config.active_record.raise_in_transactional_callbacks = true\n\n"
-
-
1
included do
-
1
define_callbacks :commit, :rollback,
-
terminator: ->(_, result) { result == false },
-
scope: [:kind, :name]
-
-
1
mattr_accessor :raise_in_transactional_callbacks, instance_writer: false
-
1
self.raise_in_transactional_callbacks = false
-
end
-
-
# = Active Record Transactions
-
#
-
# Transactions are protective blocks where SQL statements are only permanent
-
# if they can all succeed as one atomic action. The classic example is a
-
# transfer between two accounts where you can only have a deposit if the
-
# withdrawal succeeded and vice versa. Transactions enforce the integrity of
-
# the database and guard the data against program errors or database
-
# break-downs. So basically you should use transaction blocks whenever you
-
# have a number of statements that must be executed together or not at all.
-
#
-
# For example:
-
#
-
# ActiveRecord::Base.transaction do
-
# david.withdrawal(100)
-
# mary.deposit(100)
-
# end
-
#
-
# This example will only take money from David and give it to Mary if neither
-
# +withdrawal+ nor +deposit+ raise an exception. Exceptions will force a
-
# ROLLBACK that returns the database to the state before the transaction
-
# began. Be aware, though, that the objects will _not_ have their instance
-
# data returned to their pre-transactional state.
-
#
-
# == Different Active Record classes in a single transaction
-
#
-
# Though the transaction class method is called on some Active Record class,
-
# the objects within the transaction block need not all be instances of
-
# that class. This is because transactions are per-database connection, not
-
# per-model.
-
#
-
# In this example a +balance+ record is transactionally saved even
-
# though +transaction+ is called on the +Account+ class:
-
#
-
# Account.transaction do
-
# balance.save!
-
# account.save!
-
# end
-
#
-
# The +transaction+ method is also available as a model instance method.
-
# For example, you can also do this:
-
#
-
# balance.transaction do
-
# balance.save!
-
# account.save!
-
# end
-
#
-
# == Transactions are not distributed across database connections
-
#
-
# A transaction acts on a single database connection. If you have
-
# multiple class-specific databases, the transaction will not protect
-
# interaction among them. One workaround is to begin a transaction
-
# on each class whose models you alter:
-
#
-
# Student.transaction do
-
# Course.transaction do
-
# course.enroll(student)
-
# student.units += course.units
-
# end
-
# end
-
#
-
# This is a poor solution, but fully distributed transactions are beyond
-
# the scope of Active Record.
-
#
-
# == +save+ and +destroy+ are automatically wrapped in a transaction
-
#
-
# Both +save+ and +destroy+ come wrapped in a transaction that ensures
-
# that whatever you do in validations or callbacks will happen under its
-
# protected cover. So you can use validations to check for values that
-
# the transaction depends on or you can raise exceptions in the callbacks
-
# to rollback, including <tt>after_*</tt> callbacks.
-
#
-
# As a consequence changes to the database are not seen outside your connection
-
# until the operation is complete. For example, if you try to update the index
-
# of a search engine in +after_save+ the indexer won't see the updated record.
-
# The +after_commit+ callback is the only one that is triggered once the update
-
# is committed. See below.
-
#
-
# == Exception handling and rolling back
-
#
-
# Also have in mind that exceptions thrown within a transaction block will
-
# be propagated (after triggering the ROLLBACK), so you should be ready to
-
# catch those in your application code.
-
#
-
# One exception is the <tt>ActiveRecord::Rollback</tt> exception, which will trigger
-
# a ROLLBACK when raised, but not be re-raised by the transaction block.
-
#
-
# *Warning*: one should not catch <tt>ActiveRecord::StatementInvalid</tt> exceptions
-
# inside a transaction block. <tt>ActiveRecord::StatementInvalid</tt> exceptions indicate that an
-
# error occurred at the database level, for example when a unique constraint
-
# is violated. On some database systems, such as PostgreSQL, database errors
-
# inside a transaction cause the entire transaction to become unusable
-
# until it's restarted from the beginning. Here is an example which
-
# demonstrates the problem:
-
#
-
# # Suppose that we have a Number model with a unique column called 'i'.
-
# Number.transaction do
-
# Number.create(i: 0)
-
# begin
-
# # This will raise a unique constraint error...
-
# Number.create(i: 0)
-
# rescue ActiveRecord::StatementInvalid
-
# # ...which we ignore.
-
# end
-
#
-
# # On PostgreSQL, the transaction is now unusable. The following
-
# # statement will cause a PostgreSQL error, even though the unique
-
# # constraint is no longer violated:
-
# Number.create(i: 1)
-
# # => "PGError: ERROR: current transaction is aborted, commands
-
# # ignored until end of transaction block"
-
# end
-
#
-
# One should restart the entire transaction if an
-
# <tt>ActiveRecord::StatementInvalid</tt> occurred.
-
#
-
# == Nested transactions
-
#
-
# +transaction+ calls can be nested. By default, this makes all database
-
# statements in the nested transaction block become part of the parent
-
# transaction. For example, the following behavior may be surprising:
-
#
-
# User.transaction do
-
# User.create(username: 'Kotori')
-
# User.transaction do
-
# User.create(username: 'Nemu')
-
# raise ActiveRecord::Rollback
-
# end
-
# end
-
#
-
# creates both "Kotori" and "Nemu". Reason is the <tt>ActiveRecord::Rollback</tt>
-
# exception in the nested block does not issue a ROLLBACK. Since these exceptions
-
# are captured in transaction blocks, the parent block does not see it and the
-
# real transaction is committed.
-
#
-
# In order to get a ROLLBACK for the nested transaction you may ask for a real
-
# sub-transaction by passing <tt>requires_new: true</tt>. If anything goes wrong,
-
# the database rolls back to the beginning of the sub-transaction without rolling
-
# back the parent transaction. If we add it to the previous example:
-
#
-
# User.transaction do
-
# User.create(username: 'Kotori')
-
# User.transaction(requires_new: true) do
-
# User.create(username: 'Nemu')
-
# raise ActiveRecord::Rollback
-
# end
-
# end
-
#
-
# only "Kotori" is created. This works on MySQL and PostgreSQL. SQLite3 version >= '3.6.8' also supports it.
-
#
-
# Most databases don't support true nested transactions. At the time of
-
# writing, the only database that we're aware of that supports true nested
-
# transactions, is MS-SQL. Because of this, Active Record emulates nested
-
# transactions by using savepoints on MySQL and PostgreSQL. See
-
# http://dev.mysql.com/doc/refman/5.6/en/savepoint.html
-
# for more information about savepoints.
-
#
-
# === Callbacks
-
#
-
# There are two types of callbacks associated with committing and rolling back transactions:
-
# +after_commit+ and +after_rollback+.
-
#
-
# +after_commit+ callbacks are called on every record saved or destroyed within a
-
# transaction immediately after the transaction is committed. +after_rollback+ callbacks
-
# are called on every record saved or destroyed within a transaction immediately after the
-
# transaction or savepoint is rolled back.
-
#
-
# These callbacks are useful for interacting with other systems since you will be guaranteed
-
# that the callback is only executed when the database is in a permanent state. For example,
-
# +after_commit+ is a good spot to put in a hook to clearing a cache since clearing it from
-
# within a transaction could trigger the cache to be regenerated before the database is updated.
-
#
-
# === Caveats
-
#
-
# If you're on MySQL, then do not use DDL operations in nested transactions
-
# blocks that are emulated with savepoints. That is, do not execute statements
-
# like 'CREATE TABLE' inside such blocks. This is because MySQL automatically
-
# releases all savepoints upon executing a DDL operation. When +transaction+
-
# is finished and tries to release the savepoint it created earlier, a
-
# database error will occur because the savepoint has already been
-
# automatically released. The following example demonstrates the problem:
-
#
-
# Model.connection.transaction do # BEGIN
-
# Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
-
# Model.connection.create_table(...) # active_record_1 now automatically released
-
# end # RELEASE savepoint active_record_1
-
# # ^^^^ BOOM! database error!
-
# end
-
#
-
# Note that "TRUNCATE" is also a MySQL DDL statement!
-
1
module ClassMethods
-
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
-
1
def transaction(options = {}, &block)
-
# See the ConnectionAdapters::DatabaseStatements#transaction API docs.
-
36
connection.transaction(options, &block)
-
end
-
-
# This callback is called after a record has been created, updated, or destroyed.
-
#
-
# You can specify that the callback should only be fired by a certain action with
-
# the +:on+ option:
-
#
-
# after_commit :do_foo, on: :create
-
# after_commit :do_bar, on: :update
-
# after_commit :do_baz, on: :destroy
-
#
-
# after_commit :do_foo_bar, on: [:create, :update]
-
# after_commit :do_bar_baz, on: [:update, :destroy]
-
#
-
# Note that transactional fixtures do not play well with this feature. Please
-
# use the +test_after_commit+ gem to have these hooks fired in tests.
-
1
def after_commit(*args, &block)
-
set_options_for_callbacks!(args)
-
set_callback(:commit, :after, *args, &block)
-
unless ActiveRecord::Base.raise_in_transactional_callbacks
-
ActiveSupport::Deprecation.warn(CALLBACK_WARN_MESSAGE)
-
end
-
end
-
-
# This callback is called after a create, update, or destroy are rolled back.
-
#
-
# Please check the documentation of +after_commit+ for options.
-
1
def after_rollback(*args, &block)
-
set_options_for_callbacks!(args)
-
set_callback(:rollback, :after, *args, &block)
-
unless ActiveRecord::Base.raise_in_transactional_callbacks
-
ActiveSupport::Deprecation.warn(CALLBACK_WARN_MESSAGE)
-
end
-
end
-
-
1
private
-
-
1
def set_options_for_callbacks!(args)
-
options = args.last
-
if options.is_a?(Hash) && options[:on]
-
fire_on = Array(options[:on])
-
assert_valid_transaction_action(fire_on)
-
options[:if] = Array(options[:if])
-
options[:if] << "transaction_include_any_action?(#{fire_on})"
-
end
-
end
-
-
1
def assert_valid_transaction_action(actions)
-
if (actions - ACTIONS).any?
-
raise ArgumentError, ":on conditions for after_commit and after_rollback callbacks have to be one of #{ACTIONS}"
-
end
-
end
-
end
-
-
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
-
1
def transaction(options = {}, &block)
-
self.class.transaction(options, &block)
-
end
-
-
1
def destroy #:nodoc:
-
6
with_transaction_returning_status { super }
-
end
-
-
1
def save(*) #:nodoc:
-
6
rollback_active_record_state! do
-
12
with_transaction_returning_status { super }
-
end
-
end
-
-
1
def save!(*) #:nodoc:
-
46
with_transaction_returning_status { super }
-
end
-
-
1
def touch(*) #:nodoc:
-
with_transaction_returning_status { super }
-
end
-
-
# Reset id and @new_record if the transaction rolls back.
-
1
def rollback_active_record_state!
-
6
remember_transaction_record_state
-
6
yield
-
rescue Exception
-
restore_transaction_record_state
-
raise
-
ensure
-
6
clear_transaction_record_state
-
end
-
-
# Call the +after_commit+ callbacks.
-
#
-
# Ensure that it is not called if the object was never persisted (failed create),
-
# but call it after the commit of a destroyed object.
-
1
def committed!(should_run_callbacks = true) #:nodoc:
-
_run_commit_callbacks if should_run_callbacks && destroyed? || persisted?
-
ensure
-
force_clear_transaction_record_state
-
end
-
-
# Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record
-
# state should be rolled back to the beginning or just to the last savepoint.
-
1
def rolledback!(force_restore_state = false, should_run_callbacks = true) #:nodoc:
-
3
_run_rollback_callbacks if should_run_callbacks
-
ensure
-
3
restore_transaction_record_state(force_restore_state)
-
3
clear_transaction_record_state
-
end
-
-
# Add the record to the current transaction so that the +after_rollback+ and +after_commit+ callbacks
-
# can be called.
-
1
def add_to_transaction
-
36
if has_transactional_callbacks?
-
self.class.connection.add_transaction_record(self)
-
else
-
36
sync_with_transaction_state
-
36
set_transaction_state(self.class.connection.transaction_state)
-
end
-
36
remember_transaction_record_state
-
end
-
-
# Executes +method+ within a transaction and captures its return value as a
-
# status flag. If the status is true the transaction is committed, otherwise
-
# a ROLLBACK is issued. In any case the status flag is returned.
-
#
-
# This method is available within the context of an ActiveRecord::Base
-
# instance.
-
1
def with_transaction_returning_status
-
36
status = nil
-
36
self.class.transaction do
-
36
add_to_transaction
-
36
begin
-
36
status = yield
-
rescue ActiveRecord::Rollback
-
clear_transaction_record_state
-
status = nil
-
end
-
-
36
raise ActiveRecord::Rollback unless status
-
end
-
36
status
-
ensure
-
36
if @transaction_state && @transaction_state.committed?
-
32
clear_transaction_record_state
-
end
-
end
-
-
1
protected
-
-
# Save the new record state and id of a record so it can be restored later if a transaction fails.
-
1
def remember_transaction_record_state #:nodoc:
-
42
@_start_transaction_state[:id] = id
-
42
@_start_transaction_state.reverse_merge!(
-
new_record: @new_record,
-
destroyed: @destroyed,
-
frozen?: frozen?,
-
)
-
42
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
-
end
-
-
# Clear the new record state and id of a record.
-
1
def clear_transaction_record_state #:nodoc:
-
55
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
-
55
force_clear_transaction_record_state if @_start_transaction_state[:level] < 1
-
end
-
-
# Force to clear the transaction record state.
-
1
def force_clear_transaction_record_state #:nodoc:
-
45
@_start_transaction_state.clear
-
end
-
-
# Restore the new record state and id of a record that was previously saved by a call to save_record_state.
-
1
def restore_transaction_record_state(force = false) #:nodoc:
-
3
unless @_start_transaction_state.empty?
-
transaction_level = (@_start_transaction_state[:level] || 0) - 1
-
if transaction_level < 1 || force
-
restore_state = @_start_transaction_state
-
thaw
-
@new_record = restore_state[:new_record]
-
@destroyed = restore_state[:destroyed]
-
pk = self.class.primary_key
-
if pk && read_attribute(pk) != restore_state[:id]
-
write_attribute(pk, restore_state[:id])
-
end
-
freeze if restore_state[:frozen?]
-
end
-
end
-
end
-
-
# Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed.
-
1
def transaction_record_state(state) #:nodoc:
-
@_start_transaction_state[state]
-
end
-
-
# Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks.
-
1
def transaction_include_any_action?(actions) #:nodoc:
-
actions.any? do |action|
-
case action
-
when :create
-
transaction_record_state(:new_record)
-
when :destroy
-
destroyed?
-
when :update
-
!(transaction_record_state(:new_record) || destroyed?)
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Translation
-
1
include ActiveModel::Translation
-
-
# Set the lookup ancestors for ActiveModel.
-
1
def lookup_ancestors #:nodoc:
-
8
klass = self
-
8
classes = [klass]
-
8
return classes if klass == ActiveRecord::Base
-
-
8
while klass != klass.base_class
-
classes << klass = klass.superclass
-
end
-
8
classes
-
end
-
-
# Set the i18n scope to overwrite ActiveModel.
-
1
def i18n_scope #:nodoc:
-
8
:activerecord
-
end
-
end
-
end
-
1
require 'active_record/type/decorator'
-
1
require 'active_record/type/mutable'
-
1
require 'active_record/type/numeric'
-
1
require 'active_record/type/time_value'
-
1
require 'active_record/type/value'
-
-
1
require 'active_record/type/big_integer'
-
1
require 'active_record/type/binary'
-
1
require 'active_record/type/boolean'
-
1
require 'active_record/type/date'
-
1
require 'active_record/type/date_time'
-
1
require 'active_record/type/decimal'
-
1
require 'active_record/type/decimal_without_scale'
-
1
require 'active_record/type/float'
-
1
require 'active_record/type/integer'
-
1
require 'active_record/type/serialized'
-
1
require 'active_record/type/string'
-
1
require 'active_record/type/text'
-
1
require 'active_record/type/time'
-
1
require 'active_record/type/unsigned_integer'
-
-
1
require 'active_record/type/type_map'
-
1
require 'active_record/type/hash_lookup_type_map'
-
1
require 'active_record/type/integer'
-
-
1
module ActiveRecord
-
1
module Type
-
1
class BigInteger < Integer # :nodoc:
-
1
private
-
-
1
def max_value
-
::Float::INFINITY
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class Binary < Value # :nodoc:
-
1
def type
-
:binary
-
end
-
-
1
def binary?
-
true
-
end
-
-
1
def type_cast(value)
-
if value.is_a?(Data)
-
value.to_s
-
else
-
super
-
end
-
end
-
-
1
def type_cast_for_database(value)
-
return if value.nil?
-
Data.new(super)
-
end
-
-
1
def changed_in_place?(raw_old_value, value)
-
old_value = type_cast_from_database(raw_old_value)
-
old_value != value
-
end
-
-
1
class Data # :nodoc:
-
1
def initialize(value)
-
@value = value.to_s
-
end
-
-
1
def to_s
-
@value
-
end
-
1
alias_method :to_str, :to_s
-
-
1
def hex
-
@value.unpack('H*')[0]
-
end
-
-
1
def ==(other)
-
other == to_s || super
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class Boolean < Value # :nodoc:
-
1
def type
-
:boolean
-
end
-
-
1
private
-
-
1
def cast_value(value)
-
if value == ''
-
nil
-
elsif ConnectionAdapters::Column::TRUE_VALUES.include?(value)
-
true
-
else
-
if !ConnectionAdapters::Column::FALSE_VALUES.include?(value)
-
ActiveSupport::Deprecation.warn(<<-MSG.squish)
-
You attempted to assign a value which is not explicitly `true` or `false`
-
(#{value.inspect})
-
to a boolean column. Currently this value casts to `false`. This will
-
change to match Ruby's semantics, and will cast to `true` in Rails 5.
-
If you would like to maintain the current behavior, you should
-
explicitly handle the values you would like cast to `false`.
-
MSG
-
end
-
false
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class Date < Value # :nodoc:
-
1
def type
-
2
:date
-
end
-
-
1
def klass
-
2
::Date
-
end
-
-
1
def type_cast_for_schema(value)
-
"'#{value.to_s(:db)}'"
-
end
-
-
1
private
-
-
1
def cast_value(value)
-
17
if value.is_a?(::String)
-
15
return if value.empty?
-
15
fast_string_to_date(value) || fallback_string_to_date(value)
-
2
elsif value.respond_to?(:to_date)
-
2
value.to_date
-
else
-
value
-
end
-
end
-
-
1
def fast_string_to_date(string)
-
15
if string =~ ConnectionAdapters::Column::Format::ISO_DATE
-
10
new_date $1.to_i, $2.to_i, $3.to_i
-
end
-
end
-
-
1
def fallback_string_to_date(string)
-
5
new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))
-
end
-
-
1
def new_date(year, mon, mday)
-
15
if year && year != 0
-
15
::Date.new(year, mon, mday) rescue nil
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class DateTime < Value # :nodoc:
-
1
include TimeValue
-
-
1
def type
-
8
:datetime
-
end
-
-
1
def type_cast_for_database(value)
-
166
return super unless value.acts_like?(:time)
-
-
166
zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
-
-
166
if value.respond_to?(zone_conversion_method)
-
166
value = value.send(zone_conversion_method)
-
end
-
-
166
return value unless has_precision?
-
-
result = value.to_s(:db)
-
if value.respond_to?(:usec) && (1..6).cover?(precision)
-
"#{result}.#{sprintf("%0#{precision}d", value.usec / 10 ** (6 - precision))}"
-
else
-
result
-
end
-
end
-
-
1
private
-
-
1
alias has_precision? precision
-
-
1
def cast_value(string)
-
8
return string unless string.is_a?(::String)
-
8
return if string.empty?
-
-
8
fast_string_to_time(string) || fallback_string_to_time(string)
-
end
-
-
# '0.123456' -> 123456
-
# '1.123456' -> 123456
-
1
def microseconds(time)
-
time[:sec_fraction] ? (time[:sec_fraction] * 1_000_000).to_i : 0
-
end
-
-
1
def fallback_string_to_time(string)
-
time_hash = ::Date._parse(string)
-
time_hash[:sec_fraction] = microseconds(time_hash)
-
-
new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset))
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class Decimal < Value # :nodoc:
-
1
include Numeric
-
-
1
def type
-
:decimal
-
end
-
-
1
def type_cast_for_schema(value)
-
value.to_s
-
end
-
-
1
private
-
-
1
def cast_value(value)
-
casted_value = case value
-
when ::Float
-
convert_float_to_big_decimal(value)
-
when ::Numeric, ::String
-
BigDecimal(value, precision.to_i)
-
else
-
if value.respond_to?(:to_d)
-
value.to_d
-
else
-
cast_value(value.to_s)
-
end
-
end
-
-
scale ? casted_value.round(scale) : casted_value
-
end
-
-
1
def convert_float_to_big_decimal(value)
-
if precision
-
BigDecimal(value, float_precision)
-
else
-
value.to_d
-
end
-
end
-
-
1
def float_precision
-
if precision.to_i > ::Float::DIG + 1
-
::Float::DIG + 1
-
else
-
precision.to_i
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_record/type/big_integer'
-
-
1
module ActiveRecord
-
1
module Type
-
1
class DecimalWithoutScale < BigInteger # :nodoc:
-
1
def type
-
:decimal
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
module Decorator # :nodoc:
-
1
def init_with(coder)
-
@subtype = coder['subtype']
-
__setobj__(@subtype)
-
end
-
-
1
def encode_with(coder)
-
coder['subtype'] = __getobj__
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class Float < Value # :nodoc:
-
1
include Numeric
-
-
1
def type
-
:float
-
end
-
-
1
alias type_cast_for_database type_cast
-
-
1
private
-
-
1
def cast_value(value)
-
value.to_f
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class HashLookupTypeMap < TypeMap # :nodoc:
-
1
def alias_type(type, alias_type)
-
register_type(type) { |_, *args| lookup(alias_type, *args) }
-
end
-
-
1
def key?(key)
-
@mapping.key?(key)
-
end
-
-
1
def keys
-
@mapping.keys
-
end
-
-
1
private
-
-
1
def perform_fetch(type, *args, &block)
-
@mapping.fetch(type, block).call(type, *args)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class Integer < Value # :nodoc:
-
1
include Numeric
-
-
1
def initialize(*)
-
2
super
-
2
@range = min_value...max_value
-
end
-
-
1
def type
-
7
:integer
-
end
-
-
1
def type_cast_from_database(value)
-
118
return if value.nil?
-
68
value.to_i
-
end
-
-
1
def type_cast_for_database(value)
-
130
result = type_cast(value)
-
130
if result
-
123
ensure_in_range(result)
-
end
-
130
result
-
end
-
-
1
protected
-
-
1
attr_reader :range
-
-
1
private
-
-
1
def cast_value(value)
-
162
case value
-
when true then 1
-
when false then 0
-
else
-
162
value.to_i rescue nil
-
end
-
end
-
-
1
def ensure_in_range(value)
-
123
unless range.cover?(value)
-
raise RangeError, "#{value} is out of range for #{self.class} with limit #{limit || 4}"
-
end
-
end
-
-
1
def max_value
-
4
limit = self.limit || 4
-
4
1 << (limit * 8 - 1) # 8 bits per byte with one bit for sign
-
end
-
-
1
def min_value
-
2
-max_value
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
module Mutable # :nodoc:
-
1
def type_cast_from_user(value)
-
type_cast_from_database(type_cast_for_database(value))
-
end
-
-
# +raw_old_value+ will be the `_before_type_cast` version of the
-
# value (likely a string). +new_value+ will be the current, type
-
# cast value.
-
1
def changed_in_place?(raw_old_value, new_value)
-
raw_old_value != type_cast_for_database(new_value)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
module Numeric # :nodoc:
-
1
def number?
-
true
-
end
-
-
1
def type_cast(value)
-
169
value = case value
-
when true then 1
-
when false then 0
-
36
when ::String then value.presence
-
133
else value
-
end
-
169
super(value)
-
end
-
-
1
def changed?(old_value, _new_value, new_value_before_type_cast) # :nodoc:
-
39
super || number_to_non_number?(old_value, new_value_before_type_cast)
-
end
-
-
1
private
-
-
1
def number_to_non_number?(old_value, new_value_before_type_cast)
-
2
old_value != nil && non_numeric_string?(new_value_before_type_cast)
-
end
-
-
1
def non_numeric_string?(value)
-
# 'wibble'.to_i will give zero, we want to make sure
-
# that we aren't marking int zero to string zero as
-
# changed.
-
2
value.to_s !~ /\A-?\d+\.?\d*\z/
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class Serialized < DelegateClass(Type::Value) # :nodoc:
-
1
include Mutable
-
1
include Decorator
-
-
1
attr_reader :subtype, :coder
-
-
1
def initialize(subtype, coder)
-
@subtype = subtype
-
@coder = coder
-
super(subtype)
-
end
-
-
1
def type_cast_from_database(value)
-
if default_value?(value)
-
value
-
else
-
coder.load(super)
-
end
-
end
-
-
1
def type_cast_for_database(value)
-
return if value.nil?
-
unless default_value?(value)
-
super coder.dump(value)
-
end
-
end
-
-
1
def inspect
-
Kernel.instance_method(:inspect).bind(self).call
-
end
-
-
1
def changed_in_place?(raw_old_value, value)
-
return false if value.nil?
-
raw_new_value = type_cast_for_database(value)
-
raw_old_value.nil? != raw_new_value.nil? ||
-
subtype.changed_in_place?(raw_old_value, raw_new_value)
-
end
-
-
1
def accessor
-
ActiveRecord::Store::IndifferentHashAccessor
-
end
-
-
1
def init_with(coder)
-
@coder = coder['coder']
-
super
-
end
-
-
1
def encode_with(coder)
-
coder['coder'] = @coder
-
super
-
end
-
-
1
private
-
-
1
def default_value?(value)
-
value == coder.load(nil)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class String < Value # :nodoc:
-
1
def type
-
11
:string
-
end
-
-
1
def changed_in_place?(raw_old_value, new_value)
-
154
if new_value.is_a?(::String)
-
154
raw_old_value != new_value
-
end
-
end
-
-
1
def type_cast_for_database(value)
-
211
case value
-
when ::Numeric, ActiveSupport::Duration then value.to_s
-
211
when ::String then ::String.new(value)
-
when true then "t"
-
when false then "f"
-
else super
-
end
-
end
-
-
1
def text?
-
true
-
end
-
-
1
private
-
-
1
def cast_value(value)
-
188
case value
-
when true then "t"
-
when false then "f"
-
# String.new is slightly faster than dup
-
188
else ::String.new(value.to_s)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_record/type/string'
-
-
1
module ActiveRecord
-
1
module Type
-
1
class Text < String # :nodoc:
-
1
def type
-
:text
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class Time < Value # :nodoc:
-
1
include TimeValue
-
-
1
def type
-
:time
-
end
-
-
1
private
-
-
1
def cast_value(value)
-
return value unless value.is_a?(::String)
-
return if value.empty?
-
-
dummy_time_value = "2000-01-01 #{value}"
-
-
fast_string_to_time(dummy_time_value) || begin
-
time_hash = ::Date._parse(dummy_time_value)
-
return if time_hash[:hour].nil?
-
new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
module TimeValue # :nodoc:
-
1
def klass
-
::Time
-
end
-
-
1
def type_cast_for_schema(value)
-
"'#{value.to_s(:db)}'"
-
end
-
-
1
private
-
-
1
def new_time(year, mon, mday, hour, min, sec, microsec, offset = nil)
-
# Treat 0000-00-00 00:00:00 as nil.
-
8
return if year.nil? || (year == 0 && mon == 0 && mday == 0)
-
-
8
if offset
-
time = ::Time.utc(year, mon, mday, hour, min, sec, microsec) rescue nil
-
return unless time
-
-
time -= offset
-
Base.default_timezone == :utc ? time : time.getlocal
-
else
-
8
::Time.public_send(Base.default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil
-
end
-
end
-
-
# Doesn't handle time zones.
-
1
def fast_string_to_time(string)
-
8
if string =~ ConnectionAdapters::Column::Format::ISO_DATETIME
-
8
microsec = ($7.to_r * 1_000_000).to_i
-
8
new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
-
end
-
end
-
end
-
end
-
end
-
1
require 'thread_safe'
-
-
1
module ActiveRecord
-
1
module Type
-
1
class TypeMap # :nodoc:
-
1
def initialize
-
1
@mapping = {}
-
1
@cache = ThreadSafe::Cache.new do |h, key|
-
5
h.fetch_or_store(key, ThreadSafe::Cache.new)
-
end
-
end
-
-
1
def lookup(lookup_key, *args)
-
28
fetch(lookup_key, *args) { default_value }
-
end
-
-
1
def fetch(lookup_key, *args, &block)
-
28
@cache[lookup_key].fetch_or_store(args) do
-
5
perform_fetch(lookup_key, *args, &block)
-
end
-
end
-
-
1
def register_type(key, value = nil, &block)
-
17
raise ::ArgumentError unless value || block
-
17
@cache.clear
-
-
17
if block
-
16
@mapping[key] = block
-
else
-
1
@mapping[key] = proc { value }
-
end
-
end
-
-
1
def alias_type(key, target_key)
-
6
register_type(key) do |sql_type, *args|
-
metadata = sql_type[/\(.*\)/, 0]
-
lookup("#{target_key}#{metadata}", *args)
-
end
-
end
-
-
1
def clear
-
@mapping.clear
-
end
-
-
1
private
-
-
1
def perform_fetch(lookup_key, *args)
-
5
matching_pair = @mapping.reverse_each.detect do |key, _|
-
53
key === lookup_key
-
end
-
-
5
if matching_pair
-
5
matching_pair.last.call(lookup_key, *args)
-
else
-
yield lookup_key, *args
-
end
-
end
-
-
1
def default_value
-
@default_value ||= Value.new
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class UnsignedInteger < Integer # :nodoc:
-
1
private
-
-
1
def max_value
-
super * 2
-
end
-
-
1
def min_value
-
0
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Type
-
1
class Value # :nodoc:
-
1
attr_reader :precision, :scale, :limit
-
-
# Valid options are +precision+, +scale+, and +limit+. They are only
-
# used when dumping schema.
-
1
def initialize(options = {})
-
12
options.assert_valid_keys(:precision, :scale, :limit)
-
12
@precision = options[:precision]
-
12
@scale = options[:scale]
-
12
@limit = options[:limit]
-
end
-
-
# The simplified type that this object represents. Returns a symbol such
-
# as +:string+ or +:integer+
-
1
def type; end
-
-
# Type casts a string from the database into the appropriate ruby type.
-
# Classes which do not need separate type casting behavior for database
-
# and user provided values should override +cast_value+ instead.
-
1
def type_cast_from_database(value)
-
270
type_cast(value)
-
end
-
-
# Type casts a value from user input (e.g. from a setter). This value may
-
# be a string from the form builder, or an already type cast value
-
# provided manually to a setter.
-
#
-
# Classes which do not need separate type casting behavior for database
-
# and user provided values should override +type_cast+ or +cast_value+
-
# instead.
-
1
def type_cast_from_user(value)
-
118
type_cast(value)
-
end
-
-
# Cast a value from the ruby type to a type that the database knows how
-
# to understand. The returned value from this method should be a
-
# +String+, +Numeric+, +Date+, +Time+, +Symbol+, +true+, +false+, or
-
# +nil+
-
1
def type_cast_for_database(value)
-
27
value
-
end
-
-
# Type cast a value for schema dumping. This method is private, as we are
-
# hoping to remove it entirely.
-
1
def type_cast_for_schema(value) # :nodoc:
-
value.inspect
-
end
-
-
# These predicates are not documented, as I need to look further into
-
# their use, and see if they can be removed entirely.
-
1
def text? # :nodoc:
-
false
-
end
-
-
1
def number? # :nodoc:
-
false
-
end
-
-
1
def binary? # :nodoc:
-
168
false
-
end
-
-
1
def klass # :nodoc:
-
end
-
-
# Determines whether a value has changed for dirty checking. +old_value+
-
# and +new_value+ will always be type-cast. Types should not need to
-
# override this method.
-
1
def changed?(old_value, new_value, _new_value_before_type_cast)
-
172
old_value != new_value
-
end
-
-
# Determines whether the mutable value has been modified since it was
-
# read. Returns +false+ by default. This method should not be overridden
-
# directly. Types which return a mutable value should include
-
# +Type::Mutable+, which will define this method.
-
1
def changed_in_place?(*)
-
294
false
-
end
-
-
1
def ==(other)
-
self.class == other.class &&
-
precision == other.precision &&
-
scale == other.scale &&
-
limit == other.limit
-
end
-
-
1
private
-
-
1
def type_cast(value)
-
518
cast_value(value) unless value.nil?
-
end
-
-
# Convenience method for types which do not need separate type casting
-
# behavior for user and database inputs. Called by
-
# `type_cast_from_database` and `type_cast_from_user` for all values
-
# except `nil`.
-
1
def cast_value(value) # :doc:
-
value
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record RecordInvalid
-
#
-
# Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
-
# +record+ method to retrieve the record which did not validate.
-
#
-
# begin
-
# complex_operation_that_internally_calls_save!
-
# rescue ActiveRecord::RecordInvalid => invalid
-
# puts invalid.record.errors
-
# end
-
1
class RecordInvalid < ActiveRecordError
-
1
attr_reader :record
-
-
1
def initialize(record)
-
@record = record
-
errors = @record.errors.full_messages.join(", ")
-
super(I18n.t(:"#{@record.class.i18n_scope}.errors.messages.record_invalid", :errors => errors, :default => :"errors.messages.record_invalid"))
-
end
-
end
-
-
# = Active Record Validations
-
#
-
# Active Record includes the majority of its validations from <tt>ActiveModel::Validations</tt>
-
# all of which accept the <tt>:on</tt> argument to define the context where the
-
# validations are active. Active Record will always supply either the context of
-
# <tt>:create</tt> or <tt>:update</tt> dependent on whether the model is a
-
# <tt>new_record?</tt>.
-
1
module Validations
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Validations
-
-
# The validation process on save can be skipped by passing <tt>validate: false</tt>.
-
# The regular Base#save method is replaced with this when the validations
-
# module is mixed in, which it is by default.
-
1
def save(options={})
-
6
perform_validations(options) ? super : false
-
end
-
-
# Attempts to save the record just like Base#save but will raise a +RecordInvalid+
-
# exception instead of returning +false+ if the record is not valid.
-
1
def save!(options={})
-
23
perform_validations(options) ? super : raise_record_invalid
-
end
-
-
# Runs all the validations within the specified context. Returns +true+ if
-
# no errors are found, +false+ otherwise.
-
#
-
# Aliased as validate.
-
#
-
# If the argument is +false+ (default is +nil+), the context is set to <tt>:create</tt> if
-
# <tt>new_record?</tt> is +true+, and to <tt>:update</tt> if it is not.
-
#
-
# Validations with no <tt>:on</tt> option will run no matter the context. Validations with
-
# some <tt>:on</tt> option will only run in the specified context.
-
1
def valid?(context = nil)
-
29
context ||= (new_record? ? :create : :update)
-
29
output = super(context)
-
29
errors.empty? && output
-
end
-
-
1
alias_method :validate, :valid?
-
-
# Runs all the validations within the specified context. Returns +true+ if
-
# no errors are found, raises +RecordInvalid+ otherwise.
-
#
-
# If the argument is +false+ (default is +nil+), the context is set to <tt>:create</tt> if
-
# <tt>new_record?</tt> is +true+, and to <tt>:update</tt> if it is not.
-
#
-
# Validations with no <tt>:on</tt> option will run no matter the context. Validations with
-
# some <tt>:on</tt> option will only run in the specified context.
-
1
def validate!(context = nil)
-
valid?(context) || raise_record_invalid
-
end
-
-
1
protected
-
-
1
def raise_record_invalid
-
raise(RecordInvalid.new(self))
-
end
-
-
1
def perform_validations(options={}) # :nodoc:
-
29
options[:validate] == false || valid?(options[:context])
-
end
-
end
-
end
-
-
1
require "active_record/validations/associated"
-
1
require "active_record/validations/uniqueness"
-
1
require "active_record/validations/presence"
-
1
module ActiveRecord
-
1
module Validations
-
1
class AssociatedValidator < ActiveModel::EachValidator #:nodoc:
-
1
def validate_each(record, attribute, value)
-
if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?}.any?
-
record.errors.add(attribute, :invalid, options.merge(:value => value))
-
end
-
end
-
end
-
-
1
module ClassMethods
-
# Validates whether the associated object or objects are all valid.
-
# Works with any kind of association.
-
#
-
# class Book < ActiveRecord::Base
-
# has_many :pages
-
# belongs_to :library
-
#
-
# validates_associated :pages, :library
-
# end
-
#
-
# WARNING: This validation must not be used on both ends of an association.
-
# Doing so will lead to a circular dependency and cause infinite recursion.
-
#
-
# NOTE: This validation will not fail if the association hasn't been
-
# assigned. If you want to ensure that the association is both present and
-
# guaranteed to be valid, you also need to use +validates_presence_of+.
-
#
-
# Configuration options:
-
#
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
-
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
-
# Runs in all validation contexts by default (nil). You can pass a symbol
-
# or an array of symbols. (e.g. <tt>on: :create</tt> or
-
# <tt>on: :custom_validation_context</tt> or
-
# <tt>on: [:create, :custom_validation_context]</tt>)
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
1
def validates_associated(*attr_names)
-
validates_with AssociatedValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Validations
-
1
class PresenceValidator < ActiveModel::Validations::PresenceValidator # :nodoc:
-
1
def validate(record)
-
29
super
-
29
attributes.each do |attribute|
-
93
next unless record.class._reflect_on_association(attribute)
-
associated_records = Array.wrap(record.send(attribute))
-
-
# Superclass validates presence. Ensure present records aren't about to be destroyed.
-
if associated_records.present? && associated_records.all? { |r| r.marked_for_destruction? }
-
record.errors.add(attribute, :blank, options)
-
end
-
end
-
end
-
end
-
-
1
module ClassMethods
-
# Validates that the specified attributes are not blank (as defined by
-
# Object#blank?), and, if the attribute is an association, that the
-
# associated object is not marked for destruction. Happens by default
-
# on save.
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :face
-
# validates_presence_of :face
-
# end
-
#
-
# The face attribute must be in the object and it cannot be blank or marked
-
# for destruction.
-
#
-
# If you want to validate the presence of a boolean field (where the real values
-
# are true and false), you will want to use
-
# <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
-
#
-
# This is due to the way Object#blank? handles boolean values:
-
# <tt>false.blank? # => true</tt>.
-
#
-
# This validator defers to the ActiveModel validation for presence, adding the
-
# check to see that an associated object is not marked for destruction. This
-
# prevents the parent object from validating successfully and saving, which then
-
# deletes the associated object, thus putting the parent object into an invalid
-
# state.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
-
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
-
# Runs in all validation contexts by default (nil). You can pass a symbol
-
# or an array of symbols. (e.g. <tt>on: :create</tt> or
-
# <tt>on: :custom_validation_context</tt> or
-
# <tt>on: [:create, :custom_validation_context]</tt>)
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
-
# the validation should occur (e.g. <tt>if: :allow_validation</tt>, or
-
# <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
-
# or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
1
def validates_presence_of(*attr_names)
-
4
validates_with PresenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Validations
-
1
class UniquenessValidator < ActiveModel::EachValidator # :nodoc:
-
1
def initialize(options)
-
if options[:conditions] && !options[:conditions].respond_to?(:call)
-
raise ArgumentError, "#{options[:conditions]} was passed as :conditions but is not callable. " \
-
"Pass a callable instead: `conditions: -> { where(approved: true) }`"
-
end
-
super({ case_sensitive: true }.merge!(options))
-
@klass = options[:class]
-
end
-
-
1
def validate_each(record, attribute, value)
-
finder_class = find_finder_class_for(record)
-
table = finder_class.arel_table
-
value = map_enum_attribute(finder_class, attribute, value)
-
-
begin
-
relation = build_relation(finder_class, table, attribute, value)
-
if record.persisted?
-
if finder_class.primary_key
-
relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.id))
-
else
-
raise UnknownPrimaryKey.new(finder_class, "Can not validate uniqueness for persisted record without primary key.")
-
end
-
end
-
relation = scope_relation(record, table, relation)
-
relation = finder_class.unscoped.where(relation)
-
relation = relation.merge(options[:conditions]) if options[:conditions]
-
rescue RangeError
-
relation = finder_class.none
-
end
-
-
if relation.exists?
-
error_options = options.except(:case_sensitive, :scope, :conditions)
-
error_options[:value] = value
-
-
record.errors.add(attribute, :taken, error_options)
-
end
-
end
-
-
1
protected
-
# The check for an existing value should be run from a class that
-
# isn't abstract. This means working down from the current class
-
# (self), to the first non-abstract class. Since classes don't know
-
# their subclasses, we have to build the hierarchy between self and
-
# the record's class.
-
1
def find_finder_class_for(record) #:nodoc:
-
class_hierarchy = [record.class]
-
-
while class_hierarchy.first != @klass
-
class_hierarchy.unshift(class_hierarchy.first.superclass)
-
end
-
-
class_hierarchy.detect { |klass| !klass.abstract_class? }
-
end
-
-
1
def build_relation(klass, table, attribute, value) #:nodoc:
-
if reflection = klass._reflect_on_association(attribute)
-
attribute = reflection.foreign_key
-
value = value.attributes[reflection.klass.primary_key] unless value.nil?
-
end
-
-
attribute_name = attribute.to_s
-
-
# the attribute may be an aliased attribute
-
if klass.attribute_aliases[attribute_name]
-
attribute = klass.attribute_aliases[attribute_name]
-
attribute_name = attribute.to_s
-
end
-
-
column = klass.columns_hash[attribute_name]
-
value = klass.connection.type_cast(value, column)
-
if value.is_a?(String) && column.limit
-
value = value.to_s[0, column.limit]
-
end
-
-
if !options[:case_sensitive] && value && column.text?
-
# will use SQL LOWER function before comparison, unless it detects a case insensitive collation
-
klass.connection.case_insensitive_comparison(table, attribute, column, value)
-
else
-
klass.connection.case_sensitive_comparison(table, attribute, column, value)
-
end
-
end
-
-
1
def scope_relation(record, table, relation)
-
Array(options[:scope]).each do |scope_item|
-
if reflection = record.class._reflect_on_association(scope_item)
-
scope_value = record.send(reflection.foreign_key)
-
scope_item = reflection.foreign_key
-
else
-
scope_value = record._read_attribute(scope_item)
-
end
-
relation = relation.and(table[scope_item].eq(scope_value))
-
end
-
-
relation
-
end
-
-
1
def map_enum_attribute(klass, attribute, value)
-
mapping = klass.defined_enums[attribute.to_s]
-
value = mapping[value] if value && mapping
-
value
-
end
-
end
-
-
1
module ClassMethods
-
# Validates whether the value of the specified attributes are unique
-
# across the system. Useful for making sure that only one user
-
# can be named "davidhh".
-
#
-
# class Person < ActiveRecord::Base
-
# validates_uniqueness_of :user_name
-
# end
-
#
-
# It can also validate whether the value of the specified attributes are
-
# unique based on a <tt>:scope</tt> parameter:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_uniqueness_of :user_name, scope: :account_id
-
# end
-
#
-
# Or even multiple scope parameters. For example, making sure that a
-
# teacher can only be on the schedule once per semester for a particular
-
# class.
-
#
-
# class TeacherSchedule < ActiveRecord::Base
-
# validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id]
-
# end
-
#
-
# It is also possible to limit the uniqueness constraint to a set of
-
# records matching certain conditions. In this example archived articles
-
# are not being taken into consideration when validating uniqueness
-
# of the title attribute:
-
#
-
# class Article < ActiveRecord::Base
-
# validates_uniqueness_of :title, conditions: -> { where.not(status: 'archived') }
-
# end
-
#
-
# When the record is created, a check is performed to make sure that no
-
# record exists in the database with the given value for the specified
-
# attribute (that maps to a column). When the record is updated,
-
# the same check is made but disregarding the record itself.
-
#
-
# Configuration options:
-
#
-
# * <tt>:message</tt> - Specifies a custom error message (default is:
-
# "has already been taken").
-
# * <tt>:scope</tt> - One or more columns by which to limit the scope of
-
# the uniqueness constraint.
-
# * <tt>:conditions</tt> - Specify the conditions to be included as a
-
# <tt>WHERE</tt> SQL fragment to limit the uniqueness constraint lookup
-
# (e.g. <tt>conditions: -> { where(status: 'active') }</tt>).
-
# * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by
-
# non-text columns (+true+ by default).
-
# * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the
-
# attribute is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the
-
# attribute is blank (default is +false+).
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
#
-
# === Concurrency and integrity
-
#
-
# Using this validation method in conjunction with ActiveRecord::Base#save
-
# does not guarantee the absence of duplicate record insertions, because
-
# uniqueness checks on the application level are inherently prone to race
-
# conditions. For example, suppose that two users try to post a Comment at
-
# the same time, and a Comment's title must be unique. At the database-level,
-
# the actions performed by these users could be interleaved in the following manner:
-
#
-
# User 1 | User 2
-
# ------------------------------------+--------------------------------------
-
# # User 1 checks whether there's |
-
# # already a comment with the title |
-
# # 'My Post'. This is not the case. |
-
# SELECT * FROM comments |
-
# WHERE title = 'My Post' |
-
# |
-
# | # User 2 does the same thing and also
-
# | # infers that their title is unique.
-
# | SELECT * FROM comments
-
# | WHERE title = 'My Post'
-
# |
-
# # User 1 inserts their comment. |
-
# INSERT INTO comments |
-
# (title, content) VALUES |
-
# ('My Post', 'hi!') |
-
# |
-
# | # User 2 does the same thing.
-
# | INSERT INTO comments
-
# | (title, content) VALUES
-
# | ('My Post', 'hello!')
-
# |
-
# | # ^^^^^^
-
# | # Boom! We now have a duplicate
-
# | # title!
-
#
-
# This could even happen if you use transactions with the 'serializable'
-
# isolation level. The best way to work around this problem is to add a unique
-
# index to the database table using
-
# ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
-
# rare case that a race condition occurs, the database will guarantee
-
# the field's uniqueness.
-
#
-
# When the database catches such a duplicate insertion,
-
# ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
-
# exception. You can either choose to let this error propagate (which
-
# will result in the default Rails exception page being shown), or you
-
# can catch it and restart the transaction (e.g. by telling the user
-
# that the title already exists, and asking them to re-enter the title).
-
# This technique is also known as
-
# {optimistic concurrency control}[http://en.wikipedia.org/wiki/Optimistic_concurrency_control].
-
#
-
# The bundled ActiveRecord::ConnectionAdapters distinguish unique index
-
# constraint errors from other types of database errors by throwing an
-
# ActiveRecord::RecordNotUnique exception. For other adapters you will
-
# have to parse the (database-specific) exception message to detect such
-
# a case.
-
#
-
# The following bundled adapters throw the ActiveRecord::RecordNotUnique exception:
-
#
-
# * ActiveRecord::ConnectionAdapters::MysqlAdapter.
-
# * ActiveRecord::ConnectionAdapters::Mysql2Adapter.
-
# * ActiveRecord::ConnectionAdapters::SQLite3Adapter.
-
# * ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.
-
1
def validates_uniqueness_of(*attr_names)
-
validates_with UniquenessValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActiveRecord
-
# Returns the version of the currently loaded ActiveRecord as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
#--
-
# Copyright (c) 2005-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'securerandom'
-
1
require "active_support/dependencies/autoload"
-
1
require "active_support/version"
-
1
require "active_support/logger"
-
1
require "active_support/lazy_load_hooks"
-
-
1
module ActiveSupport
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Concern
-
1
autoload :Dependencies
-
1
autoload :DescendantsTracker
-
1
autoload :FileUpdateChecker
-
1
autoload :LogSubscriber
-
1
autoload :Notifications
-
-
1
eager_autoload do
-
1
autoload :BacktraceCleaner
-
1
autoload :ProxyObject
-
1
autoload :Benchmarkable
-
1
autoload :Cache
-
1
autoload :Callbacks
-
1
autoload :Configurable
-
1
autoload :Deprecation
-
1
autoload :Gzip
-
1
autoload :Inflector
-
1
autoload :JSON
-
1
autoload :KeyGenerator
-
1
autoload :MessageEncryptor
-
1
autoload :MessageVerifier
-
1
autoload :Multibyte
-
1
autoload :NumberHelper
-
1
autoload :OptionMerger
-
1
autoload :OrderedHash
-
1
autoload :OrderedOptions
-
1
autoload :StringInquirer
-
1
autoload :TaggedLogging
-
1
autoload :XmlMini
-
end
-
-
1
autoload :Rescuable
-
1
autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
-
1
autoload :TestCase
-
-
1
def self.eager_load!
-
super
-
-
NumberHelper.eager_load!
-
end
-
-
1
@@test_order = nil
-
-
1
def self.test_order=(new_order) # :nodoc:
-
1
@@test_order = new_order
-
end
-
-
1
def self.test_order # :nodoc:
-
@@test_order
-
end
-
end
-
-
1
autoload :I18n, "active_support/i18n"
-
1
require 'active_support'
-
1
require 'active_support/time'
-
1
require 'active_support/core_ext'
-
1
module ActiveSupport
-
# Backtraces often include many lines that are not relevant for the context
-
# under review. This makes it hard to find the signal amongst the backtrace
-
# noise, and adds debugging time. With a BacktraceCleaner, filters and
-
# silencers are used to remove the noisy lines, so that only the most relevant
-
# lines remain.
-
#
-
# Filters are used to modify lines of data, while silencers are used to remove
-
# lines entirely. The typical filter use case is to remove lengthy path
-
# information from the start of each line, and view file paths relevant to the
-
# app directory instead of the file system root. The typical silencer use case
-
# is to exclude the output of a noisy library from the backtrace, so that you
-
# can focus on the rest.
-
#
-
# bc = BacktraceCleaner.new
-
# bc.add_filter { |line| line.gsub(Rails.root.to_s, '') } # strip the Rails.root prefix
-
# bc.add_silencer { |line| line =~ /mongrel|rubygems/ } # skip any lines from mongrel or rubygems
-
# bc.clean(exception.backtrace) # perform the cleanup
-
#
-
# To reconfigure an existing BacktraceCleaner (like the default one in Rails)
-
# and show as much data as possible, you can always call
-
# <tt>BacktraceCleaner#remove_silencers!</tt>, which will restore the
-
# backtrace to a pristine state. If you need to reconfigure an existing
-
# BacktraceCleaner so that it does not filter or modify the paths of any lines
-
# of the backtrace, you can call <tt>BacktraceCleaner#remove_filters!</tt>
-
# These two methods will give you a completely untouched backtrace.
-
#
-
# Inspired by the Quiet Backtrace gem by Thoughtbot.
-
1
class BacktraceCleaner
-
1
def initialize
-
1
@filters, @silencers = [], []
-
end
-
-
# Returns the backtrace after all filters and silencers have been run
-
# against it. Filters run first, then silencers.
-
1
def clean(backtrace, kind = :silent)
-
filtered = filter_backtrace(backtrace)
-
-
case kind
-
when :silent
-
silence(filtered)
-
when :noise
-
noise(filtered)
-
else
-
filtered
-
end
-
end
-
1
alias :filter :clean
-
-
# Adds a filter from the block provided. Each line in the backtrace will be
-
# mapped against this filter.
-
#
-
# # Will turn "/my/rails/root/app/models/person.rb" into "/app/models/person.rb"
-
# backtrace_cleaner.add_filter { |line| line.gsub(Rails.root, '') }
-
1
def add_filter(&block)
-
4
@filters << block
-
end
-
-
# Adds a silencer from the block provided. If the silencer returns +true+
-
# for a given line, it will be excluded from the clean backtrace.
-
#
-
# # Will reject all lines that include the word "mongrel", like "/gems/mongrel/server.rb" or "/app/my_mongrel_server/rb"
-
# backtrace_cleaner.add_silencer { |line| line =~ /mongrel/ }
-
1
def add_silencer(&block)
-
1
@silencers << block
-
end
-
-
# Removes all silencers, but leaves in the filters. Useful if your
-
# context of debugging suddenly expands as you suspect a bug in one of
-
# the libraries you use.
-
1
def remove_silencers!
-
@silencers = []
-
end
-
-
# Removes all filters, but leaves in the silencers. Useful if you suddenly
-
# need to see entire filepaths in the backtrace that you had already
-
# filtered out.
-
1
def remove_filters!
-
@filters = []
-
end
-
-
1
private
-
1
def filter_backtrace(backtrace)
-
@filters.each do |f|
-
backtrace = backtrace.map { |line| f.call(line) }
-
end
-
-
backtrace
-
end
-
-
1
def silence(backtrace)
-
@silencers.each do |s|
-
backtrace = backtrace.reject { |line| s.call(line) }
-
end
-
-
backtrace
-
end
-
-
1
def noise(backtrace)
-
backtrace - silence(backtrace)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/benchmark'
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActiveSupport
-
1
module Benchmarkable
-
# Allows you to measure the execution time of a block in a template and
-
# records the result to the log. Wrap this block around expensive operations
-
# or possible bottlenecks to get a time reading for the operation. For
-
# example, let's say you thought your file processing method was taking too
-
# long; you could wrap it in a benchmark block.
-
#
-
# <% benchmark 'Process data files' do %>
-
# <%= expensive_files_operation %>
-
# <% end %>
-
#
-
# That would add something like "Process data files (345.2ms)" to the log,
-
# which you can then use to compare timings when optimizing your code.
-
#
-
# You may give an optional logger level (<tt>:debug</tt>, <tt>:info</tt>,
-
# <tt>:warn</tt>, <tt>:error</tt>) as the <tt>:level</tt> option. The
-
# default logger level value is <tt>:info</tt>.
-
#
-
# <% benchmark 'Low-level files', level: :debug do %>
-
# <%= lowlevel_files_operation %>
-
# <% end %>
-
#
-
# Finally, you can pass true as the third argument to silence all log
-
# activity (other than the timing information) from inside the block. This
-
# is great for boiling down a noisy block to just a single statement that
-
# produces one log line:
-
#
-
# <% benchmark 'Process data files', level: :info, silence: true do %>
-
# <%= expensive_and_chatty_files_operation %>
-
# <% end %>
-
1
def benchmark(message = "Benchmarking", options = {})
-
if logger
-
options.assert_valid_keys(:level, :silence)
-
options[:level] ||= :info
-
-
result = nil
-
ms = Benchmark.ms { result = options[:silence] ? silence { yield } : yield }
-
logger.send(options[:level], '%s (%.1fms)' % [ message, ms ])
-
result
-
else
-
yield
-
end
-
end
-
end
-
end
-
1
require 'benchmark'
-
1
require 'zlib'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/benchmark'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/numeric/bytes'
-
1
require 'active_support/core_ext/numeric/time'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/deprecation'
-
-
1
module ActiveSupport
-
# See ActiveSupport::Cache::Store for documentation.
-
1
module Cache
-
1
autoload :FileStore, 'active_support/cache/file_store'
-
1
autoload :MemoryStore, 'active_support/cache/memory_store'
-
1
autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
-
1
autoload :NullStore, 'active_support/cache/null_store'
-
-
# These options mean something to all cache implementations. Individual cache
-
# implementations may support additional options.
-
1
UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl]
-
-
1
module Strategy
-
1
autoload :LocalCache, 'active_support/cache/strategy/local_cache'
-
end
-
-
1
class << self
-
# Creates a new Store object according to the given options.
-
#
-
# If no arguments are passed to this method, then a new
-
# ActiveSupport::Cache::MemoryStore object will be returned.
-
#
-
# If you pass a Symbol as the first argument, then a corresponding cache
-
# store class under the ActiveSupport::Cache namespace will be created.
-
# For example:
-
#
-
# ActiveSupport::Cache.lookup_store(:memory_store)
-
# # => returns a new ActiveSupport::Cache::MemoryStore object
-
#
-
# ActiveSupport::Cache.lookup_store(:mem_cache_store)
-
# # => returns a new ActiveSupport::Cache::MemCacheStore object
-
#
-
# Any additional arguments will be passed to the corresponding cache store
-
# class's constructor:
-
#
-
# ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache')
-
# # => same as: ActiveSupport::Cache::FileStore.new('/tmp/cache')
-
#
-
# If the first argument is not a Symbol, then it will simply be returned:
-
#
-
# ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
-
# # => returns MyOwnCacheStore.new
-
1
def lookup_store(*store_option)
-
2
store, *parameters = *Array.wrap(store_option).flatten
-
-
2
case store
-
when Symbol
-
1
retrieve_store_class(store).new(*parameters)
-
when nil
-
ActiveSupport::Cache::MemoryStore.new
-
else
-
1
store
-
end
-
end
-
-
# Expands out the +key+ argument into a key that can be used for the
-
# cache store. Optionally accepts a namespace, and all keys will be
-
# scoped within that namespace.
-
#
-
# If the +key+ argument provided is an array, or responds to +to_a+, then
-
# each of elements in the array will be turned into parameters/keys and
-
# concatenated into a single key. For example:
-
#
-
# expand_cache_key([:foo, :bar]) # => "foo/bar"
-
# expand_cache_key([:foo, :bar], "namespace") # => "namespace/foo/bar"
-
#
-
# The +key+ argument can also respond to +cache_key+ or +to_param+.
-
1
def expand_cache_key(key, namespace = nil)
-
expanded_cache_key = namespace ? "#{namespace}/" : ""
-
-
if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
-
expanded_cache_key << "#{prefix}/"
-
end
-
-
expanded_cache_key << retrieve_cache_key(key)
-
expanded_cache_key
-
end
-
-
1
private
-
1
def retrieve_cache_key(key)
-
case
-
when key.respond_to?(:cache_key) then key.cache_key
-
when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param
-
when key.respond_to?(:to_a) then retrieve_cache_key(key.to_a)
-
else key.to_param
-
end.to_s
-
end
-
-
# Obtains the specified cache store class, given the name of the +store+.
-
# Raises an error when the store class cannot be found.
-
1
def retrieve_store_class(store)
-
1
require "active_support/cache/#{store}"
-
rescue LoadError => e
-
raise "Could not find cache store adapter for #{store} (#{e})"
-
else
-
1
ActiveSupport::Cache.const_get(store.to_s.camelize)
-
end
-
end
-
-
# An abstract cache store class. There are multiple cache store
-
# implementations, each having its own additional features. See the classes
-
# under the ActiveSupport::Cache module, e.g.
-
# ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
-
# popular cache store for large production websites.
-
#
-
# Some implementations may not support all methods beyond the basic cache
-
# methods of +fetch+, +write+, +read+, +exist?+, and +delete+.
-
#
-
# ActiveSupport::Cache::Store can store any serializable Ruby object.
-
#
-
# cache = ActiveSupport::Cache::MemoryStore.new
-
#
-
# cache.read('city') # => nil
-
# cache.write('city', "Duckburgh")
-
# cache.read('city') # => "Duckburgh"
-
#
-
# Keys are always translated into Strings and are case sensitive. When an
-
# object is specified as a key and has a +cache_key+ method defined, this
-
# method will be called to define the key. Otherwise, the +to_param+
-
# method will be called. Hashes and Arrays can also be used as keys. The
-
# elements will be delimited by slashes, and the elements within a Hash
-
# will be sorted by key so they are consistent.
-
#
-
# cache.read('city') == cache.read(:city) # => true
-
#
-
# Nil values can be cached.
-
#
-
# If your cache is on a shared infrastructure, you can define a namespace
-
# for your cache entries. If a namespace is defined, it will be prefixed on
-
# to every key. The namespace can be either a static value or a Proc. If it
-
# is a Proc, it will be invoked when each key is evaluated so that you can
-
# use application logic to invalidate keys.
-
#
-
# cache.namespace = -> { @last_mod_time } # Set the namespace to a variable
-
# @last_mod_time = Time.now # Invalidate the entire cache by changing namespace
-
#
-
# Caches can also store values in a compressed format to save space and
-
# reduce time spent sending data. Since there is overhead, values must be
-
# large enough to warrant compression. To turn on compression either pass
-
# <tt>compress: true</tt> in the initializer or as an option to +fetch+
-
# or +write+. To specify the threshold at which to compress values, set the
-
# <tt>:compress_threshold</tt> option. The default threshold is 16K.
-
1
class Store
-
1
cattr_accessor :logger, :instance_writer => true
-
-
1
attr_reader :silence, :options
-
1
alias :silence? :silence
-
-
# Create a new cache. The options will be passed to any write method calls
-
# except for <tt>:namespace</tt> which can be used to set the global
-
# namespace for the cache.
-
1
def initialize(options = nil)
-
67
@options = options ? options.dup : {}
-
end
-
-
# Silence the logger.
-
1
def silence!
-
@silence = true
-
self
-
end
-
-
# Silence the logger within a block.
-
1
def mute
-
previous_silence, @silence = defined?(@silence) && @silence, true
-
yield
-
ensure
-
@silence = previous_silence
-
end
-
-
# :deprecated:
-
1
def self.instrument=(boolean)
-
ActiveSupport::Deprecation.warn "ActiveSupport::Cache.instrument= is deprecated and will be removed in Rails 5. Instrumentation is now always on so you can safely stop using it."
-
true
-
end
-
-
# :deprecated:
-
1
def self.instrument
-
ActiveSupport::Deprecation.warn "ActiveSupport::Cache.instrument is deprecated and will be removed in Rails 5. Instrumentation is now always on so you can safely stop using it."
-
true
-
end
-
-
# Fetches data from the cache, using the given key. If there is data in
-
# the cache with the given key, then that data is returned.
-
#
-
# If there is no such data in the cache (a cache miss), then +nil+ will be
-
# returned. However, if a block has been passed, that block will be passed
-
# the key and executed in the event of a cache miss. The return value of the
-
# block will be written to the cache under the given cache key, and that
-
# return value will be returned.
-
#
-
# cache.write('today', 'Monday')
-
# cache.fetch('today') # => "Monday"
-
#
-
# cache.fetch('city') # => nil
-
# cache.fetch('city') do
-
# 'Duckburgh'
-
# end
-
# cache.fetch('city') # => "Duckburgh"
-
#
-
# You may also specify additional options via the +options+ argument.
-
# Setting <tt>force: true</tt> will force a cache miss:
-
#
-
# cache.write('today', 'Monday')
-
# cache.fetch('today', force: true) # => nil
-
#
-
# Setting <tt>:compress</tt> will store a large cache entry set by the call
-
# in a compressed format.
-
#
-
# Setting <tt>:expires_in</tt> will set an expiration time on the cache.
-
# All caches support auto-expiring content after a specified number of
-
# seconds. This value can be specified as an option to the constructor
-
# (in which case all entries will be affected), or it can be supplied to
-
# the +fetch+ or +write+ method to effect just one entry.
-
#
-
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)
-
# cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry
-
#
-
# Setting <tt>:race_condition_ttl</tt> is very useful in situations where
-
# a cache entry is used very frequently and is under heavy load. If a
-
# cache expires and due to heavy load several different processes will try
-
# to read data natively and then they all will try to write to cache. To
-
# avoid that case the first process to find an expired cache entry will
-
# bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>.
-
# Yes, this process is extending the time for a stale value by another few
-
# seconds. Because of extended life of the previous cache, other processes
-
# will continue to use slightly stale data for a just a bit longer. In the
-
# meantime that first process will go ahead and will write into cache the
-
# new value. After that all the processes will start getting the new value.
-
# The key is to keep <tt>:race_condition_ttl</tt> small.
-
#
-
# If the process regenerating the entry errors out, the entry will be
-
# regenerated after the specified number of seconds. Also note that the
-
# life of stale cache is extended only if it expired recently. Otherwise
-
# a new value is generated and <tt>:race_condition_ttl</tt> does not play
-
# any role.
-
#
-
# # Set all values to expire after one minute.
-
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute)
-
#
-
# cache.write('foo', 'original value')
-
# val_1 = nil
-
# val_2 = nil
-
# sleep 60
-
#
-
# Thread.new do
-
# val_1 = cache.fetch('foo', race_condition_ttl: 10) do
-
# sleep 1
-
# 'new value 1'
-
# end
-
# end
-
#
-
# Thread.new do
-
# val_2 = cache.fetch('foo', race_condition_ttl: 10) do
-
# 'new value 2'
-
# end
-
# end
-
#
-
# # val_1 => "new value 1"
-
# # val_2 => "original value"
-
# # sleep 10 # First thread extend the life of cache by another 10 seconds
-
# # cache.fetch('foo') => "new value 1"
-
#
-
# Other options will be handled by the specific cache store implementation.
-
# Internally, #fetch calls #read_entry, and calls #write_entry on a cache
-
# miss. +options+ will be passed to the #read and #write calls.
-
#
-
# For example, MemCacheStore's #write method supports the +:raw+
-
# option, which tells the memcached server to store all values as strings.
-
# We can use this option with #fetch too:
-
#
-
# cache = ActiveSupport::Cache::MemCacheStore.new
-
# cache.fetch("foo", force: true, raw: true) do
-
# :bar
-
# end
-
# cache.fetch('foo') # => "bar"
-
1
def fetch(name, options = nil)
-
if block_given?
-
options = merged_options(options)
-
key = namespaced_key(name, options)
-
-
cached_entry = find_cached_entry(key, name, options) unless options[:force]
-
entry = handle_expired_entry(cached_entry, key, options)
-
-
if entry
-
get_entry_value(entry, name, options)
-
else
-
save_block_result_to_cache(name, options) { |_name| yield _name }
-
end
-
else
-
read(name, options)
-
end
-
end
-
-
# Fetches data from the cache, using the given key. If there is data in
-
# the cache with the given key, then that data is returned. Otherwise,
-
# +nil+ is returned.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def read(name, options = nil)
-
options = merged_options(options)
-
key = namespaced_key(name, options)
-
instrument(:read, name, options) do |payload|
-
entry = read_entry(key, options)
-
if entry
-
if entry.expired?
-
delete_entry(key, options)
-
payload[:hit] = false if payload
-
nil
-
else
-
payload[:hit] = true if payload
-
entry.value
-
end
-
else
-
payload[:hit] = false if payload
-
nil
-
end
-
end
-
end
-
-
# Read multiple values at once from the cache. Options can be passed
-
# in the last argument.
-
#
-
# Some cache implementation may optimize this method.
-
#
-
# Returns a hash mapping the names provided to the values found.
-
1
def read_multi(*names)
-
options = names.extract_options!
-
options = merged_options(options)
-
results = {}
-
names.each do |name|
-
key = namespaced_key(name, options)
-
entry = read_entry(key, options)
-
if entry
-
if entry.expired?
-
delete_entry(key, options)
-
else
-
results[name] = entry.value
-
end
-
end
-
end
-
results
-
end
-
-
# Fetches data from the cache, using the given keys. If there is data in
-
# the cache with the given keys, then that data is returned. Otherwise,
-
# the supplied block is called for each key for which there was no data,
-
# and the result will be written to the cache and returned.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# Returns a hash with the data for each of the names. For example:
-
#
-
# cache.write("bim", "bam")
-
# cache.fetch_multi("bim", "boom") { |key| key * 2 }
-
# # => { "bam" => "bam", "boom" => "boomboom" }
-
#
-
1
def fetch_multi(*names)
-
options = names.extract_options!
-
options = merged_options(options)
-
results = read_multi(*names, options)
-
-
names.each_with_object({}) do |name, memo|
-
memo[name] = results.fetch(name) do
-
value = yield name
-
write(name, value, options)
-
value
-
end
-
end
-
end
-
-
# Writes the value to the cache, with the key.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def write(name, value, options = nil)
-
options = merged_options(options)
-
-
instrument(:write, name, options) do
-
entry = Entry.new(value, options)
-
write_entry(namespaced_key(name, options), entry, options)
-
end
-
end
-
-
# Deletes an entry in the cache. Returns +true+ if an entry is deleted.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def delete(name, options = nil)
-
options = merged_options(options)
-
-
instrument(:delete, name) do
-
delete_entry(namespaced_key(name, options), options)
-
end
-
end
-
-
# Returns +true+ if the cache contains an entry for the given key.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def exist?(name, options = nil)
-
options = merged_options(options)
-
-
instrument(:exist?, name) do
-
entry = read_entry(namespaced_key(name, options), options)
-
(entry && !entry.expired?) || false
-
end
-
end
-
-
# Delete all entries with keys matching the pattern.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def delete_matched(matcher, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support delete_matched")
-
end
-
-
# Increment an integer value in the cache.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def increment(name, amount = 1, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support increment")
-
end
-
-
# Decrement an integer value in the cache.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def decrement(name, amount = 1, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support decrement")
-
end
-
-
# Cleanup the cache by removing expired entries.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def cleanup(options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support cleanup")
-
end
-
-
# Clear the entire cache. Be careful with this method since it could
-
# affect other processes if shared cache is being used.
-
#
-
# The options hash is passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def clear(options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support clear")
-
end
-
-
1
protected
-
# Add the namespace defined in the options to a pattern designed to
-
# match keys. Implementations that support delete_matched should call
-
# this method to translate a pattern that matches names into one that
-
# matches namespaced keys.
-
1
def key_matcher(pattern, options)
-
prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace]
-
if prefix
-
source = pattern.source
-
if source.start_with?('^')
-
source = source[1, source.length]
-
else
-
source = ".*#{source[0, source.length]}"
-
end
-
Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options)
-
else
-
pattern
-
end
-
end
-
-
# Read an entry from the cache implementation. Subclasses must implement
-
# this method.
-
1
def read_entry(key, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
# Write an entry to the cache implementation. Subclasses must implement
-
# this method.
-
1
def write_entry(key, entry, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
# Delete an entry from the cache implementation. Subclasses must
-
# implement this method.
-
1
def delete_entry(key, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
1
private
-
# Merge the default options with ones specific to a method call.
-
1
def merged_options(call_options) # :nodoc:
-
if call_options
-
options.merge(call_options)
-
else
-
options.dup
-
end
-
end
-
-
# Expand key to be a consistent string value. Invoke +cache_key+ if
-
# object responds to +cache_key+. Otherwise, +to_param+ method will be
-
# called. If the key is a Hash, then keys will be sorted alphabetically.
-
1
def expanded_key(key) # :nodoc:
-
return key.cache_key.to_s if key.respond_to?(:cache_key)
-
-
case key
-
when Array
-
if key.size > 1
-
key = key.collect{|element| expanded_key(element)}
-
else
-
key = key.first
-
end
-
when Hash
-
key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"}
-
end
-
-
key.to_param
-
end
-
-
# Prefix a key with the namespace. Namespace and key will be delimited
-
# with a colon.
-
1
def namespaced_key(key, options)
-
key = expanded_key(key)
-
namespace = options[:namespace] if options
-
prefix = namespace.is_a?(Proc) ? namespace.call : namespace
-
key = "#{prefix}:#{key}" if prefix
-
key
-
end
-
-
1
def instrument(operation, key, options = nil)
-
log(operation, key, options)
-
-
payload = { :key => key }
-
payload.merge!(options) if options.is_a?(Hash)
-
ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
-
end
-
-
1
def log(operation, key, options = nil)
-
return unless logger && logger.debug? && !silence?
-
logger.debug("Cache #{operation}: #{key}#{options.blank? ? "" : " (#{options.inspect})"}")
-
end
-
-
1
def find_cached_entry(key, name, options)
-
instrument(:read, name, options) do |payload|
-
payload[:super_operation] = :fetch if payload
-
read_entry(key, options)
-
end
-
end
-
-
1
def handle_expired_entry(entry, key, options)
-
if entry && entry.expired?
-
race_ttl = options[:race_condition_ttl].to_i
-
if (race_ttl > 0) && (Time.now.to_f - entry.expires_at <= race_ttl)
-
# When an entry has :race_condition_ttl defined, put the stale entry back into the cache
-
# for a brief period while the entry is begin recalculated.
-
entry.expires_at = Time.now + race_ttl
-
write_entry(key, entry, :expires_in => race_ttl * 2)
-
else
-
delete_entry(key, options)
-
end
-
entry = nil
-
end
-
entry
-
end
-
-
1
def get_entry_value(entry, name, options)
-
instrument(:fetch_hit, name, options) { |payload| }
-
entry.value
-
end
-
-
1
def save_block_result_to_cache(name, options)
-
result = instrument(:generate, name, options) do |payload|
-
yield(name)
-
end
-
-
write(name, result, options)
-
result
-
end
-
end
-
-
# This class is used to represent cache entries. Cache entries have a value and an optional
-
# expiration time. The expiration time is used to support the :race_condition_ttl option
-
# on the cache.
-
#
-
# Since cache entries in most instances will be serialized, the internals of this class are highly optimized
-
# using short instance variable names that are lazily defined.
-
1
class Entry # :nodoc:
-
1
DEFAULT_COMPRESS_LIMIT = 16.kilobytes
-
-
# Create a new cache entry for the specified value. Options supported are
-
# +:compress+, +:compress_threshold+, and +:expires_in+.
-
1
def initialize(value, options = {})
-
if should_compress?(value, options)
-
@value = compress(value)
-
@compressed = true
-
else
-
@value = value
-
end
-
-
@created_at = Time.now.to_f
-
@expires_in = options[:expires_in]
-
@expires_in = @expires_in.to_f if @expires_in
-
end
-
-
1
def value
-
convert_version_4beta1_entry! if defined?(@v)
-
compressed? ? uncompress(@value) : @value
-
end
-
-
# Check if the entry is expired. The +expires_in+ parameter can override
-
# the value set when the entry was created.
-
1
def expired?
-
convert_version_4beta1_entry! if defined?(@v)
-
@expires_in && @created_at + @expires_in <= Time.now.to_f
-
end
-
-
1
def expires_at
-
@expires_in ? @created_at + @expires_in : nil
-
end
-
-
1
def expires_at=(value)
-
if value
-
@expires_in = value.to_f - @created_at
-
else
-
@expires_in = nil
-
end
-
end
-
-
# Returns the size of the cached value. This could be less than
-
# <tt>value.size</tt> if the data is compressed.
-
1
def size
-
if defined?(@s)
-
@s
-
else
-
case value
-
when NilClass
-
0
-
when String
-
@value.bytesize
-
else
-
@s = Marshal.dump(@value).bytesize
-
end
-
end
-
end
-
-
# Duplicate the value in a class. This is used by cache implementations that don't natively
-
# serialize entries to protect against accidental cache modifications.
-
1
def dup_value!
-
convert_version_4beta1_entry! if defined?(@v)
-
-
if @value && !compressed? && !(@value.is_a?(Numeric) || @value == true || @value == false)
-
if @value.is_a?(String)
-
@value = @value.dup
-
else
-
@value = Marshal.load(Marshal.dump(@value))
-
end
-
end
-
end
-
-
1
private
-
1
def should_compress?(value, options)
-
if value && options[:compress]
-
compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
-
serialized_value_size = (value.is_a?(String) ? value : Marshal.dump(value)).bytesize
-
-
return true if serialized_value_size >= compress_threshold
-
end
-
-
false
-
end
-
-
1
def compressed?
-
defined?(@compressed) ? @compressed : false
-
end
-
-
1
def compress(value)
-
Zlib::Deflate.deflate(Marshal.dump(value))
-
end
-
-
1
def uncompress(value)
-
Marshal.load(Zlib::Inflate.inflate(value))
-
end
-
-
# The internals of this method changed between Rails 3.x and 4.0. This method provides the glue
-
# to ensure that cache entries created under the old version still work with the new class definition.
-
1
def convert_version_4beta1_entry!
-
if defined?(@v)
-
@value = @v
-
remove_instance_variable(:@v)
-
end
-
-
if defined?(@c)
-
@compressed = @c
-
remove_instance_variable(:@c)
-
end
-
-
if defined?(@x) && @x
-
@created_at ||= Time.now.to_f
-
@expires_in = @x - @created_at
-
remove_instance_variable(:@x)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/marshal'
-
1
require 'active_support/core_ext/file/atomic'
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'uri/common'
-
-
1
module ActiveSupport
-
1
module Cache
-
# A cache store implementation which stores everything on the filesystem.
-
#
-
# FileStore implements the Strategy::LocalCache strategy which implements
-
# an in-memory cache inside of a block.
-
1
class FileStore < Store
-
1
attr_reader :cache_path
-
-
1
DIR_FORMATTER = "%03X"
-
1
FILENAME_MAX_SIZE = 228 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)
-
1
FILEPATH_MAX_SIZE = 900 # max is 1024, plus some room
-
1
EXCLUDED_DIRS = ['.', '..'].freeze
-
-
1
def initialize(cache_path, options = nil)
-
1
super(options)
-
1
@cache_path = cache_path.to_s
-
1
extend Strategy::LocalCache
-
end
-
-
# Deletes all items from the cache. In this case it deletes all the entries in the specified
-
# file store directory except for .gitkeep. Be careful which directory is specified in your
-
# config file when using +FileStore+ because everything in that directory will be deleted.
-
1
def clear(options = nil)
-
root_dirs = Dir.entries(cache_path).reject {|f| (EXCLUDED_DIRS + [".gitkeep"]).include?(f)}
-
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
-
end
-
-
# Preemptively iterates through all stored keys and removes the ones which have expired.
-
1
def cleanup(options = nil)
-
options = merged_options(options)
-
search_dir(cache_path) do |fname|
-
key = file_path_key(fname)
-
entry = read_entry(key, options)
-
delete_entry(key, options) if entry && entry.expired?
-
end
-
end
-
-
# Increments an already existing integer value that is stored in the cache.
-
# If the key is not found nothing is done.
-
1
def increment(name, amount = 1, options = nil)
-
modify_value(name, amount, options)
-
end
-
-
# Decrements an already existing integer value that is stored in the cache.
-
# If the key is not found nothing is done.
-
1
def decrement(name, amount = 1, options = nil)
-
modify_value(name, -amount, options)
-
end
-
-
1
def delete_matched(matcher, options = nil)
-
options = merged_options(options)
-
instrument(:delete_matched, matcher.inspect) do
-
matcher = key_matcher(matcher, options)
-
search_dir(cache_path) do |path|
-
key = file_path_key(path)
-
delete_entry(key, options) if key.match(matcher)
-
end
-
end
-
end
-
-
1
protected
-
-
1
def read_entry(key, options)
-
file_name = key_file_path(key)
-
if File.exist?(file_name)
-
File.open(file_name) { |f| Marshal.load(f) }
-
end
-
rescue => e
-
logger.error("FileStoreError (#{e}): #{e.message}") if logger
-
nil
-
end
-
-
1
def write_entry(key, entry, options)
-
file_name = key_file_path(key)
-
return false if options[:unless_exist] && File.exist?(file_name)
-
ensure_cache_path(File.dirname(file_name))
-
File.atomic_write(file_name, cache_path) {|f| Marshal.dump(entry, f)}
-
true
-
end
-
-
1
def delete_entry(key, options)
-
file_name = key_file_path(key)
-
if File.exist?(file_name)
-
begin
-
File.delete(file_name)
-
delete_empty_directories(File.dirname(file_name))
-
true
-
rescue => e
-
# Just in case the error was caused by another process deleting the file first.
-
raise e if File.exist?(file_name)
-
false
-
end
-
end
-
end
-
-
1
private
-
# Lock a file for a block so only one process can modify it at a time.
-
1
def lock_file(file_name, &block) # :nodoc:
-
if File.exist?(file_name)
-
File.open(file_name, 'r+') do |f|
-
begin
-
f.flock File::LOCK_EX
-
yield
-
ensure
-
f.flock File::LOCK_UN
-
end
-
end
-
else
-
yield
-
end
-
end
-
-
# Translate a key into a file path.
-
1
def key_file_path(key)
-
if key.size > FILEPATH_MAX_SIZE
-
key = Digest::MD5.hexdigest(key)
-
end
-
-
fname = URI.encode_www_form_component(key)
-
hash = Zlib.adler32(fname)
-
hash, dir_1 = hash.divmod(0x1000)
-
dir_2 = hash.modulo(0x1000)
-
fname_paths = []
-
-
# Make sure file name doesn't exceed file system limits.
-
begin
-
fname_paths << fname[0, FILENAME_MAX_SIZE]
-
fname = fname[FILENAME_MAX_SIZE..-1]
-
end until fname.blank?
-
-
File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, *fname_paths)
-
end
-
-
# Translate a file path into a key.
-
1
def file_path_key(path)
-
fname = path[cache_path.to_s.size..-1].split(File::SEPARATOR, 4).last
-
URI.decode_www_form_component(fname, Encoding::UTF_8)
-
end
-
-
# Delete empty directories in the cache.
-
1
def delete_empty_directories(dir)
-
return if File.realpath(dir) == File.realpath(cache_path)
-
if Dir.entries(dir).reject {|f| EXCLUDED_DIRS.include?(f)}.empty?
-
Dir.delete(dir) rescue nil
-
delete_empty_directories(File.dirname(dir))
-
end
-
end
-
-
# Make sure a file path's directories exist.
-
1
def ensure_cache_path(path)
-
FileUtils.makedirs(path) unless File.exist?(path)
-
end
-
-
1
def search_dir(dir, &callback)
-
return if !File.exist?(dir)
-
Dir.foreach(dir) do |d|
-
next if EXCLUDED_DIRS.include?(d)
-
name = File.join(dir, d)
-
if File.directory?(name)
-
search_dir(name, &callback)
-
else
-
callback.call name
-
end
-
end
-
end
-
-
# Modifies the amount of an already existing integer value that is stored in the cache.
-
# If the key is not found nothing is done.
-
1
def modify_value(name, amount, options)
-
file_name = key_file_path(namespaced_key(name, options))
-
-
lock_file(file_name) do
-
options = merged_options(options)
-
-
if num = read(name, options)
-
num = num.to_i + amount
-
write(name, num, options)
-
num
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveSupport
-
1
module Cache
-
1
module Strategy
-
# Caches that implement LocalCache will be backed by an in-memory cache for the
-
# duration of a block. Repeated calls to the cache for the same key will hit the
-
# in-memory cache for faster access.
-
1
module LocalCache
-
1
autoload :Middleware, 'active_support/cache/strategy/local_cache_middleware'
-
-
# Class for storing and registering the local caches.
-
1
class LocalCacheRegistry # :nodoc:
-
1
extend ActiveSupport::PerThreadRegistry
-
-
1
def initialize
-
1
@registry = {}
-
end
-
-
1
def cache_for(local_cache_key)
-
@registry[local_cache_key]
-
end
-
-
1
def set_cache_for(local_cache_key, value)
-
132
@registry[local_cache_key] = value
-
end
-
-
133
def self.set_cache_for(l, v); instance.set_cache_for l, v; end
-
1
def self.cache_for(l); instance.cache_for l; end
-
end
-
-
# Simple memory backed cache. This cache is not thread safe and is intended only
-
# for serving as a temporary memory cache for a single thread.
-
1
class LocalStore < Store
-
1
def initialize
-
66
super
-
66
@data = {}
-
end
-
-
# Don't allow synchronizing since it isn't thread safe,
-
1
def synchronize # :nodoc:
-
yield
-
end
-
-
1
def clear(options = nil)
-
@data.clear
-
end
-
-
1
def read_entry(key, options)
-
@data[key]
-
end
-
-
1
def write_entry(key, value, options)
-
@data[key] = value
-
true
-
end
-
-
1
def delete_entry(key, options)
-
!!@data.delete(key)
-
end
-
end
-
-
# Use a local cache for the duration of block.
-
1
def with_local_cache
-
use_temporary_local_cache(LocalStore.new) { yield }
-
end
-
# Middleware class can be inserted as a Rack handler to be local cache for the
-
# duration of request.
-
1
def middleware
-
@middleware ||= Middleware.new(
-
"ActiveSupport::Cache::Strategy::LocalCache",
-
1
local_cache_key)
-
end
-
-
1
def clear(options = nil) # :nodoc:
-
local_cache.clear(options) if local_cache
-
super
-
end
-
-
1
def cleanup(options = nil) # :nodoc:
-
local_cache.clear(options) if local_cache
-
super
-
end
-
-
1
def increment(name, amount = 1, options = nil) # :nodoc:
-
value = bypass_local_cache{super}
-
set_cache_value(value, name, amount, options)
-
value
-
end
-
-
1
def decrement(name, amount = 1, options = nil) # :nodoc:
-
value = bypass_local_cache{super}
-
set_cache_value(value, name, amount, options)
-
value
-
end
-
-
1
protected
-
1
def read_entry(key, options) # :nodoc:
-
if local_cache
-
entry = local_cache.read_entry(key, options)
-
unless entry
-
entry = super
-
local_cache.write_entry(key, entry, options)
-
end
-
entry
-
else
-
super
-
end
-
end
-
-
1
def write_entry(key, entry, options) # :nodoc:
-
local_cache.write_entry(key, entry, options) if local_cache
-
super
-
end
-
-
1
def delete_entry(key, options) # :nodoc:
-
local_cache.delete_entry(key, options) if local_cache
-
super
-
end
-
-
1
def set_cache_value(value, name, amount, options)
-
if local_cache
-
local_cache.mute do
-
if value
-
local_cache.write(name, value, options)
-
else
-
local_cache.delete(name, options)
-
end
-
end
-
end
-
end
-
-
1
private
-
-
1
def local_cache_key
-
1
@local_cache_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, '_').to_sym
-
end
-
-
1
def local_cache
-
LocalCacheRegistry.cache_for(local_cache_key)
-
end
-
-
1
def bypass_local_cache
-
use_temporary_local_cache(nil) { yield }
-
end
-
-
1
def use_temporary_local_cache(temporary_cache)
-
save_cache = LocalCacheRegistry.cache_for(local_cache_key)
-
begin
-
LocalCacheRegistry.set_cache_for(local_cache_key, temporary_cache)
-
yield
-
ensure
-
LocalCacheRegistry.set_cache_for(local_cache_key, save_cache)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'rack/body_proxy'
-
1
require 'rack/utils'
-
-
1
module ActiveSupport
-
1
module Cache
-
1
module Strategy
-
1
module LocalCache
-
-
#--
-
# This class wraps up local storage for middlewares. Only the middleware method should
-
# construct them.
-
1
class Middleware # :nodoc:
-
1
attr_reader :name, :local_cache_key
-
-
1
def initialize(name, local_cache_key)
-
1
@name = name
-
1
@local_cache_key = local_cache_key
-
1
@app = nil
-
end
-
-
1
def new(app)
-
1
@app = app
-
1
self
-
end
-
-
1
def call(env)
-
66
LocalCacheRegistry.set_cache_for(local_cache_key, LocalStore.new)
-
66
response = @app.call(env)
-
66
response[2] = ::Rack::BodyProxy.new(response[2]) do
-
66
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
-
end
-
66
response
-
rescue Rack::Utils::InvalidParameterError
-
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
-
[400, {}, []]
-
rescue Exception
-
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
-
raise
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/descendants_tracker'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'thread'
-
-
1
module ActiveSupport
-
# Callbacks are code hooks that are run at key points in an object's life cycle.
-
# The typical use case is to have a base class define a set of callbacks
-
# relevant to the other functionality it supplies, so that subclasses can
-
# install callbacks that enhance or modify the base functionality without
-
# needing to override or redefine methods of the base class.
-
#
-
# Mixing in this module allows you to define the events in the object's
-
# life cycle that will support callbacks (via +ClassMethods.define_callbacks+),
-
# set the instance methods, procs, or callback objects to be called (via
-
# +ClassMethods.set_callback+), and run the installed callbacks at the
-
# appropriate times (via +run_callbacks+).
-
#
-
# Three kinds of callbacks are supported: before callbacks, run before a
-
# certain event; after callbacks, run after the event; and around callbacks,
-
# blocks that surround the event, triggering it when they yield. Callback code
-
# can be contained in instance methods, procs or lambdas, or callback objects
-
# that respond to certain predetermined methods. See +ClassMethods.set_callback+
-
# for details.
-
#
-
# class Record
-
# include ActiveSupport::Callbacks
-
# define_callbacks :save
-
#
-
# def save
-
# run_callbacks :save do
-
# puts "- save"
-
# end
-
# end
-
# end
-
#
-
# class PersonRecord < Record
-
# set_callback :save, :before, :saving_message
-
# def saving_message
-
# puts "saving..."
-
# end
-
#
-
# set_callback :save, :after do |object|
-
# puts "saved"
-
# end
-
# end
-
#
-
# person = PersonRecord.new
-
# person.save
-
#
-
# Output:
-
# saving...
-
# - save
-
# saved
-
1
module Callbacks
-
1
extend Concern
-
-
1
included do
-
7
extend ActiveSupport::DescendantsTracker
-
end
-
-
1
CALLBACK_FILTER_TYPES = [:before, :after, :around]
-
-
# Runs the callbacks for the given event.
-
#
-
# Calls the before and around callbacks in the order they were set, yields
-
# the block (if given one), and then runs the after callbacks in reverse
-
# order.
-
#
-
# If the callback chain was halted, returns +false+. Otherwise returns the
-
# result of the block, +nil+ if no callbacks have been set, or +true+
-
# if callbacks have been set but no block is given.
-
#
-
# run_callbacks :save do
-
# save
-
# end
-
1
def run_callbacks(kind, &block)
-
133
send "_run_#{kind}_callbacks", &block
-
end
-
-
1
private
-
-
1
def __run_callbacks__(callbacks, &block)
-
393
if callbacks.empty?
-
270
yield if block_given?
-
else
-
123
runner = callbacks.compile
-
123
e = Filters::Environment.new(self, false, nil, block)
-
123
runner.call(e).value
-
end
-
end
-
-
# A hook invoked every time a before callback is halted.
-
# This can be overridden in AS::Callback implementors in order
-
# to provide better debugging/logging.
-
1
def halted_callback_hook(filter)
-
end
-
-
1
module Conditionals # :nodoc:
-
1
class Value
-
1
def initialize(&block)
-
2
@block = block
-
end
-
8
def call(target, value); @block.call(value); end
-
end
-
end
-
-
1
module Filters
-
1
Environment = Struct.new(:target, :halted, :value, :run_block)
-
-
1
class End
-
1
def call(env)
-
123
block = env.run_block
-
123
env.value = !env.halted && (!block || block.call)
-
123
env
-
end
-
end
-
1
ENDING = End.new
-
-
1
class Before
-
1
def self.build(callback_sequence, user_callback, user_conditions, chain_config, filter)
-
14
halted_lambda = chain_config[:terminator]
-
-
14
if chain_config.key?(:terminator) && user_conditions.any?
-
1
halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter)
-
13
elsif chain_config.key? :terminator
-
8
halting(callback_sequence, user_callback, halted_lambda, filter)
-
5
elsif user_conditions.any?
-
conditional(callback_sequence, user_callback, user_conditions)
-
else
-
5
simple callback_sequence, user_callback
-
end
-
end
-
-
1
def self.halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter)
-
1
callback_sequence.before do |env|
-
14
target = env.target
-
14
value = env.value
-
14
halted = env.halted
-
-
28
if !halted && user_conditions.all? { |c| c.call(target, value) }
-
6
result = user_callback.call target, value
-
6
env.halted = halted_lambda.call(target, result)
-
6
if env.halted
-
target.send :halted_callback_hook, filter
-
end
-
end
-
-
14
env
-
end
-
end
-
1
private_class_method :halting_and_conditional
-
-
1
def self.halting(callback_sequence, user_callback, halted_lambda, filter)
-
8
callback_sequence.before do |env|
-
160
target = env.target
-
160
value = env.value
-
160
halted = env.halted
-
-
160
unless halted
-
160
result = user_callback.call target, value
-
160
env.halted = halted_lambda.call(target, result)
-
160
if env.halted
-
target.send :halted_callback_hook, filter
-
end
-
end
-
-
160
env
-
end
-
end
-
1
private_class_method :halting
-
-
1
def self.conditional(callback_sequence, user_callback, user_conditions)
-
callback_sequence.before do |env|
-
target = env.target
-
value = env.value
-
-
if user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call target, value
-
end
-
-
env
-
end
-
end
-
1
private_class_method :conditional
-
-
1
def self.simple(callback_sequence, user_callback)
-
5
callback_sequence.before do |env|
-
36
user_callback.call env.target, env.value
-
-
36
env
-
end
-
end
-
1
private_class_method :simple
-
end
-
-
1
class After
-
1
def self.build(callback_sequence, user_callback, user_conditions, chain_config)
-
4
if chain_config[:skip_after_callbacks_if_terminated]
-
4
if chain_config.key?(:terminator) && user_conditions.any?
-
2
halting_and_conditional(callback_sequence, user_callback, user_conditions)
-
2
elsif chain_config.key?(:terminator)
-
2
halting(callback_sequence, user_callback)
-
elsif user_conditions.any?
-
conditional callback_sequence, user_callback, user_conditions
-
else
-
simple callback_sequence, user_callback
-
end
-
else
-
if user_conditions.any?
-
conditional callback_sequence, user_callback, user_conditions
-
else
-
simple callback_sequence, user_callback
-
end
-
end
-
end
-
-
1
def self.halting_and_conditional(callback_sequence, user_callback, user_conditions)
-
2
callback_sequence.after do |env|
-
7
target = env.target
-
7
value = env.value
-
7
halted = env.halted
-
-
14
if !halted && user_conditions.all? { |c| c.call(target, value) }
-
7
user_callback.call target, value
-
end
-
-
7
env
-
end
-
end
-
1
private_class_method :halting_and_conditional
-
-
1
def self.halting(callback_sequence, user_callback)
-
2
callback_sequence.after do |env|
-
66
unless env.halted
-
66
user_callback.call env.target, env.value
-
end
-
-
66
env
-
end
-
end
-
1
private_class_method :halting
-
-
1
def self.conditional(callback_sequence, user_callback, user_conditions)
-
callback_sequence.after do |env|
-
target = env.target
-
value = env.value
-
-
if user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call target, value
-
end
-
-
env
-
end
-
end
-
1
private_class_method :conditional
-
-
1
def self.simple(callback_sequence, user_callback)
-
callback_sequence.after do |env|
-
user_callback.call env.target, env.value
-
-
env
-
end
-
end
-
1
private_class_method :simple
-
end
-
-
1
class Around
-
1
def self.build(callback_sequence, user_callback, user_conditions, chain_config)
-
if chain_config.key?(:terminator) && user_conditions.any?
-
halting_and_conditional(callback_sequence, user_callback, user_conditions)
-
elsif chain_config.key? :terminator
-
halting(callback_sequence, user_callback)
-
elsif user_conditions.any?
-
conditional(callback_sequence, user_callback, user_conditions)
-
else
-
simple(callback_sequence, user_callback)
-
end
-
end
-
-
1
def self.halting_and_conditional(callback_sequence, user_callback, user_conditions)
-
callback_sequence.around do |env, &run|
-
target = env.target
-
value = env.value
-
halted = env.halted
-
-
if !halted && user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call(target, value) {
-
env = run.call env
-
env.value
-
}
-
-
env
-
else
-
run.call env
-
end
-
end
-
end
-
1
private_class_method :halting_and_conditional
-
-
1
def self.halting(callback_sequence, user_callback)
-
callback_sequence.around do |env, &run|
-
target = env.target
-
value = env.value
-
-
if env.halted
-
run.call env
-
else
-
user_callback.call(target, value) {
-
env = run.call env
-
env.value
-
}
-
env
-
end
-
end
-
end
-
1
private_class_method :halting
-
-
1
def self.conditional(callback_sequence, user_callback, user_conditions)
-
callback_sequence.around do |env, &run|
-
target = env.target
-
value = env.value
-
-
if user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call(target, value) {
-
env = run.call env
-
env.value
-
}
-
env
-
else
-
run.call env
-
end
-
end
-
end
-
1
private_class_method :conditional
-
-
1
def self.simple(callback_sequence, user_callback)
-
callback_sequence.around do |env, &run|
-
user_callback.call(env.target, env.value) {
-
env = run.call env
-
env.value
-
}
-
env
-
end
-
end
-
1
private_class_method :simple
-
end
-
end
-
-
1
class Callback #:nodoc:#
-
1
def self.build(chain, filter, kind, options)
-
26
new chain.name, filter, kind, options, chain.config
-
end
-
-
1
attr_accessor :kind, :name
-
1
attr_reader :chain_config
-
-
1
def initialize(name, filter, kind, options, chain_config)
-
26
@chain_config = chain_config
-
26
@name = name
-
26
@kind = kind
-
26
@filter = filter
-
26
@key = compute_identifier filter
-
26
@if = Array(options[:if])
-
26
@unless = Array(options[:unless])
-
end
-
-
16
def filter; @key; end
-
1
def raw_filter; @filter; end
-
-
1
def merge(chain, new_options)
-
options = {
-
:if => @if.dup,
-
:unless => @unless.dup
-
}
-
-
options[:if].concat Array(new_options.fetch(:unless, []))
-
options[:unless].concat Array(new_options.fetch(:if, []))
-
-
self.class.build chain, @filter, @kind, options
-
end
-
-
1
def matches?(_kind, _filter)
-
9
@kind == _kind && filter == _filter
-
end
-
-
1
def duplicates?(other)
-
18
case @filter
-
when Symbol, String
-
9
matches?(other.kind, other.filter)
-
else
-
9
false
-
end
-
end
-
-
# Wraps code with filter
-
1
def apply(callback_sequence)
-
18
user_conditions = conditions_lambdas
-
18
user_callback = make_lambda @filter
-
-
18
case kind
-
when :before
-
14
Filters::Before.build(callback_sequence, user_callback, user_conditions, chain_config, @filter)
-
when :after
-
4
Filters::After.build(callback_sequence, user_callback, user_conditions, chain_config)
-
when :around
-
Filters::Around.build(callback_sequence, user_callback, user_conditions, chain_config)
-
end
-
end
-
-
1
private
-
-
1
def invert_lambda(l)
-
lambda { |*args, &blk| !l.call(*args, &blk) }
-
end
-
-
# Filters support:
-
#
-
# Symbols:: A method to call.
-
# Strings:: Some content to evaluate.
-
# Procs:: A proc to call with the object.
-
# Objects:: An object with a <tt>before_foo</tt> method on it to call.
-
#
-
# All of these objects are converted into a lambda and handled
-
# the same after this point.
-
1
def make_lambda(filter)
-
21
case filter
-
when Symbol
-
260
lambda { |target, _, &blk| target.send filter, &blk }
-
when String
-
1
l = eval "lambda { |value| #{filter} }"
-
15
lambda { |target, value| target.instance_exec(value, &l) }
-
2
when Conditionals::Value then filter
-
when ::Proc
-
if filter.arity > 1
-
return lambda { |target, _, &block|
-
raise ArgumentError unless block
-
target.instance_exec(target, block, &filter)
-
}
-
end
-
-
if filter.arity <= 0
-
lambda { |target, _| target.instance_exec(&filter) }
-
else
-
lambda { |target, _| target.instance_exec(target, &filter) }
-
end
-
else
-
4
scopes = Array(chain_config[:scope])
-
8
method_to_call = scopes.map{ |s| public_send(s) }.join("_")
-
-
4
lambda { |target, _, &blk|
-
29
filter.public_send method_to_call, target, &blk
-
}
-
end
-
end
-
-
1
def compute_identifier(filter)
-
26
case filter
-
when String, ::Proc
-
6
filter.object_id
-
else
-
20
filter
-
end
-
end
-
-
1
def conditions_lambdas
-
3
@if.map { |c| make_lambda c } +
-
18
@unless.map { |c| invert_lambda make_lambda c }
-
end
-
end
-
-
# Execute before and after filters in a sequence instead of
-
# chaining them with nested lambda calls, see:
-
# https://github.com/rails/rails/issues/18011
-
1
class CallbackSequence
-
1
def initialize(&call)
-
11
@call = call
-
11
@before = []
-
11
@after = []
-
end
-
-
1
def before(&before)
-
14
@before.unshift(before)
-
14
self
-
end
-
-
1
def after(&after)
-
4
@after.push(after)
-
4
self
-
end
-
-
1
def around(&around)
-
CallbackSequence.new do |*args|
-
around.call(*args) {
-
self.call(*args)
-
}
-
end
-
end
-
-
1
def call(*args)
-
333
@before.each { |b| b.call(*args) }
-
123
value = @call.call(*args)
-
196
@after.each { |a| a.call(*args) }
-
123
value
-
end
-
end
-
-
# An Array with a compile method.
-
1
class CallbackChain #:nodoc:#
-
1
include Enumerable
-
-
1
attr_reader :name, :config
-
-
1
def initialize(name, config)
-
20
@name = name
-
20
@config = {
-
:scope => [ :kind ]
-
}.merge!(config)
-
20
@chain = []
-
20
@callbacks = nil
-
20
@mutex = Mutex.new
-
end
-
-
1
def each(&block); @chain.each(&block); end
-
1
def index(o); @chain.index(o); end
-
494
def empty?; @chain.empty?; end
-
-
1
def insert(index, o)
-
@callbacks = nil
-
@chain.insert(index, o)
-
end
-
-
1
def delete(o)
-
@callbacks = nil
-
@chain.delete(o)
-
end
-
-
1
def clear
-
@callbacks = nil
-
@chain.clear
-
self
-
end
-
-
1
def initialize_copy(other)
-
26
@callbacks = nil
-
26
@chain = other.chain.dup
-
26
@mutex = Mutex.new
-
end
-
-
1
def compile
-
@callbacks || @mutex.synchronize do
-
134
final_sequence = CallbackSequence.new { |env| Filters::ENDING.call(env) }
-
@callbacks ||= @chain.reverse.inject(final_sequence) do |callback_sequence, callback|
-
18
callback.apply callback_sequence
-
11
end
-
123
end
-
end
-
-
1
def append(*callbacks)
-
44
callbacks.each { |c| append_one(c) }
-
end
-
-
1
def prepend(*callbacks)
-
8
callbacks.each { |c| prepend_one(c) }
-
end
-
-
1
protected
-
27
def chain; @chain; end
-
-
1
private
-
-
1
def append_one(callback)
-
22
@callbacks = nil
-
22
remove_duplicates(callback)
-
22
@chain.push(callback)
-
end
-
-
1
def prepend_one(callback)
-
4
@callbacks = nil
-
4
remove_duplicates(callback)
-
4
@chain.unshift(callback)
-
end
-
-
1
def remove_duplicates(callback)
-
26
@callbacks = nil
-
44
@chain.delete_if { |c| callback.duplicates?(c) }
-
end
-
end
-
-
1
module ClassMethods
-
1
def normalize_callback_params(filters, block) # :nodoc:
-
26
type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before
-
26
options = filters.extract_options!
-
26
filters.unshift(block) if block
-
26
[type, filters, options.dup]
-
end
-
-
# This is used internally to append, prepend and skip callbacks to the
-
# CallbackChain.
-
1
def __update_callbacks(name) #:nodoc:
-
26
([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse_each do |target|
-
26
chain = target.get_callbacks name
-
26
yield target, chain.dup
-
end
-
end
-
-
# Install a callback for the given event.
-
#
-
# set_callback :save, :before, :before_meth
-
# set_callback :save, :after, :after_meth, if: :condition
-
# set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff }
-
#
-
# The second arguments indicates whether the callback is to be run +:before+,
-
# +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
-
# means the first example above can also be written as:
-
#
-
# set_callback :save, :before_meth
-
#
-
# The callback can be specified as a symbol naming an instance method; as a
-
# proc, lambda, or block; as a string to be instance evaluated; or as an
-
# object that responds to a certain method determined by the <tt>:scope</tt>
-
# argument to +define_callbacks+.
-
#
-
# If a proc, lambda, or block is given, its body is evaluated in the context
-
# of the current object. It can also optionally accept the current object as
-
# an argument.
-
#
-
# Before and around callbacks are called in the order that they are set;
-
# after callbacks are called in the reverse order.
-
#
-
# Around callbacks can access the return value from the event, if it
-
# wasn't halted, from the +yield+ call.
-
#
-
# ===== Options
-
#
-
# * <tt>:if</tt> - A symbol, a string or an array of symbols and strings,
-
# each naming an instance method or a proc; the callback will be called
-
# only when they all return a true value.
-
# * <tt>:unless</tt> - A symbol, a string or an array of symbols and
-
# strings, each naming an instance method or a proc; the callback will
-
# be called only when they all return a false value.
-
# * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
-
# existing chain rather than appended.
-
1
def set_callback(name, *filter_list, &block)
-
26
type, filters, options = normalize_callback_params(filter_list, block)
-
26
self_chain = get_callbacks name
-
26
mapped = filters.map do |filter|
-
26
Callback.build(self_chain, filter, type, options)
-
end
-
-
26
__update_callbacks(name) do |target, chain|
-
26
options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped)
-
26
target.set_callbacks name, chain
-
end
-
end
-
-
# Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or
-
# <tt>:unless</tt> options may be passed in order to control when the
-
# callback is skipped.
-
#
-
# class Writer < Person
-
# skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
-
# end
-
1
def skip_callback(name, *filter_list, &block)
-
type, filters, options = normalize_callback_params(filter_list, block)
-
-
__update_callbacks(name) do |target, chain|
-
filters.each do |filter|
-
filter = chain.find {|c| c.matches?(type, filter) }
-
-
if filter && options.any?
-
new_filter = filter.merge(chain, options)
-
chain.insert(chain.index(filter), new_filter)
-
end
-
-
chain.delete(filter)
-
end
-
target.set_callbacks name, chain
-
end
-
end
-
-
# Remove all set callbacks for the given event.
-
1
def reset_callbacks(name)
-
callbacks = get_callbacks name
-
-
ActiveSupport::DescendantsTracker.descendants(self).each do |target|
-
chain = target.get_callbacks(name).dup
-
callbacks.each { |c| chain.delete(c) }
-
target.set_callbacks name, chain
-
end
-
-
self.set_callbacks name, callbacks.dup.clear
-
end
-
-
# Define sets of events in the object life cycle that support callbacks.
-
#
-
# define_callbacks :validate
-
# define_callbacks :initialize, :save, :destroy
-
#
-
# ===== Options
-
#
-
# * <tt>:terminator</tt> - Determines when a before filter will halt the
-
# callback chain, preventing following callbacks from being called and
-
# the event from being triggered. This should be a lambda to be executed.
-
# The current object and the return result of the callback will be called
-
# with the lambda.
-
#
-
# define_callbacks :validate, terminator: ->(target, result) { result == false }
-
#
-
# In this example, if any before validate callbacks returns +false+,
-
# other callbacks are not executed. Defaults to +false+, meaning no value
-
# halts the chain.
-
#
-
# * <tt>:skip_after_callbacks_if_terminated</tt> - Determines if after
-
# callbacks should be terminated by the <tt>:terminator</tt> option. By
-
# default after callbacks executed no matter if callback chain was
-
# terminated or not. Option makes sense only when <tt>:terminator</tt>
-
# option is specified.
-
#
-
# * <tt>:scope</tt> - Indicates which methods should be executed when an
-
# object is used as a callback.
-
#
-
# class Audit
-
# def before(caller)
-
# puts 'Audit: before is called'
-
# end
-
#
-
# def before_save(caller)
-
# puts 'Audit: before_save is called'
-
# end
-
# end
-
#
-
# class Account
-
# include ActiveSupport::Callbacks
-
#
-
# define_callbacks :save
-
# set_callback :save, :before, Audit.new
-
#
-
# def save
-
# run_callbacks :save do
-
# puts 'save in main'
-
# end
-
# end
-
# end
-
#
-
# In the above case whenever you save an account the method
-
# <tt>Audit#before</tt> will be called. On the other hand
-
#
-
# define_callbacks :save, scope: [:kind, :name]
-
#
-
# would trigger <tt>Audit#before_save</tt> instead. That's constructed
-
# by calling <tt>#{kind}_#{name}</tt> on the given instance. In this
-
# case "kind" is "before" and "name" is "save". In this context +:kind+
-
# and +:name+ have special meanings: +:kind+ refers to the kind of
-
# callback (before/after/around) and +:name+ refers to the method on
-
# which callbacks are being defined.
-
#
-
# A declaration like
-
#
-
# define_callbacks :save, scope: [:name]
-
#
-
# would call <tt>Audit#save</tt>.
-
#
-
# NOTE: +method_name+ passed to `define_model_callbacks` must not end with
-
# `!`, `?` or `=`.
-
1
def define_callbacks(*names)
-
17
options = names.extract_options!
-
-
17
names.each do |name|
-
20
class_attribute "_#{name}_callbacks"
-
20
set_callbacks name, CallbackChain.new(name, options)
-
-
20
module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def _run_#{name}_callbacks(&block)
-
__run_callbacks__(_#{name}_callbacks, &block)
-
end
-
RUBY
-
end
-
end
-
-
1
protected
-
-
1
def get_callbacks(name)
-
52
send "_#{name}_callbacks"
-
end
-
-
1
def set_callbacks(name, callbacks)
-
46
send "_#{name}_callbacks=", callbacks
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
# A typical module looks like this:
-
#
-
# module M
-
# def self.included(base)
-
# base.extend ClassMethods
-
# base.class_eval do
-
# scope :disabled, -> { where(disabled: true) }
-
# end
-
# end
-
#
-
# module ClassMethods
-
# ...
-
# end
-
# end
-
#
-
# By using <tt>ActiveSupport::Concern</tt> the above module could instead be
-
# written as:
-
#
-
# require 'active_support/concern'
-
#
-
# module M
-
# extend ActiveSupport::Concern
-
#
-
# included do
-
# scope :disabled, -> { where(disabled: true) }
-
# end
-
#
-
# class_methods do
-
# ...
-
# end
-
# end
-
#
-
# Moreover, it gracefully handles module dependencies. Given a +Foo+ module
-
# and a +Bar+ module which depends on the former, we would typically write the
-
# following:
-
#
-
# module Foo
-
# def self.included(base)
-
# base.class_eval do
-
# def self.method_injected_by_foo
-
# ...
-
# end
-
# end
-
# end
-
# end
-
#
-
# module Bar
-
# def self.included(base)
-
# base.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Foo # We need to include this dependency for Bar
-
# include Bar # Bar is the module that Host really needs
-
# end
-
#
-
# But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We
-
# could try to hide these from +Host+ directly including +Foo+ in +Bar+:
-
#
-
# module Bar
-
# include Foo
-
# def self.included(base)
-
# base.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Bar
-
# end
-
#
-
# Unfortunately this won't work, since when +Foo+ is included, its <tt>base</tt>
-
# is the +Bar+ module, not the +Host+ class. With <tt>ActiveSupport::Concern</tt>,
-
# module dependencies are properly resolved:
-
#
-
# require 'active_support/concern'
-
#
-
# module Foo
-
# extend ActiveSupport::Concern
-
# included do
-
# def self.method_injected_by_foo
-
# ...
-
# end
-
# end
-
# end
-
#
-
# module Bar
-
# extend ActiveSupport::Concern
-
# include Foo
-
#
-
# included do
-
# self.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Bar # It works, now Bar takes care of its dependencies
-
# end
-
1
module Concern
-
1
class MultipleIncludedBlocks < StandardError #:nodoc:
-
1
def initialize
-
super "Cannot define multiple 'included' blocks for a Concern"
-
end
-
end
-
-
1
def self.extended(base) #:nodoc:
-
121
base.instance_variable_set(:@_dependencies, [])
-
end
-
-
1
def append_features(base)
-
292
if base.instance_variable_defined?(:@_dependencies)
-
61
base.instance_variable_get(:@_dependencies) << self
-
61
return false
-
else
-
231
return false if base < self
-
270
@_dependencies.each { |dep| base.send(:include, dep) }
-
186
super
-
186
base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods)
-
186
base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block)
-
end
-
end
-
-
1
def included(base = nil, &block)
-
366
if base.nil?
-
74
raise MultipleIncludedBlocks if instance_variable_defined?(:@_included_block)
-
-
74
@_included_block = block
-
else
-
292
super
-
end
-
end
-
-
1
def class_methods(&class_methods_module_definition)
-
mod = const_defined?(:ClassMethods, false) ?
-
const_get(:ClassMethods) :
-
const_set(:ClassMethods, Module.new)
-
-
mod.module_eval(&class_methods_module_definition)
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/ordered_options'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveSupport
-
# Configurable provides a <tt>config</tt> method to store and retrieve
-
# configuration options as an <tt>OrderedHash</tt>.
-
1
module Configurable
-
1
extend ActiveSupport::Concern
-
-
1
class Configuration < ActiveSupport::InheritableOptions
-
1
def compile_methods!
-
2
self.class.compile_methods!(keys)
-
end
-
-
# Compiles reader methods so we don't have to go through method_missing.
-
1
def self.compile_methods!(keys)
-
21
keys.reject { |m| method_defined?(m) }.each do |key|
-
13
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{key}; _get(#{key.inspect}); end
-
RUBY
-
end
-
end
-
end
-
-
1
module ClassMethods
-
1
def config
-
@_config ||= if respond_to?(:superclass) && superclass.respond_to?(:config)
-
9
superclass.config.inheritable_copy
-
else
-
# create a new "anonymous" class that will host the compiled reader methods
-
1
Class.new(Configuration).new
-
907
end
-
end
-
-
1
def configure
-
yield config
-
end
-
-
# Allows you to add shortcut so that you don't have to refer to attribute
-
# through config. Also look at the example for config to contrast.
-
#
-
# Defines both class and instance config accessors.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access
-
# end
-
#
-
# User.allowed_access # => nil
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# user = User.new
-
# user.allowed_access # => false
-
# user.allowed_access = true
-
# user.allowed_access # => true
-
#
-
# User.allowed_access # => false
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :"1_Badname"
-
# end
-
# # => NameError: invalid config attribute name
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access, instance_reader: false, instance_writer: false
-
# end
-
#
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# User.new.allowed_access = true # => NoMethodError
-
# User.new.allowed_access # => NoMethodError
-
#
-
# Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access, instance_accessor: false
-
# end
-
#
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# User.new.allowed_access = true # => NoMethodError
-
# User.new.allowed_access # => NoMethodError
-
#
-
# Also you can pass a block to set up the attribute with a default value.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# User.hair_colors # => [:brown, :black, :blonde, :red]
-
1
def config_accessor(*names)
-
10
options = names.extract_options!
-
-
10
names.each do |name|
-
20
raise NameError.new('invalid config attribute name') unless name =~ /\A[_A-Za-z]\w*\z/
-
-
20
reader, reader_line = "def #{name}; config.#{name}; end", __LINE__
-
20
writer, writer_line = "def #{name}=(value); config.#{name} = value; end", __LINE__
-
-
20
singleton_class.class_eval reader, __FILE__, reader_line
-
20
singleton_class.class_eval writer, __FILE__, writer_line
-
-
20
unless options[:instance_accessor] == false
-
20
class_eval reader, __FILE__, reader_line unless options[:instance_reader] == false
-
20
class_eval writer, __FILE__, writer_line unless options[:instance_writer] == false
-
end
-
20
send("#{name}=", yield) if block_given?
-
end
-
end
-
end
-
-
# Reads and writes attributes from a configuration <tt>OrderedHash</tt>.
-
#
-
# require 'active_support/configurable'
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# end
-
#
-
# user = User.new
-
#
-
# user.config.allowed_access = true
-
# user.config.level = 1
-
#
-
# user.config.allowed_access # => true
-
# user.config.level # => 1
-
1
def config
-
184
@_config ||= self.class.config.inheritable_copy
-
end
-
end
-
end
-
-
1
Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"].each do |path|
-
24
require path
-
end
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/array/access'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/array/grouping'
-
1
require 'active_support/core_ext/array/prepend_and_append'
-
1
class Array
-
# Returns the tail of the array from +position+.
-
#
-
# %w( a b c d ).from(0) # => ["a", "b", "c", "d"]
-
# %w( a b c d ).from(2) # => ["c", "d"]
-
# %w( a b c d ).from(10) # => []
-
# %w().from(0) # => []
-
# %w( a b c d ).from(-2) # => ["c", "d"]
-
# %w( a b c ).from(-10) # => []
-
1
def from(position)
-
self[position, length] || []
-
end
-
-
# Returns the beginning of the array up to +position+.
-
#
-
# %w( a b c d ).to(0) # => ["a"]
-
# %w( a b c d ).to(2) # => ["a", "b", "c"]
-
# %w( a b c d ).to(10) # => ["a", "b", "c", "d"]
-
# %w().to(0) # => []
-
# %w( a b c d ).to(-2) # => ["a", "b", "c"]
-
# %w( a b c ).to(-10) # => []
-
1
def to(position)
-
if position >= 0
-
first position + 1
-
else
-
self[0..position]
-
end
-
end
-
-
# Equal to <tt>self[1]</tt>.
-
#
-
# %w( a b c d e ).second # => "b"
-
1
def second
-
self[1]
-
end
-
-
# Equal to <tt>self[2]</tt>.
-
#
-
# %w( a b c d e ).third # => "c"
-
1
def third
-
self[2]
-
end
-
-
# Equal to <tt>self[3]</tt>.
-
#
-
# %w( a b c d e ).fourth # => "d"
-
1
def fourth
-
self[3]
-
end
-
-
# Equal to <tt>self[4]</tt>.
-
#
-
# %w( a b c d e ).fifth # => "e"
-
1
def fifth
-
self[4]
-
end
-
-
# Equal to <tt>self[41]</tt>. Also known as accessing "the reddit".
-
#
-
# (1..42).to_a.forty_two # => 42
-
1
def forty_two
-
self[41]
-
end
-
end
-
1
require 'active_support/xml_mini'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
-
1
class Array
-
# Converts the array to a comma-separated sentence where the last element is
-
# joined by the connector word.
-
#
-
# You can pass the following options to change the default behavior. If you
-
# pass an option key that doesn't exist in the list below, it will raise an
-
# <tt>ArgumentError</tt>.
-
#
-
# ==== Options
-
#
-
# * <tt>:words_connector</tt> - The sign or word used to join the elements
-
# in arrays with two or more elements (default: ", ").
-
# * <tt>:two_words_connector</tt> - The sign or word used to join the elements
-
# in arrays with two elements (default: " and ").
-
# * <tt>:last_word_connector</tt> - The sign or word used to join the last element
-
# in arrays with three or more elements (default: ", and ").
-
# * <tt>:locale</tt> - If +i18n+ is available, you can set a locale and use
-
# the connector options defined on the 'support.array' namespace in the
-
# corresponding dictionary file.
-
#
-
# ==== Examples
-
#
-
# [].to_sentence # => ""
-
# ['one'].to_sentence # => "one"
-
# ['one', 'two'].to_sentence # => "one and two"
-
# ['one', 'two', 'three'].to_sentence # => "one, two, and three"
-
#
-
# ['one', 'two'].to_sentence(passing: 'invalid option')
-
# # => ArgumentError: Unknown key :passing
-
#
-
# ['one', 'two'].to_sentence(two_words_connector: '-')
-
# # => "one-two"
-
#
-
# ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ')
-
# # => "one or two or at least three"
-
#
-
# Using <tt>:locale</tt> option:
-
#
-
# # Given this locale dictionary:
-
# #
-
# # es:
-
# # support:
-
# # array:
-
# # words_connector: " o "
-
# # two_words_connector: " y "
-
# # last_word_connector: " o al menos "
-
#
-
# ['uno', 'dos'].to_sentence(locale: :es)
-
# # => "uno y dos"
-
#
-
# ['uno', 'dos', 'tres'].to_sentence(locale: :es)
-
# # => "uno o dos o al menos tres"
-
1
def to_sentence(options = {})
-
options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
-
-
default_connectors = {
-
:words_connector => ', ',
-
:two_words_connector => ' and ',
-
:last_word_connector => ', and '
-
}
-
if defined?(I18n)
-
i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {})
-
default_connectors.merge!(i18n_connectors)
-
end
-
options = default_connectors.merge!(options)
-
-
case length
-
when 0
-
''
-
when 1
-
self[0].to_s.dup
-
when 2
-
"#{self[0]}#{options[:two_words_connector]}#{self[1]}"
-
else
-
"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
-
end
-
end
-
-
# Extends <tt>Array#to_s</tt> to convert a collection of elements into a
-
# comma separated id list if <tt>:db</tt> argument is given as the format.
-
#
-
# Blog.all.to_formatted_s(:db) # => "1,2,3"
-
1
def to_formatted_s(format = :default)
-
case format
-
when :db
-
if empty?
-
'null'
-
else
-
collect { |element| element.id }.join(',')
-
end
-
else
-
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
-
# Returns a string that represents the array in XML by invoking +to_xml+
-
# on each element. Active Record collections delegate their representation
-
# in XML to this method.
-
#
-
# All elements are expected to respond to +to_xml+, if any of them does
-
# not then an exception is raised.
-
#
-
# The root node reflects the class name of the first element in plural
-
# if all elements belong to the same type and that's not Hash:
-
#
-
# customer.projects.to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <projects type="array">
-
# <project>
-
# <amount type="decimal">20000.0</amount>
-
# <customer-id type="integer">1567</customer-id>
-
# <deal-date type="date">2008-04-09</deal-date>
-
# ...
-
# </project>
-
# <project>
-
# <amount type="decimal">57230.0</amount>
-
# <customer-id type="integer">1567</customer-id>
-
# <deal-date type="date">2008-04-15</deal-date>
-
# ...
-
# </project>
-
# </projects>
-
#
-
# Otherwise the root element is "objects":
-
#
-
# [{ foo: 1, bar: 2}, { baz: 3}].to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <objects type="array">
-
# <object>
-
# <bar type="integer">2</bar>
-
# <foo type="integer">1</foo>
-
# </object>
-
# <object>
-
# <baz type="integer">3</baz>
-
# </object>
-
# </objects>
-
#
-
# If the collection is empty the root element is "nil-classes" by default:
-
#
-
# [].to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <nil-classes type="array"/>
-
#
-
# To ensure a meaningful root element use the <tt>:root</tt> option:
-
#
-
# customer_with_no_projects.projects.to_xml(root: 'projects')
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <projects type="array"/>
-
#
-
# By default name of the node for the children of root is <tt>root.singularize</tt>.
-
# You can change it with the <tt>:children</tt> option.
-
#
-
# The +options+ hash is passed downwards:
-
#
-
# Message.all.to_xml(skip_types: true)
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <messages>
-
# <message>
-
# <created-at>2008-03-07T09:58:18+01:00</created-at>
-
# <id>1</id>
-
# <name>1</name>
-
# <updated-at>2008-03-07T09:58:18+01:00</updated-at>
-
# <user-id>1</user-id>
-
# </message>
-
# </messages>
-
#
-
1
def to_xml(options = {})
-
require 'active_support/builder' unless defined?(Builder)
-
-
options = options.dup
-
options[:indent] ||= 2
-
options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
-
options[:root] ||= \
-
if first.class != Hash && all? { |e| e.is_a?(first.class) }
-
underscored = ActiveSupport::Inflector.underscore(first.class.name)
-
ActiveSupport::Inflector.pluralize(underscored).tr('/', '_')
-
else
-
'objects'
-
end
-
-
builder = options[:builder]
-
builder.instruct! unless options.delete(:skip_instruct)
-
-
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
-
children = options.delete(:children) || root.singularize
-
attributes = options[:skip_types] ? {} : { type: 'array' }
-
-
if empty?
-
builder.tag!(root, attributes)
-
else
-
builder.tag!(root, attributes) do
-
each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) }
-
yield builder if block_given?
-
end
-
end
-
end
-
end
-
1
class Hash
-
# By default, only instances of Hash itself are extractable.
-
# Subclasses of Hash may implement this method and return
-
# true to declare themselves as extractable. If a Hash
-
# is extractable, Array#extract_options! pops it from
-
# the Array when it is the last element of the Array.
-
1
def extractable_options?
-
324
instance_of?(Hash)
-
end
-
end
-
-
1
class Array
-
# Extracts options from a set of arguments. Removes and returns the last
-
# element in the array if it's a hash, otherwise returns a blank hash.
-
#
-
# def options(*args)
-
# args.extract_options!
-
# end
-
#
-
# options(1, 2) # => {}
-
# options(1, 2, a: :b) # => {:a=>:b}
-
1
def extract_options!
-
644
if last.is_a?(Hash) && last.extractable_options?
-
324
pop
-
else
-
320
{}
-
end
-
end
-
end
-
1
class Array
-
# Splits or iterates over the array in groups of size +number+,
-
# padding any remaining slots with +fill_with+ unless it is +false+.
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5", "6"]
-
# ["7", "8", "9"]
-
# ["10", nil, nil]
-
#
-
# %w(1 2 3 4 5).in_groups_of(2, ' ') {|group| p group}
-
# ["1", "2"]
-
# ["3", "4"]
-
# ["5", " "]
-
#
-
# %w(1 2 3 4 5).in_groups_of(2, false) {|group| p group}
-
# ["1", "2"]
-
# ["3", "4"]
-
# ["5"]
-
1
def in_groups_of(number, fill_with = nil)
-
if number.to_i <= 0
-
raise ArgumentError,
-
"Group size must be a positive integer, was #{number.inspect}"
-
end
-
-
if fill_with == false
-
collection = self
-
else
-
# size % number gives how many extra we have;
-
# subtracting from number gives how many to add;
-
# modulo number ensures we don't add group of just fill.
-
padding = (number - size % number) % number
-
collection = dup.concat(Array.new(padding, fill_with))
-
end
-
-
if block_given?
-
collection.each_slice(number) { |slice| yield(slice) }
-
else
-
collection.each_slice(number).to_a
-
end
-
end
-
-
# Splits or iterates over the array in +number+ of groups, padding any
-
# remaining slots with +fill_with+ unless it is +false+.
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
-
# ["1", "2", "3", "4"]
-
# ["5", "6", "7", nil]
-
# ["8", "9", "10", nil]
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups(3, ' ') {|group| p group}
-
# ["1", "2", "3", "4"]
-
# ["5", "6", "7", " "]
-
# ["8", "9", "10", " "]
-
#
-
# %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5"]
-
# ["6", "7"]
-
1
def in_groups(number, fill_with = nil)
-
# size.div number gives minor group size;
-
# size % number gives how many objects need extra accommodation;
-
# each group hold either division or division + 1 items.
-
division = size.div number
-
modulo = size % number
-
-
# create a new array avoiding dup
-
groups = []
-
start = 0
-
-
number.times do |index|
-
length = division + (modulo > 0 && modulo > index ? 1 : 0)
-
groups << last_group = slice(start, length)
-
last_group << fill_with if fill_with != false &&
-
modulo > 0 && length == division
-
start += length
-
end
-
-
if block_given?
-
groups.each { |g| yield(g) }
-
else
-
groups
-
end
-
end
-
-
# Divides the array into one or more subarrays based on a delimiting +value+
-
# or the result of an optional block.
-
#
-
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
-
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
-
1
def split(value = nil)
-
if block_given?
-
inject([[]]) do |results, element|
-
if yield(element)
-
results << []
-
else
-
results.last << element
-
end
-
-
results
-
end
-
else
-
results, arr = [[]], self.dup
-
until arr.empty?
-
if (idx = arr.index(value))
-
results.last.concat(arr.shift(idx))
-
arr.shift
-
results << []
-
else
-
results.last.concat(arr.shift(arr.size))
-
end
-
end
-
results
-
end
-
end
-
end
-
1
class Array
-
# The human way of thinking about adding stuff to the end of a list is with append.
-
1
alias_method :append, :<<
-
-
# The human way of thinking about adding stuff to the beginning of a list is with prepend.
-
1
alias_method :prepend, :unshift
-
end
-
1
class Array
-
# Wraps its argument in an array unless it is already an array (or array-like).
-
#
-
# Specifically:
-
#
-
# * If the argument is +nil+ an empty list is returned.
-
# * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned.
-
# * Otherwise, returns an array with the argument as its single element.
-
#
-
# Array.wrap(nil) # => []
-
# Array.wrap([1, 2, 3]) # => [1, 2, 3]
-
# Array.wrap(0) # => [0]
-
#
-
# This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
-
#
-
# * If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt>
-
# moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns
-
# +nil+ right away.
-
# * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt>
-
# raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
-
# * It does not call +to_a+ on the argument, but returns an empty array if argument is +nil+.
-
#
-
# The second point is easily explained with some enumerables:
-
#
-
# Array(foo: :bar) # => [[:foo, :bar]]
-
# Array.wrap(foo: :bar) # => [{:foo=>:bar}]
-
#
-
# There's also a related idiom that uses the splat operator:
-
#
-
# [*object]
-
#
-
# which returns <tt>[]</tt> for +nil+, but calls to <tt>Array(object)</tt> otherwise.
-
#
-
# The differences with <tt>Kernel#Array</tt> explained above
-
# apply to the rest of <tt>object</tt>s.
-
1
def self.wrap(object)
-
36
if object.nil?
-
[]
-
36
elsif object.respond_to?(:to_ary)
-
2
object.to_ary || [object]
-
else
-
34
[object]
-
end
-
end
-
end
-
1
require 'benchmark'
-
-
1
class << Benchmark
-
# Benchmark realtime in milliseconds.
-
#
-
# Benchmark.realtime { User.all }
-
# # => 8.0e-05
-
#
-
# Benchmark.ms { User.all }
-
# # => 0.074
-
1
def ms
-
110
1000 * realtime { yield }
-
end
-
end
-
1
require 'active_support/core_ext/big_decimal/conversions'
-
1
require 'bigdecimal'
-
1
require 'bigdecimal/util'
-
-
1
class BigDecimal
-
1
DEFAULT_STRING_FORMAT = 'F'
-
1
def to_formatted_s(*args)
-
if args[0].is_a?(Symbol)
-
super
-
else
-
format = args[0] || DEFAULT_STRING_FORMAT
-
_original_to_s(format)
-
end
-
end
-
1
alias_method :_original_to_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
end
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/class/delegating_attributes'
-
1
require 'active_support/core_ext/class/subclasses'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
class Class
-
# Declare a class-level attribute whose value is inheritable by subclasses.
-
# Subclasses can change their own value and it will not impact parent class.
-
#
-
# class Base
-
# class_attribute :setting
-
# end
-
#
-
# class Subclass < Base
-
# end
-
#
-
# Base.setting = true
-
# Subclass.setting # => true
-
# Subclass.setting = false
-
# Subclass.setting # => false
-
# Base.setting # => true
-
#
-
# In the above case as long as Subclass does not assign a value to setting
-
# by performing <tt>Subclass.setting = _something_ </tt>, <tt>Subclass.setting</tt>
-
# would read value assigned to parent class. Once Subclass assigns a value then
-
# the value assigned by Subclass would be returned.
-
#
-
# This matches normal Ruby method inheritance: think of writing an attribute
-
# on a subclass as overriding the reader method. However, you need to be aware
-
# when using +class_attribute+ with mutable structures as +Array+ or +Hash+.
-
# In such cases, you don't want to do changes in places but use setters:
-
#
-
# Base.setting = []
-
# Base.setting # => []
-
# Subclass.setting # => []
-
#
-
# # Appending in child changes both parent and child because it is the same object:
-
# Subclass.setting << :foo
-
# Base.setting # => [:foo]
-
# Subclass.setting # => [:foo]
-
#
-
# # Use setters to not propagate changes:
-
# Base.setting = []
-
# Subclass.setting += [:foo]
-
# Base.setting # => []
-
# Subclass.setting # => [:foo]
-
#
-
# For convenience, an instance predicate method is defined as well.
-
# To skip it, pass <tt>instance_predicate: false</tt>.
-
#
-
# Subclass.setting? # => false
-
#
-
# Instances may overwrite the class value in the same way:
-
#
-
# Base.setting = true
-
# object = Base.new
-
# object.setting # => true
-
# object.setting = false
-
# object.setting # => false
-
# Base.setting # => true
-
#
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# object.setting # => NoMethodError
-
# object.setting? # => NoMethodError
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
#
-
# object.setting = false # => NoMethodError
-
#
-
# To opt out of both instance methods, pass <tt>instance_accessor: false</tt>.
-
1
def class_attribute(*attrs)
-
102
options = attrs.extract_options!
-
102
instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
-
102
instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
-
102
instance_predicate = options.fetch(:instance_predicate, true)
-
-
102
attrs.each do |name|
-
824
define_singleton_method(name) { nil }
-
121
define_singleton_method("#{name}?") { !!public_send(name) } if instance_predicate
-
-
121
ivar = "@#{name}"
-
-
121
define_singleton_method("#{name}=") do |val|
-
224
singleton_class.class_eval do
-
224
remove_possible_method(name)
-
3983
define_method(name) { val }
-
end
-
-
224
if singleton_class?
-
class_eval do
-
remove_possible_method(name)
-
define_method(name) do
-
if instance_variable_defined? ivar
-
instance_variable_get ivar
-
else
-
singleton_class.send name
-
end
-
end
-
end
-
end
-
224
val
-
end
-
-
121
if instance_reader
-
111
remove_possible_method name
-
111
define_method(name) do
-
1560
if instance_variable_defined?(ivar)
-
instance_variable_get ivar
-
else
-
1560
self.class.public_send name
-
end
-
end
-
144
define_method("#{name}?") { !!public_send(name) } if instance_predicate
-
end
-
-
121
attr_writer name if instance_writer
-
end
-
end
-
-
1
private
-
-
1
unless respond_to?(:singleton_class?)
-
def singleton_class?
-
ancestors.first != self
-
end
-
end
-
end
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/module/deprecation'
-
-
-
1
class Class
-
1
def superclass_delegating_accessor(name, options = {})
-
# Create private _name and _name= methods that can still be used if the public
-
# methods are overridden.
-
_superclass_delegating_accessor("_#{name}", options)
-
-
# Generate the public methods name, name=, and name?.
-
# These methods dispatch to the private _name, and _name= methods, making them
-
# overridable.
-
singleton_class.send(:define_method, name) { send("_#{name}") }
-
singleton_class.send(:define_method, "#{name}?") { !!send("_#{name}") }
-
singleton_class.send(:define_method, "#{name}=") { |value| send("_#{name}=", value) }
-
-
# If an instance_reader is needed, generate public instance methods name and name?.
-
if options[:instance_reader] != false
-
define_method(name) { send("_#{name}") }
-
define_method("#{name}?") { !!send("#{name}") }
-
end
-
end
-
-
1
deprecate superclass_delegating_accessor: :class_attribute
-
-
1
private
-
# Take the object being set and store it in a method. This gives us automatic
-
# inheritance behavior, without having to store the object in an instance
-
# variable and look up the superclass chain manually.
-
1
def _stash_object_in_method(object, method, instance_reader = true)
-
singleton_class.remove_possible_method(method)
-
singleton_class.send(:define_method, method) { object }
-
remove_possible_method(method)
-
define_method(method) { object } if instance_reader
-
end
-
-
1
def _superclass_delegating_accessor(name, options = {})
-
singleton_class.send(:define_method, "#{name}=") do |value|
-
_stash_object_in_method(value, name, options[:instance_reader] != false)
-
end
-
send("#{name}=", nil)
-
end
-
end
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/module/reachable'
-
-
1
class Class
-
1
begin
-
1
ObjectSpace.each_object(Class.new) {}
-
-
1
def descendants # :nodoc:
-
descendants = []
-
ObjectSpace.each_object(singleton_class) do |k|
-
descendants.unshift k unless k == self
-
end
-
descendants
-
end
-
rescue StandardError # JRuby
-
def descendants # :nodoc:
-
descendants = []
-
ObjectSpace.each_object(Class) do |k|
-
descendants.unshift k if k < self
-
end
-
descendants.uniq!
-
descendants
-
end
-
end
-
-
# Returns an array with the direct children of +self+.
-
#
-
# Integer.subclasses # => [Fixnum, Bignum]
-
#
-
# class Foo; end
-
# class Bar < Foo; end
-
# class Baz < Bar; end
-
#
-
# Foo.subclasses # => [Bar]
-
1
def subclasses
-
subclasses, chain = [], descendants
-
chain.each do |k|
-
subclasses << k unless chain.any? { |c| c > k }
-
end
-
subclasses
-
end
-
end
-
1
require 'active_support/core_ext/date/acts_like'
-
1
require 'active_support/core_ext/date/calculations'
-
1
require 'active_support/core_ext/date/conversions'
-
1
require 'active_support/core_ext/date/zones'
-
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
class Date
-
# Duck-types as a Date-like class. See Object#acts_like?.
-
1
def acts_like_date?
-
true
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/object/acts_like'
-
1
require 'active_support/core_ext/date/zones'
-
1
require 'active_support/core_ext/time/zones'
-
1
require 'active_support/core_ext/date_and_time/calculations'
-
-
1
class Date
-
1
include DateAndTime::Calculations
-
-
1
class << self
-
1
attr_accessor :beginning_of_week_default
-
-
# Returns the week start (e.g. :monday) for the current request, if this has been set (via Date.beginning_of_week=).
-
# If <tt>Date.beginning_of_week</tt> has not been set for the current request, returns the week start specified in <tt>config.beginning_of_week</tt>.
-
# If no config.beginning_of_week was specified, returns :monday.
-
1
def beginning_of_week
-
Thread.current[:beginning_of_week] || beginning_of_week_default || :monday
-
end
-
-
# Sets <tt>Date.beginning_of_week</tt> to a week start (e.g. :monday) for current request/thread.
-
#
-
# This method accepts any of the following day symbols:
-
# :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday
-
1
def beginning_of_week=(week_start)
-
Thread.current[:beginning_of_week] = find_beginning_of_week!(week_start)
-
end
-
-
# Returns week start day symbol (e.g. :monday), or raises an ArgumentError for invalid day symbol.
-
1
def find_beginning_of_week!(week_start)
-
1
raise ArgumentError, "Invalid beginning of week: #{week_start}" unless ::Date::DAYS_INTO_WEEK.key?(week_start)
-
1
week_start
-
end
-
-
# Returns a new Date representing the date 1 day ago (i.e. yesterday's date).
-
1
def yesterday
-
::Date.current.yesterday
-
end
-
-
# Returns a new Date representing the date 1 day after today (i.e. tomorrow's date).
-
1
def tomorrow
-
::Date.current.tomorrow
-
end
-
-
# Returns Time.zone.today when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns Date.today.
-
1
def current
-
::Time.zone ? ::Time.zone.today : ::Date.today
-
end
-
end
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
# and then subtracts the specified number of seconds.
-
1
def ago(seconds)
-
in_time_zone.since(-seconds)
-
end
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
# and then adds the specified number of seconds
-
1
def since(seconds)
-
in_time_zone.since(seconds)
-
end
-
1
alias :in :since
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
1
def beginning_of_day
-
in_time_zone
-
end
-
1
alias :midnight :beginning_of_day
-
1
alias :at_midnight :beginning_of_day
-
1
alias :at_beginning_of_day :beginning_of_day
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the middle of the day (12:00)
-
1
def middle_of_day
-
in_time_zone.middle_of_day
-
end
-
1
alias :midday :middle_of_day
-
1
alias :noon :middle_of_day
-
1
alias :at_midday :middle_of_day
-
1
alias :at_noon :middle_of_day
-
1
alias :at_middle_of_day :middle_of_day
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the end of the day (23:59:59)
-
1
def end_of_day
-
in_time_zone.end_of_day
-
end
-
1
alias :at_end_of_day :end_of_day
-
-
1
def plus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
other.since(self)
-
else
-
plus_without_duration(other)
-
end
-
end
-
1
alias_method :plus_without_duration, :+
-
1
alias_method :+, :plus_with_duration
-
-
1
def minus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
plus_with_duration(-other)
-
else
-
minus_without_duration(other)
-
end
-
end
-
1
alias_method :minus_without_duration, :-
-
1
alias_method :-, :minus_with_duration
-
-
# Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with
-
# any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
-
1
def advance(options)
-
options = options.dup
-
d = self
-
d = d >> options.delete(:years) * 12 if options[:years]
-
d = d >> options.delete(:months) if options[:months]
-
d = d + options.delete(:weeks) * 7 if options[:weeks]
-
d = d + options.delete(:days) if options[:days]
-
d
-
end
-
-
# Returns a new Date where one or more of the elements have been changed according to the +options+ parameter.
-
# The +options+ parameter is a hash with a combination of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>.
-
#
-
# Date.new(2007, 5, 12).change(day: 1) # => Date.new(2007, 5, 1)
-
# Date.new(2007, 5, 12).change(year: 2005, month: 1) # => Date.new(2005, 1, 12)
-
1
def change(options)
-
::Date.new(
-
options.fetch(:year, year),
-
options.fetch(:month, month),
-
options.fetch(:day, day)
-
)
-
end
-
-
# Allow Date to be compared with Time by converting to DateTime and relying on the <=> from there.
-
1
def compare_with_coercion(other)
-
2
if other.is_a?(Time)
-
self.to_datetime <=> other
-
else
-
2
compare_without_coercion(other)
-
end
-
end
-
1
alias_method :compare_without_coercion, :<=>
-
1
alias_method :<=>, :compare_with_coercion
-
end
-
1
require 'date'
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/core_ext/date/zones'
-
1
require 'active_support/core_ext/module/remove_method'
-
-
1
class Date
-
1
DATE_FORMATS = {
-
:short => '%e %b',
-
:long => '%B %e, %Y',
-
:db => '%Y-%m-%d',
-
:number => '%Y%m%d',
-
:long_ordinal => lambda { |date|
-
day_format = ActiveSupport::Inflector.ordinalize(date.day)
-
date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007"
-
},
-
:rfc822 => '%e %b %Y',
-
:iso8601 => lambda { |date| date.iso8601 }
-
}
-
-
# Ruby 1.9 has Date#to_time which converts to localtime only.
-
1
remove_method :to_time
-
-
# Ruby 1.9 has Date#xmlschema which converts to a string without the time
-
# component. This removal may generate an issue on FreeBSD, that's why we
-
# need to use remove_possible_method here
-
1
remove_possible_method :xmlschema
-
-
# Convert to a formatted string. See DATE_FORMATS for predefined formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_formatted_s(:db) # => "2007-11-10"
-
# date.to_s(:db) # => "2007-11-10"
-
#
-
# date.to_formatted_s(:short) # => "10 Nov"
-
# date.to_formatted_s(:number) # => "20071110"
-
# date.to_formatted_s(:long) # => "November 10, 2007"
-
# date.to_formatted_s(:long_ordinal) # => "November 10th, 2007"
-
# date.to_formatted_s(:rfc822) # => "10 Nov 2007"
-
# date.to_formatted_s(:iso8601) # => "2007-11-10"
-
#
-
# == Adding your own date formats to to_formatted_s
-
# You can add your own formats to the Date::DATE_FORMATS hash.
-
# Use the format name as the hash key and either a strftime string
-
# or Proc instance that takes a date argument as the value.
-
#
-
# # config/initializers/date_formats.rb
-
# Date::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") }
-
1
def to_formatted_s(format = :default)
-
14
if formatter = DATE_FORMATS[format]
-
6
if formatter.respond_to?(:call)
-
formatter.call(self).to_s
-
else
-
6
strftime(formatter)
-
end
-
else
-
8
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
-
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
-
1
def readable_inspect
-
strftime('%a, %d %b %Y')
-
end
-
1
alias_method :default_inspect, :inspect
-
1
alias_method :inspect, :readable_inspect
-
-
# Converts a Date instance to a Time, where the time is set to the beginning of the day.
-
# The timezone can be either :local or :utc (default :local).
-
#
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_time # => Sat Nov 10 00:00:00 0800 2007
-
# date.to_time(:local) # => Sat Nov 10 00:00:00 0800 2007
-
#
-
# date.to_time(:utc) # => Sat Nov 10 00:00:00 UTC 2007
-
1
def to_time(form = :local)
-
::Time.send(form, year, month, day)
-
end
-
-
# Returns a string which represents the time in used time zone as DateTime
-
# defined by XML Schema:
-
#
-
# date = Date.new(2015, 05, 23) # => Sat, 23 May 2015
-
# date.xmlschema # => "2015-05-23T00:00:00+04:00"
-
1
def xmlschema
-
in_time_zone.xmlschema
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/core_ext/date_and_time/zones'
-
-
1
class Date
-
1
include DateAndTime::Zones
-
end
-
1
module DateAndTime
-
1
module Calculations
-
1
DAYS_INTO_WEEK = {
-
:monday => 0,
-
:tuesday => 1,
-
:wednesday => 2,
-
:thursday => 3,
-
:friday => 4,
-
:saturday => 5,
-
:sunday => 6
-
}
-
-
# Returns a new date/time representing yesterday.
-
1
def yesterday
-
advance(:days => -1)
-
end
-
-
# Returns a new date/time representing tomorrow.
-
1
def tomorrow
-
advance(:days => 1)
-
end
-
-
# Returns true if the date/time is today.
-
1
def today?
-
to_date == ::Date.current
-
end
-
-
# Returns true if the date/time is in the past.
-
1
def past?
-
self < self.class.current
-
end
-
-
# Returns true if the date/time is in the future.
-
1
def future?
-
self > self.class.current
-
end
-
-
# Returns a new date/time the specified number of days ago.
-
1
def days_ago(days)
-
advance(:days => -days)
-
end
-
-
# Returns a new date/time the specified number of days in the future.
-
1
def days_since(days)
-
advance(:days => days)
-
end
-
-
# Returns a new date/time the specified number of weeks ago.
-
1
def weeks_ago(weeks)
-
advance(:weeks => -weeks)
-
end
-
-
# Returns a new date/time the specified number of weeks in the future.
-
1
def weeks_since(weeks)
-
advance(:weeks => weeks)
-
end
-
-
# Returns a new date/time the specified number of months ago.
-
1
def months_ago(months)
-
advance(:months => -months)
-
end
-
-
# Returns a new date/time the specified number of months in the future.
-
1
def months_since(months)
-
advance(:months => months)
-
end
-
-
# Returns a new date/time the specified number of years ago.
-
1
def years_ago(years)
-
advance(:years => -years)
-
end
-
-
# Returns a new date/time the specified number of years in the future.
-
1
def years_since(years)
-
advance(:years => years)
-
end
-
-
# Returns a new date/time at the start of the month.
-
# DateTime objects will have a time set to 0:00.
-
1
def beginning_of_month
-
first_hour(change(:day => 1))
-
end
-
1
alias :at_beginning_of_month :beginning_of_month
-
-
# Returns a new date/time at the start of the quarter.
-
# Example: 1st January, 1st July, 1st October.
-
# DateTime objects will have a time set to 0:00.
-
1
def beginning_of_quarter
-
first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month }
-
beginning_of_month.change(:month => first_quarter_month)
-
end
-
1
alias :at_beginning_of_quarter :beginning_of_quarter
-
-
# Returns a new date/time at the end of the quarter.
-
# Example: 31st March, 30th June, 30th September.
-
# DateTime objects will have a time set to 23:59:59.
-
1
def end_of_quarter
-
last_quarter_month = [3, 6, 9, 12].detect { |m| m >= month }
-
beginning_of_month.change(:month => last_quarter_month).end_of_month
-
end
-
1
alias :at_end_of_quarter :end_of_quarter
-
-
# Return a new date/time at the beginning of the year.
-
# Example: 1st January.
-
# DateTime objects will have a time set to 0:00.
-
1
def beginning_of_year
-
change(:month => 1).beginning_of_month
-
end
-
1
alias :at_beginning_of_year :beginning_of_year
-
-
# Returns a new date/time representing the given day in the next week.
-
#
-
# today = Date.today # => Thu, 07 May 2015
-
# today.next_week # => Mon, 11 May 2015
-
#
-
# The +given_day_in_next_week+ defaults to the beginning of the week
-
# which is determined by +Date.beginning_of_week+ or +config.beginning_of_week+
-
#
-
# today = Date.today # => Thu, 07 May 2015
-
# today.next_week(:friday) # => Fri, 15 May 2015
-
#
-
# when set. +DateTime+ objects have their time set to 0:00.
-
#
-
# now = Time.current # => Thu, 07 May 2015 13:31:16 UTC +00:00
-
# now.next_week # => Mon, 11 May 2015 00:00:00 UTC +00:00
-
1
def next_week(given_day_in_next_week = Date.beginning_of_week)
-
first_hour(weeks_since(1).beginning_of_week.days_since(days_span(given_day_in_next_week)))
-
end
-
-
# Short-hand for months_since(1).
-
1
def next_month
-
months_since(1)
-
end
-
-
# Short-hand for months_since(3)
-
1
def next_quarter
-
months_since(3)
-
end
-
-
# Short-hand for years_since(1).
-
1
def next_year
-
years_since(1)
-
end
-
-
# Returns a new date/time representing the given day in the previous week.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# DateTime objects have their time set to 0:00.
-
1
def prev_week(start_day = Date.beginning_of_week)
-
first_hour(weeks_ago(1).beginning_of_week.days_since(days_span(start_day)))
-
end
-
1
alias_method :last_week, :prev_week
-
-
# Short-hand for months_ago(1).
-
1
def prev_month
-
months_ago(1)
-
end
-
1
alias_method :last_month, :prev_month
-
-
# Short-hand for months_ago(3).
-
1
def prev_quarter
-
months_ago(3)
-
end
-
1
alias_method :last_quarter, :prev_quarter
-
-
# Short-hand for years_ago(1).
-
1
def prev_year
-
years_ago(1)
-
end
-
1
alias_method :last_year, :prev_year
-
-
# Returns the number of days to the start of the week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
1
def days_to_week_start(start_day = Date.beginning_of_week)
-
start_day_number = DAYS_INTO_WEEK[start_day]
-
current_day_number = wday != 0 ? wday - 1 : 6
-
(current_day_number - start_day_number) % 7
-
end
-
-
# Returns a new date/time representing the start of this week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# +DateTime+ objects have their time set to 0:00.
-
1
def beginning_of_week(start_day = Date.beginning_of_week)
-
result = days_ago(days_to_week_start(start_day))
-
acts_like?(:time) ? result.midnight : result
-
end
-
1
alias :at_beginning_of_week :beginning_of_week
-
-
# Returns Monday of this week assuming that week starts on Monday.
-
# +DateTime+ objects have their time set to 0:00.
-
1
def monday
-
beginning_of_week(:monday)
-
end
-
-
# Returns a new date/time representing the end of this week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# DateTime objects have their time set to 23:59:59.
-
1
def end_of_week(start_day = Date.beginning_of_week)
-
last_hour(days_since(6 - days_to_week_start(start_day)))
-
end
-
1
alias :at_end_of_week :end_of_week
-
-
# Returns Sunday of this week assuming that week starts on Monday.
-
# +DateTime+ objects have their time set to 23:59:59.
-
1
def sunday
-
end_of_week(:monday)
-
end
-
-
# Returns a new date/time representing the end of the month.
-
# DateTime objects will have a time set to 23:59:59.
-
1
def end_of_month
-
last_day = ::Time.days_in_month(month, year)
-
last_hour(days_since(last_day - day))
-
end
-
1
alias :at_end_of_month :end_of_month
-
-
# Returns a new date/time representing the end of the year.
-
# DateTime objects will have a time set to 23:59:59.
-
1
def end_of_year
-
change(:month => 12).end_of_month
-
end
-
1
alias :at_end_of_year :end_of_year
-
-
# Returns a Range representing the whole week of the current date/time.
-
# Week starts on start_day, default is <tt>Date.week_start</tt> or <tt>config.week_start</tt> when set.
-
1
def all_week(start_day = Date.beginning_of_week)
-
beginning_of_week(start_day)..end_of_week(start_day)
-
end
-
-
# Returns a Range representing the whole month of the current date/time.
-
1
def all_month
-
beginning_of_month..end_of_month
-
end
-
-
# Returns a Range representing the whole quarter of the current date/time.
-
1
def all_quarter
-
beginning_of_quarter..end_of_quarter
-
end
-
-
# Returns a Range representing the whole year of the current date/time.
-
1
def all_year
-
beginning_of_year..end_of_year
-
end
-
-
1
private
-
-
1
def first_hour(date_or_time)
-
date_or_time.acts_like?(:time) ? date_or_time.beginning_of_day : date_or_time
-
end
-
-
1
def last_hour(date_or_time)
-
date_or_time.acts_like?(:time) ? date_or_time.end_of_day : date_or_time
-
end
-
-
1
def days_span(day)
-
(DAYS_INTO_WEEK[day] - DAYS_INTO_WEEK[Date.beginning_of_week]) % 7
-
end
-
end
-
end
-
1
module DateAndTime
-
1
module Zones
-
# Returns the simultaneous time in <tt>Time.zone</tt> if a zone is given or
-
# if Time.zone_default is set. Otherwise, it returns the current time.
-
#
-
# Time.zone = 'Hawaii' # => 'Hawaii'
-
# DateTime.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
# Date.new(2000).in_time_zone # => Sat, 01 Jan 2000 00:00:00 HST -10:00
-
#
-
# This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
-
# instead of the operating system's time zone.
-
#
-
# You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
-
# and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
-
#
-
# Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
-
# DateTime.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
-
# Date.new(2000).in_time_zone('Alaska') # => Sat, 01 Jan 2000 00:00:00 AKST -09:00
-
1
def in_time_zone(zone = ::Time.zone)
-
63
time_zone = ::Time.find_zone! zone
-
63
time = acts_like?(:time) ? self : nil
-
-
63
if time_zone
-
63
time_with_zone(time, time_zone)
-
else
-
time || self.to_time
-
end
-
end
-
-
1
private
-
-
1
def time_with_zone(time, zone)
-
63
if time
-
63
ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone)
-
else
-
ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc))
-
end
-
end
-
end
-
end
-
-
1
require 'active_support/core_ext/date_time/acts_like'
-
1
require 'active_support/core_ext/date_time/calculations'
-
1
require 'active_support/core_ext/date_time/conversions'
-
1
require 'active_support/core_ext/date_time/zones'
-
1
require 'date'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
class DateTime
-
# Duck-types as a Date-like class. See Object#acts_like?.
-
1
def acts_like_date?
-
true
-
end
-
-
# Duck-types as a Time-like class. See Object#acts_like?.
-
1
def acts_like_time?
-
true
-
end
-
end
-
1
require 'date'
-
-
1
class DateTime
-
1
class << self
-
# Returns <tt>Time.zone.now.to_datetime</tt> when <tt>Time.zone</tt> or
-
# <tt>config.time_zone</tt> are set, otherwise returns
-
# <tt>Time.now.to_datetime</tt>.
-
1
def current
-
::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
-
end
-
end
-
-
# Seconds since midnight: DateTime.now.seconds_since_midnight.
-
1
def seconds_since_midnight
-
sec + (min * 60) + (hour * 3600)
-
end
-
-
# Returns the number of seconds until 23:59:59.
-
#
-
# DateTime.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399
-
# DateTime.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
-
# DateTime.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0
-
1
def seconds_until_end_of_day
-
end_of_day.to_i - to_i
-
end
-
-
# Returns a new DateTime where one or more of the elements have been changed
-
# according to the +options+ parameter. The time options (<tt>:hour</tt>,
-
# <tt>:min</tt>, <tt>:sec</tt>) reset cascadingly, so if only the hour is
-
# passed, then minute and sec is set to 0. If the hour and minute is passed,
-
# then sec is set to 0. The +options+ parameter takes a hash with any of these
-
# keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>,
-
# <tt>:min</tt>, <tt>:sec</tt>, <tt>:offset</tt>, <tt>:start</tt>.
-
#
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => DateTime.new(2012, 8, 1, 22, 35, 0)
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => DateTime.new(1981, 8, 1, 22, 35, 0)
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0)
-
1
def change(options)
-
::DateTime.civil(
-
options.fetch(:year, year),
-
options.fetch(:month, month),
-
options.fetch(:day, day),
-
options.fetch(:hour, hour),
-
options.fetch(:min, options[:hour] ? 0 : min),
-
options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec + sec_fraction),
-
options.fetch(:offset, offset),
-
options.fetch(:start, start)
-
)
-
end
-
-
# Uses Date to provide precise Time calculations for years, months, and days.
-
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
-
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
-
# <tt>:minutes</tt>, <tt>:seconds</tt>.
-
1
def advance(options)
-
unless options[:weeks].nil?
-
options[:weeks], partial_weeks = options[:weeks].divmod(1)
-
options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
-
end
-
-
unless options[:days].nil?
-
options[:days], partial_days = options[:days].divmod(1)
-
options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
-
end
-
-
d = to_date.advance(options)
-
datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
-
seconds_to_advance = \
-
options.fetch(:seconds, 0) +
-
options.fetch(:minutes, 0) * 60 +
-
options.fetch(:hours, 0) * 3600
-
-
if seconds_to_advance.zero?
-
datetime_advanced_by_date
-
else
-
datetime_advanced_by_date.since(seconds_to_advance)
-
end
-
end
-
-
# Returns a new DateTime representing the time a number of seconds ago.
-
# Do not use this method in combination with x.months, use months_ago instead!
-
1
def ago(seconds)
-
since(-seconds)
-
end
-
-
# Returns a new DateTime representing the time a number of seconds since the
-
# instance time. Do not use this method in combination with x.months, use
-
# months_since instead!
-
1
def since(seconds)
-
self + Rational(seconds.round, 86400)
-
end
-
1
alias :in :since
-
-
# Returns a new DateTime representing the start of the day (0:00).
-
1
def beginning_of_day
-
change(:hour => 0)
-
end
-
1
alias :midnight :beginning_of_day
-
1
alias :at_midnight :beginning_of_day
-
1
alias :at_beginning_of_day :beginning_of_day
-
-
# Returns a new DateTime representing the middle of the day (12:00)
-
1
def middle_of_day
-
change(:hour => 12)
-
end
-
1
alias :midday :middle_of_day
-
1
alias :noon :middle_of_day
-
1
alias :at_midday :middle_of_day
-
1
alias :at_noon :middle_of_day
-
1
alias :at_middle_of_day :middle_of_day
-
-
# Returns a new DateTime representing the end of the day (23:59:59).
-
1
def end_of_day
-
change(:hour => 23, :min => 59, :sec => 59)
-
end
-
1
alias :at_end_of_day :end_of_day
-
-
# Returns a new DateTime representing the start of the hour (hh:00:00).
-
1
def beginning_of_hour
-
change(:min => 0)
-
end
-
1
alias :at_beginning_of_hour :beginning_of_hour
-
-
# Returns a new DateTime representing the end of the hour (hh:59:59).
-
1
def end_of_hour
-
change(:min => 59, :sec => 59)
-
end
-
1
alias :at_end_of_hour :end_of_hour
-
-
# Returns a new DateTime representing the start of the minute (hh:mm:00).
-
1
def beginning_of_minute
-
change(:sec => 0)
-
end
-
1
alias :at_beginning_of_minute :beginning_of_minute
-
-
# Returns a new DateTime representing the end of the minute (hh:mm:59).
-
1
def end_of_minute
-
change(:sec => 59)
-
end
-
1
alias :at_end_of_minute :end_of_minute
-
-
# Adjusts DateTime to UTC by adding its offset value; offset is set to 0.
-
#
-
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)) # => Mon, 21 Feb 2005 10:11:12 -0600
-
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 +0000
-
1
def utc
-
new_offset(0)
-
end
-
1
alias_method :getutc, :utc
-
-
# Returns +true+ if <tt>offset == 0</tt>.
-
1
def utc?
-
offset == 0
-
end
-
-
# Returns the offset value in seconds.
-
1
def utc_offset
-
(offset * 86400).to_i
-
end
-
-
# Layers additional behavior on DateTime#<=> so that Time and
-
# ActiveSupport::TimeWithZone instances can be compared with a DateTime.
-
1
def <=>(other)
-
1
if other.kind_of?(Infinity)
-
super
-
1
elsif other.respond_to? :to_datetime
-
super other.to_datetime rescue nil
-
else
-
nil
-
end
-
end
-
-
end
-
1
require 'date'
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/date_time/calculations'
-
1
require 'active_support/values/time_zone'
-
-
1
class DateTime
-
# Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# === Examples
-
# datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000
-
#
-
# datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
-
# datetime.to_s(:db) # => "2007-12-04 00:00:00"
-
# datetime.to_s(:number) # => "20071204000000"
-
# datetime.to_formatted_s(:short) # => "04 Dec 00:00"
-
# datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
-
# datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
-
# datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
-
# datetime.to_formatted_s(:iso8601) # => "2007-12-04T00:00:00+00:00"
-
#
-
# == Adding your own datetime formats to to_formatted_s
-
# DateTime formats are shared with Time. You can add your own to the
-
# Time::DATE_FORMATS hash. Use the format name as the hash key and
-
# either a strftime string or Proc instance that takes a time or
-
# datetime argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Time::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
-
1
def to_formatted_s(format = :default)
-
if formatter = ::Time::DATE_FORMATS[format]
-
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s if instance_methods(false).include?(:to_s)
-
1
alias_method :to_s, :to_formatted_s
-
-
#
-
# datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24))
-
# datetime.formatted_offset # => "-06:00"
-
# datetime.formatted_offset(false) # => "-0600"
-
1
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000".
-
1
def readable_inspect
-
to_s(:rfc822)
-
end
-
1
alias_method :default_inspect, :inspect
-
1
alias_method :inspect, :readable_inspect
-
-
# Returns DateTime with local offset for given year if format is local else
-
# offset is zero.
-
#
-
# DateTime.civil_from_format :local, 2012
-
# # => Sun, 01 Jan 2012 00:00:00 +0300
-
# DateTime.civil_from_format :local, 2012, 12, 17
-
# # => Mon, 17 Dec 2012 00:00:00 +0000
-
1
def self.civil_from_format(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0)
-
if utc_or_local.to_sym == :local
-
offset = ::Time.local(year, month, day).utc_offset.to_r / 86400
-
else
-
offset = 0
-
end
-
civil(year, month, day, hour, min, sec, offset)
-
end
-
-
# Converts +self+ to a floating-point number of seconds, including fractional microseconds, since the Unix epoch.
-
1
def to_f
-
seconds_since_unix_epoch.to_f + sec_fraction
-
end
-
-
# Converts +self+ to an integer number of seconds since the Unix epoch.
-
1
def to_i
-
seconds_since_unix_epoch.to_i
-
end
-
-
# Returns the fraction of a second as microseconds
-
1
def usec
-
(sec_fraction * 1_000_000).to_i
-
end
-
-
# Returns the fraction of a second as nanoseconds
-
1
def nsec
-
(sec_fraction * 1_000_000_000).to_i
-
end
-
-
1
private
-
-
1
def offset_in_seconds
-
(offset * 86400).to_i
-
end
-
-
1
def seconds_since_unix_epoch
-
(jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/core_ext/date_and_time/zones'
-
-
1
class DateTime
-
1
include DateAndTime::Zones
-
end
-
1
require 'securerandom'
-
-
1
module Digest
-
1
module UUID
-
1
DNS_NAMESPACE = "k\xA7\xB8\x10\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc:
-
1
URL_NAMESPACE = "k\xA7\xB8\x11\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc:
-
1
OID_NAMESPACE = "k\xA7\xB8\x12\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc:
-
1
X500_NAMESPACE = "k\xA7\xB8\x14\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc:
-
-
# Generates a v5 non-random UUID (Universally Unique IDentifier).
-
#
-
# Using Digest::MD5 generates version 3 UUIDs; Digest::SHA1 generates version 5 UUIDs.
-
# uuid_from_hash always generates the same UUID for a given name and namespace combination.
-
#
-
# See RFC 4122 for details of UUID at: http://www.ietf.org/rfc/rfc4122.txt
-
1
def self.uuid_from_hash(hash_class, uuid_namespace, name)
-
if hash_class == Digest::MD5
-
version = 3
-
elsif hash_class == Digest::SHA1
-
version = 5
-
else
-
raise ArgumentError, "Expected Digest::SHA1 or Digest::MD5, got #{hash_class.name}."
-
end
-
-
hash = hash_class.new
-
hash.update(uuid_namespace)
-
hash.update(name)
-
-
ary = hash.digest.unpack('NnnnnN')
-
ary[2] = (ary[2] & 0x0FFF) | (version << 12)
-
ary[3] = (ary[3] & 0x3FFF) | 0x8000
-
-
"%08x-%04x-%04x-%04x-%04x%08x" % ary
-
end
-
-
# Convenience method for uuid_from_hash using Digest::MD5.
-
1
def self.uuid_v3(uuid_namespace, name)
-
self.uuid_from_hash(Digest::MD5, uuid_namespace, name)
-
end
-
-
# Convenience method for uuid_from_hash using Digest::SHA1.
-
1
def self.uuid_v5(uuid_namespace, name)
-
self.uuid_from_hash(Digest::SHA1, uuid_namespace, name)
-
end
-
-
# Convenience method for SecureRandom.uuid.
-
1
def self.uuid_v4
-
SecureRandom.uuid
-
end
-
end
-
end
-
1
module Enumerable
-
# Calculates a sum from the elements.
-
#
-
# payments.sum { |p| p.price * p.tax_rate }
-
# payments.sum(&:price)
-
#
-
# The latter is a shortcut for:
-
#
-
# payments.inject(0) { |sum, p| sum + p.price }
-
#
-
# It can also calculate the sum without the use of a block.
-
#
-
# [5, 15, 10].sum # => 30
-
# ['foo', 'bar'].sum # => "foobar"
-
# [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
-
#
-
# The default sum of an empty list is zero. You can override this default:
-
#
-
# [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
-
1
def sum(identity = 0, &block)
-
if block_given?
-
map(&block).sum(identity)
-
else
-
inject { |sum, element| sum + element } || identity
-
end
-
end
-
-
# Convert an enumerable to a hash.
-
#
-
# people.index_by(&:login)
-
# => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
-
# people.index_by { |person| "#{person.first_name} #{person.last_name}" }
-
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
-
1
def index_by
-
if block_given?
-
Hash[map { |elem| [yield(elem), elem] }]
-
else
-
to_enum(:index_by) { size if respond_to?(:size) }
-
end
-
end
-
-
# Returns +true+ if the enumerable has more than 1 element. Functionally
-
# equivalent to <tt>enum.to_a.size > 1</tt>. Can be called with a block too,
-
# much like any?, so <tt>people.many? { |p| p.age > 26 }</tt> returns +true+
-
# if more than one person is over 26.
-
1
def many?
-
cnt = 0
-
if block_given?
-
any? do |element|
-
cnt += 1 if yield element
-
cnt > 1
-
end
-
else
-
any? { (cnt += 1) > 1 }
-
end
-
end
-
-
# The negative of the <tt>Enumerable#include?</tt>. Returns +true+ if the
-
# collection does not include the object.
-
1
def exclude?(object)
-
!include?(object)
-
end
-
end
-
-
1
class Range #:nodoc:
-
# Optimize range sum to use arithmetic progression if a block is not given and
-
# we have a range of numeric values.
-
1
def sum(identity = 0)
-
if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer))
-
super
-
else
-
actual_last = exclude_end? ? (last - 1) : last
-
if actual_last >= first
-
(actual_last - first + 1) * (actual_last + first) / 2
-
else
-
identity
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/file/atomic'
-
1
require 'fileutils'
-
-
1
class File
-
# Write to a file atomically. Useful for situations where you don't
-
# want other processes or threads to see half-written files.
-
#
-
# File.atomic_write('important.file') do |file|
-
# file.write('hello')
-
# end
-
#
-
# If your temp directory is not on the same filesystem as the file you're
-
# trying to write, you can provide a different temporary directory.
-
#
-
# File.atomic_write('/data/something.important', '/data/tmp') do |file|
-
# file.write('hello')
-
# end
-
1
def self.atomic_write(file_name, temp_dir = Dir.tmpdir)
-
require 'tempfile' unless defined?(Tempfile)
-
require 'fileutils' unless defined?(FileUtils)
-
-
temp_file = Tempfile.new(basename(file_name), temp_dir)
-
temp_file.binmode
-
yield temp_file
-
temp_file.close
-
-
if File.exist?(file_name)
-
# Get original file permissions
-
old_stat = stat(file_name)
-
else
-
# If not possible, probe which are the default permissions in the
-
# destination directory.
-
old_stat = probe_stat_in(dirname(file_name))
-
end
-
-
# Overwrite original file with temp file
-
FileUtils.mv(temp_file.path, file_name)
-
-
# Set correct permissions on new file
-
begin
-
chown(old_stat.uid, old_stat.gid, file_name)
-
# This operation will affect filesystem ACL's
-
chmod(old_stat.mode, file_name)
-
rescue Errno::EPERM, Errno::EACCES
-
# Changing file ownership failed, moving on.
-
end
-
end
-
-
# Private utility method.
-
1
def self.probe_stat_in(dir) #:nodoc:
-
basename = [
-
'.permissions_check',
-
Thread.current.object_id,
-
Process.pid,
-
rand(1000000)
-
].join('.')
-
-
file_name = join(dir, basename)
-
FileUtils.touch(file_name)
-
stat(file_name)
-
ensure
-
FileUtils.rm_f(file_name) if file_name
-
end
-
end
-
1
require 'active_support/core_ext/hash/compact'
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'active_support/core_ext/hash/deep_merge'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/hash/transform_values'
-
1
class Hash
-
# Returns a hash with non +nil+ values.
-
#
-
# hash = { a: true, b: false, c: nil}
-
# hash.compact # => { a: true, b: false}
-
# hash # => { a: true, b: false, c: nil}
-
# { c: nil }.compact # => {}
-
1
def compact
-
self.select { |_, value| !value.nil? }
-
end
-
-
# Replaces current hash with non +nil+ values.
-
#
-
# hash = { a: true, b: false, c: nil}
-
# hash.compact! # => { a: true, b: false}
-
# hash # => { a: true, b: false}
-
1
def compact!
-
self.reject! { |_, value| value.nil? }
-
end
-
end
-
1
require 'active_support/xml_mini'
-
1
require 'active_support/time'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
class Hash
-
# Returns a string containing an XML representation of its receiver:
-
#
-
# { foo: 1, bar: 2 }.to_xml
-
# # =>
-
# # <?xml version="1.0" encoding="UTF-8"?>
-
# # <hash>
-
# # <foo type="integer">1</foo>
-
# # <bar type="integer">2</bar>
-
# # </hash>
-
#
-
# To do so, the method loops over the pairs and builds nodes that depend on
-
# the _values_. Given a pair +key+, +value+:
-
#
-
# * If +value+ is a hash there's a recursive call with +key+ as <tt>:root</tt>.
-
#
-
# * If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>,
-
# and +key+ singularized as <tt>:children</tt>.
-
#
-
# * If +value+ is a callable object it must expect one or two arguments. Depending
-
# on the arity, the callable is invoked with the +options+ hash as first argument
-
# with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. The
-
# callable can add nodes by using <tt>options[:builder]</tt>.
-
#
-
# 'foo'.to_xml(lambda { |options, key| options[:builder].b(key) })
-
# # => "<b>foo</b>"
-
#
-
# * If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
-
#
-
# class Foo
-
# def to_xml(options)
-
# options[:builder].bar 'fooing!'
-
# end
-
# end
-
#
-
# { foo: Foo.new }.to_xml(skip_instruct: true)
-
# # =>
-
# # <hash>
-
# # <bar>fooing!</bar>
-
# # </hash>
-
#
-
# * Otherwise, a node with +key+ as tag is created with a string representation of
-
# +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added.
-
# Unless the option <tt>:skip_types</tt> exists and is true, an attribute "type" is
-
# added as well according to the following mapping:
-
#
-
# XML_TYPE_NAMES = {
-
# "Symbol" => "symbol",
-
# "Fixnum" => "integer",
-
# "Bignum" => "integer",
-
# "BigDecimal" => "decimal",
-
# "Float" => "float",
-
# "TrueClass" => "boolean",
-
# "FalseClass" => "boolean",
-
# "Date" => "date",
-
# "DateTime" => "dateTime",
-
# "Time" => "dateTime"
-
# }
-
#
-
# By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.
-
#
-
# The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can
-
# configure your own builder with the <tt>:builder</tt> option. The method also accepts
-
# options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.
-
1
def to_xml(options = {})
-
require 'active_support/builder' unless defined?(Builder)
-
-
options = options.dup
-
options[:indent] ||= 2
-
options[:root] ||= 'hash'
-
options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
-
-
builder = options[:builder]
-
builder.instruct! unless options.delete(:skip_instruct)
-
-
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
-
-
builder.tag!(root) do
-
each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) }
-
yield builder if block_given?
-
end
-
end
-
-
1
class << self
-
# Returns a Hash containing a collection of pairs when the key is the node name and the value is
-
# its content
-
#
-
# xml = <<-XML
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <hash>
-
# <foo type="integer">1</foo>
-
# <bar type="integer">2</bar>
-
# </hash>
-
# XML
-
#
-
# hash = Hash.from_xml(xml)
-
# # => {"hash"=>{"foo"=>1, "bar"=>2}}
-
#
-
# +DisallowedType+ is raised if the XML contains attributes with <tt>type="yaml"</tt> or
-
# <tt>type="symbol"</tt>. Use <tt>Hash.from_trusted_xml</tt> to parse this XML.
-
1
def from_xml(xml, disallowed_types = nil)
-
ActiveSupport::XMLConverter.new(xml, disallowed_types).to_h
-
end
-
-
# Builds a Hash from XML just like <tt>Hash.from_xml</tt>, but also allows Symbol and YAML.
-
1
def from_trusted_xml(xml)
-
from_xml xml, []
-
end
-
end
-
end
-
-
1
module ActiveSupport
-
1
class XMLConverter # :nodoc:
-
1
class DisallowedType < StandardError
-
1
def initialize(type)
-
super "Disallowed type attribute: #{type.inspect}"
-
end
-
end
-
-
1
DISALLOWED_TYPES = %w(symbol yaml)
-
-
1
def initialize(xml, disallowed_types = nil)
-
@xml = normalize_keys(XmlMini.parse(xml))
-
@disallowed_types = disallowed_types || DISALLOWED_TYPES
-
end
-
-
1
def to_h
-
deep_to_h(@xml)
-
end
-
-
1
private
-
1
def normalize_keys(params)
-
case params
-
when Hash
-
Hash[params.map { |k,v| [k.to_s.tr('-', '_'), normalize_keys(v)] } ]
-
when Array
-
params.map { |v| normalize_keys(v) }
-
else
-
params
-
end
-
end
-
-
1
def deep_to_h(value)
-
case value
-
when Hash
-
process_hash(value)
-
when Array
-
process_array(value)
-
when String
-
value
-
else
-
raise "can't typecast #{value.class.name} - #{value.inspect}"
-
end
-
end
-
-
1
def process_hash(value)
-
if value.include?('type') && !value['type'].is_a?(Hash) && @disallowed_types.include?(value['type'])
-
raise DisallowedType, value['type']
-
end
-
-
if become_array?(value)
-
_, entries = Array.wrap(value.detect { |k,v| not v.is_a?(String) })
-
if entries.nil? || value['__content__'].try(:empty?)
-
[]
-
else
-
case entries
-
when Array
-
entries.collect { |v| deep_to_h(v) }
-
when Hash
-
[deep_to_h(entries)]
-
else
-
raise "can't typecast #{entries.inspect}"
-
end
-
end
-
elsif become_content?(value)
-
process_content(value)
-
-
elsif become_empty_string?(value)
-
''
-
elsif become_hash?(value)
-
xml_value = Hash[value.map { |k,v| [k, deep_to_h(v)] }]
-
-
# Turn { files: { file: #<StringIO> } } into { files: #<StringIO> } so it is compatible with
-
# how multipart uploaded files from HTML appear
-
xml_value['file'].is_a?(StringIO) ? xml_value['file'] : xml_value
-
end
-
end
-
-
1
def become_content?(value)
-
value['type'] == 'file' || (value['__content__'] && (value.keys.size == 1 || value['__content__'].present?))
-
end
-
-
1
def become_array?(value)
-
value['type'] == 'array'
-
end
-
-
1
def become_empty_string?(value)
-
# { "string" => true }
-
# No tests fail when the second term is removed.
-
value['type'] == 'string' && value['nil'] != 'true'
-
end
-
-
1
def become_hash?(value)
-
!nothing?(value) && !garbage?(value)
-
end
-
-
1
def nothing?(value)
-
# blank or nil parsed values are represented by nil
-
value.blank? || value['nil'] == 'true'
-
end
-
-
1
def garbage?(value)
-
# If the type is the only element which makes it then
-
# this still makes the value nil, except if type is
-
# an XML node(where type['value'] is a Hash)
-
value['type'] && !value['type'].is_a?(::Hash) && value.size == 1
-
end
-
-
1
def process_content(value)
-
content = value['__content__']
-
if parser = ActiveSupport::XmlMini::PARSING[value['type']]
-
parser.arity == 1 ? parser.call(content) : parser.call(content, value)
-
else
-
content
-
end
-
end
-
-
1
def process_array(value)
-
value.map! { |i| deep_to_h(i) }
-
value.length > 1 ? value : value.first
-
end
-
-
end
-
end
-
1
class Hash
-
# Returns a new hash with +self+ and +other_hash+ merged recursively.
-
#
-
# h1 = { a: true, b: { c: [1, 2, 3] } }
-
# h2 = { a: false, b: { x: [3, 4, 5] } }
-
#
-
# h1.deep_merge(h2) #=> { a: false, b: { c: [1, 2, 3], x: [3, 4, 5] } }
-
#
-
# Like with Hash#merge in the standard library, a block can be provided
-
# to merge values:
-
#
-
# h1 = { a: 100, b: 200, c: { c1: 100 } }
-
# h2 = { b: 250, c: { c1: 200 } }
-
# h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val }
-
# # => { a: 100, b: 450, c: { c1: 300 } }
-
1
def deep_merge(other_hash, &block)
-
16
dup.deep_merge!(other_hash, &block)
-
end
-
-
# Same as +deep_merge+, but modifies +self+.
-
1
def deep_merge!(other_hash, &block)
-
79
other_hash.each_pair do |current_key, other_value|
-
87
this_value = self[current_key]
-
-
87
self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash)
-
16
this_value.deep_merge(other_value, &block)
-
else
-
71
if block_given? && key?(current_key)
-
block.call(current_key, this_value, other_value)
-
else
-
71
other_value
-
end
-
end
-
end
-
-
79
self
-
end
-
end
-
1
class Hash
-
# Returns a hash that includes everything but the given keys.
-
# hash = { a: true, b: false, c: nil}
-
# hash.except(:c) # => { a: true, b: false}
-
# hash # => { a: true, b: false, c: nil}
-
#
-
# This is useful for limiting a set of parameters to everything but a few known toggles:
-
# @person.update(params[:person].except(:admin))
-
1
def except(*keys)
-
155
dup.except!(*keys)
-
end
-
-
# Replaces the hash without the given keys.
-
# hash = { a: true, b: false, c: nil}
-
# hash.except!(:c) # => { a: true, b: false}
-
# hash # => { a: true, b: false }
-
1
def except!(*keys)
-
835
keys.each { |key| delete(key) }
-
155
self
-
end
-
end
-
1
require 'active_support/hash_with_indifferent_access'
-
-
1
class Hash
-
-
# Returns an <tt>ActiveSupport::HashWithIndifferentAccess</tt> out of its receiver:
-
#
-
# { a: 1 }.with_indifferent_access['a'] # => 1
-
1
def with_indifferent_access
-
140
ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self)
-
end
-
-
# Called when object is nested under an object that receives
-
# #with_indifferent_access. This method will be called on the current object
-
# by the enclosing object and is aliased to #with_indifferent_access by
-
# default. Subclasses of Hash may overwrite this method to return +self+ if
-
# converting to an <tt>ActiveSupport::HashWithIndifferentAccess</tt> would not be
-
# desirable.
-
#
-
# b = { b: 1 }
-
# { a: b }.with_indifferent_access['a'] # calls b.nested_under_indifferent_access
-
# # => {"b"=>1}
-
1
alias nested_under_indifferent_access with_indifferent_access
-
end
-
1
class Hash
-
# Returns a new hash with all keys converted using the block operation.
-
#
-
# hash = { name: 'Rob', age: '28' }
-
#
-
# hash.transform_keys{ |key| key.to_s.upcase }
-
# # => {"NAME"=>"Rob", "AGE"=>"28"}
-
1
def transform_keys
-
930
return enum_for(:transform_keys) unless block_given?
-
930
result = self.class.new
-
930
each_key do |key|
-
851
result[yield(key)] = self[key]
-
end
-
930
result
-
end
-
-
# Destructively convert all keys using the block operations.
-
# Same as transform_keys but modifies +self+.
-
1
def transform_keys!
-
28
return enum_for(:transform_keys!) unless block_given?
-
28
keys.each do |key|
-
210
self[yield(key)] = delete(key)
-
end
-
28
self
-
end
-
-
# Returns a new hash with all keys converted to strings.
-
#
-
# hash = { name: 'Rob', age: '28' }
-
#
-
# hash.stringify_keys
-
# # => {"name"=>"Rob", "age"=>"28"}
-
1
def stringify_keys
-
841
transform_keys{ |key| key.to_s }
-
end
-
-
# Destructively convert all keys to strings. Same as
-
# +stringify_keys+, but modifies +self+.
-
1
def stringify_keys!
-
18
transform_keys!{ |key| key.to_s }
-
end
-
-
# Returns a new hash with all keys converted to symbols, as long as
-
# they respond to +to_sym+.
-
#
-
# hash = { 'name' => 'Rob', 'age' => '28' }
-
#
-
# hash.symbolize_keys
-
# # => {:name=>"Rob", :age=>"28"}
-
1
def symbolize_keys
-
940
transform_keys{ |key| key.to_sym rescue key }
-
end
-
1
alias_method :to_options, :symbolize_keys
-
-
# Destructively convert all keys to symbols, as long as they respond
-
# to +to_sym+. Same as +symbolize_keys+, but modifies +self+.
-
1
def symbolize_keys!
-
220
transform_keys!{ |key| key.to_sym rescue key }
-
end
-
1
alias_method :to_options!, :symbolize_keys!
-
-
# Validate all keys in a hash match <tt>*valid_keys</tt>, raising
-
# ArgumentError on a mismatch.
-
#
-
# Note that keys are treated differently than HashWithIndifferentAccess,
-
# meaning that string and symbol keys will not match.
-
#
-
# { name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age"
-
# { name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'"
-
# { name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing
-
1
def assert_valid_keys(*valid_keys)
-
72
valid_keys.flatten!
-
72
each_key do |k|
-
5
unless valid_keys.include?(k)
-
raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}")
-
end
-
end
-
end
-
-
# Returns a new hash with all keys converted by the block operation.
-
# This includes the keys from the root hash and from all
-
# nested hashes and arrays.
-
#
-
# hash = { person: { name: 'Rob', age: '28' } }
-
#
-
# hash.deep_transform_keys{ |key| key.to_s.upcase }
-
# # => {"PERSON"=>{"NAME"=>"Rob", "AGE"=>"28"}}
-
1
def deep_transform_keys(&block)
-
63
_deep_transform_keys_in_object(self, &block)
-
end
-
-
# Destructively convert all keys by using the block operation.
-
# This includes the keys from the root hash and from all
-
# nested hashes and arrays.
-
1
def deep_transform_keys!(&block)
-
_deep_transform_keys_in_object!(self, &block)
-
end
-
-
# Returns a new hash with all keys converted to strings.
-
# This includes the keys from the root hash and from all
-
# nested hashes and arrays.
-
#
-
# hash = { person: { name: 'Rob', age: '28' } }
-
#
-
# hash.deep_stringify_keys
-
# # => {"person"=>{"name"=>"Rob", "age"=>"28"}}
-
1
def deep_stringify_keys
-
deep_transform_keys{ |key| key.to_s }
-
end
-
-
# Destructively convert all keys to strings.
-
# This includes the keys from the root hash and from all
-
# nested hashes and arrays.
-
1
def deep_stringify_keys!
-
deep_transform_keys!{ |key| key.to_s }
-
end
-
-
# Returns a new hash with all keys converted to symbols, as long as
-
# they respond to +to_sym+. This includes the keys from the root hash
-
# and from all nested hashes and arrays.
-
#
-
# hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
-
#
-
# hash.deep_symbolize_keys
-
# # => {:person=>{:name=>"Rob", :age=>"28"}}
-
1
def deep_symbolize_keys
-
2083
deep_transform_keys{ |key| key.to_sym rescue key }
-
end
-
-
# Destructively convert all keys to symbols, as long as they respond
-
# to +to_sym+. This includes the keys from the root hash and from all
-
# nested hashes and arrays.
-
1
def deep_symbolize_keys!
-
deep_transform_keys!{ |key| key.to_sym rescue key }
-
end
-
-
1
private
-
# support methods for deep transforming nested hashes and arrays
-
1
def _deep_transform_keys_in_object(object, &block)
-
71731
case object
-
when Hash
-
554
object.each_with_object({}) do |(key, value), result|
-
2020
result[yield(key)] = _deep_transform_keys_in_object(value, &block)
-
end
-
when Array
-
70938
object.map {|e| _deep_transform_keys_in_object(e, &block) }
-
else
-
69887
object
-
end
-
end
-
-
1
def _deep_transform_keys_in_object!(object, &block)
-
case object
-
when Hash
-
object.keys.each do |key|
-
value = object.delete(key)
-
object[yield(key)] = _deep_transform_keys_in_object!(value, &block)
-
end
-
object
-
when Array
-
object.map! {|e| _deep_transform_keys_in_object!(e, &block)}
-
else
-
object
-
end
-
end
-
end
-
1
class Hash
-
# Merges the caller into +other_hash+. For example,
-
#
-
# options = options.reverse_merge(size: 25, velocity: 10)
-
#
-
# is equivalent to
-
#
-
# options = { size: 25, velocity: 10 }.merge(options)
-
#
-
# This is particularly useful for initializing an options hash
-
# with default values.
-
1
def reverse_merge(other_hash)
-
62
other_hash.merge(self)
-
end
-
-
# Destructive +reverse_merge+.
-
1
def reverse_merge!(other_hash)
-
# right wins if there is no left
-
245
merge!( other_hash ){|key,left,right| left }
-
end
-
1
alias_method :reverse_update, :reverse_merge!
-
end
-
1
class Hash
-
# Slice a hash to include only the given keys. Returns a hash containing
-
# the given keys.
-
#
-
# { a: 1, b: 2, c: 3, d: 4 }.slice(:a, :b)
-
# # => {:a=>1, :b=>2}
-
#
-
# This is useful for limiting an options hash to valid keys before
-
# passing to a method:
-
#
-
# def search(criteria = {})
-
# criteria.assert_valid_keys(:mass, :velocity, :time)
-
# end
-
#
-
# search(options.slice(:mass, :velocity, :time))
-
#
-
# If you have an array of keys you want to limit to, you should splat them:
-
#
-
# valid_keys = [:mass, :velocity, :time]
-
# search(options.slice(*valid_keys))
-
1
def slice(*keys)
-
17
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
-
62
keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
-
end
-
-
# Replaces the hash with only the given keys.
-
# Returns a hash containing the removed key/value pairs.
-
#
-
# { a: 1, b: 2, c: 3, d: 4 }.slice!(:a, :b)
-
# # => {:c=>3, :d=>4}
-
1
def slice!(*keys)
-
4
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
-
4
omit = slice(*self.keys - keys)
-
4
hash = slice(*keys)
-
4
hash.default = default
-
4
hash.default_proc = default_proc if default_proc
-
4
replace(hash)
-
4
omit
-
end
-
-
# Removes and returns the key/value pairs matching the given keys.
-
#
-
# { a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => {:a=>1, :b=>2}
-
# { a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}
-
1
def extract!(*keys)
-
275
keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
-
end
-
end
-
1
class Hash
-
# Returns a new hash with the results of running +block+ once for every value.
-
# The keys are unchanged.
-
#
-
# { a: 1, b: 2, c: 3 }.transform_values { |x| x * 2 }
-
# # => { a: 2, b: 4, c: 6 }
-
1
def transform_values
-
38
return enum_for(:transform_values) unless block_given?
-
38
result = self.class.new
-
38
each do |key, value|
-
55
result[key] = yield(value)
-
end
-
38
result
-
end
-
-
# Destructive +transform_values+
-
1
def transform_values!
-
return enum_for(:transform_values!) unless block_given?
-
each do |key, value|
-
self[key] = yield(value)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/integer/multiple'
-
1
require 'active_support/core_ext/integer/inflections'
-
1
require 'active_support/core_ext/integer/time'
-
1
require 'active_support/inflector'
-
-
1
class Integer
-
# Ordinalize turns a number into an ordinal string used to denote the
-
# position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# 1.ordinalize # => "1st"
-
# 2.ordinalize # => "2nd"
-
# 1002.ordinalize # => "1002nd"
-
# 1003.ordinalize # => "1003rd"
-
# -11.ordinalize # => "-11th"
-
# -1001.ordinalize # => "-1001st"
-
1
def ordinalize
-
ActiveSupport::Inflector.ordinalize(self)
-
end
-
-
# Ordinal returns the suffix used to denote the position
-
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# 1.ordinal # => "st"
-
# 2.ordinal # => "nd"
-
# 1002.ordinal # => "nd"
-
# 1003.ordinal # => "rd"
-
# -11.ordinal # => "th"
-
# -1001.ordinal # => "st"
-
1
def ordinal
-
ActiveSupport::Inflector.ordinal(self)
-
end
-
end
-
1
class Integer
-
# Check whether the integer is evenly divisible by the argument.
-
#
-
# 0.multiple_of?(0) # => true
-
# 6.multiple_of?(5) # => false
-
# 10.multiple_of?(2) # => true
-
1
def multiple_of?(number)
-
number != 0 ? self % number == 0 : zero?
-
end
-
end
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/numeric/time'
-
-
1
class Integer
-
# Enables the use of time calculations and declarations, like <tt>45.minutes +
-
# 2.hours + 4.years</tt>.
-
#
-
# These methods use Time#advance for precise date calculations when using
-
# <tt>from_now</tt>, +ago+, etc. as well as adding or subtracting their
-
# results from a Time object.
-
#
-
# # equivalent to Time.now.advance(months: 1)
-
# 1.month.from_now
-
#
-
# # equivalent to Time.now.advance(years: 2)
-
# 2.years.from_now
-
#
-
# # equivalent to Time.now.advance(months: 4, years: 5)
-
# (4.months + 5.years).from_now
-
1
def months
-
1
ActiveSupport::Duration.new(self * 30.days, [[:months, self]])
-
end
-
1
alias :month :months
-
-
1
def years
-
ActiveSupport::Duration.new(self * 365.25.days, [[:years, self]])
-
end
-
1
alias :year :years
-
end
-
1
require 'active_support/core_ext/kernel/agnostics'
-
1
require 'active_support/core_ext/kernel/concern'
-
1
require 'active_support/core_ext/kernel/debugger' if RUBY_VERSION < '2.0.0'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
class Object
-
# Makes backticks behave (somewhat more) similarly on all platforms.
-
# On win32 `nonexistent_command` raises Errno::ENOENT; on Unix, the
-
# spawned shell prints a message to stderr and sets $?. We emulate
-
# Unix on the former but not the latter.
-
1
def `(command) #:nodoc:
-
super
-
rescue Errno::ENOENT => e
-
STDERR.puts "#$0: #{e}"
-
end
-
end
-
1
require 'active_support/core_ext/module/concerning'
-
-
1
module Kernel
-
# A shortcut to define a toplevel concern, not within a module.
-
#
-
# See Module::Concerning for more.
-
1
def concern(topic, &module_definition)
-
Object.concern topic, &module_definition
-
end
-
end
-
1
module Kernel
-
# class_eval on an object acts like singleton_class.class_eval.
-
1
def class_eval(*args, &block)
-
singleton_class.class_eval(*args, &block)
-
end
-
end
-
1
class LoadError
-
1
REGEXPS = [
-
/^no such file to load -- (.+)$/i,
-
/^Missing \w+ (?:file\s*)?([^\s]+.rb)$/i,
-
/^Missing API definition file in (.+)$/i,
-
/^cannot load such file -- (.+)$/i,
-
]
-
-
1
unless method_defined?(:path)
-
# Returns the path which was unable to be loaded.
-
def path
-
@path ||= begin
-
REGEXPS.find do |regex|
-
message =~ regex
-
end
-
$1
-
end
-
end
-
end
-
-
# Returns true if the given path name (except perhaps for the ".rb"
-
# extension) is the missing file which caused the exception to be raised.
-
1
def is_missing?(location)
-
location.sub(/\.rb$/, '') == path.sub(/\.rb$/, '')
-
end
-
end
-
-
1
MissingSourceFile = LoadError
-
1
require 'active_support/core_ext/module/aliasing'
-
-
1
module Marshal
-
1
class << self
-
1
def load_with_autoloading(source)
-
142
load_without_autoloading(source)
-
rescue ArgumentError, NameError => exc
-
if exc.message.match(%r|undefined class/module (.+)|)
-
# try loading the class/module
-
$1.constantize
-
# if it is a IO we need to go back to read the object
-
source.rewind if source.respond_to?(:rewind)
-
retry
-
else
-
raise exc
-
end
-
end
-
-
1
alias_method_chain :load, :autoloading
-
end
-
end
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/module/reachable'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/module/concerning'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/module/deprecation'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/module/qualified_const'
-
1
class Module
-
# Encapsulates the common pattern of:
-
#
-
# alias_method :foo_without_feature, :foo
-
# alias_method :foo, :foo_with_feature
-
#
-
# With this, you simply do:
-
#
-
# alias_method_chain :foo, :feature
-
#
-
# And both aliases are set up for you.
-
#
-
# Query and bang methods (foo?, foo!) keep the same punctuation:
-
#
-
# alias_method_chain :foo?, :feature
-
#
-
# is equivalent to
-
#
-
# alias_method :foo_without_feature?, :foo?
-
# alias_method :foo?, :foo_with_feature?
-
#
-
# so you can safely chain foo, foo?, foo! and/or foo= with the same feature.
-
1
def alias_method_chain(target, feature)
-
# Strip out punctuation on predicates, bang or writer methods since
-
# e.g. target?_without_feature is not a valid method name.
-
15
aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
-
15
yield(aliased_target, punctuation) if block_given?
-
-
15
with_method = "#{aliased_target}_with_#{feature}#{punctuation}"
-
15
without_method = "#{aliased_target}_without_#{feature}#{punctuation}"
-
-
15
alias_method without_method, target
-
15
alias_method target, with_method
-
-
case
-
when public_method_defined?(without_method)
-
15
public target
-
when protected_method_defined?(without_method)
-
protected target
-
when private_method_defined?(without_method)
-
private target
-
15
end
-
end
-
-
# Allows you to make aliases for attributes, which includes
-
# getter, setter, and query methods.
-
#
-
# class Content < ActiveRecord::Base
-
# # has a title attribute
-
# end
-
#
-
# class Email < Content
-
# alias_attribute :subject, :title
-
# end
-
#
-
# e = Email.find(1)
-
# e.title # => "Superstars"
-
# e.subject # => "Superstars"
-
# e.subject? # => true
-
# e.subject = "Megastars"
-
# e.title # => "Megastars"
-
1
def alias_attribute(new_name, old_name)
-
module_eval <<-STR, __FILE__, __LINE__ + 1
-
def #{new_name}; self.#{old_name}; end # def subject; self.title; end
-
def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
-
def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end
-
STR
-
end
-
end
-
1
class Module
-
# A module may or may not have a name.
-
#
-
# module M; end
-
# M.name # => "M"
-
#
-
# m = Module.new
-
# m.name # => nil
-
#
-
# A module gets a name when it is first assigned to a constant. Either
-
# via the +module+ or +class+ keyword or by an explicit assignment:
-
#
-
# m = Module.new # creates an anonymous module
-
# M = m # => m gets a name here as a side-effect
-
# m.name # => "M"
-
1
def anonymous?
-
46
name.nil?
-
end
-
end
-
1
class Module
-
# Declares an attribute reader backed by an internally-named instance variable.
-
1
def attr_internal_reader(*attrs)
-
22
attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
-
end
-
-
# Declares an attribute writer backed by an internally-named instance variable.
-
1
def attr_internal_writer(*attrs)
-
28
attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
-
end
-
-
# Declares an attribute reader and writer backed by an internally-named instance
-
# variable.
-
1
def attr_internal_accessor(*attrs)
-
9
attr_internal_reader(*attrs)
-
9
attr_internal_writer(*attrs)
-
end
-
1
alias_method :attr_internal, :attr_internal_accessor
-
-
2
class << self; attr_accessor :attr_internal_naming_format end
-
1
self.attr_internal_naming_format = '@_%s'
-
-
1
private
-
1
def attr_internal_ivar_name(attr)
-
29
Module.attr_internal_naming_format % attr
-
end
-
-
1
def attr_internal_define(attr_name, type)
-
29
internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '')
-
# class_eval is necessary on 1.9 or else the methods are made private
-
29
class_eval do
-
# use native attr_* methods as they are faster on some Ruby implementations
-
29
send("attr_#{type}", internal_name)
-
end
-
29
attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer
-
29
alias_method attr_name, internal_name
-
29
remove_method internal_name
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
-
# Extends the module object with class/module and instance accessors for
-
# class/module attributes, just like the native attr* accessors for instance
-
# attributes.
-
1
class Module
-
# Defines a class attribute and creates a class and instance reader methods.
-
# The underlying the class variable is set to +nil+, if it is not previously
-
# defined.
-
#
-
# module HairColors
-
# mattr_reader :hair_colors
-
# end
-
#
-
# HairColors.hair_colors # => nil
-
# HairColors.class_variable_set("@@hair_colors", [:brown, :black])
-
# HairColors.hair_colors # => [:brown, :black]
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# module Foo
-
# mattr_reader :"1_Badname "
-
# end
-
# # => NameError: invalid attribute name
-
#
-
# If you want to opt out the creation on the instance reader method, pass
-
# <tt>instance_reader: false</tt> or <tt>instance_accessor: false</tt>.
-
#
-
# module HairColors
-
# mattr_writer :hair_colors, instance_reader: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors # => NoMethodError
-
#
-
#
-
# Also, you can pass a block to set up the attribute with a default value.
-
#
-
# module HairColors
-
# cattr_reader :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.hair_colors # => [:brown, :black, :blonde, :red]
-
1
def mattr_reader(*syms)
-
62
options = syms.extract_options!
-
62
syms.each do |sym|
-
62
raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
-
62
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
@@#{sym} = nil unless defined? @@#{sym}
-
-
def self.#{sym}
-
@@#{sym}
-
end
-
EOS
-
-
62
unless options[:instance_reader] == false || options[:instance_accessor] == false
-
58
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}
-
@@#{sym}
-
end
-
EOS
-
end
-
62
class_variable_set("@@#{sym}", yield) if block_given?
-
end
-
end
-
1
alias :cattr_reader :mattr_reader
-
-
# Defines a class attribute and creates a class and instance writer methods to
-
# allow assignment to the attribute.
-
#
-
# module HairColors
-
# mattr_writer :hair_colors
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# HairColors.hair_colors = [:brown, :black]
-
# Person.class_variable_get("@@hair_colors") # => [:brown, :black]
-
# Person.new.hair_colors = [:blonde, :red]
-
# HairColors.class_variable_get("@@hair_colors") # => [:blonde, :red]
-
#
-
# If you want to opt out the instance writer method, pass
-
# <tt>instance_writer: false</tt> or <tt>instance_accessor: false</tt>.
-
#
-
# module HairColors
-
# mattr_writer :hair_colors, instance_writer: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors = [:blonde, :red] # => NoMethodError
-
#
-
# Also, you can pass a block to set up the attribute with a default value.
-
#
-
# class HairColors
-
# mattr_writer :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
-
1
def mattr_writer(*syms)
-
61
options = syms.extract_options!
-
61
syms.each do |sym|
-
61
raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
-
61
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
@@#{sym} = nil unless defined? @@#{sym}
-
-
def self.#{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
-
61
unless options[:instance_writer] == false || options[:instance_accessor] == false
-
46
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
end
-
61
send("#{sym}=", yield) if block_given?
-
end
-
end
-
1
alias :cattr_writer :mattr_writer
-
-
# Defines both class and instance accessors for class attributes.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.hair_colors = [:brown, :black, :blonde, :red]
-
# Person.hair_colors # => [:brown, :black, :blonde, :red]
-
# Person.new.hair_colors # => [:brown, :black, :blonde, :red]
-
#
-
# If a subclass changes the value then that would also change the value for
-
# parent class. Similarly if parent class changes the value then that would
-
# change the value of subclasses too.
-
#
-
# class Male < Person
-
# end
-
#
-
# Male.hair_colors << :blue
-
# Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors, instance_writer: false, instance_reader: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors = [:brown] # => NoMethodError
-
# Person.new.hair_colors # => NoMethodError
-
#
-
# Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors, instance_accessor: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors = [:brown] # => NoMethodError
-
# Person.new.hair_colors # => NoMethodError
-
#
-
# Also you can pass a block to set up the attribute with a default value.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]
-
1
def mattr_accessor(*syms, &blk)
-
60
mattr_reader(*syms, &blk)
-
60
mattr_writer(*syms, &blk)
-
end
-
1
alias :cattr_accessor :mattr_accessor
-
end
-
1
require 'active_support/concern'
-
-
1
class Module
-
# = Bite-sized separation of concerns
-
#
-
# We often find ourselves with a medium-sized chunk of behavior that we'd
-
# like to extract, but only mix in to a single class.
-
#
-
# Extracting a plain old Ruby object to encapsulate it and collaborate or
-
# delegate to the original object is often a good choice, but when there's
-
# no additional state to encapsulate or we're making DSL-style declarations
-
# about the parent class, introducing new collaborators can obfuscate rather
-
# than simplify.
-
#
-
# The typical route is to just dump everything in a monolithic class, perhaps
-
# with a comment, as a least-bad alternative. Using modules in separate files
-
# means tedious sifting to get a big-picture view.
-
#
-
# = Dissatisfying ways to separate small concerns
-
#
-
# == Using comments:
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# ## Event tracking
-
# has_many :events
-
#
-
# before_create :track_creation
-
# after_destroy :track_deletion
-
#
-
# private
-
# def track_creation
-
# # ...
-
# end
-
# end
-
#
-
# == With an inline module:
-
#
-
# Noisy syntax.
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# module EventTracking
-
# extend ActiveSupport::Concern
-
#
-
# included do
-
# has_many :events
-
# before_create :track_creation
-
# after_destroy :track_deletion
-
# end
-
#
-
# private
-
# def track_creation
-
# # ...
-
# end
-
# end
-
# include EventTracking
-
# end
-
#
-
# == Mix-in noise exiled to its own file:
-
#
-
# Once our chunk of behavior starts pushing the scroll-to-understand it's
-
# boundary, we give in and move it to a separate file. At this size, the
-
# overhead feels in good proportion to the size of our extraction, despite
-
# diluting our at-a-glance sense of how things really work.
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# include TodoEventTracking
-
# end
-
#
-
# = Introducing Module#concerning
-
#
-
# By quieting the mix-in noise, we arrive at a natural, low-ceremony way to
-
# separate bite-sized concerns.
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# concerning :EventTracking do
-
# included do
-
# has_many :events
-
# before_create :track_creation
-
# after_destroy :track_deletion
-
# end
-
#
-
# private
-
# def track_creation
-
# # ...
-
# end
-
# end
-
# end
-
#
-
# Todo.ancestors
-
# # => Todo, Todo::EventTracking, Object
-
#
-
# This small step has some wonderful ripple effects. We can
-
# * grok the behavior of our class in one glance,
-
# * clean up monolithic junk-drawer classes by separating their concerns, and
-
# * stop leaning on protected/private for crude "this is internal stuff" modularity.
-
1
module Concerning
-
# Define a new concern and mix it in.
-
1
def concerning(topic, &block)
-
include concern(topic, &block)
-
end
-
-
# A low-cruft shortcut to define a concern.
-
#
-
# concern :EventTracking do
-
# ...
-
# end
-
#
-
# is equivalent to
-
#
-
# module EventTracking
-
# extend ActiveSupport::Concern
-
#
-
# ...
-
# end
-
1
def concern(topic, &module_definition)
-
const_set topic, Module.new {
-
extend ::ActiveSupport::Concern
-
module_eval(&module_definition)
-
}
-
end
-
end
-
1
include Concerning
-
end
-
1
require 'set'
-
-
1
class Module
-
# Error generated by +delegate+ when a method is called on +nil+ and +allow_nil+
-
# option is not used.
-
1
class DelegationError < NoMethodError; end
-
-
1
RUBY_RESERVED_WORDS = Set.new(
-
%w(alias and BEGIN begin break case class def defined? do else elsif END
-
end ensure false for if in module next nil not or redo rescue retry
-
return self super then true undef unless until when while yield)
-
).freeze
-
-
# Provides a +delegate+ class method to easily expose contained objects'
-
# public methods as your own.
-
#
-
# ==== Options
-
# * <tt>:to</tt> - Specifies the target object
-
# * <tt>:prefix</tt> - Prefixes the new method with the target name or a custom prefix
-
# * <tt>:allow_nil</tt> - if set to true, prevents a +NoMethodError+ to be raised
-
#
-
# The macro receives one or more method names (specified as symbols or
-
# strings) and the name of the target object via the <tt>:to</tt> option
-
# (also a symbol or string).
-
#
-
# Delegation is particularly useful with Active Record associations:
-
#
-
# class Greeter < ActiveRecord::Base
-
# def hello
-
# 'hello'
-
# end
-
#
-
# def goodbye
-
# 'goodbye'
-
# end
-
# end
-
#
-
# class Foo < ActiveRecord::Base
-
# belongs_to :greeter
-
# delegate :hello, to: :greeter
-
# end
-
#
-
# Foo.new.hello # => "hello"
-
# Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
-
#
-
# Multiple delegates to the same target are allowed:
-
#
-
# class Foo < ActiveRecord::Base
-
# belongs_to :greeter
-
# delegate :hello, :goodbye, to: :greeter
-
# end
-
#
-
# Foo.new.goodbye # => "goodbye"
-
#
-
# Methods can be delegated to instance variables, class variables, or constants
-
# by providing them as a symbols:
-
#
-
# class Foo
-
# CONSTANT_ARRAY = [0,1,2,3]
-
# @@class_array = [4,5,6,7]
-
#
-
# def initialize
-
# @instance_array = [8,9,10,11]
-
# end
-
# delegate :sum, to: :CONSTANT_ARRAY
-
# delegate :min, to: :@@class_array
-
# delegate :max, to: :@instance_array
-
# end
-
#
-
# Foo.new.sum # => 6
-
# Foo.new.min # => 4
-
# Foo.new.max # => 11
-
#
-
# It's also possible to delegate a method to the class by using +:class+:
-
#
-
# class Foo
-
# def self.hello
-
# "world"
-
# end
-
#
-
# delegate :hello, to: :class
-
# end
-
#
-
# Foo.new.hello # => "world"
-
#
-
# Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value
-
# is <tt>true</tt>, the delegate methods are prefixed with the name of the object being
-
# delegated to.
-
#
-
# Person = Struct.new(:name, :address)
-
#
-
# class Invoice < Struct.new(:client)
-
# delegate :name, :address, to: :client, prefix: true
-
# end
-
#
-
# john_doe = Person.new('John Doe', 'Vimmersvej 13')
-
# invoice = Invoice.new(john_doe)
-
# invoice.client_name # => "John Doe"
-
# invoice.client_address # => "Vimmersvej 13"
-
#
-
# It is also possible to supply a custom prefix.
-
#
-
# class Invoice < Struct.new(:client)
-
# delegate :name, :address, to: :client, prefix: :customer
-
# end
-
#
-
# invoice = Invoice.new(john_doe)
-
# invoice.customer_name # => 'John Doe'
-
# invoice.customer_address # => 'Vimmersvej 13'
-
#
-
# If the target is +nil+ and does not respond to the delegated method a
-
# +NoMethodError+ is raised, as with any other value. Sometimes, however, it
-
# makes sense to be robust to that situation and that is the purpose of the
-
# <tt>:allow_nil</tt> option: If the target is not +nil+, or it is and
-
# responds to the method, everything works as usual. But if it is +nil+ and
-
# does not respond to the delegated method, +nil+ is returned.
-
#
-
# class User < ActiveRecord::Base
-
# has_one :profile
-
# delegate :age, to: :profile
-
# end
-
#
-
# User.new.age # raises NoMethodError: undefined method `age'
-
#
-
# But if not having a profile yet is fine and should not be an error
-
# condition:
-
#
-
# class User < ActiveRecord::Base
-
# has_one :profile
-
# delegate :age, to: :profile, allow_nil: true
-
# end
-
#
-
# User.new.age # nil
-
#
-
# Note that if the target is not +nil+ then the call is attempted regardless of the
-
# <tt>:allow_nil</tt> option, and thus an exception is still raised if said object
-
# does not respond to the method:
-
#
-
# class Foo
-
# def initialize(bar)
-
# @bar = bar
-
# end
-
#
-
# delegate :name, to: :@bar, allow_nil: true
-
# end
-
#
-
# Foo.new("Bar").name # raises NoMethodError: undefined method `name'
-
#
-
# The target method must be public, otherwise it will raise +NoMethodError+.
-
#
-
1
def delegate(*methods)
-
108
options = methods.pop
-
108
unless options.is_a?(Hash) && to = options[:to]
-
raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter).'
-
end
-
-
108
prefix, allow_nil = options.values_at(:prefix, :allow_nil)
-
-
108
if prefix == true && to =~ /^[^a-z_]/
-
raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.'
-
end
-
-
108
method_prefix = \
-
if prefix
-
"#{prefix == true ? to : prefix}_"
-
else
-
108
''
-
end
-
-
108
file, line = caller.first.split(':', 2)
-
108
line = line.to_i
-
-
108
to = to.to_s
-
108
to = "self.#{to}" if RUBY_RESERVED_WORDS.include?(to)
-
-
108
methods.each do |method|
-
# Attribute writer methods only accept one argument. Makes sure []=
-
# methods still accept two arguments.
-
361
definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block'
-
-
# The following generated method calls the target exactly once, storing
-
# the returned value in a dummy variable.
-
#
-
# Reason is twofold: On one hand doing less calls is in general better.
-
# On the other hand it could be that the target has side-effects,
-
# whereas conceptually, from the user point of view, the delegator should
-
# be doing one call.
-
361
if allow_nil
-
6
method_def = [
-
"def #{method_prefix}#{method}(#{definition})",
-
"_ = #{to}",
-
"if !_.nil? || nil.respond_to?(:#{method})",
-
" _.#{method}(#{definition})",
-
"end",
-
"end"
-
].join ';'
-
else
-
355
exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
-
-
355
method_def = [
-
"def #{method_prefix}#{method}(#{definition})",
-
" _ = #{to}",
-
" _.#{method}(#{definition})",
-
"rescue NoMethodError => e",
-
" if _.nil? && e.name == :#{method}",
-
" #{exception}",
-
" else",
-
" raise",
-
" end",
-
"end"
-
].join ';'
-
end
-
-
361
module_eval(method_def, file, line)
-
end
-
end
-
end
-
1
class Module
-
# deprecate :foo
-
# deprecate bar: 'message'
-
# deprecate :foo, :bar, baz: 'warning!', qux: 'gone!'
-
#
-
# You can also use custom deprecator instance:
-
#
-
# deprecate :foo, deprecator: MyLib::Deprecator.new
-
# deprecate :foo, bar: "warning!", deprecator: MyLib::Deprecator.new
-
#
-
# \Custom deprecators must respond to <tt>deprecation_warning(deprecated_method_name, message, caller_backtrace)</tt>
-
# method where you can implement your custom warning behavior.
-
#
-
# class MyLib::Deprecator
-
# def deprecation_warning(deprecated_method_name, message, caller_backtrace = nil)
-
# message = "#{deprecated_method_name} is deprecated and will be removed from MyLibrary | #{message}"
-
# Kernel.warn message
-
# end
-
# end
-
1
def deprecate(*method_names)
-
1
ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
-
end
-
end
-
1
require 'active_support/inflector'
-
-
1
class Module
-
# Returns the name of the module containing this one.
-
#
-
# M::N.parent_name # => "M"
-
1
def parent_name
-
37
if defined? @parent_name
-
24
@parent_name
-
else
-
13
@parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
-
end
-
end
-
-
# Returns the module which contains this one according to its name.
-
#
-
# module M
-
# module N
-
# end
-
# end
-
# X = M::N
-
#
-
# M::N.parent # => M
-
# X.parent # => M
-
#
-
# The parent of top-level and anonymous modules is Object.
-
#
-
# M.parent # => Object
-
# Module.new.parent # => Object
-
1
def parent
-
8
parent_name ? ActiveSupport::Inflector.constantize(parent_name) : Object
-
end
-
-
# Returns all the parents of this module according to its name, ordered from
-
# nested outwards. The receiver is not contained within the result.
-
#
-
# module M
-
# module N
-
# end
-
# end
-
# X = M::N
-
#
-
# M.parents # => [Object]
-
# M::N.parents # => [M, Object]
-
# X.parents # => [M, Object]
-
1
def parents
-
27
parents = []
-
27
if parent_name
-
1
parts = parent_name.split('::')
-
1
until parts.empty?
-
1
parents << ActiveSupport::Inflector.constantize(parts * '::')
-
1
parts.pop
-
end
-
end
-
27
parents << Object unless parents.include? Object
-
27
parents
-
end
-
-
1
def local_constants #:nodoc:
-
constants(false)
-
end
-
end
-
1
class Module
-
###
-
# TODO: remove this after 1.9 support is dropped
-
1
def methods_transplantable? # :nodoc:
-
2
x = Module.new {
-
2
def foo; end # :nodoc:
-
}
-
4
Module.new { define_method :bar, x.instance_method(:foo) }
-
2
true
-
rescue TypeError
-
false
-
end
-
end
-
1
require 'active_support/core_ext/string/inflections'
-
-
#--
-
# Allows code reuse in the methods below without polluting Module.
-
#++
-
1
module QualifiedConstUtils
-
1
def self.raise_if_absolute(path)
-
14
raise NameError.new("wrong constant name #$&") if path =~ /\A::[^:]+/
-
end
-
-
1
def self.names(path)
-
14
path.split('::')
-
end
-
end
-
-
##
-
# Extends the API for constants to be able to deal with qualified names. Arguments
-
# are assumed to be relative to the receiver.
-
#
-
#--
-
# Qualified names are required to be relative because we are extending existing
-
# methods that expect constant names, ie, relative paths of length 1. For example,
-
# Object.const_get('::String') raises NameError and so does qualified_const_get.
-
#++
-
1
class Module
-
1
def qualified_const_defined?(path, search_parents=true)
-
14
QualifiedConstUtils.raise_if_absolute(path)
-
-
14
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
15
return unless mod.const_defined?(name, search_parents)
-
15
mod.const_get(name)
-
end
-
14
return true
-
end
-
-
1
def qualified_const_get(path)
-
QualifiedConstUtils.raise_if_absolute(path)
-
-
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
mod.const_get(name)
-
end
-
end
-
-
1
def qualified_const_set(path, value)
-
QualifiedConstUtils.raise_if_absolute(path)
-
-
const_name = path.demodulize
-
mod_name = path.deconstantize
-
mod = mod_name.empty? ? self : qualified_const_get(mod_name)
-
mod.const_set(const_name, value)
-
end
-
end
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
class Module
-
1
def reachable? #:nodoc:
-
!anonymous? && name.safe_constantize.equal?(self)
-
end
-
end
-
1
class Module
-
1
def remove_possible_method(method)
-
367
if method_defined?(method) || private_method_defined?(method)
-
254
undef_method(method)
-
end
-
end
-
-
1
def redefine_method(method, &block)
-
12
remove_possible_method(method)
-
12
define_method(method, &block)
-
end
-
end
-
1
class NameError
-
# Extract the name of the missing constant from the exception message.
-
1
def missing_name
-
2
if /undefined local variable or method/ !~ message
-
2
$1 if /((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/ =~ message
-
end
-
end
-
-
# Was this exception raised because the given name was missing?
-
1
def missing_name?(name)
-
2
if name.is_a? Symbol
-
last_name = (missing_name || '').split('::').last
-
last_name == name.to_s
-
else
-
2
missing_name == name.to_s
-
end
-
end
-
end
-
1
require 'active_support/core_ext/numeric/bytes'
-
1
require 'active_support/core_ext/numeric/time'
-
1
require 'active_support/core_ext/numeric/conversions'
-
1
class Numeric
-
1
KILOBYTE = 1024
-
1
MEGABYTE = KILOBYTE * 1024
-
1
GIGABYTE = MEGABYTE * 1024
-
1
TERABYTE = GIGABYTE * 1024
-
1
PETABYTE = TERABYTE * 1024
-
1
EXABYTE = PETABYTE * 1024
-
-
# Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes
-
1
def bytes
-
self
-
end
-
1
alias :byte :bytes
-
-
1
def kilobytes
-
1
self * KILOBYTE
-
end
-
1
alias :kilobyte :kilobytes
-
-
1
def megabytes
-
1
self * MEGABYTE
-
end
-
1
alias :megabyte :megabytes
-
-
1
def gigabytes
-
self * GIGABYTE
-
end
-
1
alias :gigabyte :gigabytes
-
-
1
def terabytes
-
self * TERABYTE
-
end
-
1
alias :terabyte :terabytes
-
-
1
def petabytes
-
self * PETABYTE
-
end
-
1
alias :petabyte :petabytes
-
-
1
def exabytes
-
self * EXABYTE
-
end
-
1
alias :exabyte :exabytes
-
end
-
1
require 'active_support/core_ext/big_decimal/conversions'
-
1
require 'active_support/number_helper'
-
-
1
class Numeric
-
-
# Provides options for converting numbers into formatted strings.
-
# Options are provided for phone numbers, currency, percentage,
-
# precision, positional notation, file size and pretty printing.
-
#
-
# ==== Options
-
#
-
# For details on which formats use which options, see ActiveSupport::NumberHelper
-
#
-
# ==== Examples
-
#
-
# Phone Numbers:
-
# 5551234.to_s(:phone) # => 555-1234
-
# 1235551234.to_s(:phone) # => 123-555-1234
-
# 1235551234.to_s(:phone, area_code: true) # => (123) 555-1234
-
# 1235551234.to_s(:phone, delimiter: ' ') # => 123 555 1234
-
# 1235551234.to_s(:phone, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# 1235551234.to_s(:phone, country_code: 1) # => +1-123-555-1234
-
# 1235551234.to_s(:phone, country_code: 1, extension: 1343, delimiter: '.')
-
# # => +1.123.555.1234 x 1343
-
#
-
# Currency:
-
# 1234567890.50.to_s(:currency) # => $1,234,567,890.50
-
# 1234567890.506.to_s(:currency) # => $1,234,567,890.51
-
# 1234567890.506.to_s(:currency, precision: 3) # => $1,234,567,890.506
-
# 1234567890.506.to_s(:currency, locale: :fr) # => 1 234 567 890,51 €
-
# -1234567890.50.to_s(:currency, negative_format: '(%u%n)')
-
# # => ($1,234,567,890.50)
-
# 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '')
-
# # => £1234567890,50
-
# 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '', format: '%n %u')
-
# # => 1234567890,50 £
-
#
-
# Percentage:
-
# 100.to_s(:percentage) # => 100.000%
-
# 100.to_s(:percentage, precision: 0) # => 100%
-
# 1000.to_s(:percentage, delimiter: '.', separator: ',') # => 1.000,000%
-
# 302.24398923423.to_s(:percentage, precision: 5) # => 302.24399%
-
# 1000.to_s(:percentage, locale: :fr) # => 1 000,000%
-
# 100.to_s(:percentage, format: '%n %') # => 100.000 %
-
#
-
# Delimited:
-
# 12345678.to_s(:delimited) # => 12,345,678
-
# 12345678.05.to_s(:delimited) # => 12,345,678.05
-
# 12345678.to_s(:delimited, delimiter: '.') # => 12.345.678
-
# 12345678.to_s(:delimited, delimiter: ',') # => 12,345,678
-
# 12345678.05.to_s(:delimited, separator: ' ') # => 12,345,678 05
-
# 12345678.05.to_s(:delimited, locale: :fr) # => 12 345 678,05
-
# 98765432.98.to_s(:delimited, delimiter: ' ', separator: ',')
-
# # => 98 765 432,98
-
#
-
# Rounded:
-
# 111.2345.to_s(:rounded) # => 111.235
-
# 111.2345.to_s(:rounded, precision: 2) # => 111.23
-
# 13.to_s(:rounded, precision: 5) # => 13.00000
-
# 389.32314.to_s(:rounded, precision: 0) # => 389
-
# 111.2345.to_s(:rounded, significant: true) # => 111
-
# 111.2345.to_s(:rounded, precision: 1, significant: true) # => 100
-
# 13.to_s(:rounded, precision: 5, significant: true) # => 13.000
-
# 111.234.to_s(:rounded, locale: :fr) # => 111,234
-
# 13.to_s(:rounded, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
# 389.32314.to_s(:rounded, precision: 4, significant: true) # => 389.3
-
# 1111.2345.to_s(:rounded, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
#
-
# Human-friendly size in Bytes:
-
# 123.to_s(:human_size) # => 123 Bytes
-
# 1234.to_s(:human_size) # => 1.21 KB
-
# 12345.to_s(:human_size) # => 12.1 KB
-
# 1234567.to_s(:human_size) # => 1.18 MB
-
# 1234567890.to_s(:human_size) # => 1.15 GB
-
# 1234567890123.to_s(:human_size) # => 1.12 TB
-
# 1234567.to_s(:human_size, precision: 2) # => 1.2 MB
-
# 483989.to_s(:human_size, precision: 2) # => 470 KB
-
# 1234567.to_s(:human_size, precision: 2, separator: ',') # => 1,2 MB
-
# 1234567890123.to_s(:human_size, precision: 5) # => "1.1228 TB"
-
# 524288000.to_s(:human_size, precision: 5) # => "500 MB"
-
#
-
# Human-friendly format:
-
# 123.to_s(:human) # => "123"
-
# 1234.to_s(:human) # => "1.23 Thousand"
-
# 12345.to_s(:human) # => "12.3 Thousand"
-
# 1234567.to_s(:human) # => "1.23 Million"
-
# 1234567890.to_s(:human) # => "1.23 Billion"
-
# 1234567890123.to_s(:human) # => "1.23 Trillion"
-
# 1234567890123456.to_s(:human) # => "1.23 Quadrillion"
-
# 1234567890123456789.to_s(:human) # => "1230 Quadrillion"
-
# 489939.to_s(:human, precision: 2) # => "490 Thousand"
-
# 489939.to_s(:human, precision: 4) # => "489.9 Thousand"
-
# 1234567.to_s(:human, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# 1234567.to_s(:human, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
1
def to_formatted_s(format = :default, options = {})
-
case format
-
when :phone
-
return ActiveSupport::NumberHelper.number_to_phone(self, options)
-
when :currency
-
return ActiveSupport::NumberHelper.number_to_currency(self, options)
-
when :percentage
-
return ActiveSupport::NumberHelper.number_to_percentage(self, options)
-
when :delimited
-
return ActiveSupport::NumberHelper.number_to_delimited(self, options)
-
when :rounded
-
return ActiveSupport::NumberHelper.number_to_rounded(self, options)
-
when :human
-
return ActiveSupport::NumberHelper.number_to_human(self, options)
-
when :human_size
-
return ActiveSupport::NumberHelper.number_to_human_size(self, options)
-
else
-
self.to_default_s
-
end
-
end
-
-
1
[Float, Fixnum, Bignum, BigDecimal].each do |klass|
-
4
klass.send(:alias_method, :to_default_s, :to_s)
-
-
4
klass.send(:define_method, :to_s) do |*args|
-
1967
if args[0].is_a?(Symbol)
-
format = args[0]
-
options = args[1] || {}
-
-
self.to_formatted_s(format, options)
-
else
-
1967
to_default_s(*args)
-
end
-
end
-
end
-
end
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/time/calculations'
-
1
require 'active_support/core_ext/time/acts_like'
-
-
1
class Numeric
-
# Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years.
-
#
-
# These methods use Time#advance for precise date calculations when using from_now, ago, etc.
-
# as well as adding or subtracting their results from a Time object. For example:
-
#
-
# # equivalent to Time.current.advance(months: 1)
-
# 1.month.from_now
-
#
-
# # equivalent to Time.current.advance(years: 2)
-
# 2.years.from_now
-
#
-
# # equivalent to Time.current.advance(months: 4, years: 5)
-
# (4.months + 5.years).from_now
-
1
def seconds
-
ActiveSupport::Duration.new(self, [[:seconds, self]])
-
end
-
1
alias :second :seconds
-
-
1
def minutes
-
ActiveSupport::Duration.new(self * 60, [[:seconds, self * 60]])
-
end
-
1
alias :minute :minutes
-
-
1
def hours
-
1
ActiveSupport::Duration.new(self * 3600, [[:seconds, self * 3600]])
-
end
-
1
alias :hour :hours
-
-
1
def days
-
1
ActiveSupport::Duration.new(self * 24.hours, [[:days, self]])
-
end
-
1
alias :day :days
-
-
1
def weeks
-
ActiveSupport::Duration.new(self * 7.days, [[:days, self * 7]])
-
end
-
1
alias :week :weeks
-
-
1
def fortnights
-
ActiveSupport::Duration.new(self * 2.weeks, [[:days, self * 14]])
-
end
-
1
alias :fortnight :fortnights
-
-
# Used with the standard time durations, like 1.hour.in_milliseconds --
-
# so we can feed them to JavaScript functions like getTime().
-
1
def in_milliseconds
-
self * 1000
-
end
-
end
-
1
require 'active_support/core_ext/object/acts_like'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'active_support/core_ext/object/deep_dup'
-
1
require 'active_support/core_ext/object/itself'
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/core_ext/object/inclusion'
-
-
1
require 'active_support/core_ext/object/conversions'
-
1
require 'active_support/core_ext/object/instance_variables'
-
-
1
require 'active_support/core_ext/object/json'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/object/with_options'
-
1
class Object
-
# A duck-type assistant method. For example, Active Support extends Date
-
# to define an <tt>acts_like_date?</tt> method, and extends Time to define
-
# <tt>acts_like_time?</tt>. As a result, we can do <tt>x.acts_like?(:time)</tt> and
-
# <tt>x.acts_like?(:date)</tt> to do duck-type-safe comparisons, since classes that
-
# we want to act like Time simply need to define an <tt>acts_like_time?</tt> method.
-
1
def acts_like?(duck)
-
347
respond_to? :"acts_like_#{duck}?"
-
end
-
end
-
# encoding: utf-8
-
-
1
class Object
-
# An object is blank if it's false, empty, or a whitespace string.
-
# For example, +false+, '', ' ', +nil+, [], and {} are all blank.
-
#
-
# This simplifies
-
#
-
# !address || address.empty?
-
#
-
# to
-
#
-
# address.blank?
-
#
-
# @return [true, false]
-
1
def blank?
-
128
respond_to?(:empty?) ? !!empty? : !self
-
end
-
-
# An object is present if it's not blank.
-
#
-
# @return [true, false]
-
1
def present?
-
1584
!blank?
-
end
-
-
# Returns the receiver if it's present otherwise returns +nil+.
-
# <tt>object.presence</tt> is equivalent to
-
#
-
# object.present? ? object : nil
-
#
-
# For example, something like
-
#
-
# state = params[:state] if params[:state].present?
-
# country = params[:country] if params[:country].present?
-
# region = state || country || 'US'
-
#
-
# becomes
-
#
-
# region = params[:state].presence || params[:country].presence || 'US'
-
#
-
# @return [Object]
-
1
def presence
-
571
self if present?
-
end
-
end
-
-
1
class NilClass
-
# +nil+ is blank:
-
#
-
# nil.blank? # => true
-
#
-
# @return [true]
-
1
def blank?
-
630
true
-
end
-
end
-
-
1
class FalseClass
-
# +false+ is blank:
-
#
-
# false.blank? # => true
-
#
-
# @return [true]
-
1
def blank?
-
true
-
end
-
end
-
-
1
class TrueClass
-
# +true+ is not blank:
-
#
-
# true.blank? # => false
-
#
-
# @return [false]
-
1
def blank?
-
false
-
end
-
end
-
-
1
class Array
-
# An array is blank if it's empty:
-
#
-
# [].blank? # => true
-
# [1,2,3].blank? # => false
-
#
-
# @return [true, false]
-
1
alias_method :blank?, :empty?
-
end
-
-
1
class Hash
-
# A hash is blank if it's empty:
-
#
-
# {}.blank? # => true
-
# { key: 'value' }.blank? # => false
-
#
-
# @return [true, false]
-
1
alias_method :blank?, :empty?
-
end
-
-
1
class String
-
1
BLANK_RE = /\A[[:space:]]*\z/
-
-
# A string is blank if it's empty or contains whitespaces only:
-
#
-
# ''.blank? # => true
-
# ' '.blank? # => true
-
# "\t\n\r".blank? # => true
-
# ' blah '.blank? # => false
-
#
-
# Unicode whitespace is supported:
-
#
-
# "\u00a0".blank? # => true
-
#
-
# @return [true, false]
-
1
def blank?
-
859
BLANK_RE === self
-
end
-
end
-
-
1
class Numeric #:nodoc:
-
# No number is blank:
-
#
-
# 1.blank? # => false
-
# 0.blank? # => false
-
#
-
# @return [false]
-
1
def blank?
-
34
false
-
end
-
end
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'active_support/core_ext/object/duplicable'
-
-
1
class Object
-
# Returns a deep copy of object if it's duplicable. If it's
-
# not duplicable, returns +self+.
-
#
-
# object = Object.new
-
# dup = object.deep_dup
-
# dup.instance_variable_set(:@a, 1)
-
#
-
# object.instance_variable_defined?(:@a) # => false
-
# dup.instance_variable_defined?(:@a) # => true
-
1
def deep_dup
-
82
duplicable? ? dup : self
-
end
-
end
-
-
1
class Array
-
# Returns a deep copy of array.
-
#
-
# array = [1, [2, 3]]
-
# dup = array.deep_dup
-
# dup[1][2] = 4
-
#
-
# array[1][2] # => nil
-
# dup[1][2] # => 4
-
1
def deep_dup
-
map { |it| it.deep_dup }
-
end
-
end
-
-
1
class Hash
-
# Returns a deep copy of hash.
-
#
-
# hash = { a: { b: 'b' } }
-
# dup = hash.deep_dup
-
# dup[:a][:c] = 'c'
-
#
-
# hash[:a][:c] # => nil
-
# dup[:a][:c] # => "c"
-
1
def deep_dup
-
29
each_with_object(dup) do |(key, value), hash|
-
47
hash[key.deep_dup] = value.deep_dup
-
end
-
end
-
end
-
#--
-
# Most objects are cloneable, but not all. For example you can't dup +nil+:
-
#
-
# nil.dup # => TypeError: can't dup NilClass
-
#
-
# Classes may signal their instances are not duplicable removing +dup+/+clone+
-
# or raising exceptions from them. So, to dup an arbitrary object you normally
-
# use an optimistic approach and are ready to catch an exception, say:
-
#
-
# arbitrary_object.dup rescue object
-
#
-
# Rails dups objects in a few critical spots where they are not that arbitrary.
-
# That rescue is very expensive (like 40 times slower than a predicate), and it
-
# is often triggered.
-
#
-
# That's why we hardcode the following cases and check duplicable? instead of
-
# using that rescue idiom.
-
#++
-
1
class Object
-
# Can you safely dup this object?
-
#
-
# False for +nil+, +false+, +true+, symbol, number and BigDecimal(in 1.9.x) objects;
-
# true otherwise.
-
1
def duplicable?
-
15
true
-
end
-
end
-
-
1
class NilClass
-
# +nil+ is not duplicable:
-
#
-
# nil.duplicable? # => false
-
# nil.dup # => TypeError: can't dup NilClass
-
1
def duplicable?
-
159
false
-
end
-
end
-
-
1
class FalseClass
-
# +false+ is not duplicable:
-
#
-
# false.duplicable? # => false
-
# false.dup # => TypeError: can't dup FalseClass
-
1
def duplicable?
-
false
-
end
-
end
-
-
1
class TrueClass
-
# +true+ is not duplicable:
-
#
-
# true.duplicable? # => false
-
# true.dup # => TypeError: can't dup TrueClass
-
1
def duplicable?
-
12
false
-
end
-
end
-
-
1
class Symbol
-
# Symbols are not duplicable:
-
#
-
# :my_symbol.duplicable? # => false
-
# :my_symbol.dup # => TypeError: can't dup Symbol
-
1
def duplicable?
-
66
false
-
end
-
end
-
-
1
class Numeric
-
# Numbers are not duplicable:
-
#
-
# 3.duplicable? # => false
-
# 3.dup # => TypeError: can't dup Fixnum
-
1
def duplicable?
-
2
false
-
end
-
end
-
-
1
require 'bigdecimal'
-
1
class BigDecimal
-
# Needed to support Ruby 1.9.x, as it doesn't allow dup on BigDecimal, instead
-
# raises TypeError exception. Checking here on the runtime whether BigDecimal
-
# will allow dup or not.
-
1
begin
-
1
BigDecimal.new('4.56').dup
-
-
1
def duplicable?
-
true
-
end
-
rescue TypeError
-
# can't dup, so use superclass implementation
-
end
-
end
-
-
1
class Method
-
# Methods are not duplicable:
-
#
-
# method(:puts).duplicable? # => false
-
# method(:puts).dup # => TypeError: allocator undefined for Method
-
1
def duplicable?
-
false
-
end
-
end
-
1
class Object
-
# Returns true if this object is included in the argument. Argument must be
-
# any object which responds to +#include?+. Usage:
-
#
-
# characters = ["Konata", "Kagami", "Tsukasa"]
-
# "Konata".in?(characters) # => true
-
#
-
# This will throw an ArgumentError if the argument doesn't respond
-
# to +#include?+.
-
1
def in?(another_object)
-
another_object.include?(self)
-
rescue NoMethodError
-
raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
-
end
-
-
# Returns the receiver if it's included in the argument otherwise returns +nil+.
-
# Argument must be any object which responds to +#include?+. Usage:
-
#
-
# params[:bucket_type].presence_in %w( project calendar )
-
#
-
# This will throw an ArgumentError if the argument doesn't respond to +#include?+.
-
#
-
# @return [Object]
-
1
def presence_in(another_object)
-
self.in?(another_object) ? self : nil
-
end
-
end
-
1
class Object
-
# Returns a hash with string keys that maps instance variable names without "@" to their
-
# corresponding values.
-
#
-
# class C
-
# def initialize(x, y)
-
# @x, @y = x, y
-
# end
-
# end
-
#
-
# C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
-
1
def instance_values
-
Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }]
-
end
-
-
# Returns an array of instance variable names as strings including "@".
-
#
-
# class C
-
# def initialize(x, y)
-
# @x, @y = x, y
-
# end
-
# end
-
#
-
# C.new(0, 1).instance_variable_names # => ["@y", "@x"]
-
1
def instance_variable_names
-
instance_variables.map { |var| var.to_s }
-
end
-
end
-
1
class Object
-
# TODO: Remove this file when we drop support for Ruby < 2.2
-
1
unless respond_to?(:itself)
-
# Returns the object itself.
-
#
-
# Useful for chaining methods, such as Active Record scopes:
-
#
-
# Event.public_send(state.presence_in([ :trashed, :drafted ]) || :itself).order(:created_at)
-
#
-
# @return Object
-
def itself
-
self
-
end
-
end
-
end
-
# Hack to load json gem first so we can overwrite its to_json.
-
1
require 'json'
-
1
require 'bigdecimal'
-
1
require 'active_support/core_ext/big_decimal/conversions' # for #to_s
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/object/instance_variables'
-
1
require 'time'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/date_time/conversions'
-
1
require 'active_support/core_ext/date/conversions'
-
1
require 'active_support/core_ext/module/aliasing'
-
-
# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting
-
# their default behavior. That said, we need to define the basic to_json method in all of them,
-
# otherwise they will always use to_json gem implementation, which is backwards incompatible in
-
# several cases (for instance, the JSON implementation for Hash does not work) with inheritance
-
# and consequently classes as ActiveSupport::OrderedHash cannot be serialized to json.
-
#
-
# On the other hand, we should avoid conflict with ::JSON.{generate,dump}(obj). Unfortunately, the
-
# JSON gem's encoder relies on its own to_json implementation to encode objects. Since it always
-
# passes a ::JSON::State object as the only argument to to_json, we can detect that and forward the
-
# calls to the original to_json method.
-
#
-
# It should be noted that when using ::JSON.{generate,dump} directly, ActiveSupport's encoder is
-
# bypassed completely. This means that as_json won't be invoked and the JSON gem will simply
-
# ignore any options it does not natively understand. This also means that ::JSON.{generate,dump}
-
# should give exactly the same results with or without active support.
-
1
[Enumerable, Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass|
-
10
klass.class_eval do
-
10
def to_json_with_active_support_encoder(options = nil) # :nodoc:
-
77
if options.is_a?(::JSON::State)
-
# Called from JSON.{generate,dump}, forward it to JSON gem's to_json
-
77
self.to_json_without_active_support_encoder(options)
-
else
-
# to_json is being invoked directly, use ActiveSupport's encoder
-
ActiveSupport::JSON.encode(self, options)
-
end
-
end
-
-
10
alias_method_chain :to_json, :active_support_encoder
-
end
-
end
-
-
1
class Object
-
1
def as_json(options = nil) #:nodoc:
-
if respond_to?(:to_hash)
-
to_hash.as_json(options)
-
else
-
instance_values.as_json(options)
-
end
-
end
-
end
-
-
1
class Struct #:nodoc:
-
1
def as_json(options = nil)
-
Hash[members.zip(values)].as_json(options)
-
end
-
end
-
-
1
class TrueClass
-
1
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
1
class FalseClass
-
1
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
1
class NilClass
-
1
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
1
class String
-
1
def as_json(options = nil) #:nodoc:
-
26
self
-
end
-
end
-
-
1
class Symbol
-
1
def as_json(options = nil) #:nodoc:
-
to_s
-
end
-
end
-
-
1
class Numeric
-
1
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
1
class Float
-
# Encoding Infinity or NaN to JSON should return "null". The default returns
-
# "Infinity" or "NaN" which are not valid JSON.
-
1
def as_json(options = nil) #:nodoc:
-
finite? ? self : nil
-
end
-
end
-
-
1
class BigDecimal
-
# A BigDecimal would be naturally represented as a JSON number. Most libraries,
-
# however, parse non-integer JSON numbers directly as floats. Clients using
-
# those libraries would get in general a wrong number and no way to recover
-
# other than manually inspecting the string with the JSON code itself.
-
#
-
# That's why a JSON string is returned. The JSON literal is not numeric, but
-
# if the other end knows by contract that the data is supposed to be a
-
# BigDecimal, it still has the chance to post-process the string and get the
-
# real value.
-
1
def as_json(options = nil) #:nodoc:
-
finite? ? to_s : nil
-
end
-
end
-
-
1
class Regexp
-
1
def as_json(options = nil) #:nodoc:
-
to_s
-
end
-
end
-
-
1
module Enumerable
-
1
def as_json(options = nil) #:nodoc:
-
to_a.as_json(options)
-
end
-
end
-
-
1
class Range
-
1
def as_json(options = nil) #:nodoc:
-
to_s
-
end
-
end
-
-
1
class Array
-
1
def as_json(options = nil) #:nodoc:
-
15
map { |v| options ? v.as_json(options.dup) : v.as_json }
-
end
-
end
-
-
1
class Hash
-
1
def as_json(options = nil) #:nodoc:
-
# create a subset of the hash by applying :only or :except
-
31
subset = if options
-
31
if attrs = options[:only]
-
slice(*Array(attrs))
-
elsif attrs = options[:except]
-
except(*Array(attrs))
-
else
-
31
self
-
end
-
else
-
self
-
end
-
-
82
Hash[subset.map { |k, v| [k.to_s, options ? v.as_json(options.dup) : v.as_json] }]
-
end
-
end
-
-
1
class Time
-
1
def as_json(options = nil) #:nodoc:
-
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
-
else
-
%(#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
-
end
-
end
-
end
-
-
1
class Date
-
1
def as_json(options = nil) #:nodoc:
-
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
strftime("%Y-%m-%d")
-
else
-
strftime("%Y/%m/%d")
-
end
-
end
-
end
-
-
1
class DateTime
-
1
def as_json(options = nil) #:nodoc:
-
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
-
else
-
strftime('%Y/%m/%d %H:%M:%S %z')
-
end
-
end
-
end
-
-
1
class Process::Status #:nodoc:
-
1
def as_json(options = nil)
-
{ :exitstatus => exitstatus, :pid => pid }
-
end
-
end
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'cgi'
-
-
1
class Object
-
# Alias of <tt>to_s</tt>.
-
1
def to_param
-
429
to_s
-
end
-
-
# Converts an object into a string suitable for use as a URL query string,
-
# using the given <tt>key</tt> as the param name.
-
1
def to_query(key)
-
80
"#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
-
end
-
end
-
-
1
class NilClass
-
# Returns +self+.
-
1
def to_param
-
self
-
end
-
end
-
-
1
class TrueClass
-
# Returns +self+.
-
1
def to_param
-
self
-
end
-
end
-
-
1
class FalseClass
-
# Returns +self+.
-
1
def to_param
-
self
-
end
-
end
-
-
1
class Array
-
# Calls <tt>to_param</tt> on all its elements and joins the result with
-
# slashes. This is used by <tt>url_for</tt> in Action Pack.
-
1
def to_param
-
collect { |e| e.to_param }.join '/'
-
end
-
-
# Converts an array into a string suitable for use as a URL query string,
-
# using the given +key+ as the param name.
-
#
-
# ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
-
1
def to_query(key)
-
prefix = "#{key}[]"
-
-
if empty?
-
nil.to_query(prefix)
-
else
-
collect { |value| value.to_query(prefix) }.join '&'
-
end
-
end
-
end
-
-
1
class Hash
-
# Returns a string representation of the receiver suitable for use as a URL
-
# query string:
-
#
-
# {name: 'David', nationality: 'Danish'}.to_query
-
# # => "name=David&nationality=Danish"
-
#
-
# An optional namespace can be passed to enclose key names:
-
#
-
# {name: 'David', nationality: 'Danish'}.to_query('user')
-
# # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"
-
#
-
# The string pairs "key=value" that conform the query string
-
# are sorted lexicographically in ascending order.
-
#
-
# This method is also aliased as +to_param+.
-
1
def to_query(namespace = nil)
-
collect do |key, value|
-
80
unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty?
-
80
value.to_query(namespace ? "#{namespace}[#{key}]" : key)
-
end
-
40
end.compact.sort! * '&'
-
end
-
-
1
alias_method :to_param, :to_query
-
end
-
1
class Object
-
# Invokes the public method whose name goes as first argument just like
-
# +public_send+ does, except that if the receiver does not respond to it the
-
# call returns +nil+ rather than raising an exception.
-
#
-
# This method is defined to be able to write
-
#
-
# @person.try(:name)
-
#
-
# instead of
-
#
-
# @person.name if @person
-
#
-
# +try+ calls can be chained:
-
#
-
# @person.try(:spouse).try(:name)
-
#
-
# instead of
-
#
-
# @person.spouse.name if @person && @person.spouse
-
#
-
# +try+ will also return +nil+ if the receiver does not respond to the method:
-
#
-
# @person.try(:non_existing_method) #=> nil
-
#
-
# instead of
-
#
-
# @person.non_existing_method if @person.respond_to?(:non_existing_method) #=> nil
-
#
-
# +try+ returns +nil+ when called on +nil+ regardless of whether it responds
-
# to the method:
-
#
-
# nil.try(:to_i) # => nil, rather than 0
-
#
-
# Arguments and blocks are forwarded to the method if invoked:
-
#
-
# @posts.try(:each_slice, 2) do |a, b|
-
# ...
-
# end
-
#
-
# The number of arguments in the signature must match. If the object responds
-
# to the method the call is attempted and +ArgumentError+ is still raised
-
# in case of argument mismatch.
-
#
-
# If +try+ is called without arguments it yields the receiver to a given
-
# block unless it is +nil+:
-
#
-
# @person.try do |p|
-
# ...
-
# end
-
#
-
# You can also call try with a block without accepting an argument, and the block
-
# will be instance_eval'ed instead:
-
#
-
# @person.try { upcase.truncate(50) }
-
#
-
# Please also note that +try+ is defined on +Object+. Therefore, it won't work
-
# with instances of classes that do not have +Object+ among their ancestors,
-
# like direct subclasses of +BasicObject+. For example, using +try+ with
-
# +SimpleDelegator+ will delegate +try+ to the target instead of calling it on
-
# the delegator itself.
-
1
def try(*a, &b)
-
132
try!(*a, &b) if a.empty? || respond_to?(a.first)
-
end
-
-
# Same as #try, but will raise a NoMethodError exception if the receiver is not +nil+ and
-
# does not implement the tried method.
-
-
1
def try!(*a, &b)
-
132
if a.empty? && block_given?
-
if b.arity == 0
-
instance_eval(&b)
-
else
-
yield self
-
end
-
else
-
132
public_send(*a, &b)
-
end
-
end
-
end
-
-
1
class NilClass
-
# Calling +try+ on +nil+ always returns +nil+.
-
# It becomes especially helpful when navigating through associations that may return +nil+.
-
#
-
# nil.try(:name) # => nil
-
#
-
# Without +try+
-
# @person && @person.children.any? && @person.children.first.name
-
#
-
# With +try+
-
# @person.try(:children).try(:first).try(:name)
-
1
def try(*args)
-
nil
-
end
-
-
1
def try!(*args)
-
nil
-
end
-
end
-
1
require 'active_support/option_merger'
-
-
1
class Object
-
# An elegant way to factor duplication out of options passed to a series of
-
# method calls. Each method called in the block, with the block variable as
-
# the receiver, will have its options merged with the default +options+ hash
-
# provided. Each method called on the block variable must take an options
-
# hash as its final argument.
-
#
-
# Without <tt>with_options></tt>, this code contains duplication:
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :customers, dependent: :destroy
-
# has_many :products, dependent: :destroy
-
# has_many :invoices, dependent: :destroy
-
# has_many :expenses, dependent: :destroy
-
# end
-
#
-
# Using <tt>with_options</tt>, we can remove the duplication:
-
#
-
# class Account < ActiveRecord::Base
-
# with_options dependent: :destroy do |assoc|
-
# assoc.has_many :customers
-
# assoc.has_many :products
-
# assoc.has_many :invoices
-
# assoc.has_many :expenses
-
# end
-
# end
-
#
-
# It can also be used with an explicit receiver:
-
#
-
# I18n.with_options locale: user.locale, scope: 'newsletter' do |i18n|
-
# subject i18n.t :subject
-
# body i18n.t :body, user_name: user.name
-
# end
-
#
-
# When you don't pass an explicit receiver, it executes the whole block
-
# in merging options context:
-
#
-
# class Account < ActiveRecord::Base
-
# with_options dependent: :destroy do
-
# has_many :customers
-
# has_many :products
-
# has_many :invoices
-
# has_many :expenses
-
# end
-
# end
-
#
-
# <tt>with_options</tt> can also be nested since the call is forwarded to its receiver.
-
#
-
# NOTE: Each nesting level will merge inherited defaults in addition to their own.
-
#
-
# class Post < ActiveRecord::Base
-
# with_options if: :persisted?, length: { minimum: 50 } do
-
# validates :content, if: -> { content.present? }
-
# end
-
# end
-
#
-
# The code is equivalent to:
-
#
-
# validates :content, length: { minimum: 50 }, if: -> { content.present? }
-
#
-
# Hence the inherited default for `if` key is ignored.
-
#
-
1
def with_options(options, &block)
-
option_merger = ActiveSupport::OptionMerger.new(self, options)
-
block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger)
-
end
-
end
-
1
require 'active_support/core_ext/range/conversions'
-
1
require 'active_support/core_ext/range/include_range'
-
1
require 'active_support/core_ext/range/overlaps'
-
1
require 'active_support/core_ext/range/each'
-
1
class Range
-
1
RANGE_FORMATS = {
-
:db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" }
-
}
-
-
# Gives a human readable format of the range.
-
#
-
# (1..100).to_formatted_s # => "1..100"
-
1
def to_formatted_s(format = :default)
-
if formatter = RANGE_FORMATS[format]
-
formatter.call(first, last)
-
else
-
to_default_s
-
end
-
end
-
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
end
-
1
require 'active_support/core_ext/module/aliasing'
-
-
1
class Range #:nodoc:
-
-
1
def each_with_time_with_zone(&block)
-
2
ensure_iteration_allowed
-
2
each_without_time_with_zone(&block)
-
end
-
1
alias_method_chain :each, :time_with_zone
-
-
1
def step_with_time_with_zone(n = 1, &block)
-
ensure_iteration_allowed
-
step_without_time_with_zone(n, &block)
-
end
-
1
alias_method_chain :step, :time_with_zone
-
-
1
private
-
1
def ensure_iteration_allowed
-
2
if first.is_a?(Time)
-
raise TypeError, "can't iterate from #{first.class}"
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/aliasing'
-
-
1
class Range
-
# Extends the default Range#include? to support range comparisons.
-
# (1..5).include?(1..5) # => true
-
# (1..5).include?(2..3) # => true
-
# (1..5).include?(2..6) # => false
-
#
-
# The native Range#include? behavior is untouched.
-
# ('a'..'f').include?('c') # => true
-
# (5..9).include?(11) # => false
-
1
def include_with_range?(value)
-
if value.is_a?(::Range)
-
# 1...10 includes 1..9 but it does not include 1..10.
-
operator = exclude_end? && !value.exclude_end? ? :< : :<=
-
include_without_range?(value.first) && value.last.send(operator, last)
-
else
-
include_without_range?(value)
-
end
-
end
-
-
1
alias_method_chain :include?, :range
-
end
-
1
class Range
-
# Compare two ranges and see if they overlap each other
-
# (1..5).overlaps?(4..6) # => true
-
# (1..5).overlaps?(7..9) # => false
-
1
def overlaps?(other)
-
cover?(other.first) || other.cover?(first)
-
end
-
end
-
1
class Regexp #:nodoc:
-
1
def multiline?
-
options & MULTILINE == MULTILINE
-
end
-
end
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'active_support/core_ext/string/multibyte'
-
1
require 'active_support/core_ext/string/starts_ends_with'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/string/access'
-
1
require 'active_support/core_ext/string/behavior'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/core_ext/string/exclude'
-
1
require 'active_support/core_ext/string/strip'
-
1
require 'active_support/core_ext/string/inquiry'
-
1
require 'active_support/core_ext/string/indent'
-
1
require 'active_support/core_ext/string/zones'
-
1
class String
-
# If you pass a single Fixnum, returns a substring of one character at that
-
# position. The first character of the string is at position 0, the next at
-
# position 1, and so on. If a range is supplied, a substring containing
-
# characters at offsets given by the range is returned. In both cases, if an
-
# offset is negative, it is counted from the end of the string. Returns nil
-
# if the initial offset falls outside the string. Returns an empty string if
-
# the beginning of the range is greater than the end of the string.
-
#
-
# str = "hello"
-
# str.at(0) # => "h"
-
# str.at(1..3) # => "ell"
-
# str.at(-2) # => "l"
-
# str.at(-2..-1) # => "lo"
-
# str.at(5) # => nil
-
# str.at(5..-1) # => ""
-
#
-
# If a Regexp is given, the matching portion of the string is returned.
-
# If a String is given, that given string is returned if it occurs in
-
# the string. In both cases, nil is returned if there is no match.
-
#
-
# str = "hello"
-
# str.at(/lo/) # => "lo"
-
# str.at(/ol/) # => nil
-
# str.at("lo") # => "lo"
-
# str.at("ol") # => nil
-
1
def at(position)
-
self[position]
-
end
-
-
# Returns a substring from the given position to the end of the string.
-
# If the position is negative, it is counted from the end of the string.
-
#
-
# str = "hello"
-
# str.from(0) # => "hello"
-
# str.from(3) # => "lo"
-
# str.from(-2) # => "lo"
-
#
-
# You can mix it with +to+ method and do fun things like:
-
#
-
# str = "hello"
-
# str.from(0).to(-1) # => "hello"
-
# str.from(1).to(-2) # => "ell"
-
1
def from(position)
-
self[position..-1]
-
end
-
-
# Returns a substring from the beginning of the string to the given position.
-
# If the position is negative, it is counted from the end of the string.
-
#
-
# str = "hello"
-
# str.to(0) # => "h"
-
# str.to(3) # => "hell"
-
# str.to(-2) # => "hell"
-
#
-
# You can mix it with +from+ method and do fun things like:
-
#
-
# str = "hello"
-
# str.from(0).to(-1) # => "hello"
-
# str.from(1).to(-2) # => "ell"
-
1
def to(position)
-
8
self[0..position]
-
end
-
-
# Returns the first character. If a limit is supplied, returns a substring
-
# from the beginning of the string until it reaches the limit value. If the
-
# given limit is greater than or equal to the string length, returns a copy of self.
-
#
-
# str = "hello"
-
# str.first # => "h"
-
# str.first(1) # => "h"
-
# str.first(2) # => "he"
-
# str.first(0) # => ""
-
# str.first(6) # => "hello"
-
1
def first(limit = 1)
-
8
if limit == 0
-
''
-
8
elsif limit >= size
-
self.dup
-
else
-
8
to(limit - 1)
-
end
-
end
-
-
# Returns the last character of the string. If a limit is supplied, returns a substring
-
# from the end of the string until it reaches the limit value (counting backwards). If
-
# the given limit is greater than or equal to the string length, returns a copy of self.
-
#
-
# str = "hello"
-
# str.last # => "o"
-
# str.last(1) # => "o"
-
# str.last(2) # => "lo"
-
# str.last(0) # => ""
-
# str.last(6) # => "hello"
-
1
def last(limit = 1)
-
4
if limit == 0
-
''
-
4
elsif limit >= size
-
4
self.dup
-
else
-
from(-limit)
-
end
-
end
-
end
-
1
class String
-
# Enable more predictable duck-typing on String-like classes. See <tt>Object#acts_like?</tt>.
-
1
def acts_like_string?
-
true
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/core_ext/time/calculations'
-
-
1
class String
-
# Converts a string to a Time value.
-
# The +form+ can be either :utc or :local (default :local).
-
#
-
# The time is parsed using Time.parse method.
-
# If +form+ is :local, then the time is in the system timezone.
-
# If the date part is missing then the current date is used and if
-
# the time part is missing then it is assumed to be 00:00:00.
-
#
-
# "13-12-2012".to_time # => 2012-12-13 00:00:00 +0100
-
# "06:12".to_time # => 2012-12-13 06:12:00 +0100
-
# "2012-12-13 06:12".to_time # => 2012-12-13 06:12:00 +0100
-
# "2012-12-13T06:12".to_time # => 2012-12-13 06:12:00 +0100
-
# "2012-12-13T06:12".to_time(:utc) # => 2012-12-13 05:12:00 UTC
-
# "12/13/2012".to_time # => ArgumentError: argument out of range
-
1
def to_time(form = :local)
-
parts = Date._parse(self, false)
-
return if parts.empty?
-
-
now = Time.now
-
time = Time.new(
-
parts.fetch(:year, now.year),
-
parts.fetch(:mon, now.month),
-
parts.fetch(:mday, now.day),
-
parts.fetch(:hour, 0),
-
parts.fetch(:min, 0),
-
parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
-
parts.fetch(:offset, form == :utc ? 0 : nil)
-
)
-
-
form == :utc ? time.utc : time.getlocal
-
end
-
-
# Converts a string to a Date value.
-
#
-
# "1-1-2012".to_date # => Sun, 01 Jan 2012
-
# "01/01/2012".to_date # => Sun, 01 Jan 2012
-
# "2012-12-13".to_date # => Thu, 13 Dec 2012
-
# "12/13/2012".to_date # => ArgumentError: invalid date
-
1
def to_date
-
::Date.parse(self, false) unless blank?
-
end
-
-
# Converts a string to a DateTime value.
-
#
-
# "1-1-2012".to_datetime # => Sun, 01 Jan 2012 00:00:00 +0000
-
# "01/01/2012 23:59:59".to_datetime # => Sun, 01 Jan 2012 23:59:59 +0000
-
# "2012-12-13 12:50".to_datetime # => Thu, 13 Dec 2012 12:50:00 +0000
-
# "12/13/2012".to_datetime # => ArgumentError: invalid date
-
1
def to_datetime
-
::DateTime.parse(self, false) unless blank?
-
end
-
end
-
1
class String
-
# The inverse of <tt>String#include?</tt>. Returns true if the string
-
# does not include the other string.
-
#
-
# "hello".exclude? "lo" # => false
-
# "hello".exclude? "ol" # => true
-
# "hello".exclude? ?h # => false
-
1
def exclude?(string)
-
!include?(string)
-
end
-
end
-
1
class String
-
# Returns the string, first removing all whitespace on both ends of
-
# the string, and then changing remaining consecutive whitespace
-
# groups into one space each.
-
#
-
# Note that it handles both ASCII and Unicode whitespace.
-
#
-
# %{ Multi-line
-
# string }.squish # => "Multi-line string"
-
# " foo bar \n \t boo".squish # => "foo bar boo"
-
1
def squish
-
1
dup.squish!
-
end
-
-
# Performs a destructive squish. See String#squish.
-
# str = " foo bar \n \t boo"
-
# str.squish! # => "foo bar boo"
-
# str # => "foo bar boo"
-
1
def squish!
-
1
gsub!(/\A[[:space:]]+/, '')
-
1
gsub!(/[[:space:]]+\z/, '')
-
1
gsub!(/[[:space:]]+/, ' ')
-
1
self
-
end
-
-
# Returns a new string with all occurrences of the patterns removed.
-
# str = "foo bar test"
-
# str.remove(" test") # => "foo bar"
-
# str.remove(" test", /bar/) # => "foo "
-
# str # => "foo bar test"
-
1
def remove(*patterns)
-
1
dup.remove!(*patterns)
-
end
-
-
# Alters the string by removing all occurrences of the patterns.
-
# str = "foo bar test"
-
# str.remove!(" test", /bar/) # => "foo "
-
# str # => "foo "
-
1
def remove!(*patterns)
-
1
patterns.each do |pattern|
-
1
gsub! pattern, ""
-
end
-
-
1
self
-
end
-
-
# Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>:
-
#
-
# 'Once upon a time in a world far far away'.truncate(27)
-
# # => "Once upon a time in a wo..."
-
#
-
# Pass a string or regexp <tt>:separator</tt> to truncate +text+ at a natural break:
-
#
-
# 'Once upon a time in a world far far away'.truncate(27, separator: ' ')
-
# # => "Once upon a time in a..."
-
#
-
# 'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
-
# # => "Once upon a time in a..."
-
#
-
# The last characters will be replaced with the <tt>:omission</tt> string (defaults to "...")
-
# for a total length not exceeding <tt>length</tt>:
-
#
-
# 'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
-
# # => "And they f... (continued)"
-
1
def truncate(truncate_at, options = {})
-
return dup unless length > truncate_at
-
-
omission = options[:omission] || '...'
-
length_with_room_for_omission = truncate_at - omission.length
-
stop = \
-
if options[:separator]
-
rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
-
else
-
length_with_room_for_omission
-
end
-
-
"#{self[0, stop]}#{omission}"
-
end
-
-
# Truncates a given +text+ after a given number of words (<tt>words_count</tt>):
-
#
-
# 'Once upon a time in a world far far away'.truncate_words(4)
-
# # => "Once upon a time..."
-
#
-
# Pass a string or regexp <tt>:separator</tt> to specify a different separator of words:
-
#
-
# 'Once<br>upon<br>a<br>time<br>in<br>a<br>world'.truncate_words(5, separator: '<br>')
-
# # => "Once<br>upon<br>a<br>time<br>in..."
-
#
-
# The last characters will be replaced with the <tt>:omission</tt> string (defaults to "..."):
-
#
-
# 'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')
-
# # => "And they found that many... (continued)"
-
1
def truncate_words(words_count, options = {})
-
sep = options[:separator] || /\s+/
-
sep = Regexp.escape(sep.to_s) unless Regexp === sep
-
if self =~ /\A((?>.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m
-
$1 + (options[:omission] || '...')
-
else
-
dup
-
end
-
end
-
end
-
1
class String
-
# Same as +indent+, except it indents the receiver in-place.
-
#
-
# Returns the indented string, or +nil+ if there was nothing to indent.
-
1
def indent!(amount, indent_string=nil, indent_empty_lines=false)
-
249
indent_string = indent_string || self[/^[ \t]/] || ' '
-
249
re = indent_empty_lines ? /^/ : /^(?!$)/
-
249
gsub!(re, indent_string * amount)
-
end
-
-
# Indents the lines in the receiver:
-
#
-
# <<EOS.indent(2)
-
# def some_method
-
# some_code
-
# end
-
# EOS
-
# # =>
-
# def some_method
-
# some_code
-
# end
-
#
-
# The second argument, +indent_string+, specifies which indent string to
-
# use. The default is +nil+, which tells the method to make a guess by
-
# peeking at the first indented line, and fallback to a space if there is
-
# none.
-
#
-
# " foo".indent(2) # => " foo"
-
# "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
-
# "foo".indent(2, "\t") # => "\t\tfoo"
-
#
-
# While +indent_string+ is typically one space or tab, it may be any string.
-
#
-
# The third argument, +indent_empty_lines+, is a flag that says whether
-
# empty lines should be indented. Default is false.
-
#
-
# "foo\n\nbar".indent(2) # => " foo\n\n bar"
-
# "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
-
#
-
1
def indent(amount, indent_string=nil, indent_empty_lines=false)
-
498
dup.tap {|_| _.indent!(amount, indent_string, indent_empty_lines)}
-
end
-
end
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/inflector/transliterate'
-
-
# String inflections define new methods on the String class to transform names for different purposes.
-
# For instance, you can figure out the name of a table from the name of a class.
-
#
-
# 'ScaleScore'.tableize # => "scale_scores"
-
#
-
1
class String
-
# Returns the plural form of the word in the string.
-
#
-
# If the optional parameter +count+ is specified,
-
# the singular form will be returned if <tt>count == 1</tt>.
-
# For any other value of +count+ the plural will be returned.
-
#
-
# If the optional parameter +locale+ is specified,
-
# the word will be pluralized as a word of that language.
-
# By default, this parameter is set to <tt>:en</tt>.
-
# You must define your own inflection rules for languages other than English.
-
#
-
# 'post'.pluralize # => "posts"
-
# 'octopus'.pluralize # => "octopi"
-
# 'sheep'.pluralize # => "sheep"
-
# 'words'.pluralize # => "words"
-
# 'the blue mailman'.pluralize # => "the blue mailmen"
-
# 'CamelOctopus'.pluralize # => "CamelOctopi"
-
# 'apple'.pluralize(1) # => "apple"
-
# 'apple'.pluralize(2) # => "apples"
-
# 'ley'.pluralize(:es) # => "leyes"
-
# 'ley'.pluralize(1, :es) # => "ley"
-
1
def pluralize(count = nil, locale = :en)
-
8
locale = count if count.is_a?(Symbol)
-
8
if count == 1
-
self.dup
-
else
-
8
ActiveSupport::Inflector.pluralize(self, locale)
-
end
-
end
-
-
# The reverse of +pluralize+, returns the singular form of a word in a string.
-
#
-
# If the optional parameter +locale+ is specified,
-
# the word will be singularized as a word of that language.
-
# By default, this parameter is set to <tt>:en</tt>.
-
# You must define your own inflection rules for languages other than English.
-
#
-
# 'posts'.singularize # => "post"
-
# 'octopi'.singularize # => "octopus"
-
# 'sheep'.singularize # => "sheep"
-
# 'word'.singularize # => "word"
-
# 'the blue mailmen'.singularize # => "the blue mailman"
-
# 'CamelOctopi'.singularize # => "CamelOctopus"
-
# 'leyes'.singularize(:es) # => "ley"
-
1
def singularize(locale = :en)
-
6
ActiveSupport::Inflector.singularize(self, locale)
-
end
-
-
# +constantize+ tries to find a declared constant with the name specified
-
# in the string. It raises a NameError when the name is not in CamelCase
-
# or is not initialized. See ActiveSupport::Inflector.constantize
-
#
-
# 'Module'.constantize # => Module
-
# 'Class'.constantize # => Class
-
# 'blargle'.constantize # => NameError: wrong constant name blargle
-
1
def constantize
-
13
ActiveSupport::Inflector.constantize(self)
-
end
-
-
# +safe_constantize+ tries to find a declared constant with the name specified
-
# in the string. It returns nil when the name is not in CamelCase
-
# or is not initialized. See ActiveSupport::Inflector.safe_constantize
-
#
-
# 'Module'.safe_constantize # => Module
-
# 'Class'.safe_constantize # => Class
-
# 'blargle'.safe_constantize # => nil
-
1
def safe_constantize
-
ActiveSupport::Inflector.safe_constantize(self)
-
end
-
-
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize
-
# is set to <tt>:lower</tt> then camelize produces lowerCamelCase.
-
#
-
# +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
-
#
-
# 'active_record'.camelize # => "ActiveRecord"
-
# 'active_record'.camelize(:lower) # => "activeRecord"
-
# 'active_record/errors'.camelize # => "ActiveRecord::Errors"
-
# 'active_record/errors'.camelize(:lower) # => "activeRecord::Errors"
-
1
def camelize(first_letter = :upper)
-
56
case first_letter
-
when :upper
-
56
ActiveSupport::Inflector.camelize(self, true)
-
when :lower
-
ActiveSupport::Inflector.camelize(self, false)
-
end
-
end
-
1
alias_method :camelcase, :camelize
-
-
# Capitalizes all the words and replaces some characters in the string to create
-
# a nicer looking title. +titleize+ is meant for creating pretty output. It is not
-
# used in the Rails internals.
-
#
-
# +titleize+ is also aliased as +titlecase+.
-
#
-
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
-
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
-
1
def titleize
-
ActiveSupport::Inflector.titleize(self)
-
end
-
1
alias_method :titlecase, :titleize
-
-
# The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
-
#
-
# +underscore+ will also change '::' to '/' to convert namespaces to paths.
-
#
-
# 'ActiveModel'.underscore # => "active_model"
-
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
-
1
def underscore
-
147
ActiveSupport::Inflector.underscore(self)
-
end
-
-
# Replaces underscores with dashes in the string.
-
#
-
# 'puni_puni'.dasherize # => "puni-puni"
-
1
def dasherize
-
50
ActiveSupport::Inflector.dasherize(self)
-
end
-
-
# Removes the module part from the constant expression in the string.
-
#
-
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
-
# 'Inflections'.demodulize # => "Inflections"
-
# '::Inflections'.demodulize # => "Inflections"
-
# ''.demodulize # => ''
-
#
-
# See also +deconstantize+.
-
1
def demodulize
-
4
ActiveSupport::Inflector.demodulize(self)
-
end
-
-
# Removes the rightmost segment from the constant expression in the string.
-
#
-
# 'Net::HTTP'.deconstantize # => "Net"
-
# '::Net::HTTP'.deconstantize # => "::Net"
-
# 'String'.deconstantize # => ""
-
# '::String'.deconstantize # => ""
-
# ''.deconstantize # => ""
-
#
-
# See also +demodulize+.
-
1
def deconstantize
-
ActiveSupport::Inflector.deconstantize(self)
-
end
-
-
# Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
-
#
-
# class Person
-
# def to_param
-
# "#{id}-#{name.parameterize}"
-
# end
-
# end
-
#
-
# @person = Person.find(1)
-
# # => #<Person id: 1, name: "Donald E. Knuth">
-
#
-
# <%= link_to(@person.name, person_path) %>
-
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
-
1
def parameterize(sep = '-')
-
ActiveSupport::Inflector.parameterize(self, sep)
-
end
-
-
# Creates the name of a table like Rails does for models to table names. This method
-
# uses the +pluralize+ method on the last word in the string.
-
#
-
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
-
# 'egg_and_ham'.tableize # => "egg_and_hams"
-
# 'fancyCategory'.tableize # => "fancy_categories"
-
1
def tableize
-
ActiveSupport::Inflector.tableize(self)
-
end
-
-
# Create a class name from a plural table name like Rails does for table names to models.
-
# Note that this returns a string and not a class. (To convert to an actual class
-
# follow +classify+ with +constantize+.)
-
#
-
# 'egg_and_hams'.classify # => "EggAndHam"
-
# 'posts'.classify # => "Post"
-
1
def classify
-
1
ActiveSupport::Inflector.classify(self)
-
end
-
-
# Capitalizes the first word, turns underscores into spaces, and strips a
-
# trailing '_id' if present.
-
# Like +titleize+, this is meant for creating pretty output.
-
#
-
# The capitalization of the first word can be turned off by setting the
-
# optional parameter +capitalize+ to false.
-
# By default, this parameter is true.
-
#
-
# 'employee_salary'.humanize # => "Employee salary"
-
# 'author_id'.humanize # => "Author"
-
# 'author_id'.humanize(capitalize: false) # => "author"
-
# '_id'.humanize # => "Id"
-
1
def humanize(options = {})
-
14
ActiveSupport::Inflector.humanize(self, options)
-
end
-
-
# Creates a foreign key name from a class name.
-
# +separate_class_name_and_id_with_underscore+ sets whether
-
# the method should put '_' between the name and 'id'.
-
#
-
# 'Message'.foreign_key # => "message_id"
-
# 'Message'.foreign_key(false) # => "messageid"
-
# 'Admin::Post'.foreign_key # => "post_id"
-
1
def foreign_key(separate_class_name_and_id_with_underscore = true)
-
ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
-
end
-
end
-
1
require 'active_support/string_inquirer'
-
-
1
class String
-
# Wraps the current string in the <tt>ActiveSupport::StringInquirer</tt> class,
-
# which gives you a prettier way to test for equality.
-
#
-
# env = 'production'.inquiry
-
# env.production? # => true
-
# env.development? # => false
-
1
def inquiry
-
ActiveSupport::StringInquirer.new(self)
-
end
-
end
-
# encoding: utf-8
-
1
require 'active_support/multibyte'
-
-
1
class String
-
# == Multibyte proxy
-
#
-
# +mb_chars+ is a multibyte safe proxy for string methods.
-
#
-
# It creates and returns an instance of the ActiveSupport::Multibyte::Chars class which
-
# encapsulates the original string. A Unicode safe version of all the String methods are defined on this proxy
-
# class. If the proxy class doesn't respond to a certain method, it's forwarded to the encapsulated string.
-
#
-
# name = 'Claus Müller'
-
# name.reverse # => "rell??M sualC"
-
# name.length # => 13
-
#
-
# name.mb_chars.reverse.to_s # => "rellüM sualC"
-
# name.mb_chars.length # => 12
-
#
-
# == Method chaining
-
#
-
# All the methods on the Chars proxy which normally return a string will return a Chars object. This allows
-
# method chaining on the result of any of these methods.
-
#
-
# name.mb_chars.reverse.length # => 12
-
#
-
# == Interoperability and configuration
-
#
-
# The Chars object tries to be as interchangeable with String objects as possible: sorting and comparing between
-
# String and Char work like expected. The bang! methods change the internal string representation in the Chars
-
# object. Interoperability problems can be resolved easily with a +to_s+ call.
-
#
-
# For more information about the methods defined on the Chars proxy see ActiveSupport::Multibyte::Chars. For
-
# information about how to change the default Multibyte behavior see ActiveSupport::Multibyte.
-
1
def mb_chars
-
ActiveSupport::Multibyte.proxy_class.new(self)
-
end
-
-
1
def is_utf8?
-
case encoding
-
when Encoding::UTF_8
-
valid_encoding?
-
when Encoding::ASCII_8BIT, Encoding::US_ASCII
-
dup.force_encoding(Encoding::UTF_8).valid_encoding?
-
else
-
false
-
end
-
end
-
end
-
1
require 'erb'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/deprecation'
-
-
1
class ERB
-
1
module Util
-
1
HTML_ESCAPE = { '&' => '&', '>' => '>', '<' => '<', '"' => '"', "'" => ''' }
-
1
JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003e', '<' => '\u003c', "\u2028" => '\u2028', "\u2029" => '\u2029' }
-
1
HTML_ESCAPE_REGEXP = /[&"'><]/
-
1
HTML_ESCAPE_ONCE_REGEXP = /["><']|&(?!([a-zA-Z]+|(#\d+)|(#[xX][\dA-Fa-f]+));)/
-
1
JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/u
-
-
# A utility method for escaping HTML tag characters.
-
# This method is also aliased as <tt>h</tt>.
-
#
-
# In your ERB templates, use this method to escape any unsafe content. For example:
-
# <%=h @person.name %>
-
#
-
# puts html_escape('is a > 0 & a < 10?')
-
# # => is a > 0 & a < 10?
-
1
def html_escape(s)
-
197
unwrapped_html_escape(s).html_safe
-
end
-
-
# Aliasing twice issues a warning "discarding old...". Remove first to avoid it.
-
1
remove_method(:h)
-
1
alias h html_escape
-
-
1
module_function :h
-
-
1
singleton_class.send(:remove_method, :html_escape)
-
1
module_function :html_escape
-
-
# HTML escapes strings but doesn't wrap them with an ActiveSupport::SafeBuffer.
-
# This method is not for public consumption! Seriously!
-
1
def unwrapped_html_escape(s) # :nodoc:
-
1598
s = s.to_s
-
1598
if s.html_safe?
-
10
s
-
else
-
1588
s.gsub(HTML_ESCAPE_REGEXP, HTML_ESCAPE)
-
end
-
end
-
1
module_function :unwrapped_html_escape
-
-
# A utility method for escaping HTML without affecting existing escaped entities.
-
#
-
# html_escape_once('1 < 2 & 3')
-
# # => "1 < 2 & 3"
-
#
-
# html_escape_once('<< Accept & Checkout')
-
# # => "<< Accept & Checkout"
-
1
def html_escape_once(s)
-
result = s.to_s.gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
-
s.html_safe? ? result.html_safe : result
-
end
-
-
1
module_function :html_escape_once
-
-
# A utility method for escaping HTML entities in JSON strings. Specifically, the
-
# &, > and < characters are replaced with their equivalent unicode escaped form -
-
# \u0026, \u003e, and \u003c. The Unicode sequences \u2028 and \u2029 are also
-
# escaped as they are treated as newline characters in some JavaScript engines.
-
# These sequences have identical meaning as the original characters inside the
-
# context of a JSON string, so assuming the input is a valid and well-formed
-
# JSON value, the output will have equivalent meaning when parsed:
-
#
-
# json = JSON.generate({ name: "</script><script>alert('PWNED!!!')</script>"})
-
# # => "{\"name\":\"</script><script>alert('PWNED!!!')</script>\"}"
-
#
-
# json_escape(json)
-
# # => "{\"name\":\"\\u003C/script\\u003E\\u003Cscript\\u003Ealert('PWNED!!!')\\u003C/script\\u003E\"}"
-
#
-
# JSON.parse(json) == JSON.parse(json_escape(json))
-
# # => true
-
#
-
# The intended use case for this method is to escape JSON strings before including
-
# them inside a script tag to avoid XSS vulnerability:
-
#
-
# <script>
-
# var currentUser = <%= raw json_escape(current_user.to_json) %>;
-
# </script>
-
#
-
# It is necessary to +raw+ the result of +json_escape+, so that quotation marks
-
# don't get converted to <tt>"</tt> entities. +json_escape+ doesn't
-
# automatically flag the result as HTML safe, since the raw value is unsafe to
-
# use inside HTML attributes.
-
#
-
# If you need to output JSON elsewhere in your HTML, you can just do something
-
# like this, as any unsafe characters (including quotation marks) will be
-
# automatically escaped for you:
-
#
-
# <div data-user-info="<%= current_user.to_json %>">...</div>
-
#
-
# WARNING: this helper only works with valid JSON. Using this on non-JSON values
-
# will open up serious XSS vulnerabilities. For example, if you replace the
-
# +current_user.to_json+ in the example above with user input instead, the browser
-
# will happily eval() that string as JavaScript.
-
#
-
# The escaping performed in this method is identical to those performed in the
-
# Active Support JSON encoder when +ActiveSupport.escape_html_entities_in_json+ is
-
# set to true. Because this transformation is idempotent, this helper can be
-
# applied even if +ActiveSupport.escape_html_entities_in_json+ is already true.
-
#
-
# Therefore, when you are unsure if +ActiveSupport.escape_html_entities_in_json+
-
# is enabled, or if you are unsure where your JSON string originated from, it
-
# is recommended that you always apply this helper (other libraries, such as the
-
# JSON gem, do not provide this kind of protection by default; also some gems
-
# might override +to_json+ to bypass Active Support's encoder).
-
1
def json_escape(s)
-
result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE)
-
s.html_safe? ? result.html_safe : result
-
end
-
-
1
module_function :json_escape
-
end
-
end
-
-
1
class Object
-
1
def html_safe?
-
1823
false
-
end
-
end
-
-
1
class Numeric
-
1
def html_safe?
-
true
-
end
-
end
-
-
1
module ActiveSupport #:nodoc:
-
1
class SafeBuffer < String
-
1
UNSAFE_STRING_METHODS = %w(
-
capitalize chomp chop delete downcase gsub lstrip next reverse rstrip
-
slice squeeze strip sub succ swapcase tr tr_s upcase
-
)
-
-
1
alias_method :original_concat, :concat
-
1
private :original_concat
-
-
1
class SafeConcatError < StandardError
-
1
def initialize
-
super 'Could not concatenate to the buffer because it is not html safe.'
-
end
-
end
-
-
1
def [](*args)
-
8
if args.size < 2
-
8
super
-
else
-
if html_safe?
-
new_safe_buffer = super
-
-
if new_safe_buffer
-
new_safe_buffer.instance_variable_set :@html_safe, true
-
end
-
-
new_safe_buffer
-
else
-
to_str[*args]
-
end
-
end
-
end
-
-
1
def safe_concat(value)
-
8
raise SafeConcatError unless html_safe?
-
8
original_concat(value)
-
end
-
-
1
def initialize(*)
-
1579
@html_safe = true
-
1579
super
-
end
-
-
1
def initialize_copy(other)
-
54
super
-
54
@html_safe = other.html_safe?
-
end
-
-
1
def clone_empty
-
self[0, 0]
-
end
-
-
1
def concat(value)
-
58
super(html_escape_interpolated_argument(value))
-
end
-
1
alias << concat
-
-
1
def prepend(value)
-
super(html_escape_interpolated_argument(value))
-
end
-
-
1
def prepend!(value)
-
ActiveSupport::Deprecation.deprecation_warning "ActiveSupport::SafeBuffer#prepend!", :prepend
-
prepend value
-
end
-
-
1
def +(other)
-
50
dup.concat(other)
-
end
-
-
1
def %(args)
-
case args
-
when Hash
-
escaped_args = Hash[args.map { |k,arg| [k, html_escape_interpolated_argument(arg)] }]
-
else
-
escaped_args = Array(args).map { |arg| html_escape_interpolated_argument(arg) }
-
end
-
-
self.class.new(super(escaped_args))
-
end
-
-
1
def html_safe?
-
647
defined?(@html_safe) && @html_safe
-
end
-
-
1
def to_s
-
1783
self
-
end
-
-
1
def to_param
-
to_str
-
end
-
-
1
def encode_with(coder)
-
coder.represent_object nil, to_str
-
end
-
-
1
UNSAFE_STRING_METHODS.each do |unsafe_method|
-
19
if unsafe_method.respond_to?(unsafe_method)
-
19
class_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{unsafe_method}(*args, &block) # def capitalize(*args, &block)
-
to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block)
-
end # end
-
-
def #{unsafe_method}!(*args) # def capitalize!(*args)
-
@html_safe = false # @html_safe = false
-
super # super
-
end # end
-
EOT
-
end
-
end
-
-
1
private
-
-
1
def html_escape_interpolated_argument(arg)
-
58
(!html_safe? || arg.html_safe?) ? arg :
-
38
arg.to_s.gsub(ERB::Util::HTML_ESCAPE_REGEXP, ERB::Util::HTML_ESCAPE)
-
end
-
end
-
end
-
-
1
class String
-
# Marks a string as trusted safe. It will be inserted into HTML with no
-
# additional escaping performed. It is your responsibilty to ensure that the
-
# string contains no malicious content. This method is equivalent to the
-
# `raw` helper in views. It is recommended that you use `sanitize` instead of
-
# this method. It should never be called on user input.
-
1
def html_safe
-
1406
ActiveSupport::SafeBuffer.new(self)
-
end
-
end
-
1
class String
-
1
alias_method :starts_with?, :start_with?
-
1
alias_method :ends_with?, :end_with?
-
end
-
1
require 'active_support/core_ext/object/try'
-
-
1
class String
-
# Strips indentation in heredocs.
-
#
-
# For example in
-
#
-
# if options[:usage]
-
# puts <<-USAGE.strip_heredoc
-
# This command does such and such.
-
#
-
# Supported options are:
-
# -h This message
-
# ...
-
# USAGE
-
# end
-
#
-
# the user would see the usage message aligned against the left margin.
-
#
-
# Technically, it looks for the least indented line in the whole string, and removes
-
# that amount of leading whitespace.
-
1
def strip_heredoc
-
indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
-
gsub(/^[ \t]{#{indent}}/, '')
-
end
-
end
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'active_support/core_ext/time/zones'
-
-
1
class String
-
# Converts String to a TimeWithZone in the current zone if Time.zone or Time.zone_default
-
# is set, otherwise converts String to a Time via String#to_time
-
1
def in_time_zone(zone = ::Time.zone)
-
if zone
-
::Time.find_zone!(zone).parse(self)
-
else
-
to_time
-
end
-
end
-
end
-
# Backport of Struct#to_h from Ruby 2.0
-
class Struct # :nodoc:
-
def to_h
-
Hash[members.zip(values)]
-
end
-
1
end unless Struct.instance_methods.include?(:to_h)
-
class Thread
-
LOCK = Mutex.new # :nodoc:
-
-
# Returns the value of a thread local variable that has been set. Note that
-
# these are different than fiber local values.
-
#
-
# Thread local values are carried along with threads, and do not respect
-
# fibers. For example:
-
#
-
# Thread.new {
-
# Thread.current.thread_variable_set("foo", "bar") # set a thread local
-
# Thread.current["foo"] = "bar" # set a fiber local
-
#
-
# Fiber.new {
-
# Fiber.yield [
-
# Thread.current.thread_variable_get("foo"), # get the thread local
-
# Thread.current["foo"], # get the fiber local
-
# ]
-
# }.resume
-
# }.join.value # => ['bar', nil]
-
#
-
# The value <tt>"bar"</tt> is returned for the thread local, where +nil+ is returned
-
# for the fiber local. The fiber is executed in the same thread, so the
-
# thread local values are available.
-
def thread_variable_get(key)
-
_locals[key.to_sym]
-
end
-
-
# Sets a thread local with +key+ to +value+. Note that these are local to
-
# threads, and not to fibers. Please see Thread#thread_variable_get for
-
# more information.
-
def thread_variable_set(key, value)
-
_locals[key.to_sym] = value
-
end
-
-
# Returns an array of the names of the thread-local variables (as Symbols).
-
#
-
# thr = Thread.new do
-
# Thread.current.thread_variable_set(:cat, 'meow')
-
# Thread.current.thread_variable_set("dog", 'woof')
-
# end
-
# thr.join # => #<Thread:0x401b3f10 dead>
-
# thr.thread_variables # => [:dog, :cat]
-
#
-
# Note that these are not fiber local variables. Please see Thread#thread_variable_get
-
# for more details.
-
def thread_variables
-
_locals.keys
-
end
-
-
# Returns <tt>true</tt> if the given string (or symbol) exists as a
-
# thread-local variable.
-
#
-
# me = Thread.current
-
# me.thread_variable_set(:oliver, "a")
-
# me.thread_variable?(:oliver) # => true
-
# me.thread_variable?(:stanley) # => false
-
#
-
# Note that these are not fiber local variables. Please see Thread#thread_variable_get
-
# for more details.
-
def thread_variable?(key)
-
_locals.has_key?(key.to_sym)
-
end
-
-
# Freezes the thread so that thread local variables cannot be set via
-
# Thread#thread_variable_set, nor can fiber local variables be set.
-
#
-
# me = Thread.current
-
# me.freeze
-
# me.thread_variable_set(:oliver, "a") #=> RuntimeError: can't modify frozen thread locals
-
# me[:oliver] = "a" #=> RuntimeError: can't modify frozen thread locals
-
def freeze
-
_locals.freeze
-
super
-
end
-
-
private
-
-
def _locals
-
if defined?(@_locals)
-
@_locals
-
else
-
LOCK.synchronize { @_locals ||= {} }
-
end
-
end
-
1
end unless Thread.instance_methods.include?(:thread_variable_set)
-
1
require 'active_support/core_ext/time/acts_like'
-
1
require 'active_support/core_ext/time/calculations'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/time/marshal'
-
1
require 'active_support/core_ext/time/zones'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
class Time
-
# Duck-types as a Time-like class. See Object#acts_like?.
-
1
def acts_like_time?
-
true
-
end
-
end
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/time_with_zone'
-
1
require 'active_support/core_ext/time/zones'
-
1
require 'active_support/core_ext/date_and_time/calculations'
-
1
require 'active_support/core_ext/date/calculations'
-
-
1
class Time
-
1
include DateAndTime::Calculations
-
-
1
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-
-
1
class << self
-
# Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances
-
1
def ===(other)
-
162
super || (self == Time && other.is_a?(ActiveSupport::TimeWithZone))
-
end
-
-
# Return the number of days in the given month.
-
# If no year is specified, it will use the current year.
-
1
def days_in_month(month, year = now.year)
-
if month == 2 && ::Date.gregorian_leap?(year)
-
29
-
else
-
COMMON_YEAR_DAYS_IN_MONTH[month]
-
end
-
end
-
-
# Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
-
1
def current
-
1
::Time.zone ? ::Time.zone.now : ::Time.now
-
end
-
-
# Layers additional behavior on Time.at so that ActiveSupport::TimeWithZone and DateTime
-
# instances can be used when called with a single argument
-
1
def at_with_coercion(*args)
-
return at_without_coercion(*args) if args.size != 1
-
-
# Time.at can be called with a time or numerical value
-
time_or_number = args.first
-
-
if time_or_number.is_a?(ActiveSupport::TimeWithZone) || time_or_number.is_a?(DateTime)
-
at_without_coercion(time_or_number.to_f).getlocal
-
else
-
at_without_coercion(time_or_number)
-
end
-
end
-
1
alias_method :at_without_coercion, :at
-
1
alias_method :at, :at_with_coercion
-
end
-
-
# Seconds since midnight: Time.now.seconds_since_midnight
-
1
def seconds_since_midnight
-
to_i - change(:hour => 0).to_i + (usec / 1.0e+6)
-
end
-
-
# Returns the number of seconds until 23:59:59.
-
#
-
# Time.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399
-
# Time.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
-
# Time.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0
-
1
def seconds_until_end_of_day
-
end_of_day.to_i - to_i
-
end
-
-
# Returns a new Time where one or more of the elements have been changed according
-
# to the +options+ parameter. The time options (<tt>:hour</tt>, <tt>:min</tt>,
-
# <tt>:sec</tt>, <tt>:usec</tt>, <tt>:nsec</tt>) reset cascadingly, so if only
-
# the hour is passed, then minute, sec, usec and nsec is set to 0. If the hour
-
# and minute is passed, then sec, usec and nsec is set to 0. The +options+
-
# parameter takes a hash with any of these keys: <tt>:year</tt>, <tt>:month</tt>,
-
# <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>
-
# <tt>:nsec</tt>. Path either <tt>:usec</tt> or <tt>:nsec</tt>, not both.
-
#
-
# Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0)
-
# Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0)
-
# Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0)
-
1
def change(options)
-
new_year = options.fetch(:year, year)
-
new_month = options.fetch(:month, month)
-
new_day = options.fetch(:day, day)
-
new_hour = options.fetch(:hour, hour)
-
new_min = options.fetch(:min, options[:hour] ? 0 : min)
-
new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)
-
-
if new_nsec = options[:nsec]
-
raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec]
-
new_usec = Rational(new_nsec, 1000)
-
else
-
new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
-
end
-
-
if utc?
-
::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
-
elsif zone
-
::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
-
else
-
raise ArgumentError, 'argument out of range' if new_usec >= 1000000
-
::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec + (new_usec.to_r / 1000000), utc_offset)
-
end
-
end
-
-
# Uses Date to provide precise Time calculations for years, months, and days
-
# according to the proleptic Gregorian calendar. The +options+ parameter
-
# takes a hash with any of these keys: <tt>:years</tt>, <tt>:months</tt>,
-
# <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, <tt>:minutes</tt>,
-
# <tt>:seconds</tt>.
-
#
-
# Time.new(2015, 8, 1, 14, 35, 0).advance(seconds: 1) # => 2015-08-01 14:35:01 -0700
-
# Time.new(2015, 8, 1, 14, 35, 0).advance(minutes: 1) # => 2015-08-01 14:36:00 -0700
-
# Time.new(2015, 8, 1, 14, 35, 0).advance(hours: 1) # => 2015-08-01 15:35:00 -0700
-
# Time.new(2015, 8, 1, 14, 35, 0).advance(days: 1) # => 2015-08-02 14:35:00 -0700
-
# Time.new(2015, 8, 1, 14, 35, 0).advance(weeks: 1) # => 2015-08-08 14:35:00 -0700
-
1
def advance(options)
-
unless options[:weeks].nil?
-
options[:weeks], partial_weeks = options[:weeks].divmod(1)
-
options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
-
end
-
-
unless options[:days].nil?
-
options[:days], partial_days = options[:days].divmod(1)
-
options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
-
end
-
-
d = to_date.advance(options)
-
d = d.gregorian if d.julian?
-
time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
-
seconds_to_advance = \
-
options.fetch(:seconds, 0) +
-
options.fetch(:minutes, 0) * 60 +
-
options.fetch(:hours, 0) * 3600
-
-
if seconds_to_advance.zero?
-
time_advanced_by_date
-
else
-
time_advanced_by_date.since(seconds_to_advance)
-
end
-
end
-
-
# Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension
-
1
def ago(seconds)
-
since(-seconds)
-
end
-
-
# Returns a new Time representing the time a number of seconds since the instance time
-
1
def since(seconds)
-
self + seconds
-
rescue
-
to_datetime.since(seconds)
-
end
-
1
alias :in :since
-
-
# Returns a new Time representing the start of the day (0:00)
-
1
def beginning_of_day
-
#(self - seconds_since_midnight).change(usec: 0)
-
change(:hour => 0)
-
end
-
1
alias :midnight :beginning_of_day
-
1
alias :at_midnight :beginning_of_day
-
1
alias :at_beginning_of_day :beginning_of_day
-
-
# Returns a new Time representing the middle of the day (12:00)
-
1
def middle_of_day
-
change(:hour => 12)
-
end
-
1
alias :midday :middle_of_day
-
1
alias :noon :middle_of_day
-
1
alias :at_midday :middle_of_day
-
1
alias :at_noon :middle_of_day
-
1
alias :at_middle_of_day :middle_of_day
-
-
# Returns a new Time representing the end of the day, 23:59:59.999999 (.999999999 in ruby1.9)
-
1
def end_of_day
-
change(
-
:hour => 23,
-
:min => 59,
-
:sec => 59,
-
:usec => Rational(999999999, 1000)
-
)
-
end
-
1
alias :at_end_of_day :end_of_day
-
-
# Returns a new Time representing the start of the hour (x:00)
-
1
def beginning_of_hour
-
change(:min => 0)
-
end
-
1
alias :at_beginning_of_hour :beginning_of_hour
-
-
# Returns a new Time representing the end of the hour, x:59:59.999999 (.999999999 in ruby1.9)
-
1
def end_of_hour
-
change(
-
:min => 59,
-
:sec => 59,
-
:usec => Rational(999999999, 1000)
-
)
-
end
-
1
alias :at_end_of_hour :end_of_hour
-
-
# Returns a new Time representing the start of the minute (x:xx:00)
-
1
def beginning_of_minute
-
change(:sec => 0)
-
end
-
1
alias :at_beginning_of_minute :beginning_of_minute
-
-
# Returns a new Time representing the end of the minute, x:xx:59.999999 (.999999999 in ruby1.9)
-
1
def end_of_minute
-
change(
-
:sec => 59,
-
:usec => Rational(999999999, 1000)
-
)
-
end
-
1
alias :at_end_of_minute :end_of_minute
-
-
# Returns a Range representing the whole day of the current time.
-
1
def all_day
-
beginning_of_day..end_of_day
-
end
-
-
1
def plus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
other.since(self)
-
else
-
plus_without_duration(other)
-
end
-
end
-
1
alias_method :plus_without_duration, :+
-
1
alias_method :+, :plus_with_duration
-
-
1
def minus_with_duration(other) #:nodoc:
-
354
if ActiveSupport::Duration === other
-
other.until(self)
-
else
-
354
minus_without_duration(other)
-
end
-
end
-
1
alias_method :minus_without_duration, :-
-
1
alias_method :-, :minus_with_duration
-
-
# Time#- can also be used to determine the number of seconds between two Time instances.
-
# We're layering on additional behavior so that ActiveSupport::TimeWithZone instances
-
# are coerced into values that Time#- will recognize
-
1
def minus_with_coercion(other)
-
354
other = other.comparable_time if other.respond_to?(:comparable_time)
-
354
other.is_a?(DateTime) ? to_f - other.to_f : minus_without_coercion(other)
-
end
-
1
alias_method :minus_without_coercion, :-
-
1
alias_method :-, :minus_with_coercion
-
-
# Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances
-
# can be chronologically compared with a Time
-
1
def compare_with_coercion(other)
-
# we're avoiding Time#to_datetime cause it's expensive
-
294
if other.is_a?(Time)
-
293
compare_without_coercion(other.to_time)
-
else
-
1
to_datetime <=> other
-
end
-
end
-
1
alias_method :compare_without_coercion, :<=>
-
1
alias_method :<=>, :compare_with_coercion
-
-
# Layers additional behavior on Time#eql? so that ActiveSupport::TimeWithZone instances
-
# can be eql? to an equivalent Time
-
1
def eql_with_coercion(other)
-
# if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do eql? comparison
-
other = other.comparable_time if other.respond_to?(:comparable_time)
-
eql_without_coercion(other)
-
end
-
1
alias_method :eql_without_coercion, :eql?
-
1
alias_method :eql?, :eql_with_coercion
-
-
end
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/values/time_zone'
-
-
1
class Time
-
1
DATE_FORMATS = {
-
:db => '%Y-%m-%d %H:%M:%S',
-
:number => '%Y%m%d%H%M%S',
-
:nsec => '%Y%m%d%H%M%S%9N',
-
:time => '%H:%M',
-
:short => '%d %b %H:%M',
-
:long => '%B %d, %Y %H:%M',
-
:long_ordinal => lambda { |time|
-
day_format = ActiveSupport::Inflector.ordinalize(time.day)
-
time.strftime("%B #{day_format}, %Y %H:%M")
-
},
-
:rfc822 => lambda { |time|
-
offset_format = time.formatted_offset(false)
-
time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}")
-
},
-
:iso8601 => lambda { |time| time.iso8601 }
-
}
-
-
# Converts to a formatted string. See DATE_FORMATS for built-in formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# time = Time.now # => Thu Jan 18 06:10:17 CST 2007
-
#
-
# time.to_formatted_s(:time) # => "06:10"
-
# time.to_s(:time) # => "06:10"
-
#
-
# time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
-
# time.to_formatted_s(:number) # => "20070118061017"
-
# time.to_formatted_s(:short) # => "18 Jan 06:10"
-
# time.to_formatted_s(:long) # => "January 18, 2007 06:10"
-
# time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
-
# time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
-
# time.to_formatted_s(:iso8601) # => "2007-01-18T06:10:17-06:00"
-
#
-
# == Adding your own time formats to +to_formatted_s+
-
# You can add your own formats to the Time::DATE_FORMATS hash.
-
# Use the format name as the hash key and either a strftime string
-
# or Proc instance that takes a time argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Time::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Time::DATE_FORMATS[:short_ordinal] = ->(time) { time.strftime("%B #{time.day.ordinalize}") }
-
1
def to_formatted_s(format = :default)
-
54
if formatter = DATE_FORMATS[format]
-
54
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
-
# Returns the UTC offset as an +HH:MM formatted string.
-
#
-
# Time.local(2000).formatted_offset # => "-06:00"
-
# Time.local(2000).formatted_offset(false) # => "-0600"
-
1
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
end
-
# Ruby 1.9.2 adds utc_offset and zone to Time, but marshaling only
-
# preserves utc_offset. Preserve zone also, even though it may not
-
# work in some edge cases.
-
1
if Time.local(2010).zone != Marshal.load(Marshal.dump(Time.local(2010))).zone
-
class Time
-
class << self
-
alias_method :_load_without_zone, :_load
-
def _load(marshaled_time)
-
time = _load_without_zone(marshaled_time)
-
time.instance_eval do
-
if zone = defined?(@_zone) && remove_instance_variable('@_zone')
-
ary = to_a
-
ary[0] += subsec if ary[0] == sec
-
ary[-1] = zone
-
utc? ? Time.utc(*ary) : Time.local(*ary)
-
else
-
self
-
end
-
end
-
end
-
end
-
-
alias_method :_dump_without_zone, :_dump
-
def _dump(*args)
-
obj = dup
-
obj.instance_variable_set('@_zone', zone)
-
obj.send :_dump_without_zone, *args
-
end
-
end
-
end
-
1
require 'active_support/time_with_zone'
-
1
require 'active_support/core_ext/time/acts_like'
-
1
require 'active_support/core_ext/date_and_time/zones'
-
-
1
class Time
-
1
include DateAndTime::Zones
-
1
class << self
-
1
attr_accessor :zone_default
-
-
# Returns the TimeZone for the current request, if this has been set (via Time.zone=).
-
# If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>.
-
1
def zone
-
64
Thread.current[:time_zone] || zone_default
-
end
-
-
# Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread.
-
#
-
# This method accepts any of the following:
-
#
-
# * A Rails TimeZone object.
-
# * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>).
-
# * A TZInfo::Timezone object.
-
# * An identifier for a TZInfo::Timezone object (e.g., "America/New_York").
-
#
-
# Here's an example of how you might set <tt>Time.zone</tt> on a per request basis and reset it when the request is done.
-
# <tt>current_user.time_zone</tt> just needs to return a string identifying the user's preferred time zone:
-
#
-
# class ApplicationController < ActionController::Base
-
# around_filter :set_time_zone
-
#
-
# def set_time_zone
-
# if logged_in?
-
# Time.use_zone(current_user.time_zone) { yield }
-
# else
-
# yield
-
# end
-
# end
-
# end
-
1
def zone=(time_zone)
-
Thread.current[:time_zone] = find_zone!(time_zone)
-
end
-
-
# Allows override of <tt>Time.zone</tt> locally inside supplied block; resets <tt>Time.zone</tt> to existing value when done.
-
1
def use_zone(time_zone)
-
new_zone = find_zone!(time_zone)
-
begin
-
old_zone, ::Time.zone = ::Time.zone, new_zone
-
yield
-
ensure
-
::Time.zone = old_zone
-
end
-
end
-
-
# Returns a TimeZone instance or nil, or raises an ArgumentError for invalid timezones.
-
1
def find_zone!(time_zone)
-
64
if !time_zone || time_zone.is_a?(ActiveSupport::TimeZone)
-
63
time_zone
-
else
-
# lookup timezone based on identifier (unless we've been passed a TZInfo::Timezone)
-
1
unless time_zone.respond_to?(:period_for_local)
-
1
time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone)
-
end
-
-
# Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone
-
1
if time_zone.is_a?(ActiveSupport::TimeZone)
-
1
time_zone
-
else
-
ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone)
-
end
-
end
-
rescue TZInfo::InvalidTimezoneIdentifier
-
raise ArgumentError, "Invalid Timezone: #{time_zone}"
-
end
-
-
1
def find_zone(time_zone)
-
find_zone!(time_zone) rescue nil
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'uri'
-
1
str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese.
-
1
parser = URI::Parser.new
-
-
1
unless str == parser.unescape(parser.escape(str))
-
1
URI::Parser.class_eval do
-
1
remove_method :unescape
-
1
def unescape(str, escaped = /%[a-fA-F\d]{2}/)
-
# TODO: Are we actually sure that ASCII == UTF-8?
-
# YK: My initial experiments say yes, but let's be sure please
-
121
enc = str.encoding
-
121
enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
-
121
str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc)
-
end
-
end
-
end
-
-
1
module URI
-
1
class << self
-
1
def parser
-
90
@parser ||= URI::Parser.new
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'thread'
-
1
require 'thread_safe'
-
1
require 'pathname'
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/module/qualified_const'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/load_error'
-
1
require 'active_support/core_ext/name_error'
-
1
require 'active_support/core_ext/string/starts_ends_with'
-
1
require 'active_support/inflector'
-
-
1
module ActiveSupport #:nodoc:
-
1
module Dependencies #:nodoc:
-
1
extend self
-
-
# Should we turn on Ruby warnings on the first load of dependent files?
-
1
mattr_accessor :warnings_on_first_load
-
1
self.warnings_on_first_load = false
-
-
# All files ever loaded.
-
1
mattr_accessor :history
-
1
self.history = Set.new
-
-
# All files currently loaded.
-
1
mattr_accessor :loaded
-
1
self.loaded = Set.new
-
-
# Stack of files being loaded.
-
1
mattr_accessor :loading
-
1
self.loading = []
-
-
# Should we load files or require them?
-
1
mattr_accessor :mechanism
-
1
self.mechanism = ENV['NO_RELOAD'] ? :require : :load
-
-
# The set of directories from which we may automatically load files. Files
-
# under these directories will be reloaded on each request in development mode,
-
# unless the directory also appears in autoload_once_paths.
-
1
mattr_accessor :autoload_paths
-
1
self.autoload_paths = []
-
-
# The set of directories from which automatically loaded constants are loaded
-
# only once. All directories in this set must also be present in +autoload_paths+.
-
1
mattr_accessor :autoload_once_paths
-
1
self.autoload_once_paths = []
-
-
# An array of qualified constant names that have been loaded. Adding a name
-
# to this array will cause it to be unloaded the next time Dependencies are
-
# cleared.
-
1
mattr_accessor :autoloaded_constants
-
1
self.autoloaded_constants = []
-
-
# An array of constant names that need to be unloaded on every request. Used
-
# to allow arbitrary constants to be marked for unloading.
-
1
mattr_accessor :explicitly_unloadable_constants
-
1
self.explicitly_unloadable_constants = []
-
-
# The logger is used for generating information on the action run-time
-
# (including benchmarking) if available. Can be set to nil for no logging.
-
# Compatible with both Ruby's own Logger and Log4r loggers.
-
1
mattr_accessor :logger
-
-
# Set to +true+ to enable logging of const_missing and file loads.
-
1
mattr_accessor :log_activity
-
1
self.log_activity = false
-
-
# The WatchStack keeps a stack of the modules being watched as files are
-
# loaded. If a file in the process of being loaded (parent.rb) triggers the
-
# load of another file (child.rb) the stack will ensure that child.rb
-
# handles the new constants.
-
#
-
# If child.rb is being autoloaded, its constants will be added to
-
# autoloaded_constants. If it was being `require`d, they will be discarded.
-
#
-
# This is handled by walking back up the watch stack and adding the constants
-
# found by child.rb to the list of original constants in parent.rb.
-
1
class WatchStack
-
1
include Enumerable
-
-
# @watching is a stack of lists of constants being watched. For instance,
-
# if parent.rb is autoloaded, the stack will look like [[Object]]. If
-
# parent.rb then requires namespace/child.rb, the stack will look like
-
# [[Object], [Namespace]].
-
-
1
def initialize
-
1
@watching = []
-
1
@stack = Hash.new { |h,k| h[k] = [] }
-
end
-
-
1
def each(&block)
-
@stack.each(&block)
-
end
-
-
1
def watching?
-
167
!@watching.empty?
-
end
-
-
# Returns a list of new constants found since the last call to
-
# <tt>watch_namespaces</tt>.
-
1
def new_constants
-
constants = []
-
-
# Grab the list of namespaces that we're looking for new constants under
-
@watching.last.each do |namespace|
-
# Retrieve the constants that were present under the namespace when watch_namespaces
-
# was originally called
-
original_constants = @stack[namespace].last
-
-
mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace)
-
next unless mod.is_a?(Module)
-
-
# Get a list of the constants that were added
-
new_constants = mod.local_constants - original_constants
-
-
# self[namespace] returns an Array of the constants that are being evaluated
-
# for that namespace. For instance, if parent.rb requires child.rb, the first
-
# element of self[Object] will be an Array of the constants that were present
-
# before parent.rb was required. The second element will be an Array of the
-
# constants that were present before child.rb was required.
-
@stack[namespace].each do |namespace_constants|
-
namespace_constants.concat(new_constants)
-
end
-
-
# Normalize the list of new constants, and add them to the list we will return
-
new_constants.each do |suffix|
-
constants << ([namespace, suffix] - ["Object"]).join("::")
-
end
-
end
-
constants
-
ensure
-
# A call to new_constants is always called after a call to watch_namespaces
-
pop_modules(@watching.pop)
-
end
-
-
# Add a set of modules to the watch stack, remembering the initial
-
# constants.
-
1
def watch_namespaces(namespaces)
-
@watching << namespaces.map do |namespace|
-
module_name = Dependencies.to_constant_name(namespace)
-
original_constants = Dependencies.qualified_const_defined?(module_name) ?
-
Inflector.constantize(module_name).local_constants : []
-
-
@stack[module_name] << original_constants
-
module_name
-
end
-
end
-
-
1
private
-
1
def pop_modules(modules)
-
modules.each { |mod| @stack[mod].pop }
-
end
-
end
-
-
# An internal stack used to record which constants are loaded by any block.
-
1
mattr_accessor :constant_watch_stack
-
1
self.constant_watch_stack = WatchStack.new
-
-
# Module includes this module.
-
1
module ModuleConstMissing #:nodoc:
-
1
def self.append_features(base)
-
1
base.class_eval do
-
# Emulate #exclude via an ivar
-
1
return if defined?(@_const_missing) && @_const_missing
-
1
@_const_missing = instance_method(:const_missing)
-
1
remove_method(:const_missing)
-
end
-
1
super
-
end
-
-
1
def self.exclude_from(base)
-
base.class_eval do
-
define_method :const_missing, @_const_missing
-
@_const_missing = nil
-
end
-
end
-
-
1
def const_missing(const_name)
-
14
from_mod = anonymous? ? guess_for_anonymous(const_name) : self
-
14
Dependencies.load_missing_constant(from_mod, const_name)
-
end
-
-
# We assume that the name of the module reflects the nesting
-
# (unless it can be proven that is not the case) and the path to the file
-
# that defines the constant. Anonymous modules cannot follow these
-
# conventions and therefore we assume that the user wants to refer to a
-
# top-level constant.
-
1
def guess_for_anonymous(const_name)
-
if Object.const_defined?(const_name)
-
raise NameError.new "#{const_name} cannot be autoloaded from an anonymous class or module", const_name
-
else
-
Object
-
end
-
end
-
-
1
def unloadable(const_desc = self)
-
super(const_desc)
-
end
-
end
-
-
# Object includes this module.
-
1
module Loadable #:nodoc:
-
1
def self.exclude_from(base)
-
base.class_eval do
-
define_method(:load, Kernel.instance_method(:load))
-
private :load
-
end
-
end
-
-
1
def require_or_load(file_name)
-
Dependencies.require_or_load(file_name)
-
end
-
-
# Interprets a file using <tt>mechanism</tt> and marks its defined
-
# constants as autoloaded. <tt>file_name</tt> can be either a string or
-
# respond to <tt>to_path</tt>.
-
#
-
# Use this method in code that absolutely needs a certain constant to be
-
# defined at that point. A typical use case is to make constant name
-
# resolution deterministic for constants with the same relative name in
-
# different namespaces whose evaluation would depend on load order
-
# otherwise.
-
1
def require_dependency(file_name, message = "No such file to load -- %s")
-
13
file_name = file_name.to_path if file_name.respond_to?(:to_path)
-
13
unless file_name.is_a?(String)
-
raise ArgumentError, "the file name must either be a String or implement #to_path -- you passed #{file_name.inspect}"
-
end
-
-
13
Dependencies.depend_on(file_name, message)
-
end
-
-
1
def load_dependency(file)
-
1074
if Dependencies.load? && ActiveSupport::Dependencies.constant_watch_stack.watching?
-
Dependencies.new_constants_in(Object) { yield }
-
else
-
1074
yield
-
end
-
rescue Exception => exception # errors from loading file
-
2
exception.blame_file! file if exception.respond_to? :blame_file!
-
2
raise
-
end
-
-
# Mark the given constant as unloadable. Unloadable constants are removed
-
# each time dependencies are cleared.
-
#
-
# Note that marking a constant for unloading need only be done once. Setup
-
# or init scripts may list each unloadable constant that may need unloading;
-
# each constant will be removed for every subsequent clear, as opposed to
-
# for the first clear.
-
#
-
# The provided constant descriptor may be a (non-anonymous) module or class,
-
# or a qualified constant name as a string or symbol.
-
#
-
# Returns +true+ if the constant was not previously marked for unloading,
-
# +false+ otherwise.
-
1
def unloadable(const_desc)
-
Dependencies.mark_for_unload const_desc
-
end
-
-
1
private
-
-
1
def load(file, wrap = false)
-
16
result = false
-
32
load_dependency(file) { result = super }
-
16
result
-
end
-
-
1
def require(file)
-
1058
result = false
-
2116
load_dependency(file) { result = super }
-
1056
result
-
end
-
end
-
-
# Exception file-blaming.
-
1
module Blamable #:nodoc:
-
1
def blame_file!(file)
-
2
(@blamed_files ||= []).unshift file
-
end
-
-
1
def blamed_files
-
@blamed_files ||= []
-
end
-
-
1
def describe_blame
-
return nil if blamed_files.empty?
-
"This error occurred while loading the following files:\n #{blamed_files.join "\n "}"
-
end
-
-
1
def copy_blame!(exc)
-
@blamed_files = exc.blamed_files.clone
-
self
-
end
-
end
-
-
1
def hook!
-
2
Object.class_eval { include Loadable }
-
2
Module.class_eval { include ModuleConstMissing }
-
2
Exception.class_eval { include Blamable }
-
end
-
-
1
def unhook!
-
ModuleConstMissing.exclude_from(Module)
-
Loadable.exclude_from(Object)
-
end
-
-
1
def load?
-
1091
mechanism == :load
-
end
-
-
1
def depend_on(file_name, message = "No such file to load -- %s.rb")
-
13
path = search_for_file(file_name)
-
13
require_or_load(path || file_name)
-
rescue LoadError => load_error
-
if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
-
load_error.message.replace(message % file_name)
-
load_error.copy_blame!(load_error)
-
end
-
raise
-
end
-
-
1
def clear
-
log_call
-
loaded.clear
-
loading.clear
-
remove_unloadable_constants!
-
end
-
-
1
def require_or_load(file_name, const_path = nil)
-
23
log_call file_name, const_path
-
23
file_name = $` if file_name =~ /\.rb\z/
-
23
expanded = File.expand_path(file_name)
-
23
return if loaded.include?(expanded)
-
-
# Record that we've seen this file *before* loading it to avoid an
-
# infinite loop with mutual dependencies.
-
17
loaded << expanded
-
17
loading << expanded
-
-
17
begin
-
17
if load?
-
log "loading #{file_name}"
-
-
# Enable warnings if this file has not been loaded before and
-
# warnings_on_first_load is set.
-
load_args = ["#{file_name}.rb"]
-
load_args << const_path unless const_path.nil?
-
-
if !warnings_on_first_load or history.include?(expanded)
-
result = load_file(*load_args)
-
else
-
enable_warnings { result = load_file(*load_args) }
-
end
-
else
-
17
log "requiring #{file_name}"
-
17
result = require file_name
-
end
-
rescue Exception
-
loaded.delete expanded
-
raise
-
ensure
-
17
loading.pop
-
end
-
-
# Record history *after* loading so first load gets warnings.
-
17
history << expanded
-
17
result
-
end
-
-
# Is the provided constant path defined?
-
1
def qualified_const_defined?(path)
-
14
Object.qualified_const_defined?(path.sub(/^::/, ''), false)
-
end
-
-
# Given +path+, a filesystem path to a ruby file, return an array of
-
# constant paths which would cause Dependencies to attempt to load this
-
# file.
-
1
def loadable_constants_for_path(path, bases = autoload_paths)
-
path = $` if path =~ /\.rb\z/
-
expanded_path = File.expand_path(path)
-
paths = []
-
-
bases.each do |root|
-
expanded_root = File.expand_path(root)
-
next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
-
-
nesting = expanded_path[(expanded_root.size)..-1]
-
nesting = nesting[1..-1] if nesting && nesting[0] == ?/
-
next if nesting.blank?
-
-
paths << nesting.camelize
-
end
-
-
paths.uniq!
-
paths
-
end
-
-
# Search for a file in autoload_paths matching the provided suffix.
-
1
def search_for_file(path_suffix)
-
27
path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb")
-
-
27
autoload_paths.each do |root|
-
99
path = File.join(root, path_suffix)
-
99
return path if File.file? path
-
end
-
nil # Gee, I sure wish we had first_match ;-)
-
end
-
-
# Does the provided path_suffix correspond to an autoloadable module?
-
# Instead of returning a boolean, the autoload base for this module is
-
# returned.
-
1
def autoloadable_module?(path_suffix)
-
4
autoload_paths.each do |load_path|
-
28
return load_path if File.directory? File.join(load_path, path_suffix)
-
end
-
nil
-
end
-
-
1
def load_once_path?(path)
-
# to_s works around a ruby1.9 issue where String#starts_with?(Pathname)
-
# will raise a TypeError: no implicit conversion of Pathname into String
-
autoload_once_paths.any? { |base| path.starts_with? base.to_s }
-
end
-
-
# Attempt to autoload the provided module name by searching for a directory
-
# matching the expected path suffix. If found, the module is created and
-
# assigned to +into+'s constants with the name +const_name+. Provided that
-
# the directory was loaded from a reloadable base path, it is added to the
-
# set of constants that are to be unloaded.
-
1
def autoload_module!(into, const_name, qualified_name, path_suffix)
-
4
return nil unless base_path = autoloadable_module?(path_suffix)
-
mod = Module.new
-
into.const_set const_name, mod
-
autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path)
-
mod
-
end
-
-
# Load the file at the provided path. +const_paths+ is a set of qualified
-
# constant names. When loading the file, Dependencies will watch for the
-
# addition of these constants. Each that is defined will be marked as
-
# autoloaded, and will be removed when Dependencies.clear is next called.
-
#
-
# If the second parameter is left off, then Dependencies will construct a
-
# set of names that the file at +path+ may define. See
-
# +loadable_constants_for_path+ for more details.
-
1
def load_file(path, const_paths = loadable_constants_for_path(path))
-
log_call path, const_paths
-
const_paths = [const_paths].compact unless const_paths.is_a? Array
-
parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || ::Object }
-
-
result = nil
-
newly_defined_paths = new_constants_in(*parent_paths) do
-
result = Kernel.load path
-
end
-
-
autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
-
autoloaded_constants.uniq!
-
log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
-
result
-
end
-
-
# Returns the constant path for the provided parent and constant name.
-
1
def qualified_name_for(mod, name)
-
16
mod_name = to_constant_name mod
-
16
mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}"
-
end
-
-
# Load the constant named +const_name+ which is missing from +from_mod+. If
-
# it is not possible to load the constant into from_mod, try its parent
-
# module using +const_missing+.
-
1
def load_missing_constant(from_mod, const_name)
-
14
log_call from_mod, const_name
-
-
14
unless qualified_const_defined?(from_mod.name) && Inflector.constantize(from_mod.name).equal?(from_mod)
-
raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
-
end
-
-
14
qualified_name = qualified_name_for from_mod, const_name
-
14
path_suffix = qualified_name.underscore
-
-
14
file_path = search_for_file(path_suffix)
-
-
14
if file_path
-
10
expanded = File.expand_path(file_path)
-
10
expanded.sub!(/\.rb\z/, '')
-
-
10
if loading.include?(expanded)
-
raise "Circular dependency detected while autoloading constant #{qualified_name}"
-
else
-
10
require_or_load(expanded, qualified_name)
-
10
raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
-
10
return from_mod.const_get(const_name)
-
end
-
elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
-
return mod
-
4
elsif (parent = from_mod.parent) && parent != from_mod &&
-
4
! from_mod.parents.any? { |p| p.const_defined?(const_name, false) }
-
# If our parents do not have a constant named +const_name+ then we are free
-
# to attempt to load upwards. If they do have such a constant, then this
-
# const_missing must be due to from_mod::const_name, which should not
-
# return constants from from_mod's parents.
-
3
begin
-
# Since Ruby does not pass the nesting at the point the unknown
-
# constant triggered the callback we cannot fully emulate constant
-
# name lookup and need to make a trade-off: we are going to assume
-
# that the nesting in the body of Foo::Bar is [Foo::Bar, Foo] even
-
# though it might not be. Counterexamples are
-
#
-
# class Foo::Bar
-
# Module.nesting # => [Foo::Bar]
-
# end
-
#
-
# or
-
#
-
# module M::N
-
# module S::T
-
# Module.nesting # => [S::T, M::N]
-
# end
-
# end
-
#
-
# for example.
-
3
return parent.const_missing(const_name)
-
rescue NameError => e
-
2
raise unless e.missing_name? qualified_name_for(parent, const_name)
-
end
-
end
-
-
3
name_error = NameError.new("uninitialized constant #{qualified_name}", const_name)
-
63
name_error.set_backtrace(caller.reject {|l| l.starts_with? __FILE__ })
-
3
raise name_error
-
end
-
-
# Remove the constants that have been autoloaded, and those that have been
-
# marked for unloading. Before each constant is removed a callback is sent
-
# to its class/module if it implements +before_remove_const+.
-
#
-
# The callback implementation should be restricted to cleaning up caches, etc.
-
# as the environment will be in an inconsistent state, e.g. other constants
-
# may have already been unloaded and not accessible.
-
1
def remove_unloadable_constants!
-
autoloaded_constants.each { |const| remove_constant const }
-
autoloaded_constants.clear
-
Reference.clear!
-
explicitly_unloadable_constants.each { |const| remove_constant const }
-
end
-
-
1
class ClassCache
-
1
def initialize
-
1
@store = ThreadSafe::Cache.new
-
end
-
-
1
def empty?
-
@store.empty?
-
end
-
-
1
def key?(key)
-
@store.key?(key)
-
end
-
-
1
def get(key)
-
68
key = key.name if key.respond_to?(:name)
-
68
@store[key] ||= Inflector.constantize(key)
-
end
-
1
alias :[] :get
-
-
1
def safe_get(key)
-
key = key.name if key.respond_to?(:name)
-
@store[key] ||= Inflector.safe_constantize(key)
-
end
-
-
1
def store(klass)
-
return self unless klass.respond_to?(:name)
-
raise(ArgumentError, 'anonymous classes cannot be cached') if klass.name.empty?
-
@store[klass.name] = klass
-
self
-
end
-
-
1
def clear!
-
@store.clear
-
end
-
end
-
-
1
Reference = ClassCache.new
-
-
# Store a reference to a class +klass+.
-
1
def reference(klass)
-
Reference.store klass
-
end
-
-
# Get the reference for class named +name+.
-
# Raises an exception if referenced class does not exist.
-
1
def constantize(name)
-
66
Reference.get(name)
-
end
-
-
# Get the reference for class named +name+ if one exists.
-
# Otherwise returns +nil+.
-
1
def safe_constantize(name)
-
Reference.safe_get(name)
-
end
-
-
# Determine if the given constant has been automatically loaded.
-
1
def autoloaded?(desc)
-
return false if desc.is_a?(Module) && desc.anonymous?
-
name = to_constant_name desc
-
return false unless qualified_const_defined? name
-
return autoloaded_constants.include?(name)
-
end
-
-
# Will the provided constant descriptor be unloaded?
-
1
def will_unload?(const_desc)
-
autoloaded?(const_desc) ||
-
explicitly_unloadable_constants.include?(to_constant_name(const_desc))
-
end
-
-
# Mark the provided constant name for unloading. This constant will be
-
# unloaded on each request, not just the next one.
-
1
def mark_for_unload(const_desc)
-
name = to_constant_name const_desc
-
if explicitly_unloadable_constants.include? name
-
false
-
else
-
explicitly_unloadable_constants << name
-
true
-
end
-
end
-
-
# Run the provided block and detect the new constants that were loaded during
-
# its execution. Constants may only be regarded as 'new' once -- so if the
-
# block calls +new_constants_in+ again, then the constants defined within the
-
# inner call will not be reported in this one.
-
#
-
# If the provided block does not run to completion, and instead raises an
-
# exception, any new constants are regarded as being only partially defined
-
# and will be removed immediately.
-
1
def new_constants_in(*descs)
-
log_call(*descs)
-
-
constant_watch_stack.watch_namespaces(descs)
-
aborting = true
-
-
begin
-
yield # Now yield to the code that is to define new constants.
-
aborting = false
-
ensure
-
new_constants = constant_watch_stack.new_constants
-
-
log "New constants: #{new_constants * ', '}"
-
return new_constants unless aborting
-
-
log "Error during loading, removing partially loaded constants "
-
new_constants.each { |c| remove_constant(c) }.clear
-
end
-
-
[]
-
end
-
-
# Convert the provided const desc to a qualified constant name (as a string).
-
# A module, class, symbol, or string may be provided.
-
1
def to_constant_name(desc) #:nodoc:
-
16
case desc
-
when String then desc.sub(/^::/, '')
-
when Symbol then desc.to_s
-
when Module
-
desc.name ||
-
16
raise(ArgumentError, "Anonymous modules have no name to be referenced by")
-
else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
-
end
-
end
-
-
1
def remove_constant(const) #:nodoc:
-
# Normalize ::Foo, ::Object::Foo, Object::Foo, Object::Object::Foo, etc. as Foo.
-
normalized = const.to_s.sub(/\A::/, '')
-
normalized.sub!(/\A(Object::)+/, '')
-
-
constants = normalized.split('::')
-
to_remove = constants.pop
-
-
# Remove the file path from the loaded list.
-
file_path = search_for_file(const.underscore)
-
if file_path
-
expanded = File.expand_path(file_path)
-
expanded.sub!(/\.rb\z/, '')
-
self.loaded.delete(expanded)
-
end
-
-
if constants.empty?
-
parent = Object
-
else
-
# This method is robust to non-reachable constants.
-
#
-
# Non-reachable constants may be passed if some of the parents were
-
# autoloaded and already removed. It is easier to do a sanity check
-
# here than require the caller to be clever. We check the parent
-
# rather than the very const argument because we do not want to
-
# trigger Kernel#autoloads, see the comment below.
-
parent_name = constants.join('::')
-
return unless qualified_const_defined?(parent_name)
-
parent = constantize(parent_name)
-
end
-
-
log "removing constant #{const}"
-
-
# In an autoloaded user.rb like this
-
#
-
# autoload :Foo, 'foo'
-
#
-
# class User < ActiveRecord::Base
-
# end
-
#
-
# we correctly register "Foo" as being autoloaded. But if the app does
-
# not use the "Foo" constant we need to be careful not to trigger
-
# loading "foo.rb" ourselves. While #const_defined? and #const_get? do
-
# require the file, #autoload? and #remove_const don't.
-
#
-
# We are going to remove the constant nonetheless ---which exists as
-
# far as Ruby is concerned--- because if the user removes the macro
-
# call from a class or module that were not autoloaded, as in the
-
# example above with Object, accessing to that constant must err.
-
unless parent.autoload?(to_remove)
-
begin
-
constantized = parent.const_get(to_remove, false)
-
rescue NameError
-
log "the constant #{const} is not reachable anymore, skipping"
-
return
-
else
-
constantized.before_remove_const if constantized.respond_to?(:before_remove_const)
-
end
-
end
-
-
begin
-
parent.instance_eval { remove_const to_remove }
-
rescue NameError
-
log "the constant #{const} is not reachable anymore, skipping"
-
end
-
end
-
-
1
protected
-
1
def log_call(*args)
-
37
if log_activity?
-
arg_str = args.collect { |arg| arg.inspect } * ', '
-
/in `([a-z_\?\!]+)'/ =~ caller(1).first
-
selector = $1 || '<unknown>'
-
log "called #{selector}(#{arg_str})"
-
end
-
end
-
-
1
def log(msg)
-
17
logger.debug "Dependencies: #{msg}" if log_activity?
-
end
-
-
1
def log_activity?
-
54
logger && log_activity
-
end
-
end
-
end
-
-
1
ActiveSupport::Dependencies.hook!
-
1
require "active_support/inflector/methods"
-
-
1
module ActiveSupport
-
# Autoload and eager load conveniences for your library.
-
#
-
# This module allows you to define autoloads based on
-
# Rails conventions (i.e. no need to define the path
-
# it is automatically guessed based on the filename)
-
# and also define a set of constants that needs to be
-
# eager loaded:
-
#
-
# module MyLib
-
# extend ActiveSupport::Autoload
-
#
-
# autoload :Model
-
#
-
# eager_autoload do
-
# autoload :Cache
-
# end
-
# end
-
#
-
# Then your library can be eager loaded by simply calling:
-
#
-
# MyLib.eager_load!
-
1
module Autoload
-
1
def self.extended(base) # :nodoc:
-
27
base.class_eval do
-
27
@_autoloads = {}
-
27
@_under_path = nil
-
27
@_at_path = nil
-
27
@_eager_autoload = false
-
end
-
end
-
-
1
def autoload(const_name, path = @_at_path)
-
389
unless path
-
297
full = [name, @_under_path, const_name.to_s].compact.join("::")
-
297
path = Inflector.underscore(full)
-
end
-
-
389
if @_eager_autoload
-
164
@_autoloads[const_name] = path
-
end
-
-
389
super const_name, path
-
end
-
-
1
def autoload_under(path)
-
7
@_under_path, old_path = path, @_under_path
-
7
yield
-
ensure
-
7
@_under_path = old_path
-
end
-
-
1
def autoload_at(path)
-
7
@_at_path, old_path = path, @_at_path
-
7
yield
-
ensure
-
7
@_at_path = old_path
-
end
-
-
1
def eager_autoload
-
18
old_eager, @_eager_autoload = @_eager_autoload, true
-
18
yield
-
ensure
-
18
@_eager_autoload = old_eager
-
end
-
-
1
def eager_load!
-
@_autoloads.each_value { |file| require file }
-
end
-
-
1
def autoloads
-
@_autoloads
-
end
-
end
-
end
-
1
require 'singleton'
-
-
1
module ActiveSupport
-
# \Deprecation specifies the API used by Rails to deprecate methods, instance
-
# variables, objects and constants.
-
1
class Deprecation
-
# active_support.rb sets an autoload for ActiveSupport::Deprecation.
-
#
-
# If these requires were at the top of the file the constant would not be
-
# defined by the time their files were loaded. Since some of them reopen
-
# ActiveSupport::Deprecation its autoload would be triggered, resulting in
-
# a circular require warning for active_support/deprecation.rb.
-
#
-
# So, we define the constant first, and load dependencies later.
-
1
require 'active_support/deprecation/instance_delegator'
-
1
require 'active_support/deprecation/behaviors'
-
1
require 'active_support/deprecation/reporting'
-
1
require 'active_support/deprecation/method_wrappers'
-
1
require 'active_support/deprecation/proxy_wrappers'
-
1
require 'active_support/core_ext/module/deprecation'
-
-
1
include Singleton
-
1
include InstanceDelegator
-
1
include Behavior
-
1
include Reporting
-
1
include MethodWrapper
-
-
# The version number in which the deprecated behavior will be removed, by default.
-
1
attr_accessor :deprecation_horizon
-
-
# It accepts two parameters on initialization. The first is a version of library
-
# and the second is a library name
-
#
-
# ActiveSupport::Deprecation.new('2.0', 'MyLibrary')
-
1
def initialize(deprecation_horizon = '5.0', gem_name = 'Rails')
-
1
self.gem_name = gem_name
-
1
self.deprecation_horizon = deprecation_horizon
-
# By default, warnings are not silenced and debugging is off.
-
1
self.silenced = false
-
1
self.debug = false
-
end
-
end
-
end
-
1
require "active_support/notifications"
-
-
1
module ActiveSupport
-
1
class DeprecationException < StandardError
-
end
-
-
1
class Deprecation
-
# Default warning behaviors per Rails.env.
-
1
DEFAULT_BEHAVIORS = {
-
raise: ->(message, callstack) {
-
e = DeprecationException.new(message)
-
e.set_backtrace(callstack)
-
raise e
-
},
-
-
stderr: ->(message, callstack) {
-
$stderr.puts(message)
-
$stderr.puts callstack.join("\n ") if debug
-
},
-
-
log: ->(message, callstack) {
-
logger =
-
if defined?(Rails.logger) && Rails.logger
-
Rails.logger
-
else
-
require 'active_support/logger'
-
ActiveSupport::Logger.new($stderr)
-
end
-
logger.warn message
-
logger.debug callstack.join("\n ") if debug
-
},
-
-
notify: ->(message, callstack) {
-
ActiveSupport::Notifications.instrument("deprecation.rails",
-
:message => message, :callstack => callstack)
-
},
-
-
silence: ->(message, callstack) {},
-
}
-
-
1
module Behavior
-
# Whether to print a backtrace along with the warning.
-
1
attr_accessor :debug
-
-
# Returns the current behavior or if one isn't set, defaults to +:stderr+.
-
1
def behavior
-
@behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
-
end
-
-
# Sets the behavior to the specified value. Can be a single value, array,
-
# or an object that responds to +call+.
-
#
-
# Available behaviors:
-
#
-
# [+raise+] Raise <tt>ActiveSupport::DeprecationException</tt>.
-
# [+stderr+] Log all deprecation warnings to +$stderr+.
-
# [+log+] Log all deprecation warnings to +Rails.logger+.
-
# [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+.
-
# [+silence+] Do nothing.
-
#
-
# Setting behaviors only affects deprecations that happen after boot time.
-
# Deprecation warnings raised by gems are not affected by this setting
-
# because they happen before Rails boots up.
-
#
-
# ActiveSupport::Deprecation.behavior = :stderr
-
# ActiveSupport::Deprecation.behavior = [:stderr, :log]
-
# ActiveSupport::Deprecation.behavior = MyCustomHandler
-
# ActiveSupport::Deprecation.behavior = ->(message, callstack) {
-
# # custom stuff
-
# }
-
1
def behavior=(behavior)
-
2
@behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/delegation'
-
-
1
module ActiveSupport
-
1
class Deprecation
-
1
module InstanceDelegator # :nodoc:
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
1
base.public_class_method :new
-
end
-
-
1
module ClassMethods # :nodoc:
-
1
def include(included_module)
-
15
included_module.instance_methods.each { |m| method_added(m) }
-
3
super
-
end
-
-
1
def method_added(method_name)
-
15
singleton_class.delegate(method_name, to: :instance)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveSupport
-
1
class Deprecation
-
1
module MethodWrapper
-
# Declare that a method has been deprecated.
-
#
-
# module Fred
-
# extend self
-
#
-
# def foo; end
-
# def bar; end
-
# def baz; end
-
# end
-
#
-
# ActiveSupport::Deprecation.deprecate_methods(Fred, :foo, bar: :qux, baz: 'use Bar#baz instead')
-
# # => [:foo, :bar, :baz]
-
#
-
# Fred.foo
-
# # => "DEPRECATION WARNING: foo is deprecated and will be removed from Rails 4.1."
-
#
-
# Fred.bar
-
# # => "DEPRECATION WARNING: bar is deprecated and will be removed from Rails 4.1 (use qux instead)."
-
#
-
# Fred.baz
-
# # => "DEPRECATION WARNING: baz is deprecated and will be removed from Rails 4.1 (use Bar#baz instead)."
-
1
def deprecate_methods(target_module, *method_names)
-
1
options = method_names.extract_options!
-
1
deprecator = options.delete(:deprecator) || ActiveSupport::Deprecation.instance
-
1
method_names += options.keys
-
-
1
method_names.each do |method_name|
-
1
target_module.alias_method_chain(method_name, :deprecation) do |target, punctuation|
-
1
target_module.send(:define_method, "#{target}_with_deprecation#{punctuation}") do |*args, &block|
-
deprecator.deprecation_warning(method_name, options[method_name])
-
send(:"#{target}_without_deprecation#{punctuation}", *args, &block)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/inflector/methods'
-
-
1
module ActiveSupport
-
1
class Deprecation
-
1
class DeprecationProxy #:nodoc:
-
1
def self.new(*args, &block)
-
1
object = args.first
-
-
1
return object unless object
-
1
super
-
end
-
-
64
instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$/ }
-
-
# Don't give a deprecation warning on inspect since test/unit and error
-
# logs rely on it for diagnostics.
-
1
def inspect
-
target.inspect
-
end
-
-
1
private
-
1
def method_missing(called, *args, &block)
-
warn caller, called, args
-
target.__send__(called, *args, &block)
-
end
-
end
-
-
# This DeprecatedObjectProxy transforms object to deprecated object.
-
#
-
# @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!")
-
# @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!", deprecator_instance)
-
#
-
# When someone executes any method except +inspect+ on proxy object this will
-
# trigger +warn+ method on +deprecator_instance+.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>
-
1
class DeprecatedObjectProxy < DeprecationProxy
-
1
def initialize(object, message, deprecator = ActiveSupport::Deprecation.instance)
-
@object = object
-
@message = message
-
@deprecator = deprecator
-
end
-
-
1
private
-
1
def target
-
@object
-
end
-
-
1
def warn(callstack, called, args)
-
@deprecator.warn(@message, callstack)
-
end
-
end
-
-
# This DeprecatedInstanceVariableProxy transforms instance variable to
-
# deprecated instance variable.
-
#
-
# class Example
-
# def initialize(deprecator)
-
# @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request, deprecator)
-
# @_request = :a_request
-
# end
-
#
-
# def request
-
# @_request
-
# end
-
#
-
# def old_request
-
# @request
-
# end
-
# end
-
#
-
# When someone execute any method on @request variable this will trigger
-
# +warn+ method on +deprecator_instance+ and will fetch <tt>@_request</tt>
-
# variable via +request+ method and execute the same method on non-proxy
-
# instance variable.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
-
1
class DeprecatedInstanceVariableProxy < DeprecationProxy
-
1
def initialize(instance, method, var = "@#{method}", deprecator = ActiveSupport::Deprecation.instance)
-
@instance = instance
-
@method = method
-
@var = var
-
@deprecator = deprecator
-
end
-
-
1
private
-
1
def target
-
@instance.__send__(@method)
-
end
-
-
1
def warn(callstack, called, args)
-
@deprecator.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack)
-
end
-
end
-
-
# This DeprecatedConstantProxy transforms constant to deprecated constant.
-
#
-
# OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST')
-
# OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST', deprecator_instance)
-
#
-
# When someone use old constant this will trigger +warn+ method on
-
# +deprecator_instance+.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
-
1
class DeprecatedConstantProxy < DeprecationProxy
-
1
def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance)
-
1
@old_const = old_const
-
1
@new_const = new_const
-
1
@deprecator = deprecator
-
end
-
-
1
def class
-
target.class
-
end
-
-
1
private
-
1
def target
-
ActiveSupport::Inflector.constantize(@new_const.to_s)
-
end
-
-
1
def warn(callstack, called, args)
-
@deprecator.warn("#{@old_const} is deprecated! Use #{@new_const} instead.", callstack)
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
class Deprecation
-
1
module Reporting
-
# Whether to print a message (silent mode)
-
1
attr_accessor :silenced
-
# Name of gem where method is deprecated
-
1
attr_accessor :gem_name
-
-
# Outputs a deprecation warning to the output configured by
-
# <tt>ActiveSupport::Deprecation.behavior</tt>.
-
#
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
-
1
def warn(message = nil, callstack = nil)
-
return if silenced
-
-
callstack ||= caller(2)
-
deprecation_message(callstack, message).tap do |m|
-
behavior.each { |b| b.call(m, callstack) }
-
end
-
end
-
-
# Silence deprecation warnings within the block.
-
#
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
-
#
-
# ActiveSupport::Deprecation.silence do
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# end
-
# # => nil
-
1
def silence
-
old_silenced, @silenced = @silenced, true
-
yield
-
ensure
-
@silenced = old_silenced
-
end
-
-
1
def deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil)
-
caller_backtrace ||= caller(2)
-
deprecated_method_warning(deprecated_method_name, message).tap do |msg|
-
warn(msg, caller_backtrace)
-
end
-
end
-
-
1
private
-
# Outputs a deprecation warning message
-
#
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name)
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon}"
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name, :another_method)
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (use another_method instead)"
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name, "Optional message")
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (Optional message)"
-
1
def deprecated_method_warning(method_name, message = nil)
-
warning = "#{method_name} is deprecated and will be removed from #{gem_name} #{deprecation_horizon}"
-
case message
-
when Symbol then "#{warning} (use #{message} instead)"
-
when String then "#{warning} (#{message})"
-
else warning
-
end
-
end
-
-
1
def deprecation_message(callstack, message = nil)
-
message ||= "You are using deprecated behavior which will be removed from the next major or minor release."
-
message += '.' unless message =~ /\.$/
-
"DEPRECATION WARNING: #{message} #{deprecation_caller_message(callstack)}"
-
end
-
-
1
def deprecation_caller_message(callstack)
-
file, line, method = extract_callstack(callstack)
-
if file
-
if line && method
-
"(called from #{method} at #{file}:#{line})"
-
else
-
"(called from #{file}:#{line})"
-
end
-
end
-
end
-
-
1
def extract_callstack(callstack)
-
rails_gem_root = File.expand_path("../../../../..", __FILE__) + "/"
-
offending_line = callstack.find { |line| !line.start_with?(rails_gem_root) } || callstack.first
-
if offending_line
-
if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
-
md.captures
-
else
-
offending_line
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
# This module provides an internal implementation to track descendants
-
# which is faster than iterating through ObjectSpace.
-
1
module DescendantsTracker
-
1
@@direct_descendants = {}
-
-
1
class << self
-
1
def direct_descendants(klass)
-
@@direct_descendants[klass] || []
-
end
-
-
1
def descendants(klass)
-
26
arr = []
-
26
accumulate_descendants(klass, arr)
-
26
arr
-
end
-
-
1
def clear
-
if defined? ActiveSupport::Dependencies
-
@@direct_descendants.each do |klass, descendants|
-
if ActiveSupport::Dependencies.autoloaded?(klass)
-
@@direct_descendants.delete(klass)
-
else
-
descendants.reject! { |v| ActiveSupport::Dependencies.autoloaded?(v) }
-
end
-
end
-
else
-
@@direct_descendants.clear
-
end
-
end
-
-
# This is the only method that is not thread safe, but is only ever called
-
# during the eager loading phase.
-
1
def store_inherited(klass, descendant)
-
19
(@@direct_descendants[klass] ||= []) << descendant
-
end
-
-
1
private
-
1
def accumulate_descendants(klass, acc)
-
26
if direct_descendants = @@direct_descendants[klass]
-
acc.concat(direct_descendants)
-
direct_descendants.each { |direct_descendant| accumulate_descendants(direct_descendant, acc) }
-
end
-
end
-
end
-
-
1
def inherited(base)
-
19
DescendantsTracker.store_inherited(self, base)
-
19
super
-
end
-
-
1
def direct_descendants
-
DescendantsTracker.direct_descendants(self)
-
end
-
-
1
def descendants
-
DescendantsTracker.descendants(self)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
module ActiveSupport
-
# Provides accurate date and time measurements using Date#advance and
-
# Time#advance, respectively. It mainly supports the methods on Numeric.
-
#
-
# 1.month.ago # equivalent to Time.now.advance(months: -1)
-
1
class Duration
-
1
attr_accessor :value, :parts
-
-
1
def initialize(value, parts) #:nodoc:
-
3
@value, @parts = value, parts
-
end
-
-
# Adds another Duration or a Numeric to this Duration. Numeric values
-
# are treated as seconds.
-
1
def +(other)
-
if Duration === other
-
Duration.new(value + other.value, @parts + other.parts)
-
else
-
Duration.new(value + other, @parts + [[:seconds, other]])
-
end
-
end
-
-
# Subtracts another Duration or a Numeric from this Duration. Numeric
-
# values are treated as seconds.
-
1
def -(other)
-
self + (-other)
-
end
-
-
1
def -@ #:nodoc:
-
Duration.new(-value, parts.map { |type,number| [type, -number] })
-
end
-
-
1
def is_a?(klass) #:nodoc:
-
Duration == klass || value.is_a?(klass)
-
end
-
1
alias :kind_of? :is_a?
-
-
1
def instance_of?(klass) # :nodoc:
-
Duration == klass || value.instance_of?(klass)
-
end
-
-
# Returns +true+ if +other+ is also a Duration instance with the
-
# same +value+, or if <tt>other == value</tt>.
-
1
def ==(other)
-
if Duration === other
-
other.value == value
-
else
-
other == value
-
end
-
end
-
-
1
def to_s
-
@value.to_s
-
end
-
-
# Returns the number of seconds that this Duration represents.
-
#
-
# 1.minute.to_i # => 60
-
# 1.hour.to_i # => 3600
-
# 1.day.to_i # => 86400
-
#
-
# Note that this conversion makes some assumptions about the
-
# duration of some periods, e.g. months are always 30 days
-
# and years are 365.25 days:
-
#
-
# # equivalent to 30.days.to_i
-
# 1.month.to_i # => 2592000
-
#
-
# # equivalent to 365.25.days.to_i
-
# 1.year.to_i # => 31557600
-
#
-
# In such cases, Ruby's core
-
# Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
-
# Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
-
# date and time arithmetic.
-
1
def to_i
-
@value.to_i
-
end
-
-
# Returns +true+ if +other+ is also a Duration instance, which has the
-
# same parts as this one.
-
1
def eql?(other)
-
Duration === other && other.value.eql?(value)
-
end
-
-
1
def hash
-
@value.hash
-
end
-
-
1
def self.===(other) #:nodoc:
-
565
other.is_a?(Duration)
-
rescue ::NoMethodError
-
false
-
end
-
-
# Calculates a new Time or Date that is as far in the future
-
# as this Duration represents.
-
1
def since(time = ::Time.current)
-
sum(1, time)
-
end
-
1
alias :from_now :since
-
-
# Calculates a new Time or Date that is as far in the past
-
# as this Duration represents.
-
1
def ago(time = ::Time.current)
-
sum(-1, time)
-
end
-
1
alias :until :ago
-
-
1
def inspect #:nodoc:
-
parts.
-
reduce(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }.
-
sort_by {|unit, _ | [:years, :months, :days, :minutes, :seconds].index(unit)}.
-
map {|unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}"}.
-
to_sentence(locale: ::I18n.default_locale)
-
end
-
-
1
def as_json(options = nil) #:nodoc:
-
to_i
-
end
-
-
1
def respond_to_missing?(method, include_private=false) #:nodoc
-
2
@value.respond_to?(method, include_private)
-
end
-
-
1
delegate :<=>, to: :value
-
-
1
protected
-
-
1
def sum(sign, time = ::Time.current) #:nodoc:
-
parts.inject(time) do |t,(type,number)|
-
if t.acts_like?(:time) || t.acts_like?(:date)
-
if type == :seconds
-
t.since(sign * number)
-
else
-
t.advance(type => sign * number)
-
end
-
else
-
raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
-
end
-
end
-
end
-
-
1
private
-
-
# We define it as a workaround to Ruby 2.0.0-p353 bug.
-
# For more information, check rails/rails#13055.
-
# Remove it when we drop support for 2.0.0-p353.
-
1
def ===(other) #:nodoc:
-
value === other
-
end
-
-
1
def method_missing(method, *args, &block) #:nodoc:
-
2
value.send(method, *args, &block)
-
end
-
end
-
end
-
1
module ActiveSupport
-
# FileUpdateChecker specifies the API used by Rails to watch files
-
# and control reloading. The API depends on four methods:
-
#
-
# * +initialize+ which expects two parameters and one block as
-
# described below.
-
#
-
# * +updated?+ which returns a boolean if there were updates in
-
# the filesystem or not.
-
#
-
# * +execute+ which executes the given block on initialization
-
# and updates the latest watched files and timestamp.
-
#
-
# * +execute_if_updated+ which just executes the block if it was updated.
-
#
-
# After initialization, a call to +execute_if_updated+ must execute
-
# the block only if there was really a change in the filesystem.
-
#
-
# This class is used by Rails to reload the I18n framework whenever
-
# they are changed upon a new request.
-
#
-
# i18n_reloader = ActiveSupport::FileUpdateChecker.new(paths) do
-
# I18n.reload!
-
# end
-
#
-
# ActionDispatch::Reloader.to_prepare do
-
# i18n_reloader.execute_if_updated
-
# end
-
1
class FileUpdateChecker
-
# It accepts two parameters on initialization. The first is an array
-
# of files and the second is an optional hash of directories. The hash must
-
# have directories as keys and the value is an array of extensions to be
-
# watched under that directory.
-
#
-
# This method must also receive a block that will be called once a path
-
# changes. The array of files and list of directories cannot be changed
-
# after FileUpdateChecker has been initialized.
-
1
def initialize(files, dirs={}, &block)
-
3
@files = files.freeze
-
3
@glob = compile_glob(dirs)
-
3
@block = block
-
-
3
@watched = nil
-
3
@updated_at = nil
-
-
3
@last_watched = watched
-
3
@last_update_at = updated_at(@last_watched)
-
end
-
-
# Check if any of the entries were updated. If so, the watched and/or
-
# updated_at values are cached until the block is executed via +execute+
-
# or +execute_if_updated+.
-
1
def updated?
-
1
current_watched = watched
-
1
if @last_watched.size != current_watched.size
-
@watched = current_watched
-
true
-
else
-
1
current_updated_at = updated_at(current_watched)
-
1
if @last_update_at < current_updated_at
-
@watched = current_watched
-
@updated_at = current_updated_at
-
true
-
else
-
1
false
-
end
-
end
-
end
-
-
# Executes the given block and updates the latest watched files and
-
# timestamp.
-
1
def execute
-
2
@last_watched = watched
-
2
@last_update_at = updated_at(@last_watched)
-
2
@block.call
-
ensure
-
2
@watched = nil
-
2
@updated_at = nil
-
end
-
-
# Execute the block given if updated.
-
1
def execute_if_updated
-
1
if updated?
-
execute
-
true
-
else
-
1
false
-
end
-
end
-
-
1
private
-
-
1
def watched
-
@watched || begin
-
137
all = @files.select { |f| File.exist?(f) }
-
6
all.concat(Dir[@glob]) if @glob
-
6
all
-
6
end
-
end
-
-
1
def updated_at(paths)
-
6
@updated_at || max_mtime(paths) || Time.at(0)
-
end
-
-
# This method returns the maximum mtime of the files in +paths+, or +nil+
-
# if the array is empty.
-
#
-
# Files with a mtime in the future are ignored. Such abnormal situation
-
# can happen for example if the user changes the clock by hand. It is
-
# healthy to consider this edge case because with mtimes in the future
-
# reloading is not triggered.
-
1
def max_mtime(paths)
-
6
time_now = Time.now
-
300
paths.map {|path| File.mtime(path)}.reject {|mtime| time_now < mtime}.max
-
end
-
-
1
def compile_glob(hash)
-
3
hash.freeze # Freeze so changes aren't accidentally pushed
-
3
return if hash.empty?
-
-
1
globs = hash.map do |key, value|
-
7
"#{escape(key)}/**/*#{compile_ext(value)}"
-
end
-
1
"{#{globs.join(",")}}"
-
end
-
-
1
def escape(key)
-
7
key.gsub(',','\,')
-
end
-
-
1
def compile_ext(array)
-
7
array = Array(array)
-
7
return if array.empty?
-
7
".{#{array.join(",")}}"
-
end
-
end
-
end
-
1
module ActiveSupport
-
# Returns the version of the currently loaded Active Support as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 2
-
1
TINY = 5
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
-
1
module ActiveSupport
-
# Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are considered
-
# to be the same.
-
#
-
# rgb = ActiveSupport::HashWithIndifferentAccess.new
-
#
-
# rgb[:black] = '#000000'
-
# rgb[:black] # => '#000000'
-
# rgb['black'] # => '#000000'
-
#
-
# rgb['white'] = '#FFFFFF'
-
# rgb[:white] # => '#FFFFFF'
-
# rgb['white'] # => '#FFFFFF'
-
#
-
# Internally symbols are mapped to strings when used as keys in the entire
-
# writing interface (calling <tt>[]=</tt>, <tt>merge</tt>, etc). This
-
# mapping belongs to the public interface. For example, given:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
-
#
-
# You are guaranteed that the key is returned as a string:
-
#
-
# hash.keys # => ["a"]
-
#
-
# Technically other types of keys are accepted:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
-
# hash[0] = 0
-
# hash # => {"a"=>1, 0=>0}
-
#
-
# but this class is intended for use cases where strings or symbols are the
-
# expected keys and it is convenient to understand both as the same. For
-
# example the +params+ hash in Ruby on Rails.
-
#
-
# Note that core extensions define <tt>Hash#with_indifferent_access</tt>:
-
#
-
# rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access
-
#
-
# which may be handy.
-
1
class HashWithIndifferentAccess < Hash
-
# Returns +true+ so that <tt>Array#extract_options!</tt> finds members of
-
# this class.
-
1
def extractable_options?
-
true
-
end
-
-
1
def with_indifferent_access
-
dup
-
end
-
-
1
def nested_under_indifferent_access
-
16
self
-
end
-
-
1
def initialize(constructor = {})
-
507
if constructor.respond_to?(:to_hash)
-
499
super()
-
499
update(constructor)
-
else
-
8
super(constructor)
-
end
-
end
-
-
1
def default(key = nil)
-
538
if key.is_a?(Symbol) && include?(key = key.to_s)
-
78
self[key]
-
else
-
460
super
-
end
-
end
-
-
1
def self.new_from_hash_copying_default(hash)
-
202
hash = hash.to_hash
-
202
new(hash).tap do |new_hash|
-
202
new_hash.default = hash.default
-
202
new_hash.default_proc = hash.default_proc if hash.default_proc
-
end
-
end
-
-
1
def self.[](*args)
-
29
new.merge!(Hash[*args])
-
end
-
-
1
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
-
1
alias_method :regular_update, :update unless method_defined?(:regular_update)
-
-
# Assigns a new value to the hash:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash[:key] = 'value'
-
#
-
# This value can be later fetched using either +:key+ or +'key'+.
-
1
def []=(key, value)
-
202
regular_writer(convert_key(key), convert_value(value, for: :assignment))
-
end
-
-
1
alias_method :store, :[]=
-
-
# Updates the receiver in-place, merging in the hash passed as argument:
-
#
-
# hash_1 = ActiveSupport::HashWithIndifferentAccess.new
-
# hash_1[:key] = 'value'
-
#
-
# hash_2 = ActiveSupport::HashWithIndifferentAccess.new
-
# hash_2[:key] = 'New Value!'
-
#
-
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
-
#
-
# The argument can be either an
-
# <tt>ActiveSupport::HashWithIndifferentAccess</tt> or a regular +Hash+.
-
# In either case the merge respects the semantics of indifferent access.
-
#
-
# If the argument is a regular hash with keys +:key+ and +"key"+ only one
-
# of the values end up in the receiver, but which one is unspecified.
-
#
-
# When given a block, the value for duplicated keys will be determined
-
# by the result of invoking the block with the duplicated key, the value
-
# in the receiver, and the value in +other_hash+. The rules for duplicated
-
# keys follow the semantics of indifferent access:
-
#
-
# hash_1[:key] = 10
-
# hash_2['key'] = 12
-
# hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22}
-
1
def update(other_hash)
-
722
if other_hash.is_a? HashWithIndifferentAccess
-
338
super(other_hash)
-
else
-
384
other_hash.to_hash.each_pair do |key, value|
-
379
if block_given? && key?(key)
-
value = yield(convert_key(key), self[key], value)
-
end
-
379
regular_writer(convert_key(key), convert_value(value))
-
end
-
384
self
-
end
-
end
-
-
1
alias_method :merge!, :update
-
-
# Checks the hash for a key matching the argument passed in:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash['key'] = 'value'
-
# hash.key?(:key) # => true
-
# hash.key?('key') # => true
-
1
def key?(key)
-
944
super(convert_key(key))
-
end
-
-
1
alias_method :include?, :key?
-
1
alias_method :has_key?, :key?
-
1
alias_method :member?, :key?
-
-
# Same as <tt>Hash#fetch</tt> where the key passed as argument can be
-
# either a string or a symbol:
-
#
-
# counters = ActiveSupport::HashWithIndifferentAccess.new
-
# counters[:foo] = 1
-
#
-
# counters.fetch('foo') # => 1
-
# counters.fetch(:bar, 0) # => 0
-
# counters.fetch(:bar) { |key| 0 } # => 0
-
# counters.fetch(:zoo) # => KeyError: key not found: "zoo"
-
1
def fetch(key, *extras)
-
super(convert_key(key), *extras)
-
end
-
-
# Returns an array of the values at the specified indices:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash[:a] = 'x'
-
# hash[:b] = 'y'
-
# hash.values_at('a', 'b') # => ["x", "y"]
-
1
def values_at(*indices)
-
indices.collect { |key| self[convert_key(key)] }
-
end
-
-
# Returns a shallow copy of the hash.
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new({ a: { b: 'b' } })
-
# dup = hash.dup
-
# dup[:a][:c] = 'c'
-
#
-
# hash[:a][:c] # => nil
-
# dup[:a][:c] # => "c"
-
1
def dup
-
136
self.class.new(self).tap do |new_hash|
-
136
set_defaults(new_hash)
-
end
-
end
-
-
# This method has the same semantics of +update+, except it does not
-
# modify the receiver but rather returns a new hash with indifferent
-
# access with the result of the merge.
-
1
def merge(hash, &block)
-
128
self.dup.update(hash, &block)
-
end
-
-
# Like +merge+ but the other way around: Merges the receiver into the
-
# argument and returns a new hash with indifferent access as result:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash['a'] = nil
-
# hash.reverse_merge(a: 0, b: 1) # => {"a"=>nil, "b"=>1}
-
1
def reverse_merge(other_hash)
-
62
super(self.class.new_from_hash_copying_default(other_hash))
-
end
-
-
# Same semantics as +reverse_merge+ but modifies the receiver in-place.
-
1
def reverse_merge!(other_hash)
-
replace(reverse_merge( other_hash ))
-
end
-
-
# Replaces the contents of this hash with other_hash.
-
#
-
# h = { "a" => 100, "b" => 200 }
-
# h.replace({ "c" => 300, "d" => 400 }) # => {"c"=>300, "d"=>400}
-
1
def replace(other_hash)
-
super(self.class.new_from_hash_copying_default(other_hash))
-
end
-
-
# Removes the specified key from the hash.
-
1
def delete(key)
-
super(convert_key(key))
-
end
-
-
1
def stringify_keys!; self end
-
1
def deep_stringify_keys!; self end
-
9
def stringify_keys; dup end
-
1
def deep_stringify_keys; dup end
-
1
undef :symbolize_keys!
-
1
undef :deep_symbolize_keys!
-
1
def symbolize_keys; to_hash.symbolize_keys! end
-
1
def deep_symbolize_keys; to_hash.deep_symbolize_keys! end
-
1
def to_options!; self end
-
-
1
def select(*args, &block)
-
dup.tap { |hash| hash.select!(*args, &block) }
-
end
-
-
1
def reject(*args, &block)
-
dup.tap { |hash| hash.reject!(*args, &block) }
-
end
-
-
# Convert to a regular hash with string keys.
-
1
def to_hash
-
_new_hash = Hash.new
-
set_defaults(_new_hash)
-
-
each do |key, value|
-
_new_hash[key] = convert_value(value, for: :to_hash)
-
end
-
_new_hash
-
end
-
-
1
protected
-
1
def convert_key(key)
-
1525
key.kind_of?(Symbol) ? key.to_s : key
-
end
-
-
1
def convert_value(value, options = {})
-
909
if value.is_a? Hash
-
16
if options[:for] == :to_hash
-
value.to_hash
-
else
-
16
value.nested_under_indifferent_access
-
end
-
893
elsif value.is_a?(Array)
-
164
if options[:for] != :assignment || value.frozen?
-
164
value = value.dup
-
end
-
492
value.map! { |e| convert_value(e, options) }
-
else
-
729
value
-
end
-
end
-
-
1
def set_defaults(target)
-
136
if default_proc
-
target.default_proc = default_proc.dup
-
else
-
136
target.default = default
-
end
-
end
-
end
-
end
-
-
1
HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
-
1
require 'active_support/core_ext/hash/deep_merge'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
1
begin
-
1
require 'i18n'
-
rescue LoadError => e
-
$stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install"
-
raise e
-
end
-
1
require 'active_support/lazy_load_hooks'
-
-
1
ActiveSupport.run_load_hooks(:i18n)
-
1
I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
-
1
require "active_support"
-
1
require "active_support/file_update_checker"
-
1
require "active_support/core_ext/array/wrap"
-
-
1
module I18n
-
1
class Railtie < Rails::Railtie
-
1
config.i18n = ActiveSupport::OrderedOptions.new
-
1
config.i18n.railties_load_path = []
-
1
config.i18n.load_path = []
-
1
config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
-
-
# Set the i18n configuration after initialization since a lot of
-
# configuration is still usually done in application initializers.
-
1
config.after_initialize do |app|
-
1
I18n::Railtie.initialize_i18n(app)
-
end
-
-
# Trigger i18n config before any eager loading has happened
-
# so it's ready if any classes require it when eager loaded.
-
1
config.before_eager_load do |app|
-
I18n::Railtie.initialize_i18n(app)
-
end
-
-
1
protected
-
-
1
@i18n_inited = false
-
-
# Setup i18n configuration.
-
1
def self.initialize_i18n(app)
-
1
return if @i18n_inited
-
-
1
fallbacks = app.config.i18n.delete(:fallbacks)
-
-
# Avoid issues with setting the default_locale by disabling available locales
-
# check while configuring.
-
1
enforce_available_locales = app.config.i18n.delete(:enforce_available_locales)
-
1
enforce_available_locales = I18n.enforce_available_locales if enforce_available_locales.nil?
-
1
I18n.enforce_available_locales = false
-
-
1
app.config.i18n.each do |setting, value|
-
2
case setting
-
when :railties_load_path
-
1
app.config.i18n.load_path.unshift(*value)
-
when :load_path
-
1
I18n.load_path += value
-
else
-
I18n.send("#{setting}=", value)
-
end
-
end
-
-
1
init_fallbacks(fallbacks) if fallbacks && validate_fallbacks(fallbacks)
-
-
# Restore available locales check so it will take place from now on.
-
1
I18n.enforce_available_locales = enforce_available_locales
-
-
2
reloader = ActiveSupport::FileUpdateChecker.new(I18n.load_path.dup){ I18n.reload! }
-
1
app.reloaders << reloader
-
1
ActionDispatch::Reloader.to_prepare { reloader.execute_if_updated }
-
1
reloader.execute
-
-
1
@i18n_inited = true
-
end
-
-
1
def self.include_fallbacks_module
-
I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
-
end
-
-
1
def self.init_fallbacks(fallbacks)
-
include_fallbacks_module
-
-
args = case fallbacks
-
when ActiveSupport::OrderedOptions
-
[*(fallbacks[:defaults] || []) << fallbacks[:map]].compact
-
when Hash, Array
-
Array.wrap(fallbacks)
-
else # TrueClass
-
[]
-
end
-
-
I18n.fallbacks = I18n::Locale::Fallbacks.new(*args)
-
end
-
-
1
def self.validate_fallbacks(fallbacks)
-
1
case fallbacks
-
when ActiveSupport::OrderedOptions
-
1
!fallbacks.empty?
-
when TrueClass, Array, Hash
-
true
-
else
-
raise "Unexpected fallback type #{fallbacks.inspect}"
-
end
-
end
-
end
-
end
-
1
require 'active_support/inflector/inflections'
-
-
#--
-
# Defines the standard inflection rules. These are the starting point for
-
# new projects and are not considered complete. The current set of inflection
-
# rules is frozen. This means, we do not change them to become more complete.
-
# This is a safety measure to keep existing applications from breaking.
-
#++
-
1
module ActiveSupport
-
1
Inflector.inflections(:en) do |inflect|
-
1
inflect.plural(/$/, 's')
-
1
inflect.plural(/s$/i, 's')
-
1
inflect.plural(/^(ax|test)is$/i, '\1es')
-
1
inflect.plural(/(octop|vir)us$/i, '\1i')
-
1
inflect.plural(/(octop|vir)i$/i, '\1i')
-
1
inflect.plural(/(alias|status)$/i, '\1es')
-
1
inflect.plural(/(bu)s$/i, '\1ses')
-
1
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
-
1
inflect.plural(/([ti])um$/i, '\1a')
-
1
inflect.plural(/([ti])a$/i, '\1a')
-
1
inflect.plural(/sis$/i, 'ses')
-
1
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
-
1
inflect.plural(/(hive)$/i, '\1s')
-
1
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
-
1
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
-
1
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
-
1
inflect.plural(/^(m|l)ouse$/i, '\1ice')
-
1
inflect.plural(/^(m|l)ice$/i, '\1ice')
-
1
inflect.plural(/^(ox)$/i, '\1en')
-
1
inflect.plural(/^(oxen)$/i, '\1')
-
1
inflect.plural(/(quiz)$/i, '\1zes')
-
-
1
inflect.singular(/s$/i, '')
-
1
inflect.singular(/(ss)$/i, '\1')
-
1
inflect.singular(/(n)ews$/i, '\1ews')
-
1
inflect.singular(/([ti])a$/i, '\1um')
-
1
inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis')
-
1
inflect.singular(/(^analy)(sis|ses)$/i, '\1sis')
-
1
inflect.singular(/([^f])ves$/i, '\1fe')
-
1
inflect.singular(/(hive)s$/i, '\1')
-
1
inflect.singular(/(tive)s$/i, '\1')
-
1
inflect.singular(/([lr])ves$/i, '\1f')
-
1
inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
-
1
inflect.singular(/(s)eries$/i, '\1eries')
-
1
inflect.singular(/(m)ovies$/i, '\1ovie')
-
1
inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
-
1
inflect.singular(/^(m|l)ice$/i, '\1ouse')
-
1
inflect.singular(/(bus)(es)?$/i, '\1')
-
1
inflect.singular(/(o)es$/i, '\1')
-
1
inflect.singular(/(shoe)s$/i, '\1')
-
1
inflect.singular(/(cris|test)(is|es)$/i, '\1is')
-
1
inflect.singular(/^(a)x[ie]s$/i, '\1xis')
-
1
inflect.singular(/(octop|vir)(us|i)$/i, '\1us')
-
1
inflect.singular(/(alias|status)(es)?$/i, '\1')
-
1
inflect.singular(/^(ox)en/i, '\1')
-
1
inflect.singular(/(vert|ind)ices$/i, '\1ex')
-
1
inflect.singular(/(matr)ices$/i, '\1ix')
-
1
inflect.singular(/(quiz)zes$/i, '\1')
-
1
inflect.singular(/(database)s$/i, '\1')
-
-
1
inflect.irregular('person', 'people')
-
1
inflect.irregular('man', 'men')
-
1
inflect.irregular('child', 'children')
-
1
inflect.irregular('sex', 'sexes')
-
1
inflect.irregular('move', 'moves')
-
1
inflect.irregular('zombie', 'zombies')
-
-
1
inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police))
-
end
-
end
-
# in case active_support/inflector is required without the rest of active_support
-
1
require 'active_support/inflector/inflections'
-
1
require 'active_support/inflector/transliterate'
-
1
require 'active_support/inflector/methods'
-
-
1
require 'active_support/inflections'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'thread_safe'
-
1
require 'active_support/core_ext/array/prepend_and_append'
-
1
require 'active_support/i18n'
-
-
1
module ActiveSupport
-
1
module Inflector
-
1
extend self
-
-
# A singleton instance of this class is yielded by Inflector.inflections,
-
# which can then be used to specify additional inflection rules. If passed
-
# an optional locale, rules for other languages can be specified. The
-
# default locale is <tt>:en</tt>. Only rules for English are provided.
-
#
-
# ActiveSupport::Inflector.inflections(:en) do |inflect|
-
# inflect.plural /^(ox)$/i, '\1\2en'
-
# inflect.singular /^(ox)en/i, '\1'
-
#
-
# inflect.irregular 'octopus', 'octopi'
-
#
-
# inflect.uncountable 'equipment'
-
# end
-
#
-
# New rules are added at the top. So in the example above, the irregular
-
# rule for octopus will now be the first of the pluralization and
-
# singularization rules that is runs. This guarantees that your rules run
-
# before any of the rules that may already have been loaded.
-
1
class Inflections
-
1
@__instance__ = ThreadSafe::Cache.new
-
-
1
def self.instance(locale = :en)
-
595
@__instance__[locale] ||= new
-
end
-
-
1
attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex
-
-
1
def initialize
-
1
@plurals, @singulars, @uncountables, @humans, @acronyms, @acronym_regex = [], [], [], [], {}, /(?=a)b/
-
end
-
-
# Private, for the test suite.
-
1
def initialize_dup(orig) # :nodoc:
-
%w(plurals singulars uncountables humans acronyms acronym_regex).each do |scope|
-
instance_variable_set("@#{scope}", orig.send(scope).dup)
-
end
-
end
-
-
# Specifies a new acronym. An acronym must be specified as it will appear
-
# in a camelized string. An underscore string that contains the acronym
-
# will retain the acronym when passed to +camelize+, +humanize+, or
-
# +titleize+. A camelized string that contains the acronym will maintain
-
# the acronym when titleized or humanized, and will convert the acronym
-
# into a non-delimited single lowercase word when passed to +underscore+.
-
#
-
# acronym 'HTML'
-
# titleize 'html' # => 'HTML'
-
# camelize 'html' # => 'HTML'
-
# underscore 'MyHTML' # => 'my_html'
-
#
-
# The acronym, however, must occur as a delimited unit and not be part of
-
# another word for conversions to recognize it:
-
#
-
# acronym 'HTTP'
-
# camelize 'my_http_delimited' # => 'MyHTTPDelimited'
-
# camelize 'https' # => 'Https', not 'HTTPs'
-
# underscore 'HTTPS' # => 'http_s', not 'https'
-
#
-
# acronym 'HTTPS'
-
# camelize 'https' # => 'HTTPS'
-
# underscore 'HTTPS' # => 'https'
-
#
-
# Note: Acronyms that are passed to +pluralize+ will no longer be
-
# recognized, since the acronym will not occur as a delimited unit in the
-
# pluralized result. To work around this, you must specify the pluralized
-
# form as an acronym as well:
-
#
-
# acronym 'API'
-
# camelize(pluralize('api')) # => 'Apis'
-
#
-
# acronym 'APIs'
-
# camelize(pluralize('api')) # => 'APIs'
-
#
-
# +acronym+ may be used to specify any word that contains an acronym or
-
# otherwise needs to maintain a non-standard capitalization. The only
-
# restriction is that the word must begin with a capital letter.
-
#
-
# acronym 'RESTful'
-
# underscore 'RESTful' # => 'restful'
-
# underscore 'RESTfulController' # => 'restful_controller'
-
# titleize 'RESTfulController' # => 'RESTful Controller'
-
# camelize 'restful' # => 'RESTful'
-
# camelize 'restful_controller' # => 'RESTfulController'
-
#
-
# acronym 'McDonald'
-
# underscore 'McDonald' # => 'mcdonald'
-
# camelize 'mcdonald' # => 'McDonald'
-
1
def acronym(word)
-
@acronyms[word.downcase] = word
-
@acronym_regex = /#{@acronyms.values.join("|")}/
-
end
-
-
# Specifies a new pluralization rule and its replacement. The rule can
-
# either be a string or a regular expression. The replacement should
-
# always be a string that may include references to the matched data from
-
# the rule.
-
1
def plural(rule, replacement)
-
33
@uncountables.delete(rule) if rule.is_a?(String)
-
33
@uncountables.delete(replacement)
-
33
@plurals.prepend([rule, replacement])
-
end
-
-
# Specifies a new singularization rule and its replacement. The rule can
-
# either be a string or a regular expression. The replacement should
-
# always be a string that may include references to the matched data from
-
# the rule.
-
1
def singular(rule, replacement)
-
39
@uncountables.delete(rule) if rule.is_a?(String)
-
39
@uncountables.delete(replacement)
-
39
@singulars.prepend([rule, replacement])
-
end
-
-
# Specifies a new irregular that applies to both pluralization and
-
# singularization at the same time. This can only be used for strings, not
-
# regular expressions. You simply pass the irregular in singular and
-
# plural form.
-
#
-
# irregular 'octopus', 'octopi'
-
# irregular 'person', 'people'
-
1
def irregular(singular, plural)
-
6
@uncountables.delete(singular)
-
6
@uncountables.delete(plural)
-
-
6
s0 = singular[0]
-
6
srest = singular[1..-1]
-
-
6
p0 = plural[0]
-
6
prest = plural[1..-1]
-
-
6
if s0.upcase == p0.upcase
-
6
plural(/(#{s0})#{srest}$/i, '\1' + prest)
-
6
plural(/(#{p0})#{prest}$/i, '\1' + prest)
-
-
6
singular(/(#{s0})#{srest}$/i, '\1' + srest)
-
6
singular(/(#{p0})#{prest}$/i, '\1' + srest)
-
else
-
plural(/#{s0.upcase}(?i)#{srest}$/, p0.upcase + prest)
-
plural(/#{s0.downcase}(?i)#{srest}$/, p0.downcase + prest)
-
plural(/#{p0.upcase}(?i)#{prest}$/, p0.upcase + prest)
-
plural(/#{p0.downcase}(?i)#{prest}$/, p0.downcase + prest)
-
-
singular(/#{s0.upcase}(?i)#{srest}$/, s0.upcase + srest)
-
singular(/#{s0.downcase}(?i)#{srest}$/, s0.downcase + srest)
-
singular(/#{p0.upcase}(?i)#{prest}$/, s0.upcase + srest)
-
singular(/#{p0.downcase}(?i)#{prest}$/, s0.downcase + srest)
-
end
-
end
-
-
# Specifies words that are uncountable and should not be inflected.
-
#
-
# uncountable 'money'
-
# uncountable 'money', 'information'
-
# uncountable %w( money information rice )
-
1
def uncountable(*words)
-
1
@uncountables += words.flatten.map(&:downcase)
-
end
-
-
# Specifies a humanized form of a string by a regular expression rule or
-
# by a string mapping. When using a regular expression based replacement,
-
# the normal humanize formatting is called after the replacement. When a
-
# string is used, the human form should be specified as desired (example:
-
# 'The name', not 'the_name').
-
#
-
# human /_cnt$/i, '\1_count'
-
# human 'legacy_col_person_name', 'Name'
-
1
def human(rule, replacement)
-
@humans.prepend([rule, replacement])
-
end
-
-
# Clears the loaded inflections within a given scope (default is
-
# <tt>:all</tt>). Give the scope as a symbol of the inflection type, the
-
# options are: <tt>:plurals</tt>, <tt>:singulars</tt>, <tt>:uncountables</tt>,
-
# <tt>:humans</tt>.
-
#
-
# clear :all
-
# clear :plurals
-
1
def clear(scope = :all)
-
case scope
-
when :all
-
@plurals, @singulars, @uncountables, @humans = [], [], [], []
-
else
-
instance_variable_set "@#{scope}", []
-
end
-
end
-
end
-
-
# Yields a singleton instance of Inflector::Inflections so you can specify
-
# additional inflector rules. If passed an optional locale, rules for other
-
# languages can be specified. If not specified, defaults to <tt>:en</tt>.
-
# Only rules for English are provided.
-
#
-
# ActiveSupport::Inflector.inflections(:en) do |inflect|
-
# inflect.uncountable 'rails'
-
# end
-
1
def inflections(locale = :en)
-
595
if block_given?
-
1
yield Inflections.instance(locale)
-
else
-
594
Inflections.instance(locale)
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'active_support/inflections'
-
-
1
module ActiveSupport
-
# The Inflector transforms words from singular to plural, class names to table
-
# names, modularized class names to ones without, and class names to foreign
-
# keys. The default inflections for pluralization, singularization, and
-
# uncountable words are kept in inflections.rb.
-
#
-
# The Rails core team has stated patches for the inflections library will not
-
# be accepted in order to avoid breaking legacy applications which may be
-
# relying on errant inflections. If you discover an incorrect inflection and
-
# require it for your application or wish to define rules for languages other
-
# than English, please correct or add them yourself (explained below).
-
1
module Inflector
-
1
extend self
-
-
# Returns the plural form of the word in the string.
-
#
-
# If passed an optional +locale+ parameter, the word will be
-
# pluralized using rules defined for that language. By default,
-
# this parameter is set to <tt>:en</tt>.
-
#
-
# 'post'.pluralize # => "posts"
-
# 'octopus'.pluralize # => "octopi"
-
# 'sheep'.pluralize # => "sheep"
-
# 'words'.pluralize # => "words"
-
# 'CamelOctopus'.pluralize # => "CamelOctopi"
-
# 'ley'.pluralize(:es) # => "leyes"
-
1
def pluralize(word, locale = :en)
-
16
apply_inflections(word, inflections(locale).plurals)
-
end
-
-
# The reverse of +pluralize+, returns the singular form of a word in a
-
# string.
-
#
-
# If passed an optional +locale+ parameter, the word will be
-
# singularized using rules defined for that language. By default,
-
# this parameter is set to <tt>:en</tt>.
-
#
-
# 'posts'.singularize # => "post"
-
# 'octopi'.singularize # => "octopus"
-
# 'sheep'.singularize # => "sheep"
-
# 'word'.singularize # => "word"
-
# 'CamelOctopi'.singularize # => "CamelOctopus"
-
# 'leyes'.singularize(:es) # => "ley"
-
1
def singularize(word, locale = :en)
-
11
apply_inflections(word, inflections(locale).singulars)
-
end
-
-
# By default, +camelize+ converts strings to UpperCamelCase. If the argument
-
# to +camelize+ is set to <tt>:lower</tt> then +camelize+ produces
-
# lowerCamelCase.
-
#
-
# +camelize+ will also convert '/' to '::' which is useful for converting
-
# paths to namespaces.
-
#
-
# 'active_model'.camelize # => "ActiveModel"
-
# 'active_model'.camelize(:lower) # => "activeModel"
-
# 'active_model/errors'.camelize # => "ActiveModel::Errors"
-
# 'active_model/errors'.camelize(:lower) # => "activeModel::Errors"
-
#
-
# As a rule of thumb you can think of +camelize+ as the inverse of
-
# +underscore+, though there are cases where that does not hold:
-
#
-
# 'SSLError'.underscore.camelize # => "SslError"
-
1
def camelize(term, uppercase_first_letter = true)
-
57
string = term.to_s
-
57
if uppercase_first_letter
-
114
string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize }
-
else
-
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
-
end
-
95
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
-
57
string.gsub!(/\//, '::')
-
57
string
-
end
-
-
# Makes an underscored, lowercase form from the expression in the string.
-
#
-
# Changes '::' to '/' to convert namespaces to paths.
-
#
-
# 'ActiveModel'.underscore # => "active_model"
-
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
-
#
-
# As a rule of thumb you can think of +underscore+ as the inverse of
-
# +camelize+, though there are cases where that does not hold:
-
#
-
# 'SSLError'.underscore.camelize # => "SslError"
-
1
def underscore(camel_cased_word)
-
457
return camel_cased_word unless camel_cased_word =~ /[A-Z-]|::/
-
378
word = camel_cased_word.to_s.gsub(/::/, '/')
-
378
word.gsub!(/(?:(?<=([A-Za-z\d]))|\b)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1 && '_'}#{$2.downcase}" }
-
378
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
-
378
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
-
378
word.tr!("-", "_")
-
378
word.downcase!
-
378
word
-
end
-
-
# Tweaks an attribute name for display to end users.
-
#
-
# Specifically, +humanize+ performs these transformations:
-
#
-
# * Applies human inflection rules to the argument.
-
# * Deletes leading underscores, if any.
-
# * Removes a "_id" suffix if present.
-
# * Replaces underscores with spaces, if any.
-
# * Downcases all words except acronyms.
-
# * Capitalizes the first word.
-
#
-
# The capitalization of the first word can be turned off by setting the
-
# +:capitalize+ option to false (default is true).
-
#
-
# humanize('employee_salary') # => "Employee salary"
-
# humanize('author_id') # => "Author"
-
# humanize('author_id', capitalize: false) # => "author"
-
# humanize('_id') # => "Id"
-
#
-
# If "SSL" was defined to be an acronym:
-
#
-
# humanize('ssl_error') # => "SSL error"
-
#
-
1
def humanize(lower_case_and_underscored_word, options = {})
-
18
result = lower_case_and_underscored_word.to_s.dup
-
-
18
inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
-
-
18
result.sub!(/\A_+/, '')
-
18
result.sub!(/_id\z/, '')
-
18
result.tr!('_', ' ')
-
-
18
result.gsub!(/([a-z\d]*)/i) do |match|
-
49
"#{inflections.acronyms[match] || match.downcase}"
-
end
-
-
18
if options.fetch(:capitalize, true)
-
36
result.sub!(/\A\w/) { |match| match.upcase }
-
end
-
-
18
result
-
end
-
-
# Capitalizes all the words and replaces some characters in the string to
-
# create a nicer looking title. +titleize+ is meant for creating pretty
-
# output. It is not used in the Rails internals.
-
#
-
# +titleize+ is also aliased as +titlecase+.
-
#
-
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
-
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
-
# 'TheManWithoutAPast'.titleize # => "The Man Without A Past"
-
# 'raiders_of_the_lost_ark'.titleize # => "Raiders Of The Lost Ark"
-
1
def titleize(word)
-
humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize }
-
end
-
-
# Create the name of a table like Rails does for models to table names. This
-
# method uses the +pluralize+ method on the last word in the string.
-
#
-
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
-
# 'egg_and_ham'.tableize # => "egg_and_hams"
-
# 'fancyCategory'.tableize # => "fancy_categories"
-
1
def tableize(class_name)
-
4
pluralize(underscore(class_name))
-
end
-
-
# Create a class name from a plural table name like Rails does for table
-
# names to models. Note that this returns a string and not a Class (To
-
# convert to an actual class follow +classify+ with +constantize+).
-
#
-
# 'egg_and_hams'.classify # => "EggAndHam"
-
# 'posts'.classify # => "Post"
-
#
-
# Singular names are not handled correctly:
-
#
-
# 'calculus'.classify # => "Calculu"
-
1
def classify(table_name)
-
# strip out any leading schema name
-
1
camelize(singularize(table_name.to_s.sub(/.*\./, '')))
-
end
-
-
# Replaces underscores with dashes in the string.
-
#
-
# 'puni_puni'.dasherize # => "puni-puni"
-
1
def dasherize(underscored_word)
-
50
underscored_word.tr('_', '-')
-
end
-
-
# Removes the module part from the expression in the string.
-
#
-
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
-
# 'Inflections'.demodulize # => "Inflections"
-
# '::Inflections'.demodulize # => "Inflections"
-
# ''.demodulize # => ""
-
#
-
# See also +deconstantize+.
-
1
def demodulize(path)
-
8
path = path.to_s
-
8
if i = path.rindex('::')
-
path[(i+2)..-1]
-
else
-
8
path
-
end
-
end
-
-
# Removes the rightmost segment from the constant expression in the string.
-
#
-
# 'Net::HTTP'.deconstantize # => "Net"
-
# '::Net::HTTP'.deconstantize # => "::Net"
-
# 'String'.deconstantize # => ""
-
# '::String'.deconstantize # => ""
-
# ''.deconstantize # => ""
-
#
-
# See also +demodulize+.
-
1
def deconstantize(path)
-
path.to_s[0, path.rindex('::') || 0] # implementation based on the one in facets' Module#spacename
-
end
-
-
# Creates a foreign key name from a class name.
-
# +separate_class_name_and_id_with_underscore+ sets whether
-
# the method should put '_' between the name and 'id'.
-
#
-
# 'Message'.foreign_key # => "message_id"
-
# 'Message'.foreign_key(false) # => "messageid"
-
# 'Admin::Post'.foreign_key # => "post_id"
-
1
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
-
underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
-
end
-
-
# Tries to find a constant with the name specified in the argument string.
-
#
-
# 'Module'.constantize # => Module
-
# 'Test::Unit'.constantize # => Test::Unit
-
#
-
# The name is assumed to be the one of a top-level constant, no matter
-
# whether it starts with "::" or not. No lexical context is taken into
-
# account:
-
#
-
# C = 'outside'
-
# module M
-
# C = 'inside'
-
# C # => 'inside'
-
# 'C'.constantize # => 'outside', same as ::C
-
# end
-
#
-
# NameError is raised when the name is not in CamelCase or the constant is
-
# unknown.
-
1
def constantize(camel_cased_word)
-
36
names = camel_cased_word.split('::')
-
-
# Trigger a built-in NameError exception including the ill-formed constant in the message.
-
36
Object.const_get(camel_cased_word) if names.empty?
-
-
# Remove the first blank element in case of '::ClassName' notation.
-
36
names.shift if names.size > 1 && names.first.empty?
-
-
36
names.inject(Object) do |constant, name|
-
40
if constant == Object
-
36
constant.const_get(name)
-
else
-
4
candidate = constant.const_get(name)
-
4
next candidate if constant.const_defined?(name, false)
-
next candidate unless Object.const_defined?(name)
-
-
# Go down the ancestors to check if it is owned directly. The check
-
# stops when we reach Object or the end of ancestors tree.
-
constant = constant.ancestors.inject do |const, ancestor|
-
break const if ancestor == Object
-
break ancestor if ancestor.const_defined?(name, false)
-
const
-
end
-
-
# owner is in Object, so raise
-
constant.const_get(name, false)
-
end
-
end
-
end
-
-
# Tries to find a constant with the name specified in the argument string.
-
#
-
# 'Module'.safe_constantize # => Module
-
# 'Test::Unit'.safe_constantize # => Test::Unit
-
#
-
# The name is assumed to be the one of a top-level constant, no matter
-
# whether it starts with "::" or not. No lexical context is taken into
-
# account:
-
#
-
# C = 'outside'
-
# module M
-
# C = 'inside'
-
# C # => 'inside'
-
# 'C'.safe_constantize # => 'outside', same as ::C
-
# end
-
#
-
# +nil+ is returned when the name is not in CamelCase or the constant (or
-
# part of it) is unknown.
-
#
-
# 'blargle'.safe_constantize # => nil
-
# 'UnknownModule'.safe_constantize # => nil
-
# 'UnknownModule::Foo::Bar'.safe_constantize # => nil
-
1
def safe_constantize(camel_cased_word)
-
constantize(camel_cased_word)
-
rescue NameError => e
-
raise if e.name && !(camel_cased_word.to_s.split("::").include?(e.name.to_s) ||
-
e.name.to_s == camel_cased_word.to_s)
-
rescue ArgumentError => e
-
raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
-
end
-
-
# Returns the suffix that should be added to a number to denote the position
-
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# ordinal(1) # => "st"
-
# ordinal(2) # => "nd"
-
# ordinal(1002) # => "nd"
-
# ordinal(1003) # => "rd"
-
# ordinal(-11) # => "th"
-
# ordinal(-1021) # => "st"
-
1
def ordinal(number)
-
abs_number = number.to_i.abs
-
-
if (11..13).include?(abs_number % 100)
-
"th"
-
else
-
case abs_number % 10
-
when 1; "st"
-
when 2; "nd"
-
when 3; "rd"
-
else "th"
-
end
-
end
-
end
-
-
# Turns a number into an ordinal string used to denote the position in an
-
# ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# ordinalize(1) # => "1st"
-
# ordinalize(2) # => "2nd"
-
# ordinalize(1002) # => "1002nd"
-
# ordinalize(1003) # => "1003rd"
-
# ordinalize(-11) # => "-11th"
-
# ordinalize(-1021) # => "-1021st"
-
1
def ordinalize(number)
-
"#{number}#{ordinal(number)}"
-
end
-
-
1
private
-
-
# Mounts a regular expression, returned as a string to ease interpolation,
-
# that will match part by part the given constant.
-
#
-
# const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?"
-
# const_regexp("::") # => "::"
-
1
def const_regexp(camel_cased_word) #:nodoc:
-
parts = camel_cased_word.split("::")
-
-
return Regexp.escape(camel_cased_word) if parts.blank?
-
-
last = parts.pop
-
-
parts.reverse.inject(last) do |acc, part|
-
part.empty? ? acc : "#{part}(::#{acc})?"
-
end
-
end
-
-
# Applies inflection rules for +singularize+ and +pluralize+.
-
#
-
# apply_inflections('post', inflections.plurals) # => "posts"
-
# apply_inflections('posts', inflections.singulars) # => "post"
-
1
def apply_inflections(word, rules)
-
27
result = word.to_s.dup
-
-
27
if word.empty? || inflections.uncountables.include?(result.downcase[/\b\w+\Z/])
-
result
-
else
-
897
rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
-
27
result
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
1
require 'active_support/core_ext/string/multibyte'
-
1
require 'active_support/i18n'
-
-
1
module ActiveSupport
-
1
module Inflector
-
-
# Replaces non-ASCII characters with an ASCII approximation, or if none
-
# exists, a replacement character which defaults to "?".
-
#
-
# transliterate('Ærøskøbing')
-
# # => "AEroskobing"
-
#
-
# Default approximations are provided for Western/Latin characters,
-
# e.g, "ø", "ñ", "é", "ß", etc.
-
#
-
# This method is I18n aware, so you can set up custom approximations for a
-
# locale. This can be useful, for example, to transliterate German's "ü"
-
# and "ö" to "ue" and "oe", or to add support for transliterating Russian
-
# to ASCII.
-
#
-
# In order to make your custom transliterations available, you must set
-
# them as the <tt>i18n.transliterate.rule</tt> i18n key:
-
#
-
# # Store the transliterations in locales/de.yml
-
# i18n:
-
# transliterate:
-
# rule:
-
# ü: "ue"
-
# ö: "oe"
-
#
-
# # Or set them using Ruby
-
# I18n.backend.store_translations(:de, i18n: {
-
# transliterate: {
-
# rule: {
-
# 'ü' => 'ue',
-
# 'ö' => 'oe'
-
# }
-
# }
-
# })
-
#
-
# The value for <tt>i18n.transliterate.rule</tt> can be a simple Hash that
-
# maps characters to ASCII approximations as shown above, or, for more
-
# complex requirements, a Proc:
-
#
-
# I18n.backend.store_translations(:de, i18n: {
-
# transliterate: {
-
# rule: ->(string) { MyTransliterator.transliterate(string) }
-
# }
-
# })
-
#
-
# Now you can have different transliterations for each locale:
-
#
-
# I18n.locale = :en
-
# transliterate('Jürgen')
-
# # => "Jurgen"
-
#
-
# I18n.locale = :de
-
# transliterate('Jürgen')
-
# # => "Juergen"
-
1
def transliterate(string, replacement = "?")
-
I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize(
-
ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c),
-
:replacement => replacement)
-
end
-
-
# Replaces special characters in a string so that it may be used as part of
-
# a 'pretty' URL.
-
#
-
# class Person
-
# def to_param
-
# "#{id}-#{name.parameterize}"
-
# end
-
# end
-
#
-
# @person = Person.find(1)
-
# # => #<Person id: 1, name: "Donald E. Knuth">
-
#
-
# <%= link_to(@person.name, person_path(@person)) %>
-
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
-
1
def parameterize(string, sep = '-')
-
# replace accented chars with their ascii equivalents
-
parameterized_string = transliterate(string)
-
# Turn unwanted chars into the separator
-
parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
-
unless sep.nil? || sep.empty?
-
re_sep = Regexp.escape(sep)
-
# No more than one of the separator in a row.
-
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
-
# Remove leading/trailing separator.
-
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
-
end
-
parameterized_string.downcase
-
end
-
-
end
-
end
-
1
require 'active_support/json/decoding'
-
1
require 'active_support/json/encoding'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'json'
-
-
1
module ActiveSupport
-
# Look for and parse json strings that look like ISO 8601 times.
-
1
mattr_accessor :parse_json_times
-
-
1
module JSON
-
# matches YAML-formatted dates
-
1
DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
-
-
1
class << self
-
# Parses a JSON string (JavaScript Object Notation) into a hash.
-
# See http://www.json.org for more info.
-
#
-
# ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}")
-
# => {"team" => "rails", "players" => "36"}
-
1
def decode(json, options = {})
-
6
if options.present?
-
raise ArgumentError, "In Rails 4.1, ActiveSupport::JSON.decode no longer " \
-
"accepts an options hash for MultiJSON. MultiJSON reached its end of life " \
-
"and has been removed."
-
end
-
-
6
data = ::JSON.parse(json, quirks_mode: true)
-
-
6
if ActiveSupport.parse_json_times
-
convert_dates_from(data)
-
else
-
6
data
-
end
-
end
-
-
# Returns the class of the error that will be raised when there is an
-
# error in decoding JSON. Using this method means you won't directly
-
# depend on the ActiveSupport's JSON implementation, in case it changes
-
# in the future.
-
#
-
# begin
-
# obj = ActiveSupport::JSON.decode(some_string)
-
# rescue ActiveSupport::JSON.parse_error
-
# Rails.logger.warn("Attempted to decode invalid JSON: #{some_string}")
-
# end
-
1
def parse_error
-
::JSON::ParserError
-
end
-
-
1
private
-
-
1
def convert_dates_from(data)
-
case data
-
when nil
-
nil
-
when DATE_REGEX
-
begin
-
DateTime.parse(data)
-
rescue ArgumentError
-
data
-
end
-
when Array
-
data.map! { |d| convert_dates_from(d) }
-
when Hash
-
data.each do |key, value|
-
data[key] = convert_dates_from(value)
-
end
-
else
-
data
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/json'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/deprecation'
-
-
1
module ActiveSupport
-
1
class << self
-
1
delegate :use_standard_json_time_format, :use_standard_json_time_format=,
-
:time_precision, :time_precision=,
-
:escape_html_entities_in_json, :escape_html_entities_in_json=,
-
:encode_big_decimal_as_string, :encode_big_decimal_as_string=,
-
:json_encoder, :json_encoder=,
-
:to => :'ActiveSupport::JSON::Encoding'
-
end
-
-
1
module JSON
-
# Dumps objects in JSON (JavaScript Object Notation).
-
# See http://www.json.org for more info.
-
#
-
# ActiveSupport::JSON.encode({ team: 'rails', players: '36' })
-
# # => "{\"team\":\"rails\",\"players\":\"36\"}"
-
1
def self.encode(value, options = nil)
-
11
Encoding.json_encoder.new(options).encode(value)
-
end
-
-
1
module Encoding #:nodoc:
-
1
class JSONGemEncoder #:nodoc:
-
1
attr_reader :options
-
-
1
def initialize(options = nil)
-
11
@options = options || {}
-
end
-
-
# Encode the given object into a JSON string
-
1
def encode(value)
-
11
stringify jsonify value.as_json(options.dup)
-
end
-
-
1
private
-
# Rails does more escaping than the JSON gem natively does (we
-
# escape \u2028 and \u2029 and optionally >, <, & to work around
-
# certain browser problems).
-
1
ESCAPED_CHARS = {
-
"\u2028" => '\u2028',
-
"\u2029" => '\u2029',
-
'>' => '\u003e',
-
'<' => '\u003c',
-
'&' => '\u0026',
-
}
-
-
1
ESCAPE_REGEX_WITH_HTML_ENTITIES = /[\u2028\u2029><&]/u
-
1
ESCAPE_REGEX_WITHOUT_HTML_ENTITIES = /[\u2028\u2029]/u
-
-
# This class wraps all the strings we see and does the extra escaping
-
1
class EscapedString < String #:nodoc:
-
1
def to_json(*)
-
77
if Encoding.escape_html_entities_in_json
-
77
super.gsub ESCAPE_REGEX_WITH_HTML_ENTITIES, ESCAPED_CHARS
-
else
-
super.gsub ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, ESCAPED_CHARS
-
end
-
end
-
-
1
def to_s
-
51
self
-
end
-
end
-
-
# Mark these as private so we don't leak encoding-specific constructs
-
1
private_constant :ESCAPED_CHARS, :ESCAPE_REGEX_WITH_HTML_ENTITIES,
-
:ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, :EscapedString
-
-
# Convert an object into a "JSON-ready" representation composed of
-
# primitives like Hash, Array, String, Numeric, and true/false/nil.
-
# Recursively calls #as_json to the object to recursively build a
-
# fully JSON-ready object.
-
#
-
# This allows developers to implement #as_json without having to
-
# worry about what base types of objects they are allowed to return
-
# or having to remember to call #as_json recursively.
-
#
-
# Note: the +options+ hash passed to +object.to_json+ is only passed
-
# to +object.as_json+, not any of this method's recursive +#as_json+
-
# calls.
-
1
def jsonify(value)
-
118
case value
-
when String
-
77
EscapedString.new(value)
-
when Numeric, NilClass, TrueClass, FalseClass
-
value
-
when Hash
-
82
Hash[value.map { |k, v| [jsonify(k), jsonify(v)] }]
-
when Array
-
15
value.map { |v| jsonify(v) }
-
else
-
jsonify value.as_json
-
end
-
end
-
-
# Encode a "jsonified" Ruby data structure using the JSON gem
-
1
def stringify(jsonified)
-
11
::JSON.generate(jsonified, quirks_mode: true, max_nesting: false)
-
end
-
end
-
-
1
class << self
-
# If true, use ISO 8601 format for dates and times. Otherwise, fall back
-
# to the Active Support legacy format.
-
1
attr_accessor :use_standard_json_time_format
-
-
# If true, encode >, <, & as escaped unicode sequences (e.g. > as \u003e)
-
# as a safety measure.
-
1
attr_accessor :escape_html_entities_in_json
-
-
# Sets the precision of encoded time values.
-
# Defaults to 3 (equivalent to millisecond precision)
-
1
attr_accessor :time_precision
-
-
# Sets the encoder used by Rails to encode Ruby objects into JSON strings
-
# in +Object#to_json+ and +ActiveSupport::JSON.encode+.
-
1
attr_accessor :json_encoder
-
-
1
def encode_big_decimal_as_string=(as_string)
-
message = \
-
"The JSON encoder in Rails 4.1 no longer supports encoding BigDecimals as JSON numbers. Instead, " \
-
"the new encoder will always encode them as strings.\n\n" \
-
"You are seeing this error because you have 'active_support.encode_big_decimal_as_string' in " \
-
"your configuration file. If you have been setting this to true, you can safely remove it from " \
-
"your configuration. Otherwise, you should add the 'activesupport-json_encoder' gem to your " \
-
"Gemfile in order to restore this functionality."
-
-
raise NotImplementedError, message
-
end
-
-
1
def encode_big_decimal_as_string
-
message = \
-
"The JSON encoder in Rails 4.1 no longer supports encoding BigDecimals as JSON numbers. Instead, " \
-
"the new encoder will always encode them as strings.\n\n" \
-
"You are seeing this error because you are trying to check the value of the related configuration, " \
-
"`active_support.encode_big_decimal_as_string`. If your application depends on this option, you should " \
-
"add the 'activesupport-json_encoder' gem to your Gemfile. For now, this option will always be true. " \
-
"In the future, it will be removed from Rails, so you should stop checking its value."
-
-
ActiveSupport::Deprecation.warn message
-
-
true
-
end
-
-
# Deprecate CircularReferenceError
-
1
def const_missing(name)
-
if name == :CircularReferenceError
-
message = "The JSON encoder in Rails 4.1 no longer offers protection from circular references. " \
-
"You are seeing this warning because you are rescuing from (or otherwise referencing) " \
-
"ActiveSupport::Encoding::CircularReferenceError. In the future, this error will be " \
-
"removed from Rails. You should remove these rescue blocks from your code and ensure " \
-
"that your data structures are free of circular references so they can be properly " \
-
"serialized into JSON.\n\n" \
-
"For example, the following Hash contains a circular reference to itself:\n" \
-
" h = {}\n" \
-
" h['circular'] = h\n" \
-
"In this case, calling h.to_json would not work properly."
-
-
ActiveSupport::Deprecation.warn message
-
-
SystemStackError
-
else
-
super
-
end
-
end
-
end
-
-
1
self.use_standard_json_time_format = true
-
1
self.escape_html_entities_in_json = true
-
1
self.json_encoder = JSONGemEncoder
-
1
self.time_precision = 3
-
end
-
end
-
end
-
1
require 'thread_safe'
-
1
require 'openssl'
-
-
1
module ActiveSupport
-
# KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2
-
# It can be used to derive a number of keys for various purposes from a given secret.
-
# This lets Rails applications have a single secure secret, but avoid reusing that
-
# key in multiple incompatible contexts.
-
1
class KeyGenerator
-
1
def initialize(secret, options = {})
-
1
@secret = secret
-
# The default iterations are higher than required for our key derivation uses
-
# on the off chance someone uses this for password storage
-
1
@iterations = options[:iterations] || 2**16
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
1
def generate_key(salt, key_size=64)
-
3
OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size)
-
end
-
end
-
-
# CachingKeyGenerator is a wrapper around KeyGenerator which allows users to avoid
-
# re-executing the key generation process when it's called using the same salt and
-
# key_size
-
1
class CachingKeyGenerator
-
1
def initialize(key_generator)
-
1
@key_generator = key_generator
-
1
@cache_keys = ThreadSafe::Cache.new
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
1
def generate_key(salt, key_size=64)
-
133
@cache_keys["#{salt}#{key_size}"] ||= @key_generator.generate_key(salt, key_size)
-
end
-
end
-
-
1
class LegacyKeyGenerator # :nodoc:
-
1
SECRET_MIN_LENGTH = 30 # Characters
-
-
1
def initialize(secret)
-
ensure_secret_secure(secret)
-
@secret = secret
-
end
-
-
1
def generate_key(salt)
-
@secret
-
end
-
-
1
private
-
-
# To prevent users from using something insecure like "Password" we make sure that the
-
# secret they've provided is at least 30 characters in length.
-
1
def ensure_secret_secure(secret)
-
if secret.blank?
-
raise ArgumentError, "A secret is required to generate an integrity hash " \
-
"for cookie session data. Set a secret_key_base of at least " \
-
"#{SECRET_MIN_LENGTH} characters in config/secrets.yml."
-
end
-
-
if secret.length < SECRET_MIN_LENGTH
-
raise ArgumentError, "Secret should be something secure, " \
-
"like \"#{SecureRandom.hex(16)}\". The value you " \
-
"provided, \"#{secret}\", is shorter than the minimum length " \
-
"of #{SECRET_MIN_LENGTH} characters."
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
# lazy_load_hooks allows Rails to lazily load a lot of components and thus
-
# making the app boot faster. Because of this feature now there is no need to
-
# require <tt>ActiveRecord::Base</tt> at boot time purely to apply
-
# configuration. Instead a hook is registered that applies configuration once
-
# <tt>ActiveRecord::Base</tt> is loaded. Here <tt>ActiveRecord::Base</tt> is
-
# used as example but this feature can be applied elsewhere too.
-
#
-
# Here is an example where +on_load+ method is called to register a hook.
-
#
-
# initializer 'active_record.initialize_timezone' do
-
# ActiveSupport.on_load(:active_record) do
-
# self.time_zone_aware_attributes = true
-
# self.default_timezone = :utc
-
# end
-
# end
-
#
-
# When the entirety of +activerecord/lib/active_record/base.rb+ has been
-
# evaluated then +run_load_hooks+ is invoked. The very last line of
-
# +activerecord/lib/active_record/base.rb+ is:
-
#
-
# ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
-
11
@load_hooks = Hash.new { |h,k| h[k] = [] }
-
11
@loaded = Hash.new { |h,k| h[k] = [] }
-
-
1
def self.on_load(name, options = {}, &block)
-
45
@loaded[name].each do |base|
-
6
execute_hook(base, options, block)
-
end
-
-
45
@load_hooks[name] << [block, options]
-
end
-
-
1
def self.execute_hook(base, options, block)
-
43
if options[:yield]
-
8
block.call(base)
-
else
-
35
base.instance_eval(&block)
-
end
-
end
-
-
1
def self.run_load_hooks(name, base = Object)
-
8
@loaded[name] << base
-
8
@load_hooks[name].each do |hook, options|
-
37
execute_hook(base, options, hook)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/subscriber'
-
-
1
module ActiveSupport
-
# ActiveSupport::LogSubscriber is an object set to consume
-
# ActiveSupport::Notifications with the sole purpose of logging them.
-
# The log subscriber dispatches notifications to a registered object based
-
# on its given namespace.
-
#
-
# An example would be Active Record log subscriber responsible for logging
-
# queries:
-
#
-
# module ActiveRecord
-
# class LogSubscriber < ActiveSupport::LogSubscriber
-
# def sql(event)
-
# "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}"
-
# end
-
# end
-
# end
-
#
-
# And it's finally registered as:
-
#
-
# ActiveRecord::LogSubscriber.attach_to :active_record
-
#
-
# Since we need to know all instance methods before attaching the log
-
# subscriber, the line above should be called after your
-
# <tt>ActiveRecord::LogSubscriber</tt> definition.
-
#
-
# After configured, whenever a "sql.active_record" notification is published,
-
# it will properly dispatch the event (ActiveSupport::Notifications::Event) to
-
# the sql method.
-
#
-
# Log subscriber also has some helpers to deal with logging and automatically
-
# flushes all logs when the request finishes (via action_dispatch.callback
-
# notification) in a Rails environment.
-
1
class LogSubscriber < Subscriber
-
# Embed in a String to clear all previous ANSI sequences.
-
1
CLEAR = "\e[0m"
-
1
BOLD = "\e[1m"
-
-
# Colors
-
1
BLACK = "\e[30m"
-
1
RED = "\e[31m"
-
1
GREEN = "\e[32m"
-
1
YELLOW = "\e[33m"
-
1
BLUE = "\e[34m"
-
1
MAGENTA = "\e[35m"
-
1
CYAN = "\e[36m"
-
1
WHITE = "\e[37m"
-
-
1
mattr_accessor :colorize_logging
-
1
self.colorize_logging = true
-
-
1
class << self
-
1
def logger
-
@logger ||= if defined?(Rails) && Rails.respond_to?(:logger)
-
1
Rails.logger
-
132
end
-
end
-
-
1
attr_writer :logger
-
-
1
def log_subscribers
-
subscribers
-
end
-
-
# Flush all log_subscribers' logger.
-
1
def flush_all!
-
66
logger.flush if logger.respond_to?(:flush)
-
end
-
end
-
-
1
def logger
-
LogSubscriber.logger
-
end
-
-
1
def start(name, id, payload)
-
431
super if logger
-
end
-
-
1
def finish(name, id, payload)
-
431
super if logger
-
rescue Exception => e
-
logger.error "Could not log #{name.inspect} event. #{e.class}: #{e.message} #{e.backtrace}"
-
end
-
-
1
protected
-
-
1
%w(info debug warn error fatal unknown).each do |level|
-
6
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{level}(progname = nil, &block)
-
logger.#{level}(progname, &block) if logger
-
end
-
METHOD
-
end
-
-
# Set color by using a string or one of the defined constants. If a third
-
# option is set to +true+, it also adds bold to the string. This is based
-
# on the Highline implementation and will automatically append CLEAR to the
-
# end of the returned String.
-
1
def color(text, color, bold=false)
-
321
return text unless colorize_logging
-
321
color = self.class.const_get(color.upcase) if color.is_a?(Symbol)
-
321
bold = bold ? BOLD : ""
-
321
"#{bold}#{color}#{text}#{CLEAR}"
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/logger_silence'
-
1
require 'logger'
-
-
1
module ActiveSupport
-
1
class Logger < ::Logger
-
1
include LoggerSilence
-
-
# Broadcasts logs to multiple loggers.
-
1
def self.broadcast(logger) # :nodoc:
-
Module.new do
-
define_method(:add) do |*args, &block|
-
logger.add(*args, &block)
-
super(*args, &block)
-
end
-
-
define_method(:<<) do |x|
-
logger << x
-
super(x)
-
end
-
-
define_method(:close) do
-
logger.close
-
super()
-
end
-
-
define_method(:progname=) do |name|
-
logger.progname = name
-
super(name)
-
end
-
-
define_method(:formatter=) do |formatter|
-
logger.formatter = formatter
-
super(formatter)
-
end
-
-
define_method(:level=) do |level|
-
logger.level = level
-
super(level)
-
end
-
end
-
end
-
-
1
def initialize(*args)
-
1
super
-
1
@formatter = SimpleFormatter.new
-
end
-
-
# Simple formatter which only displays the message.
-
1
class SimpleFormatter < ::Logger::Formatter
-
# This method is invoked when a log event occurs
-
1
def call(severity, timestamp, progname, msg)
-
512
"#{String === msg ? msg : msg.inspect}\n"
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
-
1
module LoggerSilence
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
cattr_accessor :silencer
-
1
self.silencer = true
-
end
-
-
# Silences the logger for the duration of the block.
-
1
def silence(temporary_level = Logger::ERROR)
-
if silencer
-
begin
-
old_logger_level, self.level = level, temporary_level
-
yield self
-
ensure
-
self.level = old_logger_level
-
end
-
else
-
yield self
-
end
-
end
-
end
-
1
require 'base64'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/security_utils'
-
-
1
module ActiveSupport
-
# +MessageVerifier+ makes it easy to generate and verify messages which are
-
# signed to prevent tampering.
-
#
-
# This is useful for cases like remember-me tokens and auto-unsubscribe links
-
# where the session store isn't suitable or available.
-
#
-
# Remember Me:
-
# cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
-
#
-
# In the authentication filter:
-
#
-
# id, time = @verifier.verify(cookies[:remember_me])
-
# if time < Time.now
-
# self.current_user = User.find(id)
-
# end
-
#
-
# By default it uses Marshal to serialize the message. If you want to use
-
# another serialization method, you can set the serializer in the options
-
# hash upon initialization:
-
#
-
# @verifier = ActiveSupport::MessageVerifier.new('s3Krit', serializer: YAML)
-
1
class MessageVerifier
-
1
class InvalidSignature < StandardError; end
-
-
1
def initialize(secret, options = {})
-
67
raise ArgumentError, 'Secret should not be nil.' unless secret
-
67
@secret = secret
-
67
@digest = options[:digest] || 'SHA1'
-
67
@serializer = options[:serializer] || Marshal
-
end
-
-
1
def verify(signed_message)
-
6
raise InvalidSignature if signed_message.nil? || !signed_message.valid_encoding? || signed_message.blank?
-
-
6
data, digest = signed_message.split("--")
-
6
if data.present? && digest.present? && ActiveSupport::SecurityUtils.secure_compare(digest, generate_digest(data))
-
6
begin
-
6
@serializer.load(decode(data))
-
rescue ArgumentError => argument_error
-
raise InvalidSignature if argument_error.message =~ %r{invalid base64}
-
raise
-
end
-
else
-
raise InvalidSignature
-
end
-
end
-
-
1
def generate(value)
-
11
data = encode(@serializer.dump(value))
-
11
"#{data}--#{generate_digest(data)}"
-
end
-
-
1
private
-
1
def encode(data)
-
11
::Base64.strict_encode64(data)
-
end
-
-
1
def decode(data)
-
6
::Base64.strict_decode64(data)
-
end
-
-
1
def generate_digest(data)
-
17
require 'openssl' unless defined?(OpenSSL)
-
17
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data)
-
end
-
end
-
end
-
1
module ActiveSupport #:nodoc:
-
1
module Multibyte
-
1
autoload :Chars, 'active_support/multibyte/chars'
-
1
autoload :Unicode, 'active_support/multibyte/unicode'
-
-
# The proxy class returned when calling mb_chars. You can use this accessor
-
# to configure your own proxy class so you can support other encodings. See
-
# the ActiveSupport::Multibyte::Chars implementation for an example how to
-
# do this.
-
#
-
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
-
1
def self.proxy_class=(klass)
-
@proxy_class = klass
-
end
-
-
# Returns the current proxy class.
-
1
def self.proxy_class
-
@proxy_class ||= ActiveSupport::Multibyte::Chars
-
end
-
end
-
end
-
# encoding: utf-8
-
1
require 'active_support/json'
-
1
require 'active_support/core_ext/string/access'
-
1
require 'active_support/core_ext/string/behavior'
-
1
require 'active_support/core_ext/module/delegation'
-
-
1
module ActiveSupport #:nodoc:
-
1
module Multibyte #:nodoc:
-
# Chars enables you to work transparently with UTF-8 encoding in the Ruby
-
# String class without having extensive knowledge about the encoding. A
-
# Chars object accepts a string upon initialization and proxies String
-
# methods in an encoding safe manner. All the normal String methods are also
-
# implemented on the proxy.
-
#
-
# String methods are proxied through the Chars object, and can be accessed
-
# through the +mb_chars+ method. Methods which would normally return a
-
# String object now return a Chars object so methods can be chained.
-
#
-
# 'The Perfect String '.mb_chars.downcase.strip.normalize # => "the perfect string"
-
#
-
# Chars objects are perfectly interchangeable with String objects as long as
-
# no explicit class checks are made. If certain methods do explicitly check
-
# the class, call +to_s+ before you pass chars objects to them.
-
#
-
# bad.explicit_checking_method 'T'.mb_chars.downcase.to_s
-
#
-
# The default Chars implementation assumes that the encoding of the string
-
# is UTF-8, if you want to handle different encodings you can write your own
-
# multibyte string handler and configure it through
-
# ActiveSupport::Multibyte.proxy_class.
-
#
-
# class CharsForUTF32
-
# def size
-
# @wrapped_string.size / 4
-
# end
-
#
-
# def self.accepts?(string)
-
# string.length % 4 == 0
-
# end
-
# end
-
#
-
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
-
1
class Chars
-
1
include Comparable
-
1
attr_reader :wrapped_string
-
1
alias to_s wrapped_string
-
1
alias to_str wrapped_string
-
-
1
delegate :<=>, :=~, :acts_like_string?, :to => :wrapped_string
-
-
# Creates a new Chars instance by wrapping _string_.
-
1
def initialize(string)
-
@wrapped_string = string
-
@wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen?
-
end
-
-
# Forward all undefined methods to the wrapped string.
-
1
def method_missing(method, *args, &block)
-
result = @wrapped_string.__send__(method, *args, &block)
-
if method.to_s =~ /!$/
-
self if result
-
else
-
result.kind_of?(String) ? chars(result) : result
-
end
-
end
-
-
# Returns +true+ if _obj_ responds to the given method. Private methods
-
# are included in the search only if the optional second parameter
-
# evaluates to +true+.
-
1
def respond_to_missing?(method, include_private)
-
@wrapped_string.respond_to?(method, include_private)
-
end
-
-
# Returns +true+ when the proxy class can handle the string. Returns
-
# +false+ otherwise.
-
1
def self.consumes?(string)
-
string.encoding == Encoding::UTF_8
-
end
-
-
# Works just like <tt>String#split</tt>, with the exception that the items
-
# in the resulting list are Chars instances instead of String. This makes
-
# chaining methods easier.
-
#
-
# 'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s } # => ["CAF", " P", "RIFERÔL"]
-
1
def split(*args)
-
@wrapped_string.split(*args).map { |i| self.class.new(i) }
-
end
-
-
# Works like <tt>String#slice!</tt>, but returns an instance of
-
# Chars, or nil if the string was not modified.
-
1
def slice!(*args)
-
chars(@wrapped_string.slice!(*args))
-
end
-
-
# Reverses all characters in the string.
-
#
-
# 'Café'.mb_chars.reverse.to_s # => 'éfaC'
-
1
def reverse
-
chars(Unicode.unpack_graphemes(@wrapped_string).reverse.flatten.pack('U*'))
-
end
-
-
# Limits the byte size of the string to a number of bytes without breaking
-
# characters. Usable when the storage for a string is limited for some
-
# reason.
-
#
-
# 'こんにちは'.mb_chars.limit(7).to_s # => "こん"
-
1
def limit(limit)
-
slice(0...translate_offset(limit))
-
end
-
-
# Converts characters in the string to uppercase.
-
#
-
# 'Laurent, où sont les tests ?'.mb_chars.upcase.to_s # => "LAURENT, OÙ SONT LES TESTS ?"
-
1
def upcase
-
chars Unicode.upcase(@wrapped_string)
-
end
-
-
# Converts characters in the string to lowercase.
-
#
-
# 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s # => "věda a výzkum"
-
1
def downcase
-
chars Unicode.downcase(@wrapped_string)
-
end
-
-
# Converts characters in the string to the opposite case.
-
#
-
# 'El Cañón".mb_chars.swapcase.to_s # => "eL cAÑÓN"
-
1
def swapcase
-
chars Unicode.swapcase(@wrapped_string)
-
end
-
-
# Converts the first character to uppercase and the remainder to lowercase.
-
#
-
# 'über'.mb_chars.capitalize.to_s # => "Über"
-
1
def capitalize
-
(slice(0) || chars('')).upcase + (slice(1..-1) || chars('')).downcase
-
end
-
-
# Capitalizes the first letter of every word, when possible.
-
#
-
# "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró"
-
# "日本語".mb_chars.titleize # => "日本語"
-
1
def titleize
-
chars(downcase.to_s.gsub(/\b('?\S)/u) { Unicode.upcase($1)})
-
end
-
1
alias_method :titlecase, :titleize
-
-
# Returns the KC normalization of the string by default. NFKC is
-
# considered the best normalization form for passing strings to databases
-
# and validations.
-
#
-
# * <tt>form</tt> - The form you want to normalize in. Should be one of the following:
-
# <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>. Default is
-
# ActiveSupport::Multibyte::Unicode.default_normalization_form
-
1
def normalize(form = nil)
-
chars(Unicode.normalize(@wrapped_string, form))
-
end
-
-
# Performs canonical decomposition on all the characters.
-
#
-
# 'é'.length # => 2
-
# 'é'.mb_chars.decompose.to_s.length # => 3
-
1
def decompose
-
chars(Unicode.decompose(:canonical, @wrapped_string.codepoints.to_a).pack('U*'))
-
end
-
-
# Performs composition on all the characters.
-
#
-
# 'é'.length # => 3
-
# 'é'.mb_chars.compose.to_s.length # => 2
-
1
def compose
-
chars(Unicode.compose(@wrapped_string.codepoints.to_a).pack('U*'))
-
end
-
-
# Returns the number of grapheme clusters in the string.
-
#
-
# 'क्षि'.mb_chars.length # => 4
-
# 'क्षि'.mb_chars.grapheme_length # => 3
-
1
def grapheme_length
-
Unicode.unpack_graphemes(@wrapped_string).length
-
end
-
-
# Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent
-
# resulting in a valid UTF-8 string.
-
#
-
# Passing +true+ will forcibly tidy all bytes, assuming that the string's
-
# encoding is entirely CP1252 or ISO-8859-1.
-
1
def tidy_bytes(force = false)
-
chars(Unicode.tidy_bytes(@wrapped_string, force))
-
end
-
-
1
def as_json(options = nil) #:nodoc:
-
to_s.as_json(options)
-
end
-
-
1
%w(capitalize downcase reverse tidy_bytes upcase).each do |method|
-
5
define_method("#{method}!") do |*args|
-
@wrapped_string = send(method, *args).to_s
-
self
-
end
-
end
-
-
1
protected
-
-
1
def translate_offset(byte_offset) #:nodoc:
-
return nil if byte_offset.nil?
-
return 0 if @wrapped_string == ''
-
-
begin
-
@wrapped_string.byteslice(0...byte_offset).unpack('U*').length
-
rescue ArgumentError
-
byte_offset -= 1
-
retry
-
end
-
end
-
-
1
def chars(string) #:nodoc:
-
self.class.new(string)
-
end
-
end
-
end
-
end
-
1
require 'active_support/notifications/instrumenter'
-
1
require 'active_support/notifications/fanout'
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveSupport
-
# = Notifications
-
#
-
# <tt>ActiveSupport::Notifications</tt> provides an instrumentation API for
-
# Ruby.
-
#
-
# == Instrumenters
-
#
-
# To instrument an event you just need to do:
-
#
-
# ActiveSupport::Notifications.instrument('render', extra: :information) do
-
# render text: 'Foo'
-
# end
-
#
-
# That first executes the block and then notifies all subscribers once done.
-
#
-
# In the example above +render+ is the name of the event, and the rest is called
-
# the _payload_. The payload is a mechanism that allows instrumenters to pass
-
# extra information to subscribers. Payloads consist of a hash whose contents
-
# are arbitrary and generally depend on the event.
-
#
-
# == Subscribers
-
#
-
# You can consume those events and the information they provide by registering
-
# a subscriber.
-
#
-
# ActiveSupport::Notifications.subscribe('render') do |name, start, finish, id, payload|
-
# name # => String, name of the event (such as 'render' from above)
-
# start # => Time, when the instrumented block started execution
-
# finish # => Time, when the instrumented block ended execution
-
# id # => String, unique ID for this notification
-
# payload # => Hash, the payload
-
# end
-
#
-
# For instance, let's store all "render" events in an array:
-
#
-
# events = []
-
#
-
# ActiveSupport::Notifications.subscribe('render') do |*args|
-
# events << ActiveSupport::Notifications::Event.new(*args)
-
# end
-
#
-
# That code returns right away, you are just subscribing to "render" events.
-
# The block is saved and will be called whenever someone instruments "render":
-
#
-
# ActiveSupport::Notifications.instrument('render', extra: :information) do
-
# render text: 'Foo'
-
# end
-
#
-
# event = events.first
-
# event.name # => "render"
-
# event.duration # => 10 (in milliseconds)
-
# event.payload # => { extra: :information }
-
#
-
# The block in the <tt>subscribe</tt> call gets the name of the event, start
-
# timestamp, end timestamp, a string with a unique identifier for that event
-
# (something like "535801666f04d0298cd6"), and a hash with the payload, in
-
# that order.
-
#
-
# If an exception happens during that particular instrumentation the payload will
-
# have a key <tt>:exception</tt> with an array of two elements as value: a string with
-
# the name of the exception class, and the exception message.
-
#
-
# As the previous example depicts, the class <tt>ActiveSupport::Notifications::Event</tt>
-
# is able to take the arguments as they come and provide an object-oriented
-
# interface to that data.
-
#
-
# It is also possible to pass an object as the second parameter passed to the
-
# <tt>subscribe</tt> method instead of a block:
-
#
-
# module ActionController
-
# class PageRequest
-
# def call(name, started, finished, unique_id, payload)
-
# Rails.logger.debug ['notification:', name, started, finished, unique_id, payload].join(' ')
-
# end
-
# end
-
# end
-
#
-
# ActiveSupport::Notifications.subscribe('process_action.action_controller', ActionController::PageRequest.new)
-
#
-
# resulting in the following output within the logs including a hash with the payload:
-
#
-
# notification: process_action.action_controller 2012-04-13 01:08:35 +0300 2012-04-13 01:08:35 +0300 af358ed7fab884532ec7 {
-
# controller: "Devise::SessionsController",
-
# action: "new",
-
# params: {"action"=>"new", "controller"=>"devise/sessions"},
-
# format: :html,
-
# method: "GET",
-
# path: "/login/sign_in",
-
# status: 200,
-
# view_runtime: 279.3080806732178,
-
# db_runtime: 40.053
-
# }
-
#
-
# You can also subscribe to all events whose name matches a certain regexp:
-
#
-
# ActiveSupport::Notifications.subscribe(/render/) do |*args|
-
# ...
-
# end
-
#
-
# and even pass no argument to <tt>subscribe</tt>, in which case you are subscribing
-
# to all events.
-
#
-
# == Temporary Subscriptions
-
#
-
# Sometimes you do not want to subscribe to an event for the entire life of
-
# the application. There are two ways to unsubscribe.
-
#
-
# WARNING: The instrumentation framework is designed for long-running subscribers,
-
# use this feature sparingly because it wipes some internal caches and that has
-
# a negative impact on performance.
-
#
-
# === Subscribe While a Block Runs
-
#
-
# You can subscribe to some event temporarily while some block runs. For
-
# example, in
-
#
-
# callback = lambda {|*args| ... }
-
# ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
-
# ...
-
# end
-
#
-
# the callback will be called for all "sql.active_record" events instrumented
-
# during the execution of the block. The callback is unsubscribed automatically
-
# after that.
-
#
-
# === Manual Unsubscription
-
#
-
# The +subscribe+ method returns a subscriber object:
-
#
-
# subscriber = ActiveSupport::Notifications.subscribe("render") do |*args|
-
# ...
-
# end
-
#
-
# To prevent that block from being called anymore, just unsubscribe passing
-
# that reference:
-
#
-
# ActiveSupport::Notifications.unsubscribe(subscriber)
-
#
-
# You can also unsubscribe by passing the name of the subscriber object. Note
-
# that this will unsubscribe all subscriptions with the given name:
-
#
-
# ActiveSupport::Notifications.unsubscribe("render")
-
#
-
# == Default Queue
-
#
-
# Notifications ships with a queue implementation that consumes and publishes events
-
# to all log subscribers. You can use any queue implementation you want.
-
#
-
1
module Notifications
-
1
class << self
-
1
attr_accessor :notifier
-
-
1
def publish(name, *args)
-
notifier.publish(name, *args)
-
end
-
-
1
def instrument(name, payload = {})
-
354
if notifier.listening?(name)
-
412
instrumenter.instrument(name, payload) { yield payload if block_given? }
-
else
-
148
yield payload if block_given?
-
end
-
end
-
-
1
def subscribe(*args, &block)
-
28
notifier.subscribe(*args, &block)
-
end
-
-
1
def subscribed(callback, *args, &block)
-
subscriber = subscribe(*args, &callback)
-
yield
-
ensure
-
unsubscribe(subscriber)
-
end
-
-
1
def unsubscribe(subscriber_or_name)
-
notifier.unsubscribe(subscriber_or_name)
-
end
-
-
1
def instrumenter
-
385
InstrumentationRegistry.instance.instrumenter_for(notifier)
-
end
-
end
-
-
# This class is a registry which holds all of the +Instrumenter+ objects
-
# in a particular thread local. To access the +Instrumenter+ object for a
-
# particular +notifier+, you can call the following method:
-
#
-
# InstrumentationRegistry.instrumenter_for(notifier)
-
#
-
# The instrumenters for multiple notifiers are held in a single instance of
-
# this class.
-
1
class InstrumentationRegistry # :nodoc:
-
1
extend ActiveSupport::PerThreadRegistry
-
-
1
def initialize
-
1
@registry = {}
-
end
-
-
1
def instrumenter_for(notifier)
-
385
@registry[notifier] ||= Instrumenter.new(notifier)
-
end
-
end
-
-
1
self.notifier = Fanout.new
-
end
-
end
-
1
require 'mutex_m'
-
1
require 'thread_safe'
-
-
1
module ActiveSupport
-
1
module Notifications
-
# This is a default queue implementation that ships with Notifications.
-
# It just pushes events to all registered log subscribers.
-
#
-
# This class is thread safe. All methods are reentrant.
-
1
class Fanout
-
1
include Mutex_m
-
-
1
def initialize
-
1
@subscribers = []
-
1
@listeners_for = ThreadSafe::Cache.new
-
1
super
-
end
-
-
1
def subscribe(pattern = nil, block = Proc.new)
-
28
subscriber = Subscribers.new pattern, block
-
28
synchronize do
-
28
@subscribers << subscriber
-
28
@listeners_for.clear
-
end
-
28
subscriber
-
end
-
-
1
def unsubscribe(subscriber_or_name)
-
synchronize do
-
case subscriber_or_name
-
when String
-
@subscribers.reject! { |s| s.matches?(subscriber_or_name) }
-
else
-
@subscribers.delete(subscriber_or_name)
-
end
-
-
@listeners_for.clear
-
end
-
end
-
-
1
def start(name, id, payload)
-
1199
listeners_for(name).each { |s| s.start(name, id, payload) }
-
end
-
-
1
def finish(name, id, payload)
-
1199
listeners_for(name).each { |s| s.finish(name, id, payload) }
-
end
-
-
1
def publish(name, *args)
-
listeners_for(name).each { |s| s.publish(name, *args) }
-
end
-
-
1
def listeners_for(name)
-
# this is correctly done double-checked locking (ThreadSafe::Cache's lookups have volatile semantics)
-
@listeners_for[name] || synchronize do
-
# use synchronisation when accessing @subscribers
-
295
@listeners_for[name] ||= @subscribers.select { |s| s.subscribed_to?(name) }
-
1440
end
-
end
-
-
1
def listening?(name)
-
354
listeners_for(name).any?
-
end
-
-
# This is a sync queue, so there is no waiting.
-
1
def wait
-
end
-
-
1
module Subscribers # :nodoc:
-
1
def self.new(pattern, listener)
-
28
if listener.respond_to?(:start) and listener.respond_to?(:finish)
-
28
subscriber = Evented.new pattern, listener
-
else
-
subscriber = Timed.new pattern, listener
-
end
-
-
28
unless pattern
-
AllMessages.new(subscriber)
-
else
-
28
subscriber
-
end
-
end
-
-
1
class Evented #:nodoc:
-
1
def initialize(pattern, delegate)
-
28
@pattern = pattern
-
28
@delegate = delegate
-
28
@can_publish = delegate.respond_to?(:publish)
-
end
-
-
1
def publish(name, *args)
-
if @can_publish
-
@delegate.publish name, *args
-
end
-
end
-
-
1
def start(name, id, payload)
-
656
@delegate.start name, id, payload
-
end
-
-
1
def finish(name, id, payload)
-
656
@delegate.finish name, id, payload
-
end
-
-
1
def subscribed_to?(name)
-
284
@pattern === name
-
end
-
-
1
def matches?(name)
-
@pattern && @pattern === name
-
end
-
end
-
-
1
class Timed < Evented # :nodoc:
-
1
def publish(name, *args)
-
@delegate.call name, *args
-
end
-
-
1
def start(name, id, payload)
-
timestack = Thread.current[:_timestack] ||= []
-
timestack.push Time.now
-
end
-
-
1
def finish(name, id, payload)
-
timestack = Thread.current[:_timestack]
-
started = timestack.pop
-
@delegate.call(name, started, Time.now, id, payload)
-
end
-
end
-
-
1
class AllMessages # :nodoc:
-
1
def initialize(delegate)
-
@delegate = delegate
-
end
-
-
1
def start(name, id, payload)
-
@delegate.start name, id, payload
-
end
-
-
1
def finish(name, id, payload)
-
@delegate.finish name, id, payload
-
end
-
-
1
def publish(name, *args)
-
@delegate.publish name, *args
-
end
-
-
1
def subscribed_to?(name)
-
true
-
end
-
-
1
alias :matches? :===
-
end
-
end
-
end
-
end
-
end
-
1
require 'securerandom'
-
-
1
module ActiveSupport
-
1
module Notifications
-
# Instrumenters are stored in a thread local.
-
1
class Instrumenter
-
1
attr_reader :id
-
-
1
def initialize(notifier)
-
1
@id = unique_id
-
1
@notifier = notifier
-
end
-
-
# Instrument the given block by measuring the time taken to execute it
-
# and publish it. Notice that events get sent even if an error occurs
-
# in the passed-in block.
-
1
def instrument(name, payload={})
-
477
start name, payload
-
477
begin
-
477
yield payload
-
rescue Exception => e
-
payload[:exception] = [e.class.name, e.message]
-
raise e
-
ensure
-
477
finish name, payload
-
477
end
-
end
-
-
# Send a start notification with +name+ and +payload+.
-
1
def start(name, payload)
-
543
@notifier.start name, @id, payload
-
end
-
-
# Send a finish notification with +name+ and +payload+.
-
1
def finish(name, payload)
-
543
@notifier.finish name, @id, payload
-
end
-
-
1
private
-
-
1
def unique_id
-
1
SecureRandom.hex(10)
-
end
-
end
-
-
1
class Event
-
1
attr_reader :name, :time, :transaction_id, :payload, :children
-
1
attr_accessor :end
-
-
1
def initialize(name, start, ending, transaction_id, payload)
-
431
@name = name
-
431
@payload = payload.dup
-
431
@time = start
-
431
@transaction_id = transaction_id
-
431
@end = ending
-
431
@children = []
-
431
@duration = nil
-
end
-
-
1
def duration
-
568
@duration ||= 1000.0 * (self.end - time)
-
end
-
-
1
def <<(event)
-
19
@children << event
-
end
-
-
1
def parent_of?(event)
-
@children.include? event
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module NumberHelper
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :NumberConverter
-
1
autoload :NumberToRoundedConverter
-
1
autoload :NumberToDelimitedConverter
-
1
autoload :NumberToHumanConverter
-
1
autoload :NumberToHumanSizeConverter
-
1
autoload :NumberToPhoneConverter
-
1
autoload :NumberToCurrencyConverter
-
1
autoload :NumberToPercentageConverter
-
end
-
-
1
extend self
-
-
# Formats a +number+ into a US phone number (e.g., (555)
-
# 123-9876). You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:area_code</tt> - Adds parentheses around the area code.
-
# * <tt>:delimiter</tt> - Specifies the delimiter to use
-
# (defaults to "-").
-
# * <tt>:extension</tt> - Specifies an extension to add to the
-
# end of the generated number.
-
# * <tt>:country_code</tt> - Sets the country code for the phone
-
# number.
-
# ==== Examples
-
#
-
# number_to_phone(5551234) # => 555-1234
-
# number_to_phone('5551234') # => 555-1234
-
# number_to_phone(1235551234) # => 123-555-1234
-
# number_to_phone(1235551234, area_code: true) # => (123) 555-1234
-
# number_to_phone(1235551234, delimiter: ' ') # => 123 555 1234
-
# number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
-
# number_to_phone('123a456') # => 123a456
-
#
-
# number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: '.')
-
# # => +1.123.555.1234 x 1343
-
1
def number_to_phone(number, options = {})
-
NumberToPhoneConverter.convert(number, options)
-
end
-
-
# Formats a +number+ into a currency string (e.g., $13.65). You
-
# can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the level of precision (defaults
-
# to 2).
-
# * <tt>:unit</tt> - Sets the denomination of the currency
-
# (defaults to "$").
-
# * <tt>:separator</tt> - Sets the separator between the units
-
# (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:format</tt> - Sets the format for non-negative numbers
-
# (defaults to "%u%n"). Fields are <tt>%u</tt> for the
-
# currency, and <tt>%n</tt> for the number.
-
# * <tt>:negative_format</tt> - Sets the format for negative
-
# numbers (defaults to prepending an hyphen to the formatted
-
# number given by <tt>:format</tt>). Accepts the same fields
-
# than <tt>:format</tt>, except <tt>%n</tt> is here the
-
# absolute value of the number.
-
#
-
# ==== Examples
-
#
-
# number_to_currency(1234567890.50) # => $1,234,567,890.50
-
# number_to_currency(1234567890.506) # => $1,234,567,890.51
-
# number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506
-
# number_to_currency(1234567890.506, locale: :fr) # => 1 234 567 890,51 €
-
# number_to_currency('123a456') # => $123a456
-
#
-
# number_to_currency(-1234567890.50, negative_format: '(%u%n)')
-
# # => ($1,234,567,890.50)
-
# number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '')
-
# # => £1234567890,50
-
# number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '', format: '%n %u')
-
# # => 1234567890,50 £
-
1
def number_to_currency(number, options = {})
-
NumberToCurrencyConverter.convert(number, options)
-
end
-
-
# Formats a +number+ as a percentage string (e.g., 65%). You can
-
# customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:format</tt> - Specifies the format of the percentage
-
# string The number field is <tt>%n</tt> (defaults to "%n%").
-
#
-
# ==== Examples
-
#
-
# number_to_percentage(100) # => 100.000%
-
# number_to_percentage('98') # => 98.000%
-
# number_to_percentage(100, precision: 0) # => 100%
-
# number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000%
-
# number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
-
# number_to_percentage(1000, locale: :fr) # => 1 000,000%
-
# number_to_percentage('98a') # => 98a%
-
# number_to_percentage(100, format: '%n %') # => 100 %
-
1
def number_to_percentage(number, options = {})
-
NumberToPercentageConverter.convert(number, options)
-
end
-
-
# Formats a +number+ with grouped thousands using +delimiter+
-
# (e.g., 12,324). You can customize the format in the +options+
-
# hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
#
-
# ==== Examples
-
#
-
# number_to_delimited(12345678) # => 12,345,678
-
# number_to_delimited('123456') # => 123,456
-
# number_to_delimited(12345678.05) # => 12,345,678.05
-
# number_to_delimited(12345678, delimiter: '.') # => 12.345.678
-
# number_to_delimited(12345678, delimiter: ',') # => 12,345,678
-
# number_to_delimited(12345678.05, separator: ' ') # => 12,345,678 05
-
# number_to_delimited(12345678.05, locale: :fr) # => 12 345 678,05
-
# number_to_delimited('112a') # => 112a
-
# number_to_delimited(98765432.98, delimiter: ' ', separator: ',')
-
# # => 98 765 432,98
-
1
def number_to_delimited(number, options = {})
-
NumberToDelimitedConverter.convert(number, options)
-
end
-
-
# Formats a +number+ with the specified level of
-
# <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
-
# +:significant+ is +false+, and 5 if +:significant+ is +true+).
-
# You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
#
-
# ==== Examples
-
#
-
# number_to_rounded(111.2345) # => 111.235
-
# number_to_rounded(111.2345, precision: 2) # => 111.23
-
# number_to_rounded(13, precision: 5) # => 13.00000
-
# number_to_rounded(389.32314, precision: 0) # => 389
-
# number_to_rounded(111.2345, significant: true) # => 111
-
# number_to_rounded(111.2345, precision: 1, significant: true) # => 100
-
# number_to_rounded(13, precision: 5, significant: true) # => 13.000
-
# number_to_rounded(111.234, locale: :fr) # => 111,234
-
#
-
# number_to_rounded(13, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
#
-
# number_to_rounded(389.32314, precision: 4, significant: true) # => 389.3
-
# number_to_rounded(1111.2345, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
1
def number_to_rounded(number, options = {})
-
NumberToRoundedConverter.convert(number, options)
-
end
-
-
# Formats the bytes in +number+ into a more understandable
-
# representation (e.g., giving it 1500 yields 1.5 KB). This
-
# method is useful for reporting file sizes to users. You can
-
# customize the format in the +options+ hash.
-
#
-
# See <tt>number_to_human</tt> if you want to pretty-print a
-
# generic number.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:prefix</tt> - If +:si+ formats the number using the SI
-
# prefix (defaults to :binary)
-
#
-
# ==== Examples
-
#
-
# number_to_human_size(123) # => 123 Bytes
-
# number_to_human_size(1234) # => 1.21 KB
-
# number_to_human_size(12345) # => 12.1 KB
-
# number_to_human_size(1234567) # => 1.18 MB
-
# number_to_human_size(1234567890) # => 1.15 GB
-
# number_to_human_size(1234567890123) # => 1.12 TB
-
# number_to_human_size(1234567, precision: 2) # => 1.2 MB
-
# number_to_human_size(483989, precision: 2) # => 470 KB
-
# number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB
-
# number_to_human_size(1234567890123, precision: 5) # => "1.1228 TB"
-
# number_to_human_size(524288000, precision: 5) # => "500 MB"
-
1
def number_to_human_size(number, options = {})
-
NumberToHumanSizeConverter.convert(number, options)
-
end
-
-
# Pretty prints (formats and approximates) a number in a way it
-
# is more readable by humans (eg.: 1200000000 becomes "1.2
-
# Billion"). This is useful for numbers that can get very large
-
# (and too hard to read).
-
#
-
# See <tt>number_to_human_size</tt> if you want to print a file
-
# size.
-
#
-
# You can also define your own unit-quantifier names if you want
-
# to use other decimal units (eg.: 1500 becomes "1.5
-
# kilometers", 0.150 becomes "150 milliliters", etc). You may
-
# define a wide range of unit quantifiers, even fractional ones
-
# (centi, deci, mili, etc).
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:units</tt> - A Hash of unit quantifier names. Or a
-
# string containing an i18n scope where to find this hash. It
-
# might have the following keys:
-
# * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
-
# <tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
-
# <tt>:billion</tt>, <tt>:trillion</tt>,
-
# <tt>:quadrillion</tt>
-
# * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
-
# <tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
-
# <tt>:pico</tt>, <tt>:femto</tt>
-
# * <tt>:format</tt> - Sets the format of the output string
-
# (defaults to "%n %u"). The field types are:
-
# * %u - The quantifier (ex.: 'thousand')
-
# * %n - The number
-
#
-
# ==== Examples
-
#
-
# number_to_human(123) # => "123"
-
# number_to_human(1234) # => "1.23 Thousand"
-
# number_to_human(12345) # => "12.3 Thousand"
-
# number_to_human(1234567) # => "1.23 Million"
-
# number_to_human(1234567890) # => "1.23 Billion"
-
# number_to_human(1234567890123) # => "1.23 Trillion"
-
# number_to_human(1234567890123456) # => "1.23 Quadrillion"
-
# number_to_human(1234567890123456789) # => "1230 Quadrillion"
-
# number_to_human(489939, precision: 2) # => "490 Thousand"
-
# number_to_human(489939, precision: 4) # => "489.9 Thousand"
-
# number_to_human(1234567, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# number_to_human(1234567, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
#
-
# number_to_human(500000000, precision: 5) # => "500 Million"
-
# number_to_human(12345012345, significant: false) # => "12.345 Billion"
-
#
-
# Non-significant zeros after the decimal separator are stripped
-
# out by default (set <tt>:strip_insignificant_zeros</tt> to
-
# +false+ to change that):
-
#
-
# number_to_human(12.00001) # => "12"
-
# number_to_human(12.00001, strip_insignificant_zeros: false) # => "12.0"
-
#
-
# ==== Custom Unit Quantifiers
-
#
-
# You can also use your own custom unit quantifiers:
-
# number_to_human(500000, units: { unit: 'ml', thousand: 'lt' }) # => "500 lt"
-
#
-
# If in your I18n locale you have:
-
#
-
# distance:
-
# centi:
-
# one: "centimeter"
-
# other: "centimeters"
-
# unit:
-
# one: "meter"
-
# other: "meters"
-
# thousand:
-
# one: "kilometer"
-
# other: "kilometers"
-
# billion: "gazillion-distance"
-
#
-
# Then you could do:
-
#
-
# number_to_human(543934, units: :distance) # => "544 kilometers"
-
# number_to_human(54393498, units: :distance) # => "54400 kilometers"
-
# number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance"
-
# number_to_human(343, units: :distance, precision: 1) # => "300 meters"
-
# number_to_human(1, units: :distance) # => "1 meter"
-
# number_to_human(0.34, units: :distance) # => "34 centimeters"
-
1
def number_to_human(number, options = {})
-
NumberToHumanConverter.convert(number, options)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/deep_merge'
-
-
1
module ActiveSupport
-
1
class OptionMerger #:nodoc:
-
1
instance_methods.each do |method|
-
89
undef_method(method) if method !~ /^(__|instance_eval|class|object_id)/
-
end
-
-
1
def initialize(context, options)
-
@context, @options = context, options
-
end
-
-
1
private
-
1
def method_missing(method, *arguments, &block)
-
if arguments.first.is_a?(Proc)
-
proc = arguments.pop
-
arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) }
-
else
-
arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup)
-
end
-
-
@context.__send__(method, *arguments, &block)
-
end
-
end
-
end
-
1
module ActiveSupport
-
# Usually key value pairs are handled something like this:
-
#
-
# h = {}
-
# h[:boy] = 'John'
-
# h[:girl] = 'Mary'
-
# h[:boy] # => 'John'
-
# h[:girl] # => 'Mary'
-
#
-
# Using +OrderedOptions+, the above code could be reduced to:
-
#
-
# h = ActiveSupport::OrderedOptions.new
-
# h.boy = 'John'
-
# h.girl = 'Mary'
-
# h.boy # => 'John'
-
# h.girl # => 'Mary'
-
1
class OrderedOptions < Hash
-
1
alias_method :_get, :[] # preserve the original #[] method
-
1
protected :_get # make it protected
-
-
1
def []=(key, value)
-
110
super(key.to_sym, value)
-
end
-
-
1
def [](key)
-
120
super(key.to_sym)
-
end
-
-
1
def method_missing(name, *args)
-
229
name_string = name.to_s
-
229
if name_string.chomp!('=')
-
110
self[name_string] = args.first
-
else
-
119
self[name]
-
end
-
end
-
-
1
def respond_to_missing?(name, include_private)
-
true
-
end
-
end
-
-
# +InheritableOptions+ provides a constructor to build an +OrderedOptions+
-
# hash inherited from another hash.
-
#
-
# Use this if you already have some hash and you want to create a new one based on it.
-
#
-
# h = ActiveSupport::InheritableOptions.new({ girl: 'Mary', boy: 'John' })
-
# h.girl # => 'Mary'
-
# h.boy # => 'John'
-
1
class InheritableOptions < OrderedOptions
-
1
def initialize(parent = nil)
-
186
if parent.kind_of?(OrderedOptions)
-
# use the faster _get when dealing with OrderedOptions
-
1407
super() { |h,k| parent._get(k) }
-
56
elsif parent
-
super() { |h,k| parent[k] }
-
else
-
56
super()
-
end
-
end
-
-
1
def inheritable_copy
-
130
self.class.new(self)
-
end
-
end
-
end
-
1
module ActiveSupport
-
# This module is used to encapsulate access to thread local variables.
-
#
-
# Instead of polluting the thread locals namespace:
-
#
-
# Thread.current[:connection_handler]
-
#
-
# you define a class that extends this module:
-
#
-
# module ActiveRecord
-
# class RuntimeRegistry
-
# extend ActiveSupport::PerThreadRegistry
-
#
-
# attr_accessor :connection_handler
-
# end
-
# end
-
#
-
# and invoke the declared instance accessors as class methods. So
-
#
-
# ActiveRecord::RuntimeRegistry.connection_handler = connection_handler
-
#
-
# sets a connection handler local to the current thread, and
-
#
-
# ActiveRecord::RuntimeRegistry.connection_handler
-
#
-
# returns a connection handler local to the current thread.
-
#
-
# This feature is accomplished by instantiating the class and storing the
-
# instance as a thread local keyed by the class name. In the example above
-
# a key "ActiveRecord::RuntimeRegistry" is stored in <tt>Thread.current</tt>.
-
# The class methods proxy to said thread local instance.
-
#
-
# If the class has an initializer, it must accept no arguments.
-
1
module PerThreadRegistry
-
1
def self.extended(object)
-
6
object.instance_variable_set '@per_thread_registry_key', object.name.freeze
-
end
-
-
1
def instance
-
4719
Thread.current[@per_thread_registry_key] ||= new
-
end
-
-
1
protected
-
1
def method_missing(name, *args, &block) # :nodoc:
-
# Caches the method definition as a singleton method of the receiver.
-
#
-
# By letting #delegate handle it, we avoid an enclosure that'll capture args.
-
2
singleton_class.delegate name, to: :instance
-
-
2
send(name, *args, &block)
-
end
-
end
-
end
-
1
module ActiveSupport
-
# A class with no predefined methods that behaves similarly to Builder's
-
# BlankSlate. Used for proxy classes.
-
1
class ProxyObject < ::BasicObject
-
1
undef_method :==
-
1
undef_method :equal?
-
-
# Let ActiveSupport::ProxyObject at least raise exceptions.
-
1
def raise(*args)
-
::Object.send(:raise, *args)
-
end
-
end
-
end
-
# This is private interface.
-
#
-
# Rails components cherry pick from Active Support as needed, but there are a
-
# few features that are used for sure some way or another and it is not worth
-
# to put individual requires absolutely everywhere. Think blank? for example.
-
#
-
# This file is loaded by every Rails component except Active Support itself,
-
# but it does not belong to the Rails public interface. It is internal to
-
# Rails and can change anytime.
-
-
# Defines Object#blank? and Object#present?.
-
1
require 'active_support/core_ext/object/blank'
-
-
# Rails own autoload, eager_load, etc.
-
1
require 'active_support/dependencies/autoload'
-
-
# Support for ClassMethods and the included macro.
-
1
require 'active_support/concern'
-
-
# Defines Class#class_attribute.
-
1
require 'active_support/core_ext/class/attribute'
-
-
# Defines Module#delegate.
-
1
require 'active_support/core_ext/module/delegation'
-
-
# Defines ActiveSupport::Deprecation.
-
1
require 'active_support/deprecation'
-
1
require "active_support"
-
1
require "active_support/i18n_railtie"
-
-
1
module ActiveSupport
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.active_support = ActiveSupport::OrderedOptions.new
-
-
1
config.eager_load_namespaces << ActiveSupport
-
-
1
initializer "active_support.deprecation_behavior" do |app|
-
1
if deprecation = app.config.active_support.deprecation
-
1
ActiveSupport::Deprecation.behavior = deprecation
-
end
-
end
-
-
# Sets the default value for Time.zone
-
# If assigned value cannot be matched to a TimeZone, an exception will be raised.
-
1
initializer "active_support.initialize_time_zone" do |app|
-
1
require 'active_support/core_ext/time/zones'
-
1
zone_default = Time.find_zone!(app.config.time_zone)
-
-
1
unless zone_default
-
raise 'Value assigned to config.time_zone not recognized. ' \
-
'Run "rake -D time" for a list of tasks for finding appropriate time zone names.'
-
end
-
-
1
Time.zone_default = zone_default
-
end
-
-
# Sets the default week start
-
# If assigned value is not a valid day symbol (e.g. :sunday, :monday, ...), an exception will be raised.
-
1
initializer "active_support.initialize_beginning_of_week" do |app|
-
1
require 'active_support/core_ext/date/calculations'
-
1
beginning_of_week_default = Date.find_beginning_of_week!(app.config.beginning_of_week)
-
-
1
Date.beginning_of_week_default = beginning_of_week_default
-
end
-
-
1
initializer "active_support.set_configs" do |app|
-
1
app.config.active_support.each do |k, v|
-
2
k = "#{k}="
-
2
ActiveSupport.send(k, v) if ActiveSupport.respond_to? k
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveSupport
-
# Rescuable module adds support for easier exception handling.
-
1
module Rescuable
-
1
extend Concern
-
-
1
included do
-
1
class_attribute :rescue_handlers
-
1
self.rescue_handlers = []
-
end
-
-
1
module ClassMethods
-
# Rescue exceptions raised in controller actions.
-
#
-
# <tt>rescue_from</tt> receives a series of exception classes or class
-
# names, and a trailing <tt>:with</tt> option with the name of a method
-
# or a Proc object to be called to handle them. Alternatively a block can
-
# be given.
-
#
-
# Handlers that take one argument will be called with the exception, so
-
# that the exception can be inspected when dealing with it.
-
#
-
# Handlers are inherited. They are searched from right to left, from
-
# bottom to top, and up the hierarchy. The handler of the first class for
-
# which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if
-
# any.
-
#
-
# class ApplicationController < ActionController::Base
-
# rescue_from User::NotAuthorized, with: :deny_access # self defined exception
-
# rescue_from ActiveRecord::RecordInvalid, with: :show_errors
-
#
-
# rescue_from 'MyAppError::Base' do |exception|
-
# render xml: exception, status: 500
-
# end
-
#
-
# protected
-
# def deny_access
-
# ...
-
# end
-
#
-
# def show_errors(exception)
-
# exception.record.new_record? ? ...
-
# end
-
# end
-
#
-
# Exceptions raised inside exception handlers are not propagated up.
-
1
def rescue_from(*klasses, &block)
-
options = klasses.extract_options!
-
-
unless options.has_key?(:with)
-
if block_given?
-
options[:with] = block
-
else
-
raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
-
end
-
end
-
-
klasses.each do |klass|
-
key = if klass.is_a?(Class) && klass <= Exception
-
klass.name
-
elsif klass.is_a?(String)
-
klass
-
else
-
raise ArgumentError, "#{klass} is neither an Exception nor a String"
-
end
-
-
# put the new handler at the end because the list is read in reverse
-
self.rescue_handlers += [[key, options[:with]]]
-
end
-
end
-
end
-
-
# Tries to rescue the exception by looking up and calling a registered handler.
-
1
def rescue_with_handler(exception)
-
if handler = handler_for_rescue(exception)
-
handler.arity != 0 ? handler.call(exception) : handler.call
-
true # don't rely on the return value of the handler
-
end
-
end
-
-
1
def handler_for_rescue(exception)
-
# We go from right to left because pairs are pushed onto rescue_handlers
-
# as rescue_from declarations are found.
-
_, rescuer = self.class.rescue_handlers.reverse.detect do |klass_name, handler|
-
# The purpose of allowing strings in rescue_from is to support the
-
# declaration of handler associations for exception classes whose
-
# definition is yet unknown.
-
#
-
# Since this loop needs the constants it would be inconsistent to
-
# assume they should exist at this point. An early raised exception
-
# could trigger some other handler and the array could include
-
# precisely a string whose corresponding constant has not yet been
-
# seen. This is why we are tolerant to unknown constants.
-
#
-
# Note that this tolerance only matters if the exception was given as
-
# a string, otherwise a NameError will be raised by the interpreter
-
# itself when rescue_from CONSTANT is executed.
-
klass = self.class.const_get(klass_name) rescue nil
-
klass ||= klass_name.constantize rescue nil
-
exception.is_a?(klass) if klass
-
end
-
-
case rescuer
-
when Symbol
-
method(rescuer)
-
when Proc
-
if rescuer.arity == 0
-
Proc.new { instance_exec(&rescuer) }
-
else
-
Proc.new { |_exception| instance_exec(_exception, &rescuer) }
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module SecurityUtils
-
# Constant time string comparison.
-
#
-
# The values compared should be of fixed length, such as strings
-
# that have already been processed by HMAC. This should not be used
-
# on variable length plaintext strings because it could leak length info
-
# via timing attacks.
-
1
def secure_compare(a, b)
-
6
return false unless a.bytesize == b.bytesize
-
-
6
l = a.unpack "C#{a.bytesize}"
-
-
6
res = 0
-
246
b.each_byte { |byte| res |= byte ^ l.shift }
-
6
res == 0
-
end
-
1
module_function :secure_compare
-
end
-
end
-
1
module ActiveSupport
-
# Wrapping a string in this class gives you a prettier way to test
-
# for equality. The value returned by <tt>Rails.env</tt> is wrapped
-
# in a StringInquirer object so instead of calling this:
-
#
-
# Rails.env == 'production'
-
#
-
# you can call this:
-
#
-
# Rails.env.production?
-
1
class StringInquirer < String
-
1
private
-
-
1
def respond_to_missing?(method_name, include_private = false)
-
method_name[-1] == '?'
-
end
-
-
1
def method_missing(method_name, *arguments)
-
76
if method_name[-1] == '?'
-
76
self == method_name[0..-2]
-
else
-
super
-
end
-
end
-
end
-
end
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveSupport
-
# ActiveSupport::Subscriber is an object set to consume
-
# ActiveSupport::Notifications. The subscriber dispatches notifications to
-
# a registered object based on its given namespace.
-
#
-
# An example would be Active Record subscriber responsible for collecting
-
# statistics about queries:
-
#
-
# module ActiveRecord
-
# class StatsSubscriber < ActiveSupport::Subscriber
-
# def sql(event)
-
# Statsd.timing("sql.#{event.payload[:name]}", event.duration)
-
# end
-
# end
-
# end
-
#
-
# And it's finally registered as:
-
#
-
# ActiveRecord::StatsSubscriber.attach_to :active_record
-
#
-
# Since we need to know all instance methods before attaching the log
-
# subscriber, the line above should be called after your subscriber definition.
-
#
-
# After configured, whenever a "sql.active_record" notification is published,
-
# it will properly dispatch the event (ActiveSupport::Notifications::Event) to
-
# the +sql+ method.
-
1
class Subscriber
-
1
class << self
-
-
# Attach the subscriber to a namespace.
-
1
def attach_to(namespace, subscriber=new, notifier=ActiveSupport::Notifications)
-
4
@namespace = namespace
-
4
@subscriber = subscriber
-
4
@notifier = notifier
-
-
4
subscribers << subscriber
-
-
# Add event subscribers for all existing methods on the class.
-
4
subscriber.public_methods(false).each do |event|
-
27
add_event_subscriber(event)
-
end
-
end
-
-
# Adds event subscribers for all new methods added to the class.
-
1
def method_added(event)
-
# Only public methods are added as subscribers, and only if a notifier
-
# has been set up. This means that subscribers will only be set up for
-
# classes that call #attach_to.
-
56
if public_method_defined?(event) && notifier
-
add_event_subscriber(event)
-
end
-
end
-
-
1
def subscribers
-
4
@@subscribers ||= []
-
end
-
-
1
protected
-
-
1
attr_reader :subscriber, :notifier, :namespace
-
-
1
def add_event_subscriber(event)
-
27
return if %w{ start finish }.include?(event.to_s)
-
-
27
pattern = "#{event}.#{namespace}"
-
-
# don't add multiple subscribers (eg. if methods are redefined)
-
27
return if subscriber.patterns.include?(pattern)
-
-
27
subscriber.patterns << pattern
-
27
notifier.subscribe(pattern, subscriber)
-
end
-
end
-
-
1
attr_reader :patterns # :nodoc:
-
-
1
def initialize
-
4
@queue_key = [self.class.name, object_id].join "-"
-
4
@patterns = []
-
4
super
-
end
-
-
1
def start(name, id, payload)
-
431
e = ActiveSupport::Notifications::Event.new(name, Time.now, nil, id, payload)
-
431
parent = event_stack.last
-
431
parent << e if parent
-
-
431
event_stack.push e
-
end
-
-
1
def finish(name, id, payload)
-
431
finished = Time.now
-
431
event = event_stack.pop
-
431
event.end = finished
-
431
event.payload.merge!(payload)
-
-
431
method = name.split('.').first
-
431
send(method, event)
-
end
-
-
1
private
-
-
1
def event_stack
-
1293
SubscriberQueueRegistry.instance.get_queue(@queue_key)
-
end
-
end
-
-
# This is a registry for all the event stacks kept for subscribers.
-
#
-
# See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
-
# for further details.
-
1
class SubscriberQueueRegistry # :nodoc:
-
1
extend PerThreadRegistry
-
-
1
def initialize
-
1
@registry = {}
-
end
-
-
1
def get_queue(queue_key)
-
1293
@registry[queue_key] ||= []
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'logger'
-
1
require 'active_support/logger'
-
-
1
module ActiveSupport
-
# Wraps any standard Logger object to provide tagging capabilities.
-
#
-
# logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
-
# logger.tagged('BCX') { logger.info 'Stuff' } # Logs "[BCX] Stuff"
-
# logger.tagged('BCX', "Jason") { logger.info 'Stuff' } # Logs "[BCX] [Jason] Stuff"
-
# logger.tagged('BCX') { logger.tagged('Jason') { logger.info 'Stuff' } } # Logs "[BCX] [Jason] Stuff"
-
#
-
# This is used by the default Rails.logger as configured by Railties to make
-
# it easy to stamp log lines with subdomains, request ids, and anything else
-
# to aid debugging of multi-user production applications.
-
1
module TaggedLogging
-
1
module Formatter # :nodoc:
-
# This method is invoked when a log event occurs.
-
1
def call(severity, timestamp, progname, msg)
-
512
super(severity, timestamp, progname, "#{tags_text}#{msg}")
-
end
-
-
1
def tagged(*tags)
-
66
new_tags = push_tags(*tags)
-
66
yield self
-
ensure
-
66
pop_tags(new_tags.size)
-
end
-
-
1
def push_tags(*tags)
-
66
tags.flatten.reject(&:blank?).tap do |new_tags|
-
66
current_tags.concat new_tags
-
end
-
end
-
-
1
def pop_tags(size = 1)
-
66
current_tags.pop size
-
end
-
-
1
def clear_tags!
-
66
current_tags.clear
-
end
-
-
1
def current_tags
-
710
Thread.current[:activesupport_tagged_logging_tags] ||= []
-
end
-
-
1
private
-
1
def tags_text
-
512
tags = current_tags
-
512
if tags.any?
-
tags.collect { |tag| "[#{tag}] " }.join
-
end
-
end
-
end
-
-
1
def self.new(logger)
-
# Ensure we set a default formatter so we aren't extending nil!
-
1
logger.formatter ||= ActiveSupport::Logger::SimpleFormatter.new
-
1
logger.formatter.extend Formatter
-
1
logger.extend(self)
-
end
-
-
1
delegate :push_tags, :pop_tags, :clear_tags!, to: :formatter
-
-
1
def tagged(*tags)
-
132
formatter.tagged(*tags) { yield self }
-
end
-
-
1
def flush
-
66
clear_tags!
-
66
super if defined?(super)
-
end
-
end
-
end
-
1
gem 'minitest' # make sure we get the gem, not stdlib
-
1
require 'minitest'
-
1
require 'active_support/testing/tagged_logging'
-
1
require 'active_support/testing/setup_and_teardown'
-
1
require 'active_support/testing/assertions'
-
1
require 'active_support/testing/deprecation'
-
1
require 'active_support/testing/declarative'
-
1
require 'active_support/testing/isolation'
-
1
require 'active_support/testing/constant_lookup'
-
1
require 'active_support/testing/time_helpers'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/deprecation'
-
-
1
module ActiveSupport
-
1
class TestCase < ::Minitest::Test
-
1
Assertion = Minitest::Assertion
-
-
1
class << self
-
# Sets the order in which test cases are run.
-
#
-
# ActiveSupport::TestCase.test_order = :random # => :random
-
#
-
# Valid values are:
-
# * +:random+ (to run tests in random order)
-
# * +:parallel+ (to run tests in parallel)
-
# * +:sorted+ (to run tests alphabetically by method name)
-
# * +:alpha+ (equivalent to +:sorted+)
-
1
def test_order=(new_order)
-
ActiveSupport.test_order = new_order
-
end
-
-
# Returns the order in which test cases are run.
-
#
-
# ActiveSupport::TestCase.test_order # => :sorted
-
#
-
# Possible values are +:random+, +:parallel+, +:alpha+, +:sorted+.
-
# Defaults to +:sorted+.
-
1
def test_order
-
test_order = ActiveSupport.test_order
-
-
if test_order.nil?
-
ActiveSupport::Deprecation.warn "You did not specify a value for the " \
-
"configuration option `active_support.test_order`. In Rails 5, " \
-
"the default value of this option will change from `:sorted` to " \
-
"`:random`.\n" \
-
"To disable this warning and keep the current behavior, you can add " \
-
"the following line to your `config/environments/test.rb`:\n" \
-
"\n" \
-
" Rails.application.configure do\n" \
-
" config.active_support.test_order = :sorted\n" \
-
" end\n" \
-
"\n" \
-
"Alternatively, you can opt into the future behavior by setting this " \
-
"option to `:random`."
-
-
test_order = :sorted
-
self.test_order = test_order
-
end
-
-
test_order
-
end
-
-
1
alias :my_tests_are_order_dependent! :i_suck_and_my_tests_are_order_dependent!
-
end
-
-
1
alias_method :method_name, :name
-
-
1
include ActiveSupport::Testing::TaggedLogging
-
1
include ActiveSupport::Testing::SetupAndTeardown
-
1
include ActiveSupport::Testing::Assertions
-
1
include ActiveSupport::Testing::Deprecation
-
1
include ActiveSupport::Testing::TimeHelpers
-
1
extend ActiveSupport::Testing::Declarative
-
-
# test/unit backwards compatibility methods
-
1
alias :assert_raise :assert_raises
-
1
alias :assert_not_empty :refute_empty
-
1
alias :assert_not_equal :refute_equal
-
1
alias :assert_not_in_delta :refute_in_delta
-
1
alias :assert_not_in_epsilon :refute_in_epsilon
-
1
alias :assert_not_includes :refute_includes
-
1
alias :assert_not_instance_of :refute_instance_of
-
1
alias :assert_not_kind_of :refute_kind_of
-
1
alias :assert_no_match :refute_match
-
1
alias :assert_not_nil :refute_nil
-
1
alias :assert_not_operator :refute_operator
-
1
alias :assert_not_predicate :refute_predicate
-
1
alias :assert_not_respond_to :refute_respond_to
-
1
alias :assert_not_same :refute_same
-
-
# Fails if the block raises an exception.
-
#
-
# assert_nothing_raised do
-
# ...
-
# end
-
1
def assert_nothing_raised(*args)
-
yield
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/blank'
-
-
1
module ActiveSupport
-
1
module Testing
-
1
module Assertions
-
# Assert that an expression is not truthy. Passes if <tt>object</tt> is
-
# +nil+ or +false+. "Truthy" means "considered true in a conditional"
-
# like <tt>if foo</tt>.
-
#
-
# assert_not nil # => true
-
# assert_not false # => true
-
# assert_not 'foo' # => Expected "foo" to be nil or false
-
#
-
# An error message can be specified.
-
#
-
# assert_not foo, 'foo should be false'
-
1
def assert_not(object, message = nil)
-
message ||= "Expected #{mu_pp(object)} to be nil or false"
-
assert !object, message
-
end
-
-
# Test numeric difference between the return value of an expression as a
-
# result of what is evaluated in the yielded block.
-
#
-
# assert_difference 'Article.count' do
-
# post :create, article: {...}
-
# end
-
#
-
# An arbitrary expression is passed in and evaluated.
-
#
-
# assert_difference 'assigns(:article).comments(:reload).size' do
-
# post :create, comment: {...}
-
# end
-
#
-
# An arbitrary positive or negative difference can be specified.
-
# The default is <tt>1</tt>.
-
#
-
# assert_difference 'Article.count', -1 do
-
# post :delete, id: ...
-
# end
-
#
-
# An array of expressions can also be passed in and evaluated.
-
#
-
# assert_difference [ 'Article.count', 'Post.count' ], 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# A lambda or a list of lambdas can be passed in and evaluated:
-
#
-
# assert_difference ->{ Article.count }, 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# assert_difference [->{ Article.count }, ->{ Post.count }], 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# An error message can be specified.
-
#
-
# assert_difference 'Article.count', -1, 'An Article should be destroyed' do
-
# post :delete, id: ...
-
# end
-
1
def assert_difference(expression, difference = 1, message = nil, &block)
-
expressions = Array(expression)
-
-
exps = expressions.map { |e|
-
e.respond_to?(:call) ? e : lambda { eval(e, block.binding) }
-
}
-
before = exps.map { |e| e.call }
-
-
yield
-
-
expressions.zip(exps).each_with_index do |(code, e), i|
-
error = "#{code.inspect} didn't change by #{difference}"
-
error = "#{message}.\n#{error}" if message
-
assert_equal(before[i] + difference, e.call, error)
-
end
-
end
-
-
# Assertion that the numeric result of evaluating an expression is not
-
# changed before and after invoking the passed in block.
-
#
-
# assert_no_difference 'Article.count' do
-
# post :create, article: invalid_attributes
-
# end
-
#
-
# An error message can be specified.
-
#
-
# assert_no_difference 'Article.count', 'An Article should not be created' do
-
# post :create, article: invalid_attributes
-
# end
-
1
def assert_no_difference(expression, message = nil, &block)
-
assert_difference expression, 0, message, &block
-
end
-
end
-
end
-
end
-
1
gem 'minitest'
-
-
1
require 'minitest'
-
-
1
Minitest.autorun
-
1
require "active_support/concern"
-
1
require "active_support/inflector"
-
-
1
module ActiveSupport
-
1
module Testing
-
# Resolves a constant from a minitest spec name.
-
#
-
# Given the following spec-style test:
-
#
-
# describe WidgetsController, :index do
-
# describe "authenticated user" do
-
# describe "returns widgets" do
-
# it "has a controller that exists" do
-
# assert_kind_of WidgetsController, @controller
-
# end
-
# end
-
# end
-
# end
-
#
-
# The test will have the following name:
-
#
-
# "WidgetsController::index::authenticated user::returns widgets"
-
#
-
# The constant WidgetsController can be resolved from the name.
-
# The following code will resolve the constant:
-
#
-
# controller = determine_constant_from_test_name(name) do |constant|
-
# Class === constant && constant < ::ActionController::Metal
-
# end
-
1
module ConstantLookup
-
1
extend ::ActiveSupport::Concern
-
-
1
module ClassMethods # :nodoc:
-
1
def determine_constant_from_test_name(test_name)
-
names = test_name.split "::"
-
while names.size > 0 do
-
names.last.sub!(/Test$/, "")
-
begin
-
constant = names.join("::").safe_constantize
-
break(constant) if yield(constant)
-
ensure
-
names.pop
-
end
-
end
-
end
-
end
-
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module Testing
-
1
module Declarative
-
1
unless defined?(Spec)
-
# Helper to define a test method using a String. Under the hood, it replaces
-
# spaces with underscores and defines the test method.
-
#
-
# test "verify something" do
-
# ...
-
# end
-
def test(name, &block)
-
test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
-
defined = method_defined? test_name
-
raise "#{test_name} is already defined in #{self}" if defined
-
if block_given?
-
define_method(test_name, &block)
-
else
-
define_method(test_name) do
-
flunk "No implementation provided for #{name}"
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/deprecation'
-
-
1
module ActiveSupport
-
1
module Testing
-
1
module Deprecation #:nodoc:
-
1
def assert_deprecated(match = nil, &block)
-
result, warnings = collect_deprecations(&block)
-
assert !warnings.empty?, "Expected a deprecation warning within the block but received none"
-
if match
-
match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
-
assert warnings.any? { |w| w =~ match }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
-
end
-
result
-
end
-
-
1
def assert_not_deprecated(&block)
-
result, deprecations = collect_deprecations(&block)
-
assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}"
-
result
-
end
-
-
1
def collect_deprecations
-
old_behavior = ActiveSupport::Deprecation.behavior
-
deprecations = []
-
ActiveSupport::Deprecation.behavior = Proc.new do |message, callstack|
-
deprecations << message
-
end
-
result = yield
-
[result, deprecations]
-
ensure
-
ActiveSupport::Deprecation.behavior = old_behavior
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/callbacks'
-
-
1
module ActiveSupport
-
1
module Testing
-
# Adds support for +setup+ and +teardown+ callbacks.
-
# These callbacks serve as a replacement to overwriting the
-
# <tt>#setup</tt> and <tt>#teardown</tt> methods of your TestCase.
-
#
-
# class ExampleTest < ActiveSupport::TestCase
-
# setup do
-
# # ...
-
# end
-
#
-
# teardown do
-
# # ...
-
# end
-
# end
-
1
module SetupAndTeardown
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
include ActiveSupport::Callbacks
-
1
define_callbacks :setup, :teardown
-
end
-
-
1
module ClassMethods
-
# Add a callback, which runs before <tt>TestCase#setup</tt>.
-
1
def setup(*args, &block)
-
5
set_callback(:setup, :before, *args, &block)
-
end
-
-
# Add a callback, which runs after <tt>TestCase#teardown</tt>.
-
1
def teardown(*args, &block)
-
2
set_callback(:teardown, :after, *args, &block)
-
end
-
end
-
-
1
def before_setup # :nodoc:
-
super
-
run_callbacks :setup
-
end
-
-
1
def after_teardown # :nodoc:
-
run_callbacks :teardown
-
super
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module Testing
-
# Logs a "PostsControllerTest: test name" heading before each test to
-
# make test.log easier to search and follow along with.
-
1
module TaggedLogging #:nodoc:
-
1
attr_writer :tagged_logger
-
-
1
def before_setup
-
if tagged_logger && tagged_logger.info?
-
heading = "#{self.class}: #{name}"
-
divider = '-' * heading.size
-
tagged_logger.info divider
-
tagged_logger.info heading
-
tagged_logger.info divider
-
end
-
super
-
end
-
-
1
private
-
1
def tagged_logger
-
@tagged_logger ||= (defined?(Rails.logger) && Rails.logger)
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module Testing
-
1
class SimpleStubs # :nodoc:
-
1
Stub = Struct.new(:object, :method_name, :original_method)
-
-
1
def initialize
-
@stubs = {}
-
end
-
-
1
def stub_object(object, method_name, return_value)
-
key = [object.object_id, method_name]
-
-
if stub = @stubs[key]
-
unstub_object(stub)
-
end
-
-
new_name = "__simple_stub__#{method_name}"
-
-
@stubs[key] = Stub.new(object, method_name, new_name)
-
-
object.singleton_class.send :alias_method, new_name, method_name
-
object.define_singleton_method(method_name) { return_value }
-
end
-
-
1
def unstub_all!
-
@stubs.each_value do |stub|
-
unstub_object(stub)
-
end
-
@stubs = {}
-
end
-
-
1
private
-
-
1
def unstub_object(stub)
-
singleton_class = stub.object.singleton_class
-
singleton_class.send :undef_method, stub.method_name
-
singleton_class.send :alias_method, stub.method_name, stub.original_method
-
singleton_class.send :undef_method, stub.original_method
-
end
-
end
-
-
# Containing helpers that helps you test passage of time.
-
1
module TimeHelpers
-
# Changes current time to the time in the future or in the past by a given time difference by
-
# stubbing +Time.now+ and +Date.today+.
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel 1.day
-
# Time.current # => Sun, 10 Nov 2013 15:34:49 EST -05:00
-
# Date.current # => Sun, 10 Nov 2013
-
#
-
# This method also accepts a block, which will return the current time back to its original
-
# state at the end of the block:
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel 1.day do
-
# User.create.created_at # => Sun, 10 Nov 2013 15:34:49 EST -05:00
-
# end
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
1
def travel(duration, &block)
-
travel_to Time.now + duration, &block
-
end
-
-
# Changes current time to the given time by stubbing +Time.now+ and
-
# +Date.today+ to return the time or date passed into this method.
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel_to Time.new(2004, 11, 24, 01, 04, 44)
-
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
-
# Date.current # => Wed, 24 Nov 2004
-
#
-
# Dates are taken as their timestamp at the beginning of the day in the
-
# application time zone. <tt>Time.current</tt> returns said timestamp,
-
# and <tt>Time.now</tt> its equivalent in the system time zone. Similarly,
-
# <tt>Date.current</tt> returns a date equal to the argument, and
-
# <tt>Date.today</tt> the date according to <tt>Time.now</tt>, which may
-
# be different. (Note that you rarely want to deal with <tt>Time.now</tt>,
-
# or <tt>Date.today</tt>, in order to honor the application time zone
-
# please always use <tt>Time.current</tt> and <tt>Date.current</tt>.)
-
#
-
# Note that the usec for the time passed will be set to 0 to prevent rounding
-
# errors with external services, like MySQL (which will round instead of floor,
-
# leading to off-by-one-second errors).
-
#
-
# This method also accepts a block, which will return the current time back to its original
-
# state at the end of the block:
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel_to Time.new(2004, 11, 24, 01, 04, 44) do
-
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
-
# end
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
1
def travel_to(date_or_time)
-
if date_or_time.is_a?(Date) && !date_or_time.is_a?(DateTime)
-
now = date_or_time.midnight.to_time
-
else
-
now = date_or_time.to_time.change(usec: 0)
-
end
-
-
simple_stubs.stub_object(Time, :now, now)
-
simple_stubs.stub_object(Date, :today, now.to_date)
-
-
if block_given?
-
begin
-
yield
-
ensure
-
travel_back
-
end
-
end
-
end
-
-
# Returns the current time back to its original state, by removing the stubs added by
-
# `travel` and `travel_to`.
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel_to Time.new(2004, 11, 24, 01, 04, 44)
-
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
-
# travel_back
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
1
def travel_back
-
simple_stubs.unstub_all!
-
end
-
-
1
private
-
-
1
def simple_stubs
-
@simple_stubs ||= SimpleStubs.new
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
autoload :Duration, 'active_support/duration'
-
1
autoload :TimeWithZone, 'active_support/time_with_zone'
-
1
autoload :TimeZone, 'active_support/values/time_zone'
-
end
-
-
1
require 'date'
-
1
require 'time'
-
-
1
require 'active_support/core_ext/time'
-
1
require 'active_support/core_ext/date'
-
1
require 'active_support/core_ext/date_time'
-
-
1
require 'active_support/core_ext/integer/time'
-
1
require 'active_support/core_ext/numeric/time'
-
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'active_support/core_ext/string/zones'
-
1
require 'active_support/values/time_zone'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
module ActiveSupport
-
# A Time-like class that can represent a time in any time zone. Necessary
-
# because standard Ruby Time instances are limited to UTC and the
-
# system's <tt>ENV['TZ']</tt> zone.
-
#
-
# You shouldn't ever need to create a TimeWithZone instance directly via +new+.
-
# Instead use methods +local+, +parse+, +at+ and +now+ on TimeZone instances,
-
# and +in_time_zone+ on Time and DateTime instances.
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00
-
# Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
#
-
# See Time and TimeZone for further documentation of these methods.
-
#
-
# TimeWithZone instances implement the same API as Ruby Time instances, so
-
# that Time and TimeWithZone instances are interchangeable.
-
#
-
# t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00
-
# t.hour # => 13
-
# t.dst? # => true
-
# t.utc_offset # => -14400
-
# t.zone # => "EDT"
-
# t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400"
-
# t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00
-
# t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00
-
# t > Time.utc(1999) # => true
-
# t.is_a?(Time) # => true
-
# t.is_a?(ActiveSupport::TimeWithZone) # => true
-
1
class TimeWithZone
-
-
# Report class name as 'Time' to thwart type checking.
-
1
def self.name
-
'Time'
-
end
-
-
1
include Comparable
-
1
attr_reader :time_zone
-
-
1
def initialize(utc_time, time_zone, local_time = nil, period = nil)
-
63
@utc, @time_zone, @time = utc_time, time_zone, local_time
-
63
@period = @utc ? period : get_period_and_ensure_valid_local_time(period)
-
end
-
-
# Returns a Time or DateTime instance that represents the time in +time_zone+.
-
1
def time
-
68
@time ||= period.to_local(@utc)
-
end
-
-
# Returns a Time or DateTime instance that represents the time in UTC.
-
1
def utc
-
175
@utc ||= period.to_utc(@time)
-
end
-
1
alias_method :comparable_time, :utc
-
1
alias_method :getgm, :utc
-
1
alias_method :getutc, :utc
-
1
alias_method :gmtime, :utc
-
-
# Returns the underlying TZInfo::TimezonePeriod.
-
1
def period
-
55
@period ||= time_zone.period_for_utc(@utc)
-
end
-
-
# Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone.
-
1
def in_time_zone(new_zone = ::Time.zone)
-
return self if time_zone == new_zone
-
utc.in_time_zone(new_zone)
-
end
-
-
# Returns a <tt>Time.local()</tt> instance of the simultaneous time in your
-
# system's <tt>ENV['TZ']</tt> zone.
-
1
def localtime(utc_offset = nil)
-
utc.respond_to?(:getlocal) ? utc.getlocal(utc_offset) : utc.to_time.getlocal(utc_offset)
-
end
-
1
alias_method :getlocal, :localtime
-
-
# Returns true if the current time is within Daylight Savings Time for the
-
# specified time zone.
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.parse("2012-5-30").dst? # => true
-
# Time.zone.parse("2012-11-30").dst? # => false
-
1
def dst?
-
period.dst?
-
end
-
1
alias_method :isdst, :dst?
-
-
# Returns true if the current time zone is set to UTC.
-
#
-
# Time.zone = 'UTC' # => 'UTC'
-
# Time.zone.now.utc? # => true
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.now.utc? # => false
-
1
def utc?
-
time_zone.name == 'UTC'
-
end
-
1
alias_method :gmt?, :utc?
-
-
# Returns the offset from current time to UTC time in seconds.
-
1
def utc_offset
-
period.utc_total_offset
-
end
-
1
alias_method :gmt_offset, :utc_offset
-
1
alias_method :gmtoff, :utc_offset
-
-
# Returns a formatted string of the offset from UTC, or an alternative
-
# string if the time zone is already UTC.
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)"
-
# Time.zone.now.formatted_offset(true) # => "-05:00"
-
# Time.zone.now.formatted_offset(false) # => "-0500"
-
# Time.zone = 'UTC' # => "UTC"
-
# Time.zone.now.formatted_offset(true, "0") # => "0"
-
1
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Time uses +zone+ to display the time zone abbreviation, so we're
-
# duck-typing it.
-
1
def zone
-
period.zone_identifier.to_s
-
end
-
-
1
def inspect
-
"#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}"
-
end
-
-
1
def xmlschema(fraction_digits = 0)
-
fraction = if fraction_digits.to_i > 0
-
(".%06i" % time.usec)[0, fraction_digits.to_i + 1]
-
end
-
-
"#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
-
end
-
1
alias_method :iso8601, :xmlschema
-
-
# Coerces time to a string for JSON encoding. The default format is ISO 8601.
-
# You can get %Y/%m/%d %H:%M:%S +offset style by setting
-
# <tt>ActiveSupport::JSON::Encoding.use_standard_json_time_format</tt>
-
# to +false+.
-
#
-
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
-
# Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json
-
# # => "2005-02-01T05:15:10.000-10:00"
-
#
-
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
-
# Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json
-
# # => "2005/02/01 05:15:10 -1000"
-
1
def as_json(options = nil)
-
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
-
else
-
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
-
end
-
end
-
-
1
def encode_with(coder)
-
if coder.respond_to?(:represent_object)
-
coder.represent_object(nil, utc)
-
else
-
coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
-
end
-
end
-
-
# Returns a string of the object's date and time in the format used by
-
# HTTP requests.
-
#
-
# Time.zone.now.httpdate # => "Tue, 01 Jan 2013 04:39:43 GMT"
-
1
def httpdate
-
utc.httpdate
-
end
-
-
# Returns a string of the object's date and time in the RFC 2822 standard
-
# format.
-
#
-
# Time.zone.now.rfc2822 # => "Tue, 01 Jan 2013 04:51:39 +0000"
-
1
def rfc2822
-
to_s(:rfc822)
-
end
-
1
alias_method :rfc822, :rfc2822
-
-
# Returns a string of the object's date and time.
-
# Accepts an optional <tt>format</tt>:
-
# * <tt>:default</tt> - default value, mimics Ruby 1.9 Time#to_s format.
-
# * <tt>:db</tt> - format outputs time in UTC :db time. See Time#to_formatted_s(:db).
-
# * Any key in <tt>Time::DATE_FORMATS</tt> can be used. See active_support/core_ext/time/conversions.rb.
-
1
def to_s(format = :default)
-
if format == :db
-
utc.to_s(format)
-
elsif formatter = ::Time::DATE_FORMATS[format]
-
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
"#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
-
end
-
end
-
1
alias_method :to_formatted_s, :to_s
-
-
# Replaces <tt>%Z</tt> directive with +zone before passing to Time#strftime,
-
# so that zone information is correct.
-
1
def strftime(format)
-
format = format.gsub(/((?:\A|[^%])(?:%%)*)%Z/, "\\1#{zone}")
-
getlocal(utc_offset).strftime(format)
-
end
-
-
# Use the time in UTC for comparisons.
-
1
def <=>(other)
-
5
utc <=> other
-
end
-
-
# Returns true if the current object's time is within the specified
-
# +min+ and +max+ time.
-
1
def between?(min, max)
-
utc.between?(min, max)
-
end
-
-
# Returns true if the current object's time is in the past.
-
1
def past?
-
utc.past?
-
end
-
-
# Returns true if the current object's time falls within
-
# the current day.
-
1
def today?
-
time.today?
-
end
-
-
# Returns true if the current object's time is in the future.
-
1
def future?
-
utc.future?
-
end
-
-
1
def eql?(other)
-
other.eql?(utc)
-
end
-
-
1
def hash
-
utc.hash
-
end
-
-
1
def +(other)
-
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
-
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
-
if duration_of_variable_length?(other)
-
method_missing(:+, other)
-
else
-
result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other)
-
result.in_time_zone(time_zone)
-
end
-
end
-
-
1
def -(other)
-
# If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time,
-
# otherwise move backwards #utc, for accuracy when moving across DST boundaries
-
if other.acts_like?(:time)
-
to_time - other.to_time
-
elsif duration_of_variable_length?(other)
-
method_missing(:-, other)
-
else
-
result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
-
result.in_time_zone(time_zone)
-
end
-
end
-
-
1
def since(other)
-
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
-
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
-
if duration_of_variable_length?(other)
-
method_missing(:since, other)
-
else
-
utc.since(other).in_time_zone(time_zone)
-
end
-
end
-
-
1
def ago(other)
-
since(-other)
-
end
-
-
1
def advance(options)
-
# If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
-
# otherwise advance from #utc, for accuracy when moving across DST boundaries
-
if options.values_at(:years, :weeks, :months, :days).any?
-
method_missing(:advance, options)
-
else
-
utc.advance(options).in_time_zone(time_zone)
-
end
-
end
-
-
1
%w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name|
-
13
class_eval <<-EOV, __FILE__, __LINE__ + 1
-
def #{method_name} # def month
-
time.#{method_name} # time.month
-
end # end
-
EOV
-
end
-
-
1
def to_a
-
[time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
-
end
-
-
1
def to_f
-
utc.to_f
-
end
-
-
1
def to_i
-
utc.to_i
-
end
-
1
alias_method :tv_sec, :to_i
-
-
1
def to_r
-
utc.to_r
-
end
-
-
# Return an instance of Time in the system timezone.
-
1
def to_time
-
4
utc.to_time
-
end
-
-
1
def to_datetime
-
utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
-
end
-
-
# So that +self+ <tt>acts_like?(:time)</tt>.
-
1
def acts_like_time?
-
true
-
end
-
-
# Say we're a Time to thwart type checking.
-
1
def is_a?(klass)
-
142
klass == ::Time || super
-
end
-
1
alias_method :kind_of?, :is_a?
-
-
1
def freeze
-
period; utc; time # preload instance variables before freezing
-
super
-
end
-
-
1
def marshal_dump
-
[utc, time_zone.name, time]
-
end
-
-
1
def marshal_load(variables)
-
initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc)
-
end
-
-
# respond_to_missing? is not called in some cases, such as when type conversion is
-
# performed with Kernel#String
-
1
def respond_to?(sym, include_priv = false)
-
# ensure that we're not going to throw and rescue from NoMethodError in method_missing which is slow
-
386
return false if sym.to_sym == :to_str
-
386
super
-
end
-
-
# Ensure proxy class responds to all methods that underlying time instance
-
# responds to.
-
1
def respond_to_missing?(sym, include_priv)
-
# consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime
-
54
return false if sym.to_sym == :acts_like_date?
-
54
time.respond_to?(sym, include_priv)
-
end
-
-
# Send the missing method to +time+ instance, and wrap result in a new
-
# TimeWithZone with the existing +time_zone+.
-
1
def method_missing(sym, *args, &block)
-
wrap_with_time_zone time.__send__(sym, *args, &block)
-
rescue NoMethodError => e
-
raise e, e.message.sub(time.inspect, self.inspect), e.backtrace
-
end
-
-
1
private
-
1
def get_period_and_ensure_valid_local_time(period)
-
# we don't want a Time.local instance enforcing its own DST rules as well,
-
# so transfer time values to a utc constructor if necessary
-
@time = transfer_time_values_to_utc_constructor(@time) unless @time.utc?
-
begin
-
period || @time_zone.period_for_local(@time)
-
rescue ::TZInfo::PeriodNotFound
-
# time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again
-
@time += 1.hour
-
retry
-
end
-
end
-
-
1
def transfer_time_values_to_utc_constructor(time)
-
::Time.utc(time.year, time.month, time.day, time.hour, time.min, time.sec, Rational(time.nsec, 1000))
-
end
-
-
1
def duration_of_variable_length?(obj)
-
ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) }
-
end
-
-
1
def wrap_with_time_zone(time)
-
if time.acts_like?(:time)
-
periods = time_zone.periods_for_local(time)
-
self.class.new(nil, time_zone, time, periods.include?(period) ? period : nil)
-
elsif time.is_a?(Range)
-
wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end)
-
else
-
time
-
end
-
end
-
end
-
end
-
1
require 'tzinfo'
-
1
require 'thread_safe'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/object/try'
-
-
1
module ActiveSupport
-
# The TimeZone class serves as a wrapper around TZInfo::Timezone instances.
-
# It allows us to do the following:
-
#
-
# * Limit the set of zones provided by TZInfo to a meaningful subset of 146
-
# zones.
-
# * Retrieve and display zones with a friendlier name
-
# (e.g., "Eastern Time (US & Canada)" instead of "America/New_York").
-
# * Lazily load TZInfo::Timezone instances only when they're needed.
-
# * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+,
-
# +parse+, +at+ and +now+ methods.
-
#
-
# If you set <tt>config.time_zone</tt> in the Rails Application, you can
-
# access this TimeZone object via <tt>Time.zone</tt>:
-
#
-
# # application.rb:
-
# class Application < Rails::Application
-
# config.time_zone = 'Eastern Time (US & Canada)'
-
# end
-
#
-
# Time.zone # => #<TimeZone:0x514834...>
-
# Time.zone.name # => "Eastern Time (US & Canada)"
-
# Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00
-
#
-
# The version of TZInfo bundled with Active Support only includes the
-
# definitions necessary to support the zones defined by the TimeZone class.
-
# If you need to use zones that aren't defined by TimeZone, you'll need to
-
# install the TZInfo gem (if a recent version of the gem is installed locally,
-
# this will be used instead of the bundled version.)
-
1
class TimeZone
-
# Keys are Rails TimeZone names, values are TZInfo identifiers.
-
1
MAPPING = {
-
"International Date Line West" => "Pacific/Midway",
-
"Midway Island" => "Pacific/Midway",
-
"American Samoa" => "Pacific/Pago_Pago",
-
"Hawaii" => "Pacific/Honolulu",
-
"Alaska" => "America/Juneau",
-
"Pacific Time (US & Canada)" => "America/Los_Angeles",
-
"Tijuana" => "America/Tijuana",
-
"Mountain Time (US & Canada)" => "America/Denver",
-
"Arizona" => "America/Phoenix",
-
"Chihuahua" => "America/Chihuahua",
-
"Mazatlan" => "America/Mazatlan",
-
"Central Time (US & Canada)" => "America/Chicago",
-
"Saskatchewan" => "America/Regina",
-
"Guadalajara" => "America/Mexico_City",
-
"Mexico City" => "America/Mexico_City",
-
"Monterrey" => "America/Monterrey",
-
"Central America" => "America/Guatemala",
-
"Eastern Time (US & Canada)" => "America/New_York",
-
"Indiana (East)" => "America/Indiana/Indianapolis",
-
"Bogota" => "America/Bogota",
-
"Lima" => "America/Lima",
-
"Quito" => "America/Lima",
-
"Atlantic Time (Canada)" => "America/Halifax",
-
"Caracas" => "America/Caracas",
-
"La Paz" => "America/La_Paz",
-
"Santiago" => "America/Santiago",
-
"Newfoundland" => "America/St_Johns",
-
"Brasilia" => "America/Sao_Paulo",
-
"Buenos Aires" => "America/Argentina/Buenos_Aires",
-
"Montevideo" => "America/Montevideo",
-
"Georgetown" => "America/Guyana",
-
"Greenland" => "America/Godthab",
-
"Mid-Atlantic" => "Atlantic/South_Georgia",
-
"Azores" => "Atlantic/Azores",
-
"Cape Verde Is." => "Atlantic/Cape_Verde",
-
"Dublin" => "Europe/Dublin",
-
"Edinburgh" => "Europe/London",
-
"Lisbon" => "Europe/Lisbon",
-
"London" => "Europe/London",
-
"Casablanca" => "Africa/Casablanca",
-
"Monrovia" => "Africa/Monrovia",
-
"UTC" => "Etc/UTC",
-
"Belgrade" => "Europe/Belgrade",
-
"Bratislava" => "Europe/Bratislava",
-
"Budapest" => "Europe/Budapest",
-
"Ljubljana" => "Europe/Ljubljana",
-
"Prague" => "Europe/Prague",
-
"Sarajevo" => "Europe/Sarajevo",
-
"Skopje" => "Europe/Skopje",
-
"Warsaw" => "Europe/Warsaw",
-
"Zagreb" => "Europe/Zagreb",
-
"Brussels" => "Europe/Brussels",
-
"Copenhagen" => "Europe/Copenhagen",
-
"Madrid" => "Europe/Madrid",
-
"Paris" => "Europe/Paris",
-
"Amsterdam" => "Europe/Amsterdam",
-
"Berlin" => "Europe/Berlin",
-
"Bern" => "Europe/Berlin",
-
"Rome" => "Europe/Rome",
-
"Stockholm" => "Europe/Stockholm",
-
"Vienna" => "Europe/Vienna",
-
"West Central Africa" => "Africa/Algiers",
-
"Bucharest" => "Europe/Bucharest",
-
"Cairo" => "Africa/Cairo",
-
"Helsinki" => "Europe/Helsinki",
-
"Kyiv" => "Europe/Kiev",
-
"Riga" => "Europe/Riga",
-
"Sofia" => "Europe/Sofia",
-
"Tallinn" => "Europe/Tallinn",
-
"Vilnius" => "Europe/Vilnius",
-
"Athens" => "Europe/Athens",
-
"Istanbul" => "Europe/Istanbul",
-
"Minsk" => "Europe/Minsk",
-
"Jerusalem" => "Asia/Jerusalem",
-
"Harare" => "Africa/Harare",
-
"Pretoria" => "Africa/Johannesburg",
-
"Kaliningrad" => "Europe/Kaliningrad",
-
"Moscow" => "Europe/Moscow",
-
"St. Petersburg" => "Europe/Moscow",
-
"Volgograd" => "Europe/Volgograd",
-
"Samara" => "Europe/Samara",
-
"Kuwait" => "Asia/Kuwait",
-
"Riyadh" => "Asia/Riyadh",
-
"Nairobi" => "Africa/Nairobi",
-
"Baghdad" => "Asia/Baghdad",
-
"Tehran" => "Asia/Tehran",
-
"Abu Dhabi" => "Asia/Muscat",
-
"Muscat" => "Asia/Muscat",
-
"Baku" => "Asia/Baku",
-
"Tbilisi" => "Asia/Tbilisi",
-
"Yerevan" => "Asia/Yerevan",
-
"Kabul" => "Asia/Kabul",
-
"Ekaterinburg" => "Asia/Yekaterinburg",
-
"Islamabad" => "Asia/Karachi",
-
"Karachi" => "Asia/Karachi",
-
"Tashkent" => "Asia/Tashkent",
-
"Chennai" => "Asia/Kolkata",
-
"Kolkata" => "Asia/Kolkata",
-
"Mumbai" => "Asia/Kolkata",
-
"New Delhi" => "Asia/Kolkata",
-
"Kathmandu" => "Asia/Kathmandu",
-
"Astana" => "Asia/Dhaka",
-
"Dhaka" => "Asia/Dhaka",
-
"Sri Jayawardenepura" => "Asia/Colombo",
-
"Almaty" => "Asia/Almaty",
-
"Novosibirsk" => "Asia/Novosibirsk",
-
"Rangoon" => "Asia/Rangoon",
-
"Bangkok" => "Asia/Bangkok",
-
"Hanoi" => "Asia/Bangkok",
-
"Jakarta" => "Asia/Jakarta",
-
"Krasnoyarsk" => "Asia/Krasnoyarsk",
-
"Beijing" => "Asia/Shanghai",
-
"Chongqing" => "Asia/Chongqing",
-
"Hong Kong" => "Asia/Hong_Kong",
-
"Urumqi" => "Asia/Urumqi",
-
"Kuala Lumpur" => "Asia/Kuala_Lumpur",
-
"Singapore" => "Asia/Singapore",
-
"Taipei" => "Asia/Taipei",
-
"Perth" => "Australia/Perth",
-
"Irkutsk" => "Asia/Irkutsk",
-
"Ulaanbaatar" => "Asia/Ulaanbaatar",
-
"Seoul" => "Asia/Seoul",
-
"Osaka" => "Asia/Tokyo",
-
"Sapporo" => "Asia/Tokyo",
-
"Tokyo" => "Asia/Tokyo",
-
"Yakutsk" => "Asia/Yakutsk",
-
"Darwin" => "Australia/Darwin",
-
"Adelaide" => "Australia/Adelaide",
-
"Canberra" => "Australia/Melbourne",
-
"Melbourne" => "Australia/Melbourne",
-
"Sydney" => "Australia/Sydney",
-
"Brisbane" => "Australia/Brisbane",
-
"Hobart" => "Australia/Hobart",
-
"Vladivostok" => "Asia/Vladivostok",
-
"Guam" => "Pacific/Guam",
-
"Port Moresby" => "Pacific/Port_Moresby",
-
"Magadan" => "Asia/Magadan",
-
"Srednekolymsk" => "Asia/Srednekolymsk",
-
"Solomon Is." => "Pacific/Guadalcanal",
-
"New Caledonia" => "Pacific/Noumea",
-
"Fiji" => "Pacific/Fiji",
-
"Kamchatka" => "Asia/Kamchatka",
-
"Marshall Is." => "Pacific/Majuro",
-
"Auckland" => "Pacific/Auckland",
-
"Wellington" => "Pacific/Auckland",
-
"Nuku'alofa" => "Pacific/Tongatapu",
-
"Tokelau Is." => "Pacific/Fakaofo",
-
"Chatham Is." => "Pacific/Chatham",
-
"Samoa" => "Pacific/Apia"
-
}
-
-
1
UTC_OFFSET_WITH_COLON = '%s%02d:%02d'
-
1
UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.tr(':', '')
-
-
1
@lazy_zones_map = ThreadSafe::Cache.new
-
-
1
class << self
-
# Assumes self represents an offset from UTC in seconds (as returned from
-
# Time#utc_offset) and turns this into an +HH:MM formatted string.
-
#
-
# TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00"
-
1
def seconds_to_utc_offset(seconds, colon = true)
-
format = colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON
-
sign = (seconds < 0 ? '-' : '+')
-
hours = seconds.abs / 3600
-
minutes = (seconds.abs % 3600) / 60
-
format % [sign, hours, minutes]
-
end
-
-
1
def find_tzinfo(name)
-
1
TZInfo::TimezoneProxy.new(MAPPING[name] || name)
-
end
-
-
1
alias_method :create, :new
-
-
# Returns a TimeZone instance with the given name, or +nil+ if no
-
# such TimeZone instance exists. (This exists to support the use of
-
# this class with the +composed_of+ macro.)
-
1
def new(name)
-
self[name]
-
end
-
-
# Returns an array of all TimeZone objects. There are multiple
-
# TimeZone objects per time zone, in many cases, to make it easier
-
# for users to find their own time zone.
-
1
def all
-
@zones ||= zones_map.values.sort
-
end
-
-
1
def zones_map #:nodoc:
-
@zones_map ||= begin
-
MAPPING.each_key {|place| self[place]} # load all the zones
-
@lazy_zones_map
-
end
-
end
-
-
# Locate a specific time zone object. If the argument is a string, it
-
# is interpreted to mean the name of the timezone to locate. If it is a
-
# numeric value it is either the hour offset, or the second offset, of the
-
# timezone to find. (The first one with that offset will be returned.)
-
# Returns +nil+ if no such time zone is known to the system.
-
1
def [](arg)
-
1
case arg
-
when String
-
1
begin
-
2
@lazy_zones_map[arg] ||= create(arg).tap { |tz| tz.utc_offset }
-
rescue TZInfo::InvalidTimezoneIdentifier
-
nil
-
end
-
when Numeric, ActiveSupport::Duration
-
arg *= 3600 if arg.abs <= 13
-
all.find { |z| z.utc_offset == arg.to_i }
-
else
-
raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
-
end
-
end
-
-
# A convenience method for returning a collection of TimeZone objects
-
# for time zones in the USA.
-
1
def us_zones
-
@us_zones ||= all.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
-
end
-
end
-
-
1
include Comparable
-
1
attr_reader :name
-
1
attr_reader :tzinfo
-
-
# Create a new TimeZone object with the given name and offset. The
-
# offset is the number of seconds that this time zone is offset from UTC
-
# (GMT). Seconds were chosen as the offset unit because that is the unit
-
# that Ruby uses to represent time zone offsets (see Time#utc_offset).
-
1
def initialize(name, utc_offset = nil, tzinfo = nil)
-
1
@name = name
-
1
@utc_offset = utc_offset
-
1
@tzinfo = tzinfo || TimeZone.find_tzinfo(name)
-
1
@current_period = nil
-
end
-
-
# Returns the offset of this time zone from UTC in seconds.
-
1
def utc_offset
-
1
if @utc_offset
-
@utc_offset
-
else
-
1
@current_period ||= tzinfo.current_period if tzinfo
-
1
@current_period.utc_offset if @current_period
-
end
-
end
-
-
# Returns the offset of this time zone as a formatted string, of the
-
# format "+HH:MM".
-
1
def formatted_offset(colon=true, alternate_utc_string = nil)
-
utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Compare this time zone to the parameter. The two are compared first on
-
# their offsets, and then by name.
-
1
def <=>(zone)
-
return unless zone.respond_to? :utc_offset
-
result = (utc_offset <=> zone.utc_offset)
-
result = (name <=> zone.name) if result == 0
-
result
-
end
-
-
# Compare #name and TZInfo identifier to a supplied regexp, returning +true+
-
# if a match is found.
-
1
def =~(re)
-
re === name || re === MAPPING[name]
-
end
-
-
# Returns a textual representation of this time zone.
-
1
def to_s
-
"(GMT#{formatted_offset}) #{name}"
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from given values.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00
-
1
def local(*args)
-
time = Time.utc(*args)
-
ActiveSupport::TimeWithZone.new(nil, self, time)
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from number of seconds since the Unix epoch.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.utc(2000).to_f # => 946684800.0
-
# Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
1
def at(secs)
-
Time.at(secs).utc.in_time_zone(self)
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from parsed string.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
#
-
# If upper components are missing from the string, they are supplied from
-
# TimeZone#now:
-
#
-
# Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
# Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
-
#
-
# However, if the date component is not provided, but any other upper
-
# components are supplied, then the day of the month defaults to 1:
-
#
-
# Time.zone.parse('Mar 2000') # => Wed, 01 Mar 2000 00:00:00 HST -10:00
-
1
def parse(str, now=now())
-
parts = Date._parse(str, false)
-
return if parts.empty?
-
-
time = Time.new(
-
parts.fetch(:year, now.year),
-
parts.fetch(:mon, now.month),
-
parts.fetch(:mday, parts[:year] || parts[:mon] ? 1 : now.day),
-
parts.fetch(:hour, 0),
-
parts.fetch(:min, 0),
-
parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
-
parts.fetch(:offset, 0)
-
)
-
-
if parts[:offset]
-
TimeWithZone.new(time.utc, self)
-
else
-
TimeWithZone.new(nil, self, time)
-
end
-
end
-
-
# Returns an ActiveSupport::TimeWithZone instance representing the current
-
# time in the time zone represented by +self+.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00
-
1
def now
-
1
time_now.utc.in_time_zone(self)
-
end
-
-
# Return the current date in this time zone.
-
1
def today
-
tzinfo.now.to_date
-
end
-
-
# Returns the next date in this time zone.
-
1
def tomorrow
-
today + 1
-
end
-
-
# Returns the previous date in this time zone.
-
1
def yesterday
-
today - 1
-
end
-
-
# Adjust the given time to the simultaneous time in the time zone
-
# represented by +self+. Returns a Time.utc() instance -- if you want an
-
# ActiveSupport::TimeWithZone instance, use Time#in_time_zone() instead.
-
1
def utc_to_local(time)
-
tzinfo.utc_to_local(time)
-
end
-
-
# Adjust the given time to the simultaneous time in UTC. Returns a
-
# Time.utc() instance.
-
1
def local_to_utc(time, dst=true)
-
tzinfo.local_to_utc(time, dst)
-
end
-
-
# Available so that TimeZone instances respond like TZInfo::Timezone
-
# instances.
-
1
def period_for_utc(time)
-
55
tzinfo.period_for_utc(time)
-
end
-
-
# Available so that TimeZone instances respond like TZInfo::Timezone
-
# instances.
-
1
def period_for_local(time, dst=true)
-
tzinfo.period_for_local(time, dst)
-
end
-
-
1
def periods_for_local(time) #:nodoc:
-
tzinfo.periods_for_local(time)
-
end
-
-
1
private
-
1
def time_now
-
1
Time.now
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActiveSupport
-
# Returns the version of the currently loaded ActiveSupport as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
1
require 'time'
-
1
require 'base64'
-
1
require 'bigdecimal'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/date_time/calculations'
-
-
1
module ActiveSupport
-
# = XmlMini
-
#
-
# To use the much faster libxml parser:
-
# gem 'libxml-ruby', '=0.9.7'
-
# XmlMini.backend = 'LibXML'
-
1
module XmlMini
-
1
extend self
-
-
# This module decorates files deserialized using Hash.from_xml with
-
# the <tt>original_filename</tt> and <tt>content_type</tt> methods.
-
1
module FileLike #:nodoc:
-
1
attr_writer :original_filename, :content_type
-
-
1
def original_filename
-
@original_filename || 'untitled'
-
end
-
-
1
def content_type
-
@content_type || 'application/octet-stream'
-
end
-
end
-
-
DEFAULT_ENCODINGS = {
-
"binary" => "base64"
-
1
} unless defined?(DEFAULT_ENCODINGS)
-
-
TYPE_NAMES = {
-
"Symbol" => "symbol",
-
"Fixnum" => "integer",
-
"Bignum" => "integer",
-
"BigDecimal" => "decimal",
-
"Float" => "float",
-
"TrueClass" => "boolean",
-
"FalseClass" => "boolean",
-
"Date" => "date",
-
"DateTime" => "dateTime",
-
"Time" => "dateTime",
-
"Array" => "array",
-
"Hash" => "hash"
-
1
} unless defined?(TYPE_NAMES)
-
-
FORMATTING = {
-
"symbol" => Proc.new { |symbol| symbol.to_s },
-
"date" => Proc.new { |date| date.to_s(:db) },
-
"dateTime" => Proc.new { |time| time.xmlschema },
-
"binary" => Proc.new { |binary| ::Base64.encode64(binary) },
-
"yaml" => Proc.new { |yaml| yaml.to_yaml }
-
1
} unless defined?(FORMATTING)
-
-
# TODO use regexp instead of Date.parse
-
1
unless defined?(PARSING)
-
1
PARSING = {
-
"symbol" => Proc.new { |symbol| symbol.to_s.to_sym },
-
"date" => Proc.new { |date| ::Date.parse(date) },
-
"datetime" => Proc.new { |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc },
-
"integer" => Proc.new { |integer| integer.to_i },
-
"float" => Proc.new { |float| float.to_f },
-
"decimal" => Proc.new { |number| BigDecimal(number) },
-
"boolean" => Proc.new { |boolean| %w(1 true).include?(boolean.to_s.strip) },
-
"string" => Proc.new { |string| string.to_s },
-
"yaml" => Proc.new { |yaml| YAML::load(yaml) rescue yaml },
-
"base64Binary" => Proc.new { |bin| ::Base64.decode64(bin) },
-
"binary" => Proc.new { |bin, entity| _parse_binary(bin, entity) },
-
"file" => Proc.new { |file, entity| _parse_file(file, entity) }
-
}
-
-
1
PARSING.update(
-
"double" => PARSING["float"],
-
"dateTime" => PARSING["datetime"]
-
)
-
end
-
-
1
attr_accessor :depth
-
1
self.depth = 100
-
-
1
delegate :parse, :to => :backend
-
-
1
def backend
-
current_thread_backend || @backend
-
end
-
-
1
def backend=(name)
-
1
backend = name && cast_backend_name_to_module(name)
-
1
self.current_thread_backend = backend if current_thread_backend
-
1
@backend = backend
-
end
-
-
1
def with_backend(name)
-
old_backend = current_thread_backend
-
self.current_thread_backend = name && cast_backend_name_to_module(name)
-
yield
-
ensure
-
self.current_thread_backend = old_backend
-
end
-
-
1
def to_tag(key, value, options)
-
type_name = options.delete(:type)
-
merged_options = options.merge(:root => key, :skip_instruct => true)
-
-
if value.is_a?(::Method) || value.is_a?(::Proc)
-
if value.arity == 1
-
value.call(merged_options)
-
else
-
value.call(merged_options, key.to_s.singularize)
-
end
-
elsif value.respond_to?(:to_xml)
-
value.to_xml(merged_options)
-
else
-
type_name ||= TYPE_NAMES[value.class.name]
-
type_name ||= value.class.name if value && !value.respond_to?(:to_str)
-
type_name = type_name.to_s if type_name
-
type_name = "dateTime" if type_name == "datetime"
-
-
key = rename_key(key.to_s, options)
-
-
attributes = options[:skip_types] || type_name.nil? ? { } : { :type => type_name }
-
attributes[:nil] = true if value.nil?
-
-
encoding = options[:encoding] || DEFAULT_ENCODINGS[type_name]
-
attributes[:encoding] = encoding if encoding
-
-
formatted_value = FORMATTING[type_name] && !value.nil? ?
-
FORMATTING[type_name].call(value) : value
-
-
options[:builder].tag!(key, formatted_value, attributes)
-
end
-
end
-
-
1
def rename_key(key, options = {})
-
camelize = options[:camelize]
-
dasherize = !options.has_key?(:dasherize) || options[:dasherize]
-
if camelize
-
key = true == camelize ? key.camelize : key.camelize(camelize)
-
end
-
key = _dasherize(key) if dasherize
-
key
-
end
-
-
1
protected
-
-
1
def _dasherize(key)
-
# $2 must be a non-greedy regex for this to work
-
left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1,3]
-
"#{left}#{middle.tr('_ ', '--')}#{right}"
-
end
-
-
# TODO: Add support for other encodings
-
1
def _parse_binary(bin, entity) #:nodoc:
-
case entity['encoding']
-
when 'base64'
-
::Base64.decode64(bin)
-
else
-
bin
-
end
-
end
-
-
1
def _parse_file(file, entity)
-
f = StringIO.new(::Base64.decode64(file))
-
f.extend(FileLike)
-
f.original_filename = entity['name']
-
f.content_type = entity['content_type']
-
f
-
end
-
-
1
private
-
-
1
def current_thread_backend
-
1
Thread.current[:xml_mini_backend]
-
end
-
-
1
def current_thread_backend=(name)
-
Thread.current[:xml_mini_backend] = name && cast_backend_name_to_module(name)
-
end
-
-
1
def cast_backend_name_to_module(name)
-
1
if name.is_a?(Module)
-
name
-
else
-
1
require "active_support/xml_mini/#{name.downcase}"
-
1
ActiveSupport.const_get("XmlMini_#{name}")
-
end
-
end
-
end
-
-
1
XmlMini.backend = 'REXML'
-
end
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'stringio'
-
-
1
module ActiveSupport
-
1
module XmlMini_REXML #:nodoc:
-
1
extend self
-
-
1
CONTENT_KEY = '__content__'.freeze
-
-
# Parse an XML Document string or IO into a simple hash.
-
#
-
# Same as XmlSimple::xml_in but doesn't shoot itself in the foot,
-
# and uses the defaults from Active Support.
-
#
-
# data::
-
# XML Document string or IO to parse
-
1
def parse(data)
-
if !data.respond_to?(:read)
-
data = StringIO.new(data || '')
-
end
-
-
char = data.getc
-
if char.nil?
-
{}
-
else
-
data.ungetc(char)
-
silence_warnings { require 'rexml/document' } unless defined?(REXML::Document)
-
doc = REXML::Document.new(data)
-
-
if doc.root
-
merge_element!({}, doc.root, XmlMini.depth)
-
else
-
raise REXML::ParseException,
-
"The document #{doc.to_s.inspect} does not have a valid root"
-
end
-
end
-
end
-
-
1
private
-
# Convert an XML element and merge into the hash
-
#
-
# hash::
-
# Hash to merge the converted element into.
-
# element::
-
# XML element to merge into hash
-
1
def merge_element!(hash, element, depth)
-
raise REXML::ParseException, "The document is too deep" if depth == 0
-
merge!(hash, element.name, collapse(element, depth))
-
end
-
-
# Actually converts an XML document element into a data structure.
-
#
-
# element::
-
# The document element to be collapsed.
-
1
def collapse(element, depth)
-
hash = get_attributes(element)
-
-
if element.has_elements?
-
element.each_element {|child| merge_element!(hash, child, depth - 1) }
-
merge_texts!(hash, element) unless empty_content?(element)
-
hash
-
else
-
merge_texts!(hash, element)
-
end
-
end
-
-
# Merge all the texts of an element into the hash
-
#
-
# hash::
-
# Hash to add the converted element to.
-
# element::
-
# XML element whose texts are to me merged into the hash
-
1
def merge_texts!(hash, element)
-
unless element.has_text?
-
hash
-
else
-
# must use value to prevent double-escaping
-
texts = ''
-
element.texts.each { |t| texts << t.value }
-
merge!(hash, CONTENT_KEY, texts)
-
end
-
end
-
-
# Adds a new key/value pair to an existing Hash. If the key to be added
-
# already exists and the existing value associated with key is not
-
# an Array, it will be wrapped in an Array. Then the new value is
-
# appended to that Array.
-
#
-
# hash::
-
# Hash to add key/value pair to.
-
# key::
-
# Key to be added.
-
# value::
-
# Value to be associated with key.
-
1
def merge!(hash, key, value)
-
if hash.has_key?(key)
-
if hash[key].instance_of?(Array)
-
hash[key] << value
-
else
-
hash[key] = [hash[key], value]
-
end
-
elsif value.instance_of?(Array)
-
hash[key] = [value]
-
else
-
hash[key] = value
-
end
-
hash
-
end
-
-
# Converts the attributes array of an XML element into a hash.
-
# Returns an empty Hash if node has no attributes.
-
#
-
# element::
-
# XML element to extract attributes from.
-
1
def get_attributes(element)
-
attributes = {}
-
element.attributes.each { |n,v| attributes[n] = v }
-
attributes
-
end
-
-
# Determines if a document element has text content
-
#
-
# element::
-
# XML element to be checked.
-
1
def empty_content?(element)
-
element.texts.join.blank?
-
end
-
end
-
end
-
# encoding:utf-8
-
#--
-
# Copyright (C) Bob Aman
-
#
-
# Licensed under the Apache License, Version 2.0 (the "License");
-
# you may not use this file except in compliance with the License.
-
# You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing, software
-
# distributed under the License is distributed on an "AS IS" BASIS,
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
# See the License for the specific language governing permissions and
-
# limitations under the License.
-
#++
-
-
-
1
begin
-
1
require "addressable/idna/native"
-
rescue LoadError
-
# libidn or the idn gem was not available, fall back on a pure-Ruby
-
# implementation...
-
1
require "addressable/idna/pure"
-
end
-
# encoding:utf-8
-
#--
-
# Copyright (C) Bob Aman
-
#
-
# Licensed under the Apache License, Version 2.0 (the "License");
-
# you may not use this file except in compliance with the License.
-
# You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing, software
-
# distributed under the License is distributed on an "AS IS" BASIS,
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
# See the License for the specific language governing permissions and
-
# limitations under the License.
-
#++
-
-
-
1
require "idn"
-
-
module Addressable
-
module IDNA
-
def self.punycode_encode(value)
-
IDN::Punycode.encode(value.to_s)
-
end
-
-
def self.punycode_decode(value)
-
IDN::Punycode.decode(value.to_s)
-
end
-
-
def self.unicode_normalize_kc(value)
-
IDN::Stringprep.nfkc_normalize(value.to_s)
-
end
-
-
def self.to_ascii(value)
-
value.to_s.split('.', -1).map do |segment|
-
if segment.size > 0 && segment.size < 64
-
IDN::Idna.toASCII(segment)
-
elsif segment.size >= 64
-
segment
-
else
-
''
-
end
-
end.join('.')
-
end
-
-
def self.to_unicode(value)
-
value.to_s.split('.', -1).map do |segment|
-
if segment.size > 0 && segment.size < 64
-
IDN::Idna.toUnicode(segment)
-
elsif segment.size >= 64
-
segment
-
else
-
''
-
end
-
end.join('.')
-
end
-
end
-
end
-
# encoding:utf-8
-
#--
-
# Copyright (C) Bob Aman
-
#
-
# Licensed under the Apache License, Version 2.0 (the "License");
-
# you may not use this file except in compliance with the License.
-
# You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing, software
-
# distributed under the License is distributed on an "AS IS" BASIS,
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
# See the License for the specific language governing permissions and
-
# limitations under the License.
-
#++
-
-
-
1
module Addressable
-
1
module IDNA
-
# This module is loosely based on idn_actionmailer by Mick Staugaard,
-
# the unicode library by Yoshida Masato, and the punycode implementation
-
# by Kazuhiro Nishiyama. Most of the code was copied verbatim, but
-
# some reformatting was done, and some translation from C was done.
-
#
-
# Without their code to work from as a base, we'd all still be relying
-
# on the presence of libidn. Which nobody ever seems to have installed.
-
#
-
# Original sources:
-
# http://github.com/staugaard/idn_actionmailer
-
# http://www.yoshidam.net/Ruby.html#unicode
-
# http://rubyforge.org/frs/?group_id=2550
-
-
-
1
UNICODE_TABLE = File.expand_path(
-
File.join(File.dirname(__FILE__), '../../..', 'data/unicode.data')
-
)
-
-
1
ACE_PREFIX = "xn--"
-
-
1
UTF8_REGEX = /\A(?:
-
[\x09\x0A\x0D\x20-\x7E] # ASCII
-
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
-
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
-
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
-
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
-
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
-
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4nil5
-
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
-
)*\z/mnx
-
-
1
UTF8_REGEX_MULTIBYTE = /(?:
-
[\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
-
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
-
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
-
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
-
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
-
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4nil5
-
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
-
)/mnx
-
-
# :startdoc:
-
-
# Converts from a Unicode internationalized domain name to an ASCII
-
# domain name as described in RFC 3490.
-
1
def self.to_ascii(input)
-
input = input.to_s unless input.is_a?(String)
-
input = input.dup
-
if input.respond_to?(:force_encoding)
-
input.force_encoding(Encoding::ASCII_8BIT)
-
end
-
if input =~ UTF8_REGEX && input =~ UTF8_REGEX_MULTIBYTE
-
parts = unicode_downcase(input).split('.')
-
parts.map! do |part|
-
if part.respond_to?(:force_encoding)
-
part.force_encoding(Encoding::ASCII_8BIT)
-
end
-
if part =~ UTF8_REGEX && part =~ UTF8_REGEX_MULTIBYTE
-
ACE_PREFIX + punycode_encode(unicode_normalize_kc(part))
-
else
-
part
-
end
-
end
-
parts.join('.')
-
else
-
input
-
end
-
end
-
-
# Converts from an ASCII domain name to a Unicode internationalized
-
# domain name as described in RFC 3490.
-
1
def self.to_unicode(input)
-
input = input.to_s unless input.is_a?(String)
-
parts = input.split('.')
-
parts.map! do |part|
-
if part =~ /^#{ACE_PREFIX}(.+)/
-
begin
-
punycode_decode(part[/^#{ACE_PREFIX}(.+)/, 1])
-
rescue Addressable::IDNA::PunycodeBadInput
-
# toUnicode is explicitly defined as never-fails by the spec
-
part
-
end
-
else
-
part
-
end
-
end
-
output = parts.join('.')
-
if output.respond_to?(:force_encoding)
-
output.force_encoding(Encoding::UTF_8)
-
end
-
output
-
end
-
-
# Unicode normalization form KC.
-
1
def self.unicode_normalize_kc(input)
-
input = input.to_s unless input.is_a?(String)
-
unpacked = input.unpack("U*")
-
unpacked =
-
unicode_compose(unicode_sort_canonical(unicode_decompose(unpacked)))
-
return unpacked.pack("U*")
-
end
-
-
##
-
# Unicode aware downcase method.
-
#
-
# @api private
-
# @param [String] input
-
# The input string.
-
# @return [String] The downcased result.
-
1
def self.unicode_downcase(input)
-
input = input.to_s unless input.is_a?(String)
-
unpacked = input.unpack("U*")
-
unpacked.map! { |codepoint| lookup_unicode_lowercase(codepoint) }
-
return unpacked.pack("U*")
-
end
-
2
(class <<self; private :unicode_downcase; end)
-
-
1
def self.unicode_compose(unpacked)
-
unpacked_result = []
-
length = unpacked.length
-
-
return unpacked if length == 0
-
-
starter = unpacked[0]
-
starter_cc = lookup_unicode_combining_class(starter)
-
starter_cc = 256 if starter_cc != 0
-
for i in 1...length
-
ch = unpacked[i]
-
cc = lookup_unicode_combining_class(ch)
-
-
if (starter_cc == 0 &&
-
(composite = unicode_compose_pair(starter, ch)) != nil)
-
starter = composite
-
startercc = lookup_unicode_combining_class(composite)
-
else
-
unpacked_result << starter
-
starter = ch
-
startercc = cc
-
end
-
end
-
unpacked_result << starter
-
return unpacked_result
-
end
-
2
(class <<self; private :unicode_compose; end)
-
-
1
def self.unicode_compose_pair(ch_one, ch_two)
-
if ch_one >= HANGUL_LBASE && ch_one < HANGUL_LBASE + HANGUL_LCOUNT &&
-
ch_two >= HANGUL_VBASE && ch_two < HANGUL_VBASE + HANGUL_VCOUNT
-
# Hangul L + V
-
return HANGUL_SBASE + (
-
(ch_one - HANGUL_LBASE) * HANGUL_VCOUNT + (ch_two - HANGUL_VBASE)
-
) * HANGUL_TCOUNT
-
elsif ch_one >= HANGUL_SBASE &&
-
ch_one < HANGUL_SBASE + HANGUL_SCOUNT &&
-
(ch_one - HANGUL_SBASE) % HANGUL_TCOUNT == 0 &&
-
ch_two >= HANGUL_TBASE && ch_two < HANGUL_TBASE + HANGUL_TCOUNT
-
# Hangul LV + T
-
return ch_one + (ch_two - HANGUL_TBASE)
-
end
-
-
p = []
-
ucs4_to_utf8 = lambda do |ch|
-
if ch < 128
-
p << ch
-
elsif ch < 2048
-
p << (ch >> 6 | 192)
-
p << (ch & 63 | 128)
-
elsif ch < 0x10000
-
p << (ch >> 12 | 224)
-
p << (ch >> 6 & 63 | 128)
-
p << (ch & 63 | 128)
-
elsif ch < 0x200000
-
p << (ch >> 18 | 240)
-
p << (ch >> 12 & 63 | 128)
-
p << (ch >> 6 & 63 | 128)
-
p << (ch & 63 | 128)
-
elsif ch < 0x4000000
-
p << (ch >> 24 | 248)
-
p << (ch >> 18 & 63 | 128)
-
p << (ch >> 12 & 63 | 128)
-
p << (ch >> 6 & 63 | 128)
-
p << (ch & 63 | 128)
-
elsif ch < 0x80000000
-
p << (ch >> 30 | 252)
-
p << (ch >> 24 & 63 | 128)
-
p << (ch >> 18 & 63 | 128)
-
p << (ch >> 12 & 63 | 128)
-
p << (ch >> 6 & 63 | 128)
-
p << (ch & 63 | 128)
-
end
-
end
-
-
ucs4_to_utf8.call(ch_one)
-
ucs4_to_utf8.call(ch_two)
-
-
return lookup_unicode_composition(p)
-
end
-
2
(class <<self; private :unicode_compose_pair; end)
-
-
1
def self.unicode_sort_canonical(unpacked)
-
unpacked = unpacked.dup
-
i = 1
-
length = unpacked.length
-
-
return unpacked if length < 2
-
-
while i < length
-
last = unpacked[i-1]
-
ch = unpacked[i]
-
last_cc = lookup_unicode_combining_class(last)
-
cc = lookup_unicode_combining_class(ch)
-
if cc != 0 && last_cc != 0 && last_cc > cc
-
unpacked[i] = last
-
unpacked[i-1] = ch
-
i -= 1 if i > 1
-
else
-
i += 1
-
end
-
end
-
return unpacked
-
end
-
2
(class <<self; private :unicode_sort_canonical; end)
-
-
1
def self.unicode_decompose(unpacked)
-
unpacked_result = []
-
for cp in unpacked
-
if cp >= HANGUL_SBASE && cp < HANGUL_SBASE + HANGUL_SCOUNT
-
l, v, t = unicode_decompose_hangul(cp)
-
unpacked_result << l
-
unpacked_result << v if v
-
unpacked_result << t if t
-
else
-
dc = lookup_unicode_compatibility(cp)
-
unless dc
-
unpacked_result << cp
-
else
-
unpacked_result.concat(unicode_decompose(dc.unpack("U*")))
-
end
-
end
-
end
-
return unpacked_result
-
end
-
2
(class <<self; private :unicode_decompose; end)
-
-
1
def self.unicode_decompose_hangul(codepoint)
-
sindex = codepoint - HANGUL_SBASE;
-
if sindex < 0 || sindex >= HANGUL_SCOUNT
-
l = codepoint
-
v = t = nil
-
return l, v, t
-
end
-
l = HANGUL_LBASE + sindex / HANGUL_NCOUNT
-
v = HANGUL_VBASE + (sindex % HANGUL_NCOUNT) / HANGUL_TCOUNT
-
t = HANGUL_TBASE + sindex % HANGUL_TCOUNT
-
if t == HANGUL_TBASE
-
t = nil
-
end
-
return l, v, t
-
end
-
2
(class <<self; private :unicode_decompose_hangul; end)
-
-
1
def self.lookup_unicode_combining_class(codepoint)
-
codepoint_data = UNICODE_DATA[codepoint]
-
(codepoint_data ?
-
(codepoint_data[UNICODE_DATA_COMBINING_CLASS] || 0) :
-
0)
-
end
-
2
(class <<self; private :lookup_unicode_combining_class; end)
-
-
1
def self.lookup_unicode_compatibility(codepoint)
-
codepoint_data = UNICODE_DATA[codepoint]
-
(codepoint_data ?
-
codepoint_data[UNICODE_DATA_COMPATIBILITY] : nil)
-
end
-
2
(class <<self; private :lookup_unicode_compatibility; end)
-
-
1
def self.lookup_unicode_lowercase(codepoint)
-
codepoint_data = UNICODE_DATA[codepoint]
-
(codepoint_data ?
-
(codepoint_data[UNICODE_DATA_LOWERCASE] || codepoint) :
-
codepoint)
-
end
-
2
(class <<self; private :lookup_unicode_lowercase; end)
-
-
1
def self.lookup_unicode_composition(unpacked)
-
return COMPOSITION_TABLE[unpacked]
-
end
-
2
(class <<self; private :lookup_unicode_composition; end)
-
-
1
HANGUL_SBASE = 0xac00
-
1
HANGUL_LBASE = 0x1100
-
1
HANGUL_LCOUNT = 19
-
1
HANGUL_VBASE = 0x1161
-
1
HANGUL_VCOUNT = 21
-
1
HANGUL_TBASE = 0x11a7
-
1
HANGUL_TCOUNT = 28
-
1
HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT # 588
-
1
HANGUL_SCOUNT = HANGUL_LCOUNT * HANGUL_NCOUNT # 11172
-
-
1
UNICODE_DATA_COMBINING_CLASS = 0
-
1
UNICODE_DATA_EXCLUSION = 1
-
1
UNICODE_DATA_CANONICAL = 2
-
1
UNICODE_DATA_COMPATIBILITY = 3
-
1
UNICODE_DATA_UPPERCASE = 4
-
1
UNICODE_DATA_LOWERCASE = 5
-
1
UNICODE_DATA_TITLECASE = 6
-
-
1
begin
-
1
if defined?(FakeFS)
-
fakefs_state = FakeFS.activated?
-
FakeFS.deactivate!
-
end
-
# This is a sparse Unicode table. Codepoints without entries are
-
# assumed to have the value: [0, 0, nil, nil, nil, nil, nil]
-
1
UNICODE_DATA = File.open(UNICODE_TABLE, "rb") do |file|
-
1
Marshal.load(file.read)
-
end
-
ensure
-
1
if defined?(FakeFS)
-
FakeFS.activate! if fakefs_state
-
end
-
end
-
-
1
COMPOSITION_TABLE = {}
-
1
for codepoint, data in UNICODE_DATA
-
4233
canonical = data[UNICODE_DATA_CANONICAL]
-
4233
exclusion = data[UNICODE_DATA_EXCLUSION]
-
-
4233
if canonical && exclusion == 0
-
918
COMPOSITION_TABLE[canonical.unpack("C*")] = codepoint
-
end
-
end
-
-
1
UNICODE_MAX_LENGTH = 256
-
1
ACE_MAX_LENGTH = 256
-
-
1
PUNYCODE_BASE = 36
-
1
PUNYCODE_TMIN = 1
-
1
PUNYCODE_TMAX = 26
-
1
PUNYCODE_SKEW = 38
-
1
PUNYCODE_DAMP = 700
-
1
PUNYCODE_INITIAL_BIAS = 72
-
1
PUNYCODE_INITIAL_N = 0x80
-
1
PUNYCODE_DELIMITER = 0x2D
-
-
1
PUNYCODE_MAXINT = 1 << 64
-
-
1
PUNYCODE_PRINT_ASCII =
-
"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" +
-
"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" +
-
" !\"\#$%&'()*+,-./" +
-
"0123456789:;<=>?" +
-
"@ABCDEFGHIJKLMNO" +
-
"PQRSTUVWXYZ[\\]^_" +
-
"`abcdefghijklmno" +
-
"pqrstuvwxyz{|}~\n"
-
-
# Input is invalid.
-
1
class PunycodeBadInput < StandardError; end
-
# Output would exceed the space provided.
-
1
class PunycodeBigOutput < StandardError; end
-
# Input needs wider integers to process.
-
1
class PunycodeOverflow < StandardError; end
-
-
1
def self.punycode_encode(unicode)
-
unicode = unicode.to_s unless unicode.is_a?(String)
-
input = unicode.unpack("U*")
-
output = [0] * (ACE_MAX_LENGTH + 1)
-
input_length = input.size
-
output_length = [ACE_MAX_LENGTH]
-
-
# Initialize the state
-
n = PUNYCODE_INITIAL_N
-
delta = out = 0
-
max_out = output_length[0]
-
bias = PUNYCODE_INITIAL_BIAS
-
-
# Handle the basic code points:
-
input_length.times do |j|
-
if punycode_basic?(input[j])
-
if max_out - out < 2
-
raise PunycodeBigOutput,
-
"Output would exceed the space provided."
-
end
-
output[out] = input[j]
-
out += 1
-
end
-
end
-
-
h = b = out
-
-
# h is the number of code points that have been handled, b is the
-
# number of basic code points, and out is the number of characters
-
# that have been output.
-
-
if b > 0
-
output[out] = PUNYCODE_DELIMITER
-
out += 1
-
end
-
-
# Main encoding loop:
-
-
while h < input_length
-
# All non-basic code points < n have been
-
# handled already. Find the next larger one:
-
-
m = PUNYCODE_MAXINT
-
input_length.times do |j|
-
m = input[j] if (n...m) === input[j]
-
end
-
-
# Increase delta enough to advance the decoder's
-
# <n,i> state to <m,0>, but guard against overflow:
-
-
if m - n > (PUNYCODE_MAXINT - delta) / (h + 1)
-
raise PunycodeOverflow, "Input needs wider integers to process."
-
end
-
delta += (m - n) * (h + 1)
-
n = m
-
-
input_length.times do |j|
-
# Punycode does not need to check whether input[j] is basic:
-
if input[j] < n
-
delta += 1
-
if delta == 0
-
raise PunycodeOverflow,
-
"Input needs wider integers to process."
-
end
-
end
-
-
if input[j] == n
-
# Represent delta as a generalized variable-length integer:
-
-
q = delta; k = PUNYCODE_BASE
-
while true
-
if out >= max_out
-
raise PunycodeBigOutput,
-
"Output would exceed the space provided."
-
end
-
t = (
-
if k <= bias
-
PUNYCODE_TMIN
-
elsif k >= bias + PUNYCODE_TMAX
-
PUNYCODE_TMAX
-
else
-
k - bias
-
end
-
)
-
break if q < t
-
output[out] =
-
punycode_encode_digit(t + (q - t) % (PUNYCODE_BASE - t))
-
out += 1
-
q = (q - t) / (PUNYCODE_BASE - t)
-
k += PUNYCODE_BASE
-
end
-
-
output[out] = punycode_encode_digit(q)
-
out += 1
-
bias = punycode_adapt(delta, h + 1, h == b)
-
delta = 0
-
h += 1
-
end
-
end
-
-
delta += 1
-
n += 1
-
end
-
-
output_length[0] = out
-
-
outlen = out
-
outlen.times do |j|
-
c = output[j]
-
unless c >= 0 && c <= 127
-
raise StandardError, "Invalid output char."
-
end
-
unless PUNYCODE_PRINT_ASCII[c]
-
raise PunycodeBadInput, "Input is invalid."
-
end
-
end
-
-
output[0..outlen].map { |x| x.chr }.join("").sub(/\0+\z/, "")
-
end
-
2
(class <<self; private :punycode_encode; end)
-
-
1
def self.punycode_decode(punycode)
-
input = []
-
output = []
-
-
if ACE_MAX_LENGTH * 2 < punycode.size
-
raise PunycodeBigOutput, "Output would exceed the space provided."
-
end
-
punycode.each_byte do |c|
-
unless c >= 0 && c <= 127
-
raise PunycodeBadInput, "Input is invalid."
-
end
-
input.push(c)
-
end
-
-
input_length = input.length
-
output_length = [UNICODE_MAX_LENGTH]
-
-
# Initialize the state
-
n = PUNYCODE_INITIAL_N
-
-
out = i = 0
-
max_out = output_length[0]
-
bias = PUNYCODE_INITIAL_BIAS
-
-
# Handle the basic code points: Let b be the number of input code
-
# points before the last delimiter, or 0 if there is none, then
-
# copy the first b code points to the output.
-
-
b = 0
-
input_length.times do |j|
-
b = j if punycode_delimiter?(input[j])
-
end
-
if b > max_out
-
raise PunycodeBigOutput, "Output would exceed the space provided."
-
end
-
-
b.times do |j|
-
unless punycode_basic?(input[j])
-
raise PunycodeBadInput, "Input is invalid."
-
end
-
output[out] = input[j]
-
out+=1
-
end
-
-
# Main decoding loop: Start just after the last delimiter if any
-
# basic code points were copied; start at the beginning otherwise.
-
-
in_ = b > 0 ? b + 1 : 0
-
while in_ < input_length
-
-
# in_ is the index of the next character to be consumed, and
-
# out is the number of code points in the output array.
-
-
# Decode a generalized variable-length integer into delta,
-
# which gets added to i. The overflow checking is easier
-
# if we increase i as we go, then subtract off its starting
-
# value at the end to obtain delta.
-
-
oldi = i; w = 1; k = PUNYCODE_BASE
-
while true
-
if in_ >= input_length
-
raise PunycodeBadInput, "Input is invalid."
-
end
-
digit = punycode_decode_digit(input[in_])
-
in_+=1
-
if digit >= PUNYCODE_BASE
-
raise PunycodeBadInput, "Input is invalid."
-
end
-
if digit > (PUNYCODE_MAXINT - i) / w
-
raise PunycodeOverflow, "Input needs wider integers to process."
-
end
-
i += digit * w
-
t = (
-
if k <= bias
-
PUNYCODE_TMIN
-
elsif k >= bias + PUNYCODE_TMAX
-
PUNYCODE_TMAX
-
else
-
k - bias
-
end
-
)
-
break if digit < t
-
if w > PUNYCODE_MAXINT / (PUNYCODE_BASE - t)
-
raise PunycodeOverflow, "Input needs wider integers to process."
-
end
-
w *= PUNYCODE_BASE - t
-
k += PUNYCODE_BASE
-
end
-
-
bias = punycode_adapt(i - oldi, out + 1, oldi == 0)
-
-
# I was supposed to wrap around from out + 1 to 0,
-
# incrementing n each time, so we'll fix that now:
-
-
if i / (out + 1) > PUNYCODE_MAXINT - n
-
raise PunycodeOverflow, "Input needs wider integers to process."
-
end
-
n += i / (out + 1)
-
i %= out + 1
-
-
# Insert n at position i of the output:
-
-
# not needed for Punycode:
-
# raise PUNYCODE_INVALID_INPUT if decode_digit(n) <= base
-
if out >= max_out
-
raise PunycodeBigOutput, "Output would exceed the space provided."
-
end
-
-
#memmove(output + i + 1, output + i, (out - i) * sizeof *output)
-
output[i + 1, out - i] = output[i, out - i]
-
output[i] = n
-
i += 1
-
-
out += 1
-
end
-
-
output_length[0] = out
-
-
output.pack("U*")
-
end
-
2
(class <<self; private :punycode_decode; end)
-
-
1
def self.punycode_basic?(codepoint)
-
codepoint < 0x80
-
end
-
2
(class <<self; private :punycode_basic?; end)
-
-
1
def self.punycode_delimiter?(codepoint)
-
codepoint == PUNYCODE_DELIMITER
-
end
-
2
(class <<self; private :punycode_delimiter?; end)
-
-
1
def self.punycode_encode_digit(d)
-
d + 22 + 75 * ((d < 26) ? 1 : 0)
-
end
-
2
(class <<self; private :punycode_encode_digit; end)
-
-
# Returns the numeric value of a basic codepoint
-
# (for use in representing integers) in the range 0 to
-
# base - 1, or PUNYCODE_BASE if codepoint does not represent a value.
-
1
def self.punycode_decode_digit(codepoint)
-
if codepoint - 48 < 10
-
codepoint - 22
-
elsif codepoint - 65 < 26
-
codepoint - 65
-
elsif codepoint - 97 < 26
-
codepoint - 97
-
else
-
PUNYCODE_BASE
-
end
-
end
-
2
(class <<self; private :punycode_decode_digit; end)
-
-
# Bias adaptation method
-
1
def self.punycode_adapt(delta, numpoints, firsttime)
-
delta = firsttime ? delta / PUNYCODE_DAMP : delta >> 1
-
# delta >> 1 is a faster way of doing delta / 2
-
delta += delta / numpoints
-
difference = PUNYCODE_BASE - PUNYCODE_TMIN
-
-
k = 0
-
while delta > (difference * PUNYCODE_TMAX) / 2
-
delta /= difference
-
k += PUNYCODE_BASE
-
end
-
-
k + (difference + 1) * delta / (delta + PUNYCODE_SKEW)
-
end
-
2
(class <<self; private :punycode_adapt; end)
-
end
-
# :startdoc:
-
end
-
# encoding:utf-8
-
#--
-
# Copyright (C) Bob Aman
-
#
-
# Licensed under the Apache License, Version 2.0 (the "License");
-
# you may not use this file except in compliance with the License.
-
# You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing, software
-
# distributed under the License is distributed on an "AS IS" BASIS,
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
# See the License for the specific language governing permissions and
-
# limitations under the License.
-
#++
-
-
-
1
require "addressable/version"
-
1
require "addressable/idna"
-
1
require "public_suffix"
-
-
##
-
# Addressable is a library for processing links and URIs.
-
1
module Addressable
-
##
-
# This is an implementation of a URI parser based on
-
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>,
-
# <a href="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>.
-
1
class URI
-
##
-
# Raised if something other than a uri is supplied.
-
1
class InvalidURIError < StandardError
-
end
-
-
##
-
# Container for the character classes specified in
-
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
-
1
module CharacterClasses
-
1
ALPHA = "a-zA-Z"
-
1
DIGIT = "0-9"
-
1
GEN_DELIMS = "\\:\\/\\?\\#\\[\\]\\@"
-
1
SUB_DELIMS = "\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\="
-
1
RESERVED = GEN_DELIMS + SUB_DELIMS
-
1
UNRESERVED = ALPHA + DIGIT + "\\-\\.\\_\\~"
-
1
PCHAR = UNRESERVED + SUB_DELIMS + "\\:\\@"
-
1
SCHEME = ALPHA + DIGIT + "\\-\\+\\."
-
1
HOST = UNRESERVED + SUB_DELIMS + "\\[\\:\\]"
-
1
AUTHORITY = PCHAR
-
1
PATH = PCHAR + "\\/"
-
1
QUERY = PCHAR + "\\/\\?"
-
1
FRAGMENT = PCHAR + "\\/\\?"
-
end
-
-
1
SLASH = '/'
-
1
EMPTY_STR = ''
-
-
1
URIREGEX = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/
-
-
1
PORT_MAPPING = {
-
"http" => 80,
-
"https" => 443,
-
"ftp" => 21,
-
"tftp" => 69,
-
"sftp" => 22,
-
"ssh" => 22,
-
"svn+ssh" => 22,
-
"telnet" => 23,
-
"nntp" => 119,
-
"gopher" => 70,
-
"wais" => 210,
-
"ldap" => 389,
-
"prospero" => 1525
-
}
-
-
##
-
# Returns a URI object based on the parsed string.
-
#
-
# @param [String, Addressable::URI, #to_str] uri
-
# The URI string to parse.
-
# No parsing is performed if the object is already an
-
# <code>Addressable::URI</code>.
-
#
-
# @return [Addressable::URI] The parsed URI.
-
1
def self.parse(uri)
-
# If we were given nil, return nil.
-
return nil unless uri
-
# If a URI object is passed, just return itself.
-
return uri.dup if uri.kind_of?(self)
-
-
# If a URI object of the Ruby standard library variety is passed,
-
# convert it to a string, then parse the string.
-
# We do the check this way because we don't want to accidentally
-
# cause a missing constant exception to be thrown.
-
if uri.class.name =~ /^URI\b/
-
uri = uri.to_s
-
end
-
-
# Otherwise, convert to a String
-
begin
-
uri = uri.to_str
-
rescue TypeError, NoMethodError
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end if not uri.is_a? String
-
-
# This Regexp supplied as an example in RFC 3986, and it works great.
-
scan = uri.scan(URIREGEX)
-
fragments = scan[0]
-
scheme = fragments[1]
-
authority = fragments[3]
-
path = fragments[4]
-
query = fragments[6]
-
fragment = fragments[8]
-
user = nil
-
password = nil
-
host = nil
-
port = nil
-
if authority != nil
-
# The Regexp above doesn't split apart the authority.
-
userinfo = authority[/^([^\[\]]*)@/, 1]
-
if userinfo != nil
-
user = userinfo.strip[/^([^:]*):?/, 1]
-
password = userinfo.strip[/:(.*)$/, 1]
-
end
-
host = authority.gsub(
-
/^([^\[\]]*)@/, EMPTY_STR
-
).gsub(
-
/:([^:@\[\]]*?)$/, EMPTY_STR
-
)
-
port = authority[/:([^:@\[\]]*?)$/, 1]
-
end
-
if port == EMPTY_STR
-
port = nil
-
end
-
-
return new(
-
:scheme => scheme,
-
:user => user,
-
:password => password,
-
:host => host,
-
:port => port,
-
:path => path,
-
:query => query,
-
:fragment => fragment
-
)
-
end
-
-
##
-
# Converts an input to a URI. The input does not have to be a valid
-
# URI — the method will use heuristics to guess what URI was intended.
-
# This is not standards-compliant, merely user-friendly.
-
#
-
# @param [String, Addressable::URI, #to_str] uri
-
# The URI string to parse.
-
# No parsing is performed if the object is already an
-
# <code>Addressable::URI</code>.
-
# @param [Hash] hints
-
# A <code>Hash</code> of hints to the heuristic parser.
-
# Defaults to <code>{:scheme => "http"}</code>.
-
#
-
# @return [Addressable::URI] The parsed URI.
-
1
def self.heuristic_parse(uri, hints={})
-
# If we were given nil, return nil.
-
return nil unless uri
-
# If a URI object is passed, just return itself.
-
return uri.dup if uri.kind_of?(self)
-
-
# If a URI object of the Ruby standard library variety is passed,
-
# convert it to a string, then parse the string.
-
# We do the check this way because we don't want to accidentally
-
# cause a missing constant exception to be thrown.
-
if uri.class.name =~ /^URI\b/
-
uri = uri.to_s
-
end
-
-
if !uri.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end
-
# Otherwise, convert to a String
-
uri = uri.to_str.dup.strip
-
hints = {
-
:scheme => "http"
-
}.merge(hints)
-
case uri
-
when /^http:\/+/
-
uri.gsub!(/^http:\/+/, "http://")
-
when /^https:\/+/
-
uri.gsub!(/^https:\/+/, "https://")
-
when /^feed:\/+http:\/+/
-
uri.gsub!(/^feed:\/+http:\/+/, "feed:http://")
-
when /^feed:\/+/
-
uri.gsub!(/^feed:\/+/, "feed://")
-
when /^file:\/+/
-
uri.gsub!(/^file:\/+/, "file:///")
-
when /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/
-
uri.gsub!(/^/, hints[:scheme] + "://")
-
end
-
match = uri.match(URIREGEX)
-
fragments = match.captures
-
authority = fragments[3]
-
if authority && authority.length > 0
-
new_authority = authority.gsub(/\\/, '/').gsub(/ /, '%20')
-
# NOTE: We want offset 4, not 3!
-
offset = match.offset(4)
-
uri[offset[0]...offset[1]] = new_authority
-
end
-
parsed = self.parse(uri)
-
if parsed.scheme =~ /^[^\/?#\.]+\.[^\/?#]+$/
-
parsed = self.parse(hints[:scheme] + "://" + uri)
-
end
-
if parsed.path.include?(".")
-
new_host = parsed.path[/^([^\/]+\.[^\/]*)/, 1]
-
if new_host
-
parsed.defer_validation do
-
new_path = parsed.path.gsub(
-
Regexp.new("^" + Regexp.escape(new_host)), EMPTY_STR)
-
parsed.host = new_host
-
parsed.path = new_path
-
parsed.scheme = hints[:scheme] unless parsed.scheme
-
end
-
end
-
end
-
return parsed
-
end
-
-
##
-
# Converts a path to a file scheme URI. If the path supplied is
-
# relative, it will be returned as a relative URI. If the path supplied
-
# is actually a non-file URI, it will parse the URI as if it had been
-
# parsed with <code>Addressable::URI.parse</code>. Handles all of the
-
# various Microsoft-specific formats for specifying paths.
-
#
-
# @param [String, Addressable::URI, #to_str] path
-
# Typically a <code>String</code> path to a file or directory, but
-
# will return a sensible return value if an absolute URI is supplied
-
# instead.
-
#
-
# @return [Addressable::URI]
-
# The parsed file scheme URI or the original URI if some other URI
-
# scheme was provided.
-
#
-
# @example
-
# base = Addressable::URI.convert_path("/absolute/path/")
-
# uri = Addressable::URI.convert_path("relative/path")
-
# (base + uri).to_s
-
# #=> "file:///absolute/path/relative/path"
-
#
-
# Addressable::URI.convert_path(
-
# "c:\\windows\\My Documents 100%20\\foo.txt"
-
# ).to_s
-
# #=> "file:///c:/windows/My%20Documents%20100%20/foo.txt"
-
#
-
# Addressable::URI.convert_path("http://example.com/").to_s
-
# #=> "http://example.com/"
-
1
def self.convert_path(path)
-
# If we were given nil, return nil.
-
return nil unless path
-
# If a URI object is passed, just return itself.
-
return path if path.kind_of?(self)
-
if !path.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{path.class} into String."
-
end
-
# Otherwise, convert to a String
-
path = path.to_str.strip
-
-
path.gsub!(/^file:\/?\/?/, EMPTY_STR) if path =~ /^file:\/?\/?/
-
path = SLASH + path if path =~ /^([a-zA-Z])[\|:]/
-
uri = self.parse(path)
-
-
if uri.scheme == nil
-
# Adjust windows-style uris
-
uri.path.gsub!(/^\/?([a-zA-Z])[\|:][\\\/]/) do
-
"/#{$1.downcase}:/"
-
end
-
uri.path.gsub!(/\\/, SLASH)
-
if File.exist?(uri.path) &&
-
File.stat(uri.path).directory?
-
uri.path.gsub!(/\/$/, EMPTY_STR)
-
uri.path = uri.path + '/'
-
end
-
-
# If the path is absolute, set the scheme and host.
-
if uri.path =~ /^\//
-
uri.scheme = "file"
-
uri.host = EMPTY_STR
-
end
-
uri.normalize!
-
end
-
-
return uri
-
end
-
-
##
-
# Joins several URIs together.
-
#
-
# @param [String, Addressable::URI, #to_str] *uris
-
# The URIs to join.
-
#
-
# @return [Addressable::URI] The joined URI.
-
#
-
# @example
-
# base = "http://example.com/"
-
# uri = Addressable::URI.parse("relative/path")
-
# Addressable::URI.join(base, uri)
-
# #=> #<Addressable::URI:0xcab390 URI:http://example.com/relative/path>
-
1
def self.join(*uris)
-
uri_objects = uris.collect do |uri|
-
if !uri.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end
-
uri.kind_of?(self) ? uri : self.parse(uri.to_str)
-
end
-
result = uri_objects.shift.dup
-
for uri in uri_objects
-
result.join!(uri)
-
end
-
return result
-
end
-
-
##
-
# Percent encodes a URI component.
-
#
-
# @param [String, #to_str] component The URI component to encode.
-
#
-
# @param [String, Regexp] character_class
-
# The characters which are not percent encoded. If a <code>String</code>
-
# is passed, the <code>String</code> must be formatted as a regular
-
# expression character class. (Do not include the surrounding square
-
# brackets.) For example, <code>"b-zB-Z0-9"</code> would cause
-
# everything but the letters 'b' through 'z' and the numbers '0' through
-
# '9' to be percent encoded. If a <code>Regexp</code> is passed, the
-
# value <code>/[^b-zB-Z0-9]/</code> would have the same effect. A set of
-
# useful <code>String</code> values may be found in the
-
# <code>Addressable::URI::CharacterClasses</code> module. The default
-
# value is the reserved plus unreserved character classes specified in
-
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
-
#
-
# @param [Regexp] upcase_encoded
-
# A string of characters that may already be percent encoded, and whose
-
# encodings should be upcased. This allows normalization of percent
-
# encodings for characters not included in the
-
# <code>character_class</code>.
-
#
-
# @return [String] The encoded component.
-
#
-
# @example
-
# Addressable::URI.encode_component("simple/example", "b-zB-Z0-9")
-
# => "simple%2Fex%61mple"
-
# Addressable::URI.encode_component("simple/example", /[^b-zB-Z0-9]/)
-
# => "simple%2Fex%61mple"
-
# Addressable::URI.encode_component(
-
# "simple/example", Addressable::URI::CharacterClasses::UNRESERVED
-
# )
-
# => "simple%2Fexample"
-
1
def self.encode_component(component, character_class=
-
CharacterClasses::RESERVED + CharacterClasses::UNRESERVED,
-
upcase_encoded='')
-
return nil if component.nil?
-
-
begin
-
if component.kind_of?(Symbol) ||
-
component.kind_of?(Numeric) ||
-
component.kind_of?(TrueClass) ||
-
component.kind_of?(FalseClass)
-
component = component.to_s
-
else
-
component = component.to_str
-
end
-
rescue TypeError, NoMethodError
-
raise TypeError, "Can't convert #{component.class} into String."
-
end if !component.is_a? String
-
-
if ![String, Regexp].include?(character_class.class)
-
raise TypeError,
-
"Expected String or Regexp, got #{character_class.inspect}"
-
end
-
if character_class.kind_of?(String)
-
character_class = /[^#{character_class}]/
-
end
-
# We can't perform regexps on invalid UTF sequences, but
-
# here we need to, so switch to ASCII.
-
component = component.dup
-
component.force_encoding(Encoding::ASCII_8BIT)
-
# Avoiding gsub! because there are edge cases with frozen strings
-
component = component.gsub(character_class) do |sequence|
-
(sequence.unpack('C*').map { |c| "%" + ("%02x" % c).upcase }).join
-
end
-
if upcase_encoded.length > 0
-
component = component.gsub(/%(#{upcase_encoded.chars.map do |char|
-
char.unpack('C*').map { |c| '%02x' % c }.join
-
end.join('|')})/i) { |s| s.upcase }
-
end
-
return component
-
end
-
-
1
class << self
-
1
alias_method :encode_component, :encode_component
-
end
-
-
##
-
# Unencodes any percent encoded characters within a URI component.
-
# This method may be used for unencoding either components or full URIs,
-
# however, it is recommended to use the <code>unencode_component</code>
-
# alias when unencoding components.
-
#
-
# @param [String, Addressable::URI, #to_str] uri
-
# The URI or component to unencode.
-
#
-
# @param [Class] return_type
-
# The type of object to return.
-
# This value may only be set to <code>String</code> or
-
# <code>Addressable::URI</code>. All other values are invalid. Defaults
-
# to <code>String</code>.
-
#
-
# @param [String] leave_encoded
-
# A string of characters to leave encoded. If a percent encoded character
-
# in this list is encountered then it will remain percent encoded.
-
#
-
# @return [String, Addressable::URI]
-
# The unencoded component or URI.
-
# The return type is determined by the <code>return_type</code>
-
# parameter.
-
1
def self.unencode(uri, return_type=String, leave_encoded='')
-
return nil if uri.nil?
-
-
begin
-
uri = uri.to_str
-
rescue NoMethodError, TypeError
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end if !uri.is_a? String
-
if ![String, ::Addressable::URI].include?(return_type)
-
raise TypeError,
-
"Expected Class (String or Addressable::URI), " +
-
"got #{return_type.inspect}"
-
end
-
uri = uri.dup
-
# Seriously, only use UTF-8. I'm really not kidding!
-
uri.force_encoding("utf-8")
-
leave_encoded.force_encoding("utf-8")
-
result = uri.gsub(/%[0-9a-f]{2}/iu) do |sequence|
-
c = sequence[1..3].to_i(16).chr
-
c.force_encoding("utf-8")
-
leave_encoded.include?(c) ? sequence : c
-
end
-
result.force_encoding("utf-8")
-
if return_type == String
-
return result
-
elsif return_type == ::Addressable::URI
-
return ::Addressable::URI.parse(result)
-
end
-
end
-
-
1
class << self
-
1
alias_method :unescape, :unencode
-
1
alias_method :unencode_component, :unencode
-
1
alias_method :unescape_component, :unencode
-
end
-
-
-
##
-
# Normalizes the encoding of a URI component.
-
#
-
# @param [String, #to_str] component The URI component to encode.
-
#
-
# @param [String, Regexp] character_class
-
# The characters which are not percent encoded. If a <code>String</code>
-
# is passed, the <code>String</code> must be formatted as a regular
-
# expression character class. (Do not include the surrounding square
-
# brackets.) For example, <code>"b-zB-Z0-9"</code> would cause
-
# everything but the letters 'b' through 'z' and the numbers '0'
-
# through '9' to be percent encoded. If a <code>Regexp</code> is passed,
-
# the value <code>/[^b-zB-Z0-9]/</code> would have the same effect. A
-
# set of useful <code>String</code> values may be found in the
-
# <code>Addressable::URI::CharacterClasses</code> module. The default
-
# value is the reserved plus unreserved character classes specified in
-
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
-
#
-
# @param [String] leave_encoded
-
# When <code>character_class</code> is a <code>String</code> then
-
# <code>leave_encoded</code> is a string of characters that should remain
-
# percent encoded while normalizing the component; if they appear percent
-
# encoded in the original component, then they will be upcased ("%2f"
-
# normalized to "%2F") but otherwise left alone.
-
#
-
# @return [String] The normalized component.
-
#
-
# @example
-
# Addressable::URI.normalize_component("simpl%65/%65xampl%65", "b-zB-Z")
-
# => "simple%2Fex%61mple"
-
# Addressable::URI.normalize_component(
-
# "simpl%65/%65xampl%65", /[^b-zB-Z]/
-
# )
-
# => "simple%2Fex%61mple"
-
# Addressable::URI.normalize_component(
-
# "simpl%65/%65xampl%65",
-
# Addressable::URI::CharacterClasses::UNRESERVED
-
# )
-
# => "simple%2Fexample"
-
# Addressable::URI.normalize_component(
-
# "one%20two%2fthree%26four",
-
# "0-9a-zA-Z &/",
-
# "/"
-
# )
-
# => "one two%2Fthree&four"
-
1
def self.normalize_component(component, character_class=
-
CharacterClasses::RESERVED + CharacterClasses::UNRESERVED,
-
leave_encoded='')
-
return nil if component.nil?
-
-
begin
-
component = component.to_str
-
rescue NoMethodError, TypeError
-
raise TypeError, "Can't convert #{component.class} into String."
-
end if !component.is_a? String
-
-
if ![String, Regexp].include?(character_class.class)
-
raise TypeError,
-
"Expected String or Regexp, got #{character_class.inspect}"
-
end
-
if character_class.kind_of?(String)
-
leave_re = if leave_encoded.length > 0
-
character_class = "#{character_class}%" unless character_class.include?('%')
-
-
"|%(?!#{leave_encoded.chars.map do |char|
-
seq = char.unpack('C*').map { |c| '%02x' % c }.join
-
[seq.upcase, seq.downcase]
-
end.flatten.join('|')})"
-
end
-
-
character_class = /[^#{character_class}]#{leave_re}/
-
end
-
# We can't perform regexps on invalid UTF sequences, but
-
# here we need to, so switch to ASCII.
-
component = component.dup
-
component.force_encoding(Encoding::ASCII_8BIT)
-
unencoded = self.unencode_component(component, String, leave_encoded)
-
begin
-
encoded = self.encode_component(
-
Addressable::IDNA.unicode_normalize_kc(unencoded),
-
character_class,
-
leave_encoded
-
)
-
rescue ArgumentError
-
encoded = self.encode_component(unencoded)
-
end
-
encoded.force_encoding(Encoding::UTF_8)
-
return encoded
-
end
-
-
##
-
# Percent encodes any special characters in the URI.
-
#
-
# @param [String, Addressable::URI, #to_str] uri
-
# The URI to encode.
-
#
-
# @param [Class] return_type
-
# The type of object to return.
-
# This value may only be set to <code>String</code> or
-
# <code>Addressable::URI</code>. All other values are invalid. Defaults
-
# to <code>String</code>.
-
#
-
# @return [String, Addressable::URI]
-
# The encoded URI.
-
# The return type is determined by the <code>return_type</code>
-
# parameter.
-
1
def self.encode(uri, return_type=String)
-
return nil if uri.nil?
-
-
begin
-
uri = uri.to_str
-
rescue NoMethodError, TypeError
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end if !uri.is_a? String
-
-
if ![String, ::Addressable::URI].include?(return_type)
-
raise TypeError,
-
"Expected Class (String or Addressable::URI), " +
-
"got #{return_type.inspect}"
-
end
-
uri_object = uri.kind_of?(self) ? uri : self.parse(uri)
-
encoded_uri = Addressable::URI.new(
-
:scheme => self.encode_component(uri_object.scheme,
-
Addressable::URI::CharacterClasses::SCHEME),
-
:authority => self.encode_component(uri_object.authority,
-
Addressable::URI::CharacterClasses::AUTHORITY),
-
:path => self.encode_component(uri_object.path,
-
Addressable::URI::CharacterClasses::PATH),
-
:query => self.encode_component(uri_object.query,
-
Addressable::URI::CharacterClasses::QUERY),
-
:fragment => self.encode_component(uri_object.fragment,
-
Addressable::URI::CharacterClasses::FRAGMENT)
-
)
-
if return_type == String
-
return encoded_uri.to_s
-
elsif return_type == ::Addressable::URI
-
return encoded_uri
-
end
-
end
-
-
1
class << self
-
1
alias_method :escape, :encode
-
end
-
-
##
-
# Normalizes the encoding of a URI. Characters within a hostname are
-
# not percent encoded to allow for internationalized domain names.
-
#
-
# @param [String, Addressable::URI, #to_str] uri
-
# The URI to encode.
-
#
-
# @param [Class] return_type
-
# The type of object to return.
-
# This value may only be set to <code>String</code> or
-
# <code>Addressable::URI</code>. All other values are invalid. Defaults
-
# to <code>String</code>.
-
#
-
# @return [String, Addressable::URI]
-
# The encoded URI.
-
# The return type is determined by the <code>return_type</code>
-
# parameter.
-
1
def self.normalized_encode(uri, return_type=String)
-
begin
-
uri = uri.to_str
-
rescue NoMethodError, TypeError
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end if !uri.is_a? String
-
-
if ![String, ::Addressable::URI].include?(return_type)
-
raise TypeError,
-
"Expected Class (String or Addressable::URI), " +
-
"got #{return_type.inspect}"
-
end
-
uri_object = uri.kind_of?(self) ? uri : self.parse(uri)
-
components = {
-
:scheme => self.unencode_component(uri_object.scheme),
-
:user => self.unencode_component(uri_object.user),
-
:password => self.unencode_component(uri_object.password),
-
:host => self.unencode_component(uri_object.host),
-
:port => (uri_object.port.nil? ? nil : uri_object.port.to_s),
-
:path => self.unencode_component(uri_object.path),
-
:query => self.unencode_component(uri_object.query),
-
:fragment => self.unencode_component(uri_object.fragment)
-
}
-
components.each do |key, value|
-
if value != nil
-
begin
-
components[key] =
-
Addressable::IDNA.unicode_normalize_kc(value.to_str)
-
rescue ArgumentError
-
# Likely a malformed UTF-8 character, skip unicode normalization
-
components[key] = value.to_str
-
end
-
end
-
end
-
encoded_uri = Addressable::URI.new(
-
:scheme => self.encode_component(components[:scheme],
-
Addressable::URI::CharacterClasses::SCHEME),
-
:user => self.encode_component(components[:user],
-
Addressable::URI::CharacterClasses::UNRESERVED),
-
:password => self.encode_component(components[:password],
-
Addressable::URI::CharacterClasses::UNRESERVED),
-
:host => components[:host],
-
:port => components[:port],
-
:path => self.encode_component(components[:path],
-
Addressable::URI::CharacterClasses::PATH),
-
:query => self.encode_component(components[:query],
-
Addressable::URI::CharacterClasses::QUERY),
-
:fragment => self.encode_component(components[:fragment],
-
Addressable::URI::CharacterClasses::FRAGMENT)
-
)
-
if return_type == String
-
return encoded_uri.to_s
-
elsif return_type == ::Addressable::URI
-
return encoded_uri
-
end
-
end
-
-
##
-
# Encodes a set of key/value pairs according to the rules for the
-
# <code>application/x-www-form-urlencoded</code> MIME type.
-
#
-
# @param [#to_hash, #to_ary] form_values
-
# The form values to encode.
-
#
-
# @param [TrueClass, FalseClass] sort
-
# Sort the key/value pairs prior to encoding.
-
# Defaults to <code>false</code>.
-
#
-
# @return [String]
-
# The encoded value.
-
1
def self.form_encode(form_values, sort=false)
-
if form_values.respond_to?(:to_hash)
-
form_values = form_values.to_hash.to_a
-
elsif form_values.respond_to?(:to_ary)
-
form_values = form_values.to_ary
-
else
-
raise TypeError, "Can't convert #{form_values.class} into Array."
-
end
-
-
form_values = form_values.inject([]) do |accu, (key, value)|
-
if value.kind_of?(Array)
-
value.each do |v|
-
accu << [key.to_s, v.to_s]
-
end
-
else
-
accu << [key.to_s, value.to_s]
-
end
-
accu
-
end
-
-
if sort
-
# Useful for OAuth and optimizing caching systems
-
form_values = form_values.sort
-
end
-
escaped_form_values = form_values.map do |(key, value)|
-
# Line breaks are CRLF pairs
-
[
-
self.encode_component(
-
key.gsub(/(\r\n|\n|\r)/, "\r\n"),
-
CharacterClasses::UNRESERVED
-
).gsub("%20", "+"),
-
self.encode_component(
-
value.gsub(/(\r\n|\n|\r)/, "\r\n"),
-
CharacterClasses::UNRESERVED
-
).gsub("%20", "+")
-
]
-
end
-
return escaped_form_values.map do |(key, value)|
-
"#{key}=#{value}"
-
end.join("&")
-
end
-
-
##
-
# Decodes a <code>String</code> according to the rules for the
-
# <code>application/x-www-form-urlencoded</code> MIME type.
-
#
-
# @param [String, #to_str] encoded_value
-
# The form values to decode.
-
#
-
# @return [Array]
-
# The decoded values.
-
# This is not a <code>Hash</code> because of the possibility for
-
# duplicate keys.
-
1
def self.form_unencode(encoded_value)
-
if !encoded_value.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{encoded_value.class} into String."
-
end
-
encoded_value = encoded_value.to_str
-
split_values = encoded_value.split("&").map do |pair|
-
pair.split("=", 2)
-
end
-
return split_values.map do |(key, value)|
-
[
-
key ? self.unencode_component(
-
key.gsub("+", "%20")).gsub(/(\r\n|\n|\r)/, "\n") : nil,
-
value ? (self.unencode_component(
-
value.gsub("+", "%20")).gsub(/(\r\n|\n|\r)/, "\n")) : nil
-
]
-
end
-
end
-
-
##
-
# Creates a new uri object from component parts.
-
#
-
# @option [String, #to_str] scheme The scheme component.
-
# @option [String, #to_str] user The user component.
-
# @option [String, #to_str] password The password component.
-
# @option [String, #to_str] userinfo
-
# The userinfo component. If this is supplied, the user and password
-
# components must be omitted.
-
# @option [String, #to_str] host The host component.
-
# @option [String, #to_str] port The port component.
-
# @option [String, #to_str] authority
-
# The authority component. If this is supplied, the user, password,
-
# userinfo, host, and port components must be omitted.
-
# @option [String, #to_str] path The path component.
-
# @option [String, #to_str] query The query component.
-
# @option [String, #to_str] fragment The fragment component.
-
#
-
# @return [Addressable::URI] The constructed URI object.
-
1
def initialize(options={})
-
if options.has_key?(:authority)
-
if (options.keys & [:userinfo, :user, :password, :host, :port]).any?
-
raise ArgumentError,
-
"Cannot specify both an authority and any of the components " +
-
"within the authority."
-
end
-
end
-
if options.has_key?(:userinfo)
-
if (options.keys & [:user, :password]).any?
-
raise ArgumentError,
-
"Cannot specify both a userinfo and either the user or password."
-
end
-
end
-
-
self.defer_validation do
-
# Bunch of crazy logic required because of the composite components
-
# like userinfo and authority.
-
self.scheme = options[:scheme] if options[:scheme]
-
self.user = options[:user] if options[:user]
-
self.password = options[:password] if options[:password]
-
self.userinfo = options[:userinfo] if options[:userinfo]
-
self.host = options[:host] if options[:host]
-
self.port = options[:port] if options[:port]
-
self.authority = options[:authority] if options[:authority]
-
self.path = options[:path] if options[:path]
-
self.query = options[:query] if options[:query]
-
self.query_values = options[:query_values] if options[:query_values]
-
self.fragment = options[:fragment] if options[:fragment]
-
end
-
self.to_s
-
end
-
-
##
-
# Freeze URI, initializing instance variables.
-
#
-
# @return [Addressable::URI] The frozen URI object.
-
1
def freeze
-
self.normalized_scheme
-
self.normalized_user
-
self.normalized_password
-
self.normalized_userinfo
-
self.normalized_host
-
self.normalized_port
-
self.normalized_authority
-
self.normalized_site
-
self.normalized_path
-
self.normalized_query
-
self.normalized_fragment
-
self.hash
-
super
-
end
-
-
##
-
# The scheme component for this URI.
-
#
-
# @return [String] The scheme component.
-
1
def scheme
-
return defined?(@scheme) ? @scheme : nil
-
end
-
-
##
-
# The scheme component for this URI, normalized.
-
#
-
# @return [String] The scheme component, normalized.
-
1
def normalized_scheme
-
return nil unless self.scheme
-
@normalized_scheme ||= begin
-
if self.scheme =~ /^\s*ssh\+svn\s*$/i
-
"svn+ssh"
-
else
-
Addressable::URI.normalize_component(
-
self.scheme.strip.downcase,
-
Addressable::URI::CharacterClasses::SCHEME
-
)
-
end
-
end
-
# All normalized values should be UTF-8
-
@normalized_scheme.force_encoding(Encoding::UTF_8) if @normalized_scheme
-
@normalized_scheme
-
end
-
-
##
-
# Sets the scheme component for this URI.
-
#
-
# @param [String, #to_str] new_scheme The new scheme component.
-
1
def scheme=(new_scheme)
-
if new_scheme && !new_scheme.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_scheme.class} into String."
-
elsif new_scheme
-
new_scheme = new_scheme.to_str
-
end
-
if new_scheme && new_scheme !~ /\A[a-z][a-z0-9\.\+\-]*\z/i
-
raise InvalidURIError, "Invalid scheme format: #{new_scheme}"
-
end
-
@scheme = new_scheme
-
@scheme = nil if @scheme.to_s.strip.empty?
-
-
# Reset dependent values
-
remove_instance_variable(:@normalized_scheme) if defined?(@normalized_scheme)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The user component for this URI.
-
#
-
# @return [String] The user component.
-
1
def user
-
return defined?(@user) ? @user : nil
-
end
-
-
##
-
# The user component for this URI, normalized.
-
#
-
# @return [String] The user component, normalized.
-
1
def normalized_user
-
return nil unless self.user
-
return @normalized_user if defined?(@normalized_user)
-
@normalized_user ||= begin
-
if normalized_scheme =~ /https?/ && self.user.strip.empty? &&
-
(!self.password || self.password.strip.empty?)
-
nil
-
else
-
Addressable::URI.normalize_component(
-
self.user.strip,
-
Addressable::URI::CharacterClasses::UNRESERVED
-
)
-
end
-
end
-
# All normalized values should be UTF-8
-
@normalized_user.force_encoding(Encoding::UTF_8) if @normalized_user
-
@normalized_user
-
end
-
-
##
-
# Sets the user component for this URI.
-
#
-
# @param [String, #to_str] new_user The new user component.
-
1
def user=(new_user)
-
if new_user && !new_user.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_user.class} into String."
-
end
-
@user = new_user ? new_user.to_str : nil
-
-
# You can't have a nil user with a non-nil password
-
if password != nil
-
@user = EMPTY_STR if @user.nil?
-
end
-
-
# Reset dependent values
-
remove_instance_variable(:@userinfo) if defined?(@userinfo)
-
remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo)
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_instance_variable(:@normalized_user) if defined?(@normalized_user)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The password component for this URI.
-
#
-
# @return [String] The password component.
-
1
def password
-
return defined?(@password) ? @password : nil
-
end
-
-
##
-
# The password component for this URI, normalized.
-
#
-
# @return [String] The password component, normalized.
-
1
def normalized_password
-
return nil unless self.password
-
return @normalized_password if defined?(@normalized_password)
-
@normalized_password ||= begin
-
if self.normalized_scheme =~ /https?/ && self.password.strip.empty? &&
-
(!self.user || self.user.strip.empty?)
-
nil
-
else
-
Addressable::URI.normalize_component(
-
self.password.strip,
-
Addressable::URI::CharacterClasses::UNRESERVED
-
)
-
end
-
end
-
# All normalized values should be UTF-8
-
if @normalized_password
-
@normalized_password.force_encoding(Encoding::UTF_8)
-
end
-
@normalized_password
-
end
-
-
##
-
# Sets the password component for this URI.
-
#
-
# @param [String, #to_str] new_password The new password component.
-
1
def password=(new_password)
-
if new_password && !new_password.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_password.class} into String."
-
end
-
@password = new_password ? new_password.to_str : nil
-
-
# You can't have a nil user with a non-nil password
-
@password ||= nil
-
@user ||= nil
-
if @password != nil
-
@user = EMPTY_STR if @user.nil?
-
end
-
-
# Reset dependent values
-
remove_instance_variable(:@userinfo) if defined?(@userinfo)
-
remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo)
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_instance_variable(:@normalized_password) if defined?(@normalized_password)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The userinfo component for this URI.
-
# Combines the user and password components.
-
#
-
# @return [String] The userinfo component.
-
1
def userinfo
-
current_user = self.user
-
current_password = self.password
-
(current_user || current_password) && @userinfo ||= begin
-
if current_user && current_password
-
"#{current_user}:#{current_password}"
-
elsif current_user && !current_password
-
"#{current_user}"
-
end
-
end
-
end
-
-
##
-
# The userinfo component for this URI, normalized.
-
#
-
# @return [String] The userinfo component, normalized.
-
1
def normalized_userinfo
-
return nil unless self.userinfo
-
return @normalized_userinfo if defined?(@normalized_userinfo)
-
@normalized_userinfo ||= begin
-
current_user = self.normalized_user
-
current_password = self.normalized_password
-
if !current_user && !current_password
-
nil
-
elsif current_user && current_password
-
"#{current_user}:#{current_password}"
-
elsif current_user && !current_password
-
"#{current_user}"
-
end
-
end
-
# All normalized values should be UTF-8
-
if @normalized_userinfo
-
@normalized_userinfo.force_encoding(Encoding::UTF_8)
-
end
-
@normalized_userinfo
-
end
-
-
##
-
# Sets the userinfo component for this URI.
-
#
-
# @param [String, #to_str] new_userinfo The new userinfo component.
-
1
def userinfo=(new_userinfo)
-
if new_userinfo && !new_userinfo.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_userinfo.class} into String."
-
end
-
new_user, new_password = if new_userinfo
-
[
-
new_userinfo.to_str.strip[/^(.*):/, 1],
-
new_userinfo.to_str.strip[/:(.*)$/, 1]
-
]
-
else
-
[nil, nil]
-
end
-
-
# Password assigned first to ensure validity in case of nil
-
self.password = new_password
-
self.user = new_user
-
-
# Reset dependent values
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The host component for this URI.
-
#
-
# @return [String] The host component.
-
1
def host
-
return defined?(@host) ? @host : nil
-
end
-
-
##
-
# The host component for this URI, normalized.
-
#
-
# @return [String] The host component, normalized.
-
1
def normalized_host
-
return nil unless self.host
-
@normalized_host ||= begin
-
if !self.host.strip.empty?
-
result = ::Addressable::IDNA.to_ascii(
-
URI.unencode_component(self.host.strip.downcase)
-
)
-
if result =~ /[^\.]\.$/
-
# Single trailing dots are unnecessary.
-
result = result[0...-1]
-
end
-
result = Addressable::URI.normalize_component(
-
result,
-
CharacterClasses::HOST)
-
result
-
else
-
EMPTY_STR
-
end
-
end
-
# All normalized values should be UTF-8
-
@normalized_host.force_encoding(Encoding::UTF_8) if @normalized_host
-
@normalized_host
-
end
-
-
##
-
# Sets the host component for this URI.
-
#
-
# @param [String, #to_str] new_host The new host component.
-
1
def host=(new_host)
-
if new_host && !new_host.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_host.class} into String."
-
end
-
@host = new_host ? new_host.to_str : nil
-
-
# Reset dependent values
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_instance_variable(:@normalized_host) if defined?(@normalized_host)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# This method is same as URI::Generic#host except
-
# brackets for IPv6 (and 'IPvFuture') addresses are removed.
-
#
-
# @see Addressable::URI#host
-
#
-
# @return [String] The hostname for this URI.
-
1
def hostname
-
v = self.host
-
/\A\[(.*)\]\z/ =~ v ? $1 : v
-
end
-
-
##
-
# This method is same as URI::Generic#host= except
-
# the argument can be a bare IPv6 address (or 'IPvFuture').
-
#
-
# @see Addressable::URI#host=
-
#
-
# @param [String, #to_str] new_hostname The new hostname for this URI.
-
1
def hostname=(new_hostname)
-
if new_hostname &&
-
(new_hostname.respond_to?(:ipv4?) || new_hostname.respond_to?(:ipv6?))
-
new_hostname = new_hostname.to_s
-
elsif new_hostname && !new_hostname.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_hostname.class} into String."
-
end
-
v = new_hostname ? new_hostname.to_str : nil
-
v = "[#{v}]" if /\A\[.*\]\z/ !~ v && /:/ =~ v
-
self.host = v
-
end
-
-
##
-
# Returns the top-level domain for this host.
-
#
-
# @example
-
# Addressable::URI.parse("www.example.co.uk").tld # => "co.uk"
-
1
def tld
-
PublicSuffix.parse(self.host, ignore_private: true).tld
-
end
-
-
##
-
# Returns the public suffix domain for this host.
-
#
-
# @example
-
# Addressable::URI.parse("www.example.co.uk").domain # => "example.co.uk"
-
1
def domain
-
PublicSuffix.domain(self.host, ignore_private: true)
-
end
-
-
##
-
# The authority component for this URI.
-
# Combines the user, password, host, and port components.
-
#
-
# @return [String] The authority component.
-
1
def authority
-
self.host && @authority ||= begin
-
authority = String.new
-
if self.userinfo != nil
-
authority << "#{self.userinfo}@"
-
end
-
authority << self.host
-
if self.port != nil
-
authority << ":#{self.port}"
-
end
-
authority
-
end
-
end
-
-
##
-
# The authority component for this URI, normalized.
-
#
-
# @return [String] The authority component, normalized.
-
1
def normalized_authority
-
return nil unless self.authority
-
@normalized_authority ||= begin
-
authority = String.new
-
if self.normalized_userinfo != nil
-
authority << "#{self.normalized_userinfo}@"
-
end
-
authority << self.normalized_host
-
if self.normalized_port != nil
-
authority << ":#{self.normalized_port}"
-
end
-
authority
-
end
-
# All normalized values should be UTF-8
-
if @normalized_authority
-
@normalized_authority.force_encoding(Encoding::UTF_8)
-
end
-
@normalized_authority
-
end
-
-
##
-
# Sets the authority component for this URI.
-
#
-
# @param [String, #to_str] new_authority The new authority component.
-
1
def authority=(new_authority)
-
if new_authority
-
if !new_authority.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_authority.class} into String."
-
end
-
new_authority = new_authority.to_str
-
new_userinfo = new_authority[/^([^\[\]]*)@/, 1]
-
if new_userinfo
-
new_user = new_userinfo.strip[/^([^:]*):?/, 1]
-
new_password = new_userinfo.strip[/:(.*)$/, 1]
-
end
-
new_host = new_authority.gsub(
-
/^([^\[\]]*)@/, EMPTY_STR
-
).gsub(
-
/:([^:@\[\]]*?)$/, EMPTY_STR
-
)
-
new_port =
-
new_authority[/:([^:@\[\]]*?)$/, 1]
-
end
-
-
# Password assigned first to ensure validity in case of nil
-
self.password = defined?(new_password) ? new_password : nil
-
self.user = defined?(new_user) ? new_user : nil
-
self.host = defined?(new_host) ? new_host : nil
-
self.port = defined?(new_port) ? new_port : nil
-
-
# Reset dependent values
-
remove_instance_variable(:@userinfo) if defined?(@userinfo)
-
remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The origin for this URI, serialized to ASCII, as per
-
# RFC 6454, section 6.2.
-
#
-
# @return [String] The serialized origin.
-
1
def origin
-
if self.scheme && self.authority
-
if self.normalized_port
-
"#{self.normalized_scheme}://#{self.normalized_host}" +
-
":#{self.normalized_port}"
-
else
-
"#{self.normalized_scheme}://#{self.normalized_host}"
-
end
-
else
-
"null"
-
end
-
end
-
-
##
-
# Sets the origin for this URI, serialized to ASCII, as per
-
# RFC 6454, section 6.2. This assignment will reset the `userinfo`
-
# component.
-
#
-
# @param [String, #to_str] new_origin The new origin component.
-
1
def origin=(new_origin)
-
if new_origin
-
if !new_origin.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_origin.class} into String."
-
end
-
new_origin = new_origin.to_str
-
new_scheme = new_origin[/^([^:\/?#]+):\/\//, 1]
-
unless new_scheme
-
raise InvalidURIError, 'An origin cannot omit the scheme.'
-
end
-
new_host = new_origin[/:\/\/([^\/?#:]+)/, 1]
-
unless new_host
-
raise InvalidURIError, 'An origin cannot omit the host.'
-
end
-
new_port = new_origin[/:([^:@\[\]\/]*?)$/, 1]
-
end
-
-
self.scheme = defined?(new_scheme) ? new_scheme : nil
-
self.host = defined?(new_host) ? new_host : nil
-
self.port = defined?(new_port) ? new_port : nil
-
self.userinfo = nil
-
-
# Reset dependent values
-
remove_instance_variable(:@userinfo) if defined?(@userinfo)
-
remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo)
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_instance_variable(:@normalized_authority) if defined?(@normalized_authority)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
# Returns an array of known ip-based schemes. These schemes typically
-
# use a similar URI form:
-
# <code>//<user>:<password>@<host>:<port>/<url-path></code>
-
1
def self.ip_based_schemes
-
return self.port_mapping.keys
-
end
-
-
# Returns a hash of common IP-based schemes and their default port
-
# numbers. Adding new schemes to this hash, as necessary, will allow
-
# for better URI normalization.
-
1
def self.port_mapping
-
PORT_MAPPING
-
end
-
-
##
-
# The port component for this URI.
-
# This is the port number actually given in the URI. This does not
-
# infer port numbers from default values.
-
#
-
# @return [Integer] The port component.
-
1
def port
-
return defined?(@port) ? @port : nil
-
end
-
-
##
-
# The port component for this URI, normalized.
-
#
-
# @return [Integer] The port component, normalized.
-
1
def normalized_port
-
return nil unless self.port
-
return @normalized_port if defined?(@normalized_port)
-
@normalized_port ||= begin
-
if URI.port_mapping[self.normalized_scheme] == self.port
-
nil
-
else
-
self.port
-
end
-
end
-
end
-
-
##
-
# Sets the port component for this URI.
-
#
-
# @param [String, Integer, #to_s] new_port The new port component.
-
1
def port=(new_port)
-
if new_port != nil && new_port.respond_to?(:to_str)
-
new_port = Addressable::URI.unencode_component(new_port.to_str)
-
end
-
-
if new_port.respond_to?(:valid_encoding?) && !new_port.valid_encoding?
-
raise InvalidURIError, "Invalid encoding in port"
-
end
-
-
if new_port != nil && !(new_port.to_s =~ /^\d+$/)
-
raise InvalidURIError,
-
"Invalid port number: #{new_port.inspect}"
-
end
-
-
@port = new_port.to_s.to_i
-
@port = nil if @port == 0
-
-
# Reset dependent values
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_instance_variable(:@normalized_port) if defined?(@normalized_port)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The inferred port component for this URI.
-
# This method will normalize to the default port for the URI's scheme if
-
# the port isn't explicitly specified in the URI.
-
#
-
# @return [Integer] The inferred port component.
-
1
def inferred_port
-
if self.port.to_i == 0
-
self.default_port
-
else
-
self.port.to_i
-
end
-
end
-
-
##
-
# The default port for this URI's scheme.
-
# This method will always returns the default port for the URI's scheme
-
# regardless of the presence of an explicit port in the URI.
-
#
-
# @return [Integer] The default port.
-
1
def default_port
-
URI.port_mapping[self.scheme.strip.downcase] if self.scheme
-
end
-
-
##
-
# The combination of components that represent a site.
-
# Combines the scheme, user, password, host, and port components.
-
# Primarily useful for HTTP and HTTPS.
-
#
-
# For example, <code>"http://example.com/path?query"</code> would have a
-
# <code>site</code> value of <code>"http://example.com"</code>.
-
#
-
# @return [String] The components that identify a site.
-
1
def site
-
(self.scheme || self.authority) && @site ||= begin
-
site_string = ""
-
site_string << "#{self.scheme}:" if self.scheme != nil
-
site_string << "//#{self.authority}" if self.authority != nil
-
site_string
-
end
-
end
-
-
##
-
# The normalized combination of components that represent a site.
-
# Combines the scheme, user, password, host, and port components.
-
# Primarily useful for HTTP and HTTPS.
-
#
-
# For example, <code>"http://example.com/path?query"</code> would have a
-
# <code>site</code> value of <code>"http://example.com"</code>.
-
#
-
# @return [String] The normalized components that identify a site.
-
1
def normalized_site
-
return nil unless self.site
-
@normalized_site ||= begin
-
site_string = ""
-
if self.normalized_scheme != nil
-
site_string << "#{self.normalized_scheme}:"
-
end
-
if self.normalized_authority != nil
-
site_string << "//#{self.normalized_authority}"
-
end
-
site_string
-
end
-
# All normalized values should be UTF-8
-
@normalized_site.force_encoding(Encoding::UTF_8) if @normalized_site
-
@normalized_site
-
end
-
-
##
-
# Sets the site value for this URI.
-
#
-
# @param [String, #to_str] new_site The new site value.
-
1
def site=(new_site)
-
if new_site
-
if !new_site.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_site.class} into String."
-
end
-
new_site = new_site.to_str
-
# These two regular expressions derived from the primary parsing
-
# expression
-
self.scheme = new_site[/^(?:([^:\/?#]+):)?(?:\/\/(?:[^\/?#]*))?$/, 1]
-
self.authority = new_site[
-
/^(?:(?:[^:\/?#]+):)?(?:\/\/([^\/?#]*))?$/, 1
-
]
-
else
-
self.scheme = nil
-
self.authority = nil
-
end
-
end
-
-
##
-
# The path component for this URI.
-
#
-
# @return [String] The path component.
-
1
def path
-
return defined?(@path) ? @path : EMPTY_STR
-
end
-
-
1
NORMPATH = /^(?!\/)[^\/:]*:.*$/
-
##
-
# The path component for this URI, normalized.
-
#
-
# @return [String] The path component, normalized.
-
1
def normalized_path
-
@normalized_path ||= begin
-
path = self.path.to_s
-
if self.scheme == nil && path =~ NORMPATH
-
# Relative paths with colons in the first segment are ambiguous.
-
path = path.sub(":", "%2F")
-
end
-
# String#split(delimeter, -1) uses the more strict splitting behavior
-
# found by default in Python.
-
result = path.strip.split(SLASH, -1).map do |segment|
-
Addressable::URI.normalize_component(
-
segment,
-
Addressable::URI::CharacterClasses::PCHAR
-
)
-
end.join(SLASH)
-
-
result = URI.normalize_path(result)
-
if result.empty? &&
-
["http", "https", "ftp", "tftp"].include?(self.normalized_scheme)
-
result = SLASH
-
end
-
result
-
end
-
# All normalized values should be UTF-8
-
@normalized_path.force_encoding(Encoding::UTF_8) if @normalized_path
-
@normalized_path
-
end
-
-
##
-
# Sets the path component for this URI.
-
#
-
# @param [String, #to_str] new_path The new path component.
-
1
def path=(new_path)
-
if new_path && !new_path.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_path.class} into String."
-
end
-
@path = (new_path || EMPTY_STR).to_str
-
if !@path.empty? && @path[0..0] != SLASH && host != nil
-
@path = "/#{@path}"
-
end
-
-
# Reset dependent values
-
remove_instance_variable(:@normalized_path) if defined?(@normalized_path)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The basename, if any, of the file in the path component.
-
#
-
# @return [String] The path's basename.
-
1
def basename
-
# Path cannot be nil
-
return File.basename(self.path).gsub(/;[^\/]*$/, EMPTY_STR)
-
end
-
-
##
-
# The extname, if any, of the file in the path component.
-
# Empty string if there is no extension.
-
#
-
# @return [String] The path's extname.
-
1
def extname
-
return nil unless self.path
-
return File.extname(self.basename)
-
end
-
-
##
-
# The query component for this URI.
-
#
-
# @return [String] The query component.
-
1
def query
-
return defined?(@query) ? @query : nil
-
end
-
-
##
-
# The query component for this URI, normalized.
-
#
-
# @return [String] The query component, normalized.
-
1
def normalized_query(*flags)
-
return nil unless self.query
-
return @normalized_query if defined?(@normalized_query)
-
@normalized_query ||= begin
-
modified_query_class = Addressable::URI::CharacterClasses::QUERY.dup
-
# Make sure possible key-value pair delimiters are escaped.
-
modified_query_class.sub!("\\&", "").sub!("\\;", "")
-
pairs = (self.query || "").split("&", -1)
-
pairs.sort! if flags.include?(:sorted)
-
component = pairs.map do |pair|
-
Addressable::URI.normalize_component(pair, modified_query_class, "+")
-
end.join("&")
-
component == "" ? nil : component
-
end
-
# All normalized values should be UTF-8
-
@normalized_query.force_encoding(Encoding::UTF_8) if @normalized_query
-
@normalized_query
-
end
-
-
##
-
# Sets the query component for this URI.
-
#
-
# @param [String, #to_str] new_query The new query component.
-
1
def query=(new_query)
-
if new_query && !new_query.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_query.class} into String."
-
end
-
@query = new_query ? new_query.to_str : nil
-
-
# Reset dependent values
-
remove_instance_variable(:@normalized_query) if defined?(@normalized_query)
-
remove_composite_values
-
end
-
-
##
-
# Converts the query component to a Hash value.
-
#
-
# @param [Class] return_type The return type desired. Value must be either
-
# `Hash` or `Array`.
-
#
-
# @return [Hash, Array, nil] The query string parsed as a Hash or Array
-
# or nil if the query string is blank.
-
#
-
# @example
-
# Addressable::URI.parse("?one=1&two=2&three=3").query_values
-
# #=> {"one" => "1", "two" => "2", "three" => "3"}
-
# Addressable::URI.parse("?one=two&one=three").query_values(Array)
-
# #=> [["one", "two"], ["one", "three"]]
-
# Addressable::URI.parse("?one=two&one=three").query_values(Hash)
-
# #=> {"one" => "three"}
-
# Addressable::URI.parse("?").query_values
-
# #=> {}
-
# Addressable::URI.parse("").query_values
-
# #=> nil
-
1
def query_values(return_type=Hash)
-
empty_accumulator = Array == return_type ? [] : {}
-
if return_type != Hash && return_type != Array
-
raise ArgumentError, "Invalid return type. Must be Hash or Array."
-
end
-
return nil if self.query == nil
-
split_query = self.query.split("&").map do |pair|
-
pair.split("=", 2) if pair && !pair.empty?
-
end.compact
-
return split_query.inject(empty_accumulator.dup) do |accu, pair|
-
# I'd rather use key/value identifiers instead of array lookups,
-
# but in this case I really want to maintain the exact pair structure,
-
# so it's best to make all changes in-place.
-
pair[0] = URI.unencode_component(pair[0])
-
if pair[1].respond_to?(:to_str)
-
# I loathe the fact that I have to do this. Stupid HTML 4.01.
-
# Treating '+' as a space was just an unbelievably bad idea.
-
# There was nothing wrong with '%20'!
-
# If it ain't broke, don't fix it!
-
pair[1] = URI.unencode_component(pair[1].to_str.gsub(/\+/, " "))
-
end
-
if return_type == Hash
-
accu[pair[0]] = pair[1]
-
else
-
accu << pair
-
end
-
accu
-
end
-
end
-
-
##
-
# Sets the query component for this URI from a Hash object.
-
# An empty Hash or Array will result in an empty query string.
-
#
-
# @param [Hash, #to_hash, Array] new_query_values The new query values.
-
#
-
# @example
-
# uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
-
# uri.query
-
# # => "a=a&b=c&b=d&b=e"
-
# uri.query_values = [['a', 'a'], ['b', 'c'], ['b', 'd'], ['b', 'e']]
-
# uri.query
-
# # => "a=a&b=c&b=d&b=e"
-
# uri.query_values = [['a', 'a'], ['b', ['c', 'd', 'e']]]
-
# uri.query
-
# # => "a=a&b=c&b=d&b=e"
-
# uri.query_values = [['flag'], ['key', 'value']]
-
# uri.query
-
# # => "flag&key=value"
-
1
def query_values=(new_query_values)
-
if new_query_values == nil
-
self.query = nil
-
return nil
-
end
-
-
if !new_query_values.is_a?(Array)
-
if !new_query_values.respond_to?(:to_hash)
-
raise TypeError,
-
"Can't convert #{new_query_values.class} into Hash."
-
end
-
new_query_values = new_query_values.to_hash
-
new_query_values = new_query_values.map do |key, value|
-
key = key.to_s if key.kind_of?(Symbol)
-
[key, value]
-
end
-
# Useful default for OAuth and caching.
-
# Only to be used for non-Array inputs. Arrays should preserve order.
-
new_query_values.sort!
-
end
-
-
# new_query_values have form [['key1', 'value1'], ['key2', 'value2']]
-
buffer = ""
-
new_query_values.each do |key, value|
-
encoded_key = URI.encode_component(
-
key, CharacterClasses::UNRESERVED
-
)
-
if value == nil
-
buffer << "#{encoded_key}&"
-
elsif value.kind_of?(Array)
-
value.each do |sub_value|
-
encoded_value = URI.encode_component(
-
sub_value, CharacterClasses::UNRESERVED
-
)
-
buffer << "#{encoded_key}=#{encoded_value}&"
-
end
-
else
-
encoded_value = URI.encode_component(
-
value, CharacterClasses::UNRESERVED
-
)
-
buffer << "#{encoded_key}=#{encoded_value}&"
-
end
-
end
-
self.query = buffer.chop
-
end
-
-
##
-
# The HTTP request URI for this URI. This is the path and the
-
# query string.
-
#
-
# @return [String] The request URI required for an HTTP request.
-
1
def request_uri
-
return nil if self.absolute? && self.scheme !~ /^https?$/
-
return (
-
(!self.path.empty? ? self.path : SLASH) +
-
(self.query ? "?#{self.query}" : EMPTY_STR)
-
)
-
end
-
-
##
-
# Sets the HTTP request URI for this URI.
-
#
-
# @param [String, #to_str] new_request_uri The new HTTP request URI.
-
1
def request_uri=(new_request_uri)
-
if !new_request_uri.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_request_uri.class} into String."
-
end
-
if self.absolute? && self.scheme !~ /^https?$/
-
raise InvalidURIError,
-
"Cannot set an HTTP request URI for a non-HTTP URI."
-
end
-
new_request_uri = new_request_uri.to_str
-
path_component = new_request_uri[/^([^\?]*)\?(?:.*)$/, 1]
-
query_component = new_request_uri[/^(?:[^\?]*)\?(.*)$/, 1]
-
path_component = path_component.to_s
-
path_component = (!path_component.empty? ? path_component : SLASH)
-
self.path = path_component
-
self.query = query_component
-
-
# Reset dependent values
-
remove_composite_values
-
end
-
-
##
-
# The fragment component for this URI.
-
#
-
# @return [String] The fragment component.
-
1
def fragment
-
return defined?(@fragment) ? @fragment : nil
-
end
-
-
##
-
# The fragment component for this URI, normalized.
-
#
-
# @return [String] The fragment component, normalized.
-
1
def normalized_fragment
-
return nil unless self.fragment
-
return @normalized_fragment if defined?(@normalized_fragment)
-
@normalized_fragment ||= begin
-
component = Addressable::URI.normalize_component(
-
self.fragment,
-
Addressable::URI::CharacterClasses::FRAGMENT
-
)
-
component == "" ? nil : component
-
end
-
# All normalized values should be UTF-8
-
if @normalized_fragment
-
@normalized_fragment.force_encoding(Encoding::UTF_8)
-
end
-
@normalized_fragment
-
end
-
-
##
-
# Sets the fragment component for this URI.
-
#
-
# @param [String, #to_str] new_fragment The new fragment component.
-
1
def fragment=(new_fragment)
-
if new_fragment && !new_fragment.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_fragment.class} into String."
-
end
-
@fragment = new_fragment ? new_fragment.to_str : nil
-
-
# Reset dependent values
-
remove_instance_variable(:@normalized_fragment) if defined?(@normalized_fragment)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# Determines if the scheme indicates an IP-based protocol.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the scheme indicates an IP-based protocol.
-
# <code>false</code> otherwise.
-
1
def ip_based?
-
if self.scheme
-
return URI.ip_based_schemes.include?(
-
self.scheme.strip.downcase)
-
end
-
return false
-
end
-
-
##
-
# Determines if the URI is relative.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the URI is relative. <code>false</code>
-
# otherwise.
-
1
def relative?
-
return self.scheme.nil?
-
end
-
-
##
-
# Determines if the URI is absolute.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the URI is absolute. <code>false</code>
-
# otherwise.
-
1
def absolute?
-
return !relative?
-
end
-
-
##
-
# Joins two URIs together.
-
#
-
# @param [String, Addressable::URI, #to_str] The URI to join with.
-
#
-
# @return [Addressable::URI] The joined URI.
-
1
def join(uri)
-
if !uri.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end
-
if !uri.kind_of?(URI)
-
# Otherwise, convert to a String, then parse.
-
uri = URI.parse(uri.to_str)
-
end
-
if uri.to_s.empty?
-
return self.dup
-
end
-
-
joined_scheme = nil
-
joined_user = nil
-
joined_password = nil
-
joined_host = nil
-
joined_port = nil
-
joined_path = nil
-
joined_query = nil
-
joined_fragment = nil
-
-
# Section 5.2.2 of RFC 3986
-
if uri.scheme != nil
-
joined_scheme = uri.scheme
-
joined_user = uri.user
-
joined_password = uri.password
-
joined_host = uri.host
-
joined_port = uri.port
-
joined_path = URI.normalize_path(uri.path)
-
joined_query = uri.query
-
else
-
if uri.authority != nil
-
joined_user = uri.user
-
joined_password = uri.password
-
joined_host = uri.host
-
joined_port = uri.port
-
joined_path = URI.normalize_path(uri.path)
-
joined_query = uri.query
-
else
-
if uri.path == nil || uri.path.empty?
-
joined_path = self.path
-
if uri.query != nil
-
joined_query = uri.query
-
else
-
joined_query = self.query
-
end
-
else
-
if uri.path[0..0] == SLASH
-
joined_path = URI.normalize_path(uri.path)
-
else
-
base_path = self.path.dup
-
base_path = EMPTY_STR if base_path == nil
-
base_path = URI.normalize_path(base_path)
-
-
# Section 5.2.3 of RFC 3986
-
#
-
# Removes the right-most path segment from the base path.
-
if base_path =~ /\//
-
base_path.gsub!(/\/[^\/]+$/, SLASH)
-
else
-
base_path = EMPTY_STR
-
end
-
-
# If the base path is empty and an authority segment has been
-
# defined, use a base path of SLASH
-
if base_path.empty? && self.authority != nil
-
base_path = SLASH
-
end
-
-
joined_path = URI.normalize_path(base_path + uri.path)
-
end
-
joined_query = uri.query
-
end
-
joined_user = self.user
-
joined_password = self.password
-
joined_host = self.host
-
joined_port = self.port
-
end
-
joined_scheme = self.scheme
-
end
-
joined_fragment = uri.fragment
-
-
return self.class.new(
-
:scheme => joined_scheme,
-
:user => joined_user,
-
:password => joined_password,
-
:host => joined_host,
-
:port => joined_port,
-
:path => joined_path,
-
:query => joined_query,
-
:fragment => joined_fragment
-
)
-
end
-
1
alias_method :+, :join
-
-
##
-
# Destructive form of <code>join</code>.
-
#
-
# @param [String, Addressable::URI, #to_str] The URI to join with.
-
#
-
# @return [Addressable::URI] The joined URI.
-
#
-
# @see Addressable::URI#join
-
1
def join!(uri)
-
replace_self(self.join(uri))
-
end
-
-
##
-
# Merges a URI with a <code>Hash</code> of components.
-
# This method has different behavior from <code>join</code>. Any
-
# components present in the <code>hash</code> parameter will override the
-
# original components. The path component is not treated specially.
-
#
-
# @param [Hash, Addressable::URI, #to_hash] The components to merge with.
-
#
-
# @return [Addressable::URI] The merged URI.
-
#
-
# @see Hash#merge
-
1
def merge(hash)
-
if !hash.respond_to?(:to_hash)
-
raise TypeError, "Can't convert #{hash.class} into Hash."
-
end
-
hash = hash.to_hash
-
-
if hash.has_key?(:authority)
-
if (hash.keys & [:userinfo, :user, :password, :host, :port]).any?
-
raise ArgumentError,
-
"Cannot specify both an authority and any of the components " +
-
"within the authority."
-
end
-
end
-
if hash.has_key?(:userinfo)
-
if (hash.keys & [:user, :password]).any?
-
raise ArgumentError,
-
"Cannot specify both a userinfo and either the user or password."
-
end
-
end
-
-
uri = self.class.new
-
uri.defer_validation do
-
# Bunch of crazy logic required because of the composite components
-
# like userinfo and authority.
-
uri.scheme =
-
hash.has_key?(:scheme) ? hash[:scheme] : self.scheme
-
if hash.has_key?(:authority)
-
uri.authority =
-
hash.has_key?(:authority) ? hash[:authority] : self.authority
-
end
-
if hash.has_key?(:userinfo)
-
uri.userinfo =
-
hash.has_key?(:userinfo) ? hash[:userinfo] : self.userinfo
-
end
-
if !hash.has_key?(:userinfo) && !hash.has_key?(:authority)
-
uri.user =
-
hash.has_key?(:user) ? hash[:user] : self.user
-
uri.password =
-
hash.has_key?(:password) ? hash[:password] : self.password
-
end
-
if !hash.has_key?(:authority)
-
uri.host =
-
hash.has_key?(:host) ? hash[:host] : self.host
-
uri.port =
-
hash.has_key?(:port) ? hash[:port] : self.port
-
end
-
uri.path =
-
hash.has_key?(:path) ? hash[:path] : self.path
-
uri.query =
-
hash.has_key?(:query) ? hash[:query] : self.query
-
uri.fragment =
-
hash.has_key?(:fragment) ? hash[:fragment] : self.fragment
-
end
-
-
return uri
-
end
-
-
##
-
# Destructive form of <code>merge</code>.
-
#
-
# @param [Hash, Addressable::URI, #to_hash] The components to merge with.
-
#
-
# @return [Addressable::URI] The merged URI.
-
#
-
# @see Addressable::URI#merge
-
1
def merge!(uri)
-
replace_self(self.merge(uri))
-
end
-
-
##
-
# Returns the shortest normalized relative form of this URI that uses the
-
# supplied URI as a base for resolution. Returns an absolute URI if
-
# necessary. This is effectively the opposite of <code>route_to</code>.
-
#
-
# @param [String, Addressable::URI, #to_str] uri The URI to route from.
-
#
-
# @return [Addressable::URI]
-
# The normalized relative URI that is equivalent to the original URI.
-
1
def route_from(uri)
-
uri = URI.parse(uri).normalize
-
normalized_self = self.normalize
-
if normalized_self.relative?
-
raise ArgumentError, "Expected absolute URI, got: #{self.to_s}"
-
end
-
if uri.relative?
-
raise ArgumentError, "Expected absolute URI, got: #{uri.to_s}"
-
end
-
if normalized_self == uri
-
return Addressable::URI.parse("##{normalized_self.fragment}")
-
end
-
components = normalized_self.to_hash
-
if normalized_self.scheme == uri.scheme
-
components[:scheme] = nil
-
if normalized_self.authority == uri.authority
-
components[:user] = nil
-
components[:password] = nil
-
components[:host] = nil
-
components[:port] = nil
-
if normalized_self.path == uri.path
-
components[:path] = nil
-
if normalized_self.query == uri.query
-
components[:query] = nil
-
end
-
else
-
if uri.path != SLASH and components[:path]
-
self_splitted_path = split_path(components[:path])
-
uri_splitted_path = split_path(uri.path)
-
self_dir = self_splitted_path.shift
-
uri_dir = uri_splitted_path.shift
-
while !self_splitted_path.empty? && !uri_splitted_path.empty? and self_dir == uri_dir
-
self_dir = self_splitted_path.shift
-
uri_dir = uri_splitted_path.shift
-
end
-
components[:path] = (uri_splitted_path.fill('..') + [self_dir] + self_splitted_path).join(SLASH)
-
end
-
end
-
end
-
end
-
# Avoid network-path references.
-
if components[:host] != nil
-
components[:scheme] = normalized_self.scheme
-
end
-
return Addressable::URI.new(
-
:scheme => components[:scheme],
-
:user => components[:user],
-
:password => components[:password],
-
:host => components[:host],
-
:port => components[:port],
-
:path => components[:path],
-
:query => components[:query],
-
:fragment => components[:fragment]
-
)
-
end
-
-
##
-
# Returns the shortest normalized relative form of the supplied URI that
-
# uses this URI as a base for resolution. Returns an absolute URI if
-
# necessary. This is effectively the opposite of <code>route_from</code>.
-
#
-
# @param [String, Addressable::URI, #to_str] uri The URI to route to.
-
#
-
# @return [Addressable::URI]
-
# The normalized relative URI that is equivalent to the supplied URI.
-
1
def route_to(uri)
-
return URI.parse(uri).route_from(self)
-
end
-
-
##
-
# Returns a normalized URI object.
-
#
-
# NOTE: This method does not attempt to fully conform to specifications.
-
# It exists largely to correct other people's failures to read the
-
# specifications, and also to deal with caching issues since several
-
# different URIs may represent the same resource and should not be
-
# cached multiple times.
-
#
-
# @return [Addressable::URI] The normalized URI.
-
1
def normalize
-
# This is a special exception for the frequently misused feed
-
# URI scheme.
-
if normalized_scheme == "feed"
-
if self.to_s =~ /^feed:\/*http:\/*/
-
return URI.parse(
-
self.to_s[/^feed:\/*(http:\/*.*)/, 1]
-
).normalize
-
end
-
end
-
-
return self.class.new(
-
:scheme => normalized_scheme,
-
:authority => normalized_authority,
-
:path => normalized_path,
-
:query => normalized_query,
-
:fragment => normalized_fragment
-
)
-
end
-
-
##
-
# Destructively normalizes this URI object.
-
#
-
# @return [Addressable::URI] The normalized URI.
-
#
-
# @see Addressable::URI#normalize
-
1
def normalize!
-
replace_self(self.normalize)
-
end
-
-
##
-
# Creates a URI suitable for display to users. If semantic attacks are
-
# likely, the application should try to detect these and warn the user.
-
# See <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>,
-
# section 7.6 for more information.
-
#
-
# @return [Addressable::URI] A URI suitable for display purposes.
-
1
def display_uri
-
display_uri = self.normalize
-
display_uri.host = ::Addressable::IDNA.to_unicode(display_uri.host)
-
return display_uri
-
end
-
-
##
-
# Returns <code>true</code> if the URI objects are equal. This method
-
# normalizes both URIs before doing the comparison, and allows comparison
-
# against <code>Strings</code>.
-
#
-
# @param [Object] uri The URI to compare.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the URIs are equivalent, <code>false</code>
-
# otherwise.
-
1
def ===(uri)
-
if uri.respond_to?(:normalize)
-
uri_string = uri.normalize.to_s
-
else
-
begin
-
uri_string = ::Addressable::URI.parse(uri).normalize.to_s
-
rescue InvalidURIError, TypeError
-
return false
-
end
-
end
-
return self.normalize.to_s == uri_string
-
end
-
-
##
-
# Returns <code>true</code> if the URI objects are equal. This method
-
# normalizes both URIs before doing the comparison.
-
#
-
# @param [Object] uri The URI to compare.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the URIs are equivalent, <code>false</code>
-
# otherwise.
-
1
def ==(uri)
-
return false unless uri.kind_of?(URI)
-
return self.normalize.to_s == uri.normalize.to_s
-
end
-
-
##
-
# Returns <code>true</code> if the URI objects are equal. This method
-
# does NOT normalize either URI before doing the comparison.
-
#
-
# @param [Object] uri The URI to compare.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the URIs are equivalent, <code>false</code>
-
# otherwise.
-
1
def eql?(uri)
-
return false unless uri.kind_of?(URI)
-
return self.to_s == uri.to_s
-
end
-
-
##
-
# A hash value that will make a URI equivalent to its normalized
-
# form.
-
#
-
# @return [Integer] A hash of the URI.
-
1
def hash
-
@hash ||= self.to_s.hash * -1
-
end
-
-
##
-
# Clones the URI object.
-
#
-
# @return [Addressable::URI] The cloned URI.
-
1
def dup
-
duplicated_uri = self.class.new(
-
:scheme => self.scheme ? self.scheme.dup : nil,
-
:user => self.user ? self.user.dup : nil,
-
:password => self.password ? self.password.dup : nil,
-
:host => self.host ? self.host.dup : nil,
-
:port => self.port,
-
:path => self.path ? self.path.dup : nil,
-
:query => self.query ? self.query.dup : nil,
-
:fragment => self.fragment ? self.fragment.dup : nil
-
)
-
return duplicated_uri
-
end
-
-
##
-
# Omits components from a URI.
-
#
-
# @param [Symbol] *components The components to be omitted.
-
#
-
# @return [Addressable::URI] The URI with components omitted.
-
#
-
# @example
-
# uri = Addressable::URI.parse("http://example.com/path?query")
-
# #=> #<Addressable::URI:0xcc5e7a URI:http://example.com/path?query>
-
# uri.omit(:scheme, :authority)
-
# #=> #<Addressable::URI:0xcc4d86 URI:/path?query>
-
1
def omit(*components)
-
invalid_components = components - [
-
:scheme, :user, :password, :userinfo, :host, :port, :authority,
-
:path, :query, :fragment
-
]
-
unless invalid_components.empty?
-
raise ArgumentError,
-
"Invalid component names: #{invalid_components.inspect}."
-
end
-
duplicated_uri = self.dup
-
duplicated_uri.defer_validation do
-
components.each do |component|
-
duplicated_uri.send((component.to_s + "=").to_sym, nil)
-
end
-
duplicated_uri.user = duplicated_uri.normalized_user
-
end
-
duplicated_uri
-
end
-
-
##
-
# Destructive form of omit.
-
#
-
# @param [Symbol] *components The components to be omitted.
-
#
-
# @return [Addressable::URI] The URI with components omitted.
-
#
-
# @see Addressable::URI#omit
-
1
def omit!(*components)
-
replace_self(self.omit(*components))
-
end
-
-
##
-
# Determines if the URI is an empty string.
-
#
-
# @return [TrueClass, FalseClass]
-
# Returns <code>true</code> if empty, <code>false</code> otherwise.
-
1
def empty?
-
return self.to_s.empty?
-
end
-
-
##
-
# Converts the URI to a <code>String</code>.
-
#
-
# @return [String] The URI's <code>String</code> representation.
-
1
def to_s
-
if self.scheme == nil && self.path != nil && !self.path.empty? &&
-
self.path =~ NORMPATH
-
raise InvalidURIError,
-
"Cannot assemble URI string with ambiguous path: '#{self.path}'"
-
end
-
@uri_string ||= begin
-
uri_string = String.new
-
uri_string << "#{self.scheme}:" if self.scheme != nil
-
uri_string << "//#{self.authority}" if self.authority != nil
-
uri_string << self.path.to_s
-
uri_string << "?#{self.query}" if self.query != nil
-
uri_string << "##{self.fragment}" if self.fragment != nil
-
uri_string.force_encoding(Encoding::UTF_8)
-
uri_string
-
end
-
end
-
-
##
-
# URI's are glorified <code>Strings</code>. Allow implicit conversion.
-
1
alias_method :to_str, :to_s
-
-
##
-
# Returns a Hash of the URI components.
-
#
-
# @return [Hash] The URI as a <code>Hash</code> of components.
-
1
def to_hash
-
return {
-
:scheme => self.scheme,
-
:user => self.user,
-
:password => self.password,
-
:host => self.host,
-
:port => self.port,
-
:path => self.path,
-
:query => self.query,
-
:fragment => self.fragment
-
}
-
end
-
-
##
-
# Returns a <code>String</code> representation of the URI object's state.
-
#
-
# @return [String] The URI object's state, as a <code>String</code>.
-
1
def inspect
-
sprintf("#<%s:%#0x URI:%s>", URI.to_s, self.object_id, self.to_s)
-
end
-
-
##
-
# This method allows you to make several changes to a URI simultaneously,
-
# which separately would cause validation errors, but in conjunction,
-
# are valid. The URI will be revalidated as soon as the entire block has
-
# been executed.
-
#
-
# @param [Proc] block
-
# A set of operations to perform on a given URI.
-
1
def defer_validation(&block)
-
raise LocalJumpError, "No block given." unless block
-
@validation_deferred = true
-
block.call()
-
@validation_deferred = false
-
validate
-
return nil
-
end
-
-
1
protected
-
1
SELF_REF = '.'
-
1
PARENT = '..'
-
-
1
RULE_2A = /\/\.\/|\/\.$/
-
1
RULE_2B_2C = /\/([^\/]*)\/\.\.\/|\/([^\/]*)\/\.\.$/
-
1
RULE_2D = /^\.\.?\/?/
-
1
RULE_PREFIXED_PARENT = /^\/\.\.?\/|^(\/\.\.?)+\/?$/
-
-
##
-
# Resolves paths to their simplest form.
-
#
-
# @param [String] path The path to normalize.
-
#
-
# @return [String] The normalized path.
-
1
def self.normalize_path(path)
-
# Section 5.2.4 of RFC 3986
-
-
return nil if path.nil?
-
normalized_path = path.dup
-
begin
-
mod = nil
-
mod ||= normalized_path.gsub!(RULE_2A, SLASH)
-
-
pair = normalized_path.match(RULE_2B_2C)
-
parent, current = pair[1], pair[2] if pair
-
if pair && ((parent != SELF_REF && parent != PARENT) ||
-
(current != SELF_REF && current != PARENT))
-
mod ||= normalized_path.gsub!(
-
Regexp.new(
-
"/#{Regexp.escape(parent.to_s)}/\\.\\./|" +
-
"(/#{Regexp.escape(current.to_s)}/\\.\\.$)"
-
), SLASH
-
)
-
end
-
-
mod ||= normalized_path.gsub!(RULE_2D, EMPTY_STR)
-
# Non-standard, removes prefixed dotted segments from path.
-
mod ||= normalized_path.gsub!(RULE_PREFIXED_PARENT, SLASH)
-
end until mod.nil?
-
-
return normalized_path
-
end
-
-
##
-
# Ensures that the URI is valid.
-
1
def validate
-
return if !!@validation_deferred
-
if self.scheme != nil && self.ip_based? &&
-
(self.host == nil || self.host.empty?) &&
-
(self.path == nil || self.path.empty?)
-
raise InvalidURIError,
-
"Absolute URI missing hierarchical segment: '#{self.to_s}'"
-
end
-
if self.host == nil
-
if self.port != nil ||
-
self.user != nil ||
-
self.password != nil
-
raise InvalidURIError, "Hostname not supplied: '#{self.to_s}'"
-
end
-
end
-
if self.path != nil && !self.path.empty? && self.path[0..0] != SLASH &&
-
self.authority != nil
-
raise InvalidURIError,
-
"Cannot have a relative path with an authority set: '#{self.to_s}'"
-
end
-
if self.path != nil && !self.path.empty? &&
-
self.path[0..1] == SLASH + SLASH && self.authority == nil
-
raise InvalidURIError,
-
"Cannot have a path with two leading slashes " +
-
"without an authority set: '#{self.to_s}'"
-
end
-
unreserved = CharacterClasses::UNRESERVED
-
sub_delims = CharacterClasses::SUB_DELIMS
-
if !self.host.nil? && (self.host =~ /[<>{}\/\\\?\#\@"[[:space:]]]/ ||
-
(self.host[/^\[(.*)\]$/, 1] != nil && self.host[/^\[(.*)\]$/, 1] !~
-
Regexp.new("^[#{unreserved}#{sub_delims}:]*$")))
-
raise InvalidURIError, "Invalid character in host: '#{self.host.to_s}'"
-
end
-
return nil
-
end
-
-
##
-
# Replaces the internal state of self with the specified URI's state.
-
# Used in destructive operations to avoid massive code repetition.
-
#
-
# @param [Addressable::URI] uri The URI to replace <code>self</code> with.
-
#
-
# @return [Addressable::URI] <code>self</code>.
-
1
def replace_self(uri)
-
# Reset dependent values
-
instance_variables.each do |var|
-
if instance_variable_defined?(var) && var != :@validation_deferred
-
remove_instance_variable(var)
-
end
-
end
-
-
@scheme = uri.scheme
-
@user = uri.user
-
@password = uri.password
-
@host = uri.host
-
@port = uri.port
-
@path = uri.path
-
@query = uri.query
-
@fragment = uri.fragment
-
return self
-
end
-
-
##
-
# Splits path string with "/" (slash).
-
# It is considered that there is empty string after last slash when
-
# path ends with slash.
-
#
-
# @param [String] path The path to split.
-
#
-
# @return [Array<String>] An array of parts of path.
-
1
def split_path(path)
-
splitted = path.split(SLASH)
-
splitted << EMPTY_STR if path.end_with? SLASH
-
splitted
-
end
-
-
##
-
# Resets composite values for the entire URI
-
#
-
# @api private
-
1
def remove_composite_values
-
remove_instance_variable(:@uri_string) if defined?(@uri_string)
-
remove_instance_variable(:@hash) if defined?(@hash)
-
end
-
end
-
end
-
# encoding:utf-8
-
#--
-
# Copyright (C) Bob Aman
-
#
-
# Licensed under the Apache License, Version 2.0 (the "License");
-
# you may not use this file except in compliance with the License.
-
# You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing, software
-
# distributed under the License is distributed on an "AS IS" BASIS,
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
# See the License for the specific language governing permissions and
-
# limitations under the License.
-
#++
-
-
-
# Used to prevent the class/module from being loaded more than once
-
1
if !defined?(Addressable::VERSION)
-
1
module Addressable
-
1
module VERSION
-
1
MAJOR = 2
-
1
MINOR = 5
-
1
TINY = 1
-
-
1
STRING = [MAJOR, MINOR, TINY].join('.')
-
end
-
end
-
end
-
1
require 'arel/crud'
-
1
require 'arel/factory_methods'
-
-
1
require 'arel/expressions'
-
1
require 'arel/predications'
-
1
require 'arel/window_predications'
-
1
require 'arel/math'
-
1
require 'arel/alias_predication'
-
1
require 'arel/order_predications'
-
1
require 'arel/table'
-
1
require 'arel/attributes'
-
1
require 'arel/compatibility/wheres'
-
-
1
require 'arel/visitors'
-
-
1
require 'arel/tree_manager'
-
1
require 'arel/insert_manager'
-
1
require 'arel/select_manager'
-
1
require 'arel/update_manager'
-
1
require 'arel/delete_manager'
-
1
require 'arel/nodes'
-
-
1
module Arel
-
1
VERSION = '6.0.4'
-
-
1
def self.sql raw_sql
-
60
Arel::Nodes::SqlLiteral.new raw_sql
-
end
-
-
1
def self.star
-
60
sql '*'
-
end
-
## Convenience Alias
-
1
Node = Arel::Nodes::Node
-
end
-
1
module Arel
-
1
module AliasPredication
-
1
def as other
-
Nodes::As.new self, Nodes::SqlLiteral.new(other)
-
end
-
end
-
end
-
1
require 'arel/attributes/attribute'
-
-
1
module Arel
-
1
module Attributes
-
###
-
# Factory method to wrap a raw database +column+ to an Arel Attribute.
-
1
def self.for column
-
case column.type
-
when :string, :text, :binary then String
-
when :integer then Integer
-
when :float then Float
-
when :decimal then Decimal
-
when :date, :datetime, :timestamp, :time then Time
-
when :boolean then Boolean
-
else
-
Undefined
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Attributes
-
1
class Attribute < Struct.new :relation, :name
-
1
include Arel::Expressions
-
1
include Arel::Predications
-
1
include Arel::AliasPredication
-
1
include Arel::OrderPredications
-
1
include Arel::Math
-
-
###
-
# Create a node for lowering this attribute
-
1
def lower
-
relation.lower self
-
end
-
end
-
-
1
class String < Attribute; end
-
1
class Time < Attribute; end
-
1
class Boolean < Attribute; end
-
1
class Decimal < Attribute; end
-
1
class Float < Attribute; end
-
1
class Integer < Attribute; end
-
1
class Undefined < Attribute; end
-
end
-
-
1
Attribute = Attributes::Attribute
-
end
-
1
module Arel
-
1
module Collectors
-
1
class Bind
-
1
def initialize
-
@parts = []
-
end
-
-
1
def << str
-
@parts << str
-
self
-
end
-
-
1
def add_bind bind
-
@parts << bind
-
self
-
end
-
-
1
def value; @parts; end
-
-
1
def substitute_binds bvs
-
bvs = bvs.dup
-
@parts.map do |val|
-
if Arel::Nodes::BindParam === val
-
bvs.shift
-
else
-
val
-
end
-
end
-
end
-
-
1
def compile bvs
-
substitute_binds(bvs).join
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Collectors
-
1
class PlainString
-
1
def initialize
-
60
@str = ''
-
end
-
-
1
def value
-
60
@str
-
end
-
-
1
def << str
-
686
@str << str
-
686
self
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'arel/collectors/plain_string'
-
-
1
module Arel
-
1
module Collectors
-
1
class SQLString < PlainString
-
1
def initialize(*)
-
60
super
-
60
@bind_index = 1
-
end
-
-
1
def add_bind bind
-
150
self << yield(@bind_index)
-
150
@bind_index += 1
-
150
self
-
end
-
-
1
def compile bvs
-
56
value
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Compatibility # :nodoc:
-
1
class Wheres # :nodoc:
-
1
include Enumerable
-
-
1
module Value # :nodoc:
-
1
attr_accessor :visitor
-
1
def value
-
visitor.accept self
-
end
-
-
1
def name
-
super.to_sym
-
end
-
end
-
-
1
def initialize engine, collection
-
@engine = engine
-
@collection = collection
-
end
-
-
1
def each
-
to_sql = Visitors::ToSql.new @engine
-
-
@collection.each { |c|
-
c.extend(Value)
-
c.visitor = to_sql
-
yield c
-
}
-
end
-
end
-
end
-
end
-
1
module Arel
-
###
-
# FIXME hopefully we can remove this
-
1
module Crud
-
1
def compile_update values, pk
-
4
um = UpdateManager.new @engine
-
-
4
if Nodes::SqlLiteral === values
-
relation = @ctx.from
-
else
-
4
relation = values.first.first.relation
-
end
-
4
um.key = pk
-
4
um.table relation
-
4
um.set values
-
4
um.take @ast.limit.expr if @ast.limit
-
4
um.order(*@ast.orders)
-
4
um.wheres = @ctx.wheres
-
4
um
-
end
-
-
1
def compile_insert values
-
im = create_insert
-
im.insert values
-
im
-
end
-
-
1
def create_insert
-
25
InsertManager.new @engine
-
end
-
-
1
def compile_delete
-
dm = DeleteManager.new @engine
-
dm.wheres = @ctx.wheres
-
dm.from @ctx.froms
-
dm
-
end
-
-
end
-
end
-
1
module Arel
-
1
class DeleteManager < Arel::TreeManager
-
1
def initialize engine
-
3
super
-
3
@ast = Nodes::DeleteStatement.new
-
3
@ctx = @ast
-
end
-
-
1
def from relation
-
3
@ast.relation = relation
-
3
self
-
end
-
-
1
def wheres= list
-
3
@ast.wheres = list
-
end
-
end
-
end
-
1
module Arel
-
1
module Expressions
-
1
def count distinct = false
-
Nodes::Count.new [self], distinct
-
end
-
-
1
def sum
-
Nodes::Sum.new [self]
-
end
-
-
1
def maximum
-
Nodes::Max.new [self]
-
end
-
-
1
def minimum
-
Nodes::Min.new [self]
-
end
-
-
1
def average
-
Nodes::Avg.new [self]
-
end
-
-
1
def extract field
-
Nodes::Extract.new [self], field
-
end
-
-
end
-
end
-
1
module Arel
-
###
-
# Methods for creating various nodes
-
1
module FactoryMethods
-
1
def create_true
-
Arel::Nodes::True.new
-
end
-
-
1
def create_false
-
Arel::Nodes::False.new
-
end
-
-
1
def create_table_alias relation, name
-
Nodes::TableAlias.new(relation, name)
-
end
-
-
1
def create_join to, constraint = nil, klass = Nodes::InnerJoin
-
klass.new(to, constraint)
-
end
-
-
1
def create_string_join to
-
create_join to, nil, Nodes::StringJoin
-
end
-
-
1
def create_and clauses
-
Nodes::And.new clauses
-
end
-
-
1
def create_on expr
-
Nodes::On.new expr
-
end
-
-
1
def grouping expr
-
Nodes::Grouping.new expr
-
end
-
-
###
-
# Create a LOWER() function
-
1
def lower column
-
Nodes::NamedFunction.new 'LOWER', [Nodes.build_quoted(column)]
-
end
-
end
-
end
-
1
module Arel
-
1
class InsertManager < Arel::TreeManager
-
1
def initialize engine
-
25
super
-
25
@ast = Nodes::InsertStatement.new
-
end
-
-
1
def into table
-
25
@ast.relation = table
-
25
self
-
end
-
-
1
def columns; @ast.columns end
-
1
def values= val; @ast.values = val; end
-
-
1
def select select
-
@ast.select = select
-
end
-
-
1
def insert fields
-
25
return if fields.empty?
-
-
25
if String === fields
-
@ast.values = Nodes::SqlLiteral.new(fields)
-
else
-
25
@ast.relation ||= fields.first.first.relation
-
-
25
values = []
-
-
25
fields.each do |column, value|
-
130
@ast.columns << column
-
130
values << value
-
end
-
25
@ast.values = create_values values, @ast.columns
-
end
-
end
-
-
1
def create_values values, columns
-
25
Nodes::Values.new values, columns
-
end
-
end
-
end
-
1
module Arel
-
1
module Math
-
1
def *(other)
-
Arel::Nodes::Multiplication.new(self, other)
-
end
-
-
1
def +(other)
-
Arel::Nodes::Grouping.new(Arel::Nodes::Addition.new(self, other))
-
end
-
-
1
def -(other)
-
Arel::Nodes::Grouping.new(Arel::Nodes::Subtraction.new(self, other))
-
end
-
-
1
def /(other)
-
Arel::Nodes::Division.new(self, other)
-
end
-
end
-
end
-
# node
-
1
require 'arel/nodes/node'
-
1
require 'arel/nodes/select_statement'
-
1
require 'arel/nodes/select_core'
-
1
require 'arel/nodes/insert_statement'
-
1
require 'arel/nodes/update_statement'
-
1
require 'arel/nodes/bind_param'
-
-
# terminal
-
-
1
require 'arel/nodes/terminal'
-
1
require 'arel/nodes/true'
-
1
require 'arel/nodes/false'
-
-
# unary
-
1
require 'arel/nodes/unary'
-
1
require 'arel/nodes/grouping'
-
1
require 'arel/nodes/ascending'
-
1
require 'arel/nodes/descending'
-
1
require 'arel/nodes/unqualified_column'
-
1
require 'arel/nodes/with'
-
-
# binary
-
1
require 'arel/nodes/binary'
-
1
require 'arel/nodes/equality'
-
1
require 'arel/nodes/in' # Why is this subclassed from equality?
-
1
require 'arel/nodes/join_source'
-
1
require 'arel/nodes/delete_statement'
-
1
require 'arel/nodes/table_alias'
-
1
require 'arel/nodes/infix_operation'
-
1
require 'arel/nodes/over'
-
1
require 'arel/nodes/matches'
-
-
# nary
-
1
require 'arel/nodes/and'
-
-
# function
-
# FIXME: Function + Alias can be rewritten as a Function and Alias node.
-
# We should make Function a Unary node and deprecate the use of "aliaz"
-
1
require 'arel/nodes/function'
-
1
require 'arel/nodes/count'
-
1
require 'arel/nodes/extract'
-
1
require 'arel/nodes/values'
-
1
require 'arel/nodes/named_function'
-
-
# windows
-
1
require 'arel/nodes/window'
-
-
# joins
-
1
require 'arel/nodes/full_outer_join'
-
1
require 'arel/nodes/inner_join'
-
1
require 'arel/nodes/outer_join'
-
1
require 'arel/nodes/right_outer_join'
-
1
require 'arel/nodes/string_join'
-
-
1
require 'arel/nodes/sql_literal'
-
-
1
module Arel
-
1
module Nodes
-
1
class Casted < Arel::Nodes::Node # :nodoc:
-
1
attr_reader :val, :attribute
-
1
def initialize val, attribute
-
@val = val
-
@attribute = attribute
-
super()
-
end
-
-
1
def nil?; @val.nil?; end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.val == other.val &&
-
self.attribute == other.attribute
-
end
-
1
alias :== :eql?
-
end
-
-
1
class Quoted < Arel::Nodes::Unary # :nodoc:
-
end
-
-
1
def self.build_quoted other, attribute = nil
-
15
case other
-
when Arel::Nodes::Node, Arel::Attributes::Attribute, Arel::Table, Arel::Nodes::BindParam, Arel::SelectManager
-
11
other
-
else
-
4
case attribute
-
when Arel::Attributes::Attribute
-
Casted.new other, attribute
-
else
-
4
Quoted.new other
-
end
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class And < Arel::Nodes::Node
-
1
attr_reader :children
-
-
1
def initialize children
-
11
super()
-
11
@children = children
-
end
-
-
1
def left
-
children.first
-
end
-
-
1
def right
-
children[1]
-
end
-
-
1
def hash
-
children.hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.children == other.children
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Ascending < Ordering
-
-
1
def reverse
-
Descending.new(expr)
-
end
-
-
1
def direction
-
:asc
-
end
-
-
1
def ascending?
-
true
-
end
-
-
1
def descending?
-
false
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Binary < Arel::Nodes::Node
-
1
attr_accessor :left, :right
-
-
1
def initialize left, right
-
108
super()
-
108
@left = left
-
108
@right = right
-
end
-
-
1
def initialize_copy other
-
super
-
@left = @left.clone if @left
-
@right = @right.clone if @right
-
end
-
-
1
def hash
-
11
[self.class, @left, @right].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
3
self.left == other.left &&
-
self.right == other.right
-
end
-
1
alias :== :eql?
-
end
-
-
%w{
-
As
-
Assignment
-
Between
-
GreaterThan
-
GreaterThanOrEqual
-
Join
-
LessThan
-
LessThanOrEqual
-
NotEqual
-
NotIn
-
NotRegexp
-
Or
-
Regexp
-
Union
-
UnionAll
-
Intersect
-
Except
-
1
}.each do |name|
-
17
const_set name, Class.new(Binary)
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class BindParam < Node
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Count < Arel::Nodes::Function
-
1
def initialize expr, distinct = false, aliaz = nil
-
super(expr, aliaz)
-
@distinct = distinct
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class DeleteStatement < Arel::Nodes::Binary
-
1
alias :relation :left
-
1
alias :relation= :left=
-
1
alias :wheres :right
-
1
alias :wheres= :right=
-
-
1
def initialize relation = nil, wheres = []
-
3
super
-
end
-
-
1
def initialize_copy other
-
super
-
@right = @right.clone
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Descending < Ordering
-
-
1
def reverse
-
Ascending.new(expr)
-
end
-
-
1
def direction
-
:desc
-
end
-
-
1
def ascending?
-
false
-
end
-
-
1
def descending?
-
true
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Equality < Arel::Nodes::Binary
-
1
def operator; :== end
-
1
alias :operand1 :left
-
1
alias :operand2 :right
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Extract < Arel::Nodes::Unary
-
1
include Arel::AliasPredication
-
1
include Arel::Predications
-
-
1
attr_accessor :field
-
-
1
def initialize expr, field
-
super(expr)
-
@field = field
-
end
-
-
1
def hash
-
super ^ @field.hash
-
end
-
-
1
def eql? other
-
super &&
-
self.field == other.field
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class False < Arel::Nodes::Node
-
1
def hash
-
self.class.hash
-
end
-
-
1
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class FullOuterJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Function < Arel::Nodes::Node
-
1
include Arel::Predications
-
1
include Arel::WindowPredications
-
1
include Arel::OrderPredications
-
1
attr_accessor :expressions, :alias, :distinct
-
-
1
def initialize expr, aliaz = nil
-
super()
-
@expressions = expr
-
@alias = aliaz && SqlLiteral.new(aliaz)
-
@distinct = false
-
end
-
-
1
def as aliaz
-
self.alias = SqlLiteral.new(aliaz)
-
self
-
end
-
-
1
def hash
-
[@expressions, @alias, @distinct].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.expressions == other.expressions &&
-
self.alias == other.alias &&
-
self.distinct == other.distinct
-
end
-
end
-
-
%w{
-
Sum
-
Exists
-
Max
-
Min
-
Avg
-
1
}.each do |name|
-
5
const_set(name, Class.new(Function))
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Grouping < Unary
-
1
include Arel::Predications
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class In < Equality
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
-
1
class InfixOperation < Binary
-
1
include Arel::Expressions
-
1
include Arel::Predications
-
1
include Arel::OrderPredications
-
1
include Arel::AliasPredication
-
1
include Arel::Math
-
-
1
attr_reader :operator
-
-
1
def initialize operator, left, right
-
super(left, right)
-
@operator = operator
-
end
-
end
-
-
1
class Multiplication < InfixOperation
-
1
def initialize left, right
-
super(:*, left, right)
-
end
-
end
-
-
1
class Division < InfixOperation
-
1
def initialize left, right
-
super(:/, left, right)
-
end
-
end
-
-
1
class Addition < InfixOperation
-
1
def initialize left, right
-
super(:+, left, right)
-
end
-
end
-
-
1
class Subtraction < InfixOperation
-
1
def initialize left, right
-
super(:-, left, right)
-
end
-
end
-
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class InnerJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class InsertStatement < Arel::Nodes::Node
-
1
attr_accessor :relation, :columns, :values, :select
-
-
1
def initialize
-
25
super()
-
25
@relation = nil
-
25
@columns = []
-
25
@values = nil
-
25
@select = nil
-
end
-
-
1
def initialize_copy other
-
super
-
@columns = @columns.clone
-
@values = @values.clone if @values
-
@select = @select.clone if @select
-
end
-
-
1
def hash
-
[@relation, @columns, @values, @select].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.relation == other.relation &&
-
self.columns == other.columns &&
-
self.select == other.select &&
-
self.values == other.values
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
###
-
# Class that represents a join source
-
#
-
# http://www.sqlite.org/syntaxdiagrams.html#join-source
-
-
1
class JoinSource < Arel::Nodes::Binary
-
1
def initialize single_source, joinop = []
-
60
super
-
end
-
-
1
def empty?
-
28
!left && right.empty?
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Matches < Binary
-
1
attr_reader :escape
-
-
1
def initialize(left, right, escape = nil)
-
super(left, right)
-
@escape = escape && Nodes.build_quoted(escape)
-
end
-
end
-
-
1
class DoesNotMatch < Matches; end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class NamedFunction < Arel::Nodes::Function
-
1
attr_accessor :name
-
-
1
def initialize name, expr, aliaz = nil
-
super(expr, aliaz)
-
@name = name
-
end
-
-
1
def hash
-
super ^ @name.hash
-
end
-
-
1
def eql? other
-
super && self.name == other.name
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
require 'arel/collectors/sql_string'
-
-
1
module Arel
-
1
module Nodes
-
###
-
# Abstract base class for all AST nodes
-
1
class Node
-
1
include Arel::FactoryMethods
-
1
include Enumerable
-
-
1
if $DEBUG
-
def _caller
-
@caller
-
end
-
-
def initialize
-
@caller = caller.dup
-
end
-
end
-
-
###
-
# Factory method to create a Nodes::Not node that has the recipient of
-
# the caller as a child.
-
1
def not
-
Nodes::Not.new self
-
end
-
-
###
-
# Factory method to create a Nodes::Grouping node that has an Nodes::Or
-
# node as a child.
-
1
def or right
-
Nodes::Grouping.new Nodes::Or.new(self, right)
-
end
-
-
###
-
# Factory method to create an Nodes::And node.
-
1
def and right
-
Nodes::And.new [self, right]
-
end
-
-
# FIXME: this method should go away. I don't like people calling
-
# to_sql on non-head nodes. This forces us to walk the AST until we
-
# can find a node that has a "relation" member.
-
#
-
# Maybe we should just use `Table.engine`? :'(
-
1
def to_sql engine = Table.engine
-
collector = Arel::Collectors::SQLString.new
-
collector = engine.connection.visitor.accept self, collector
-
collector.value
-
end
-
-
# Iterate through AST, nodes will be yielded depth-first
-
1
def each &block
-
return enum_for(:each) unless block_given?
-
-
::Arel::Visitors::DepthFirst.new(block).accept self
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class OuterJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
-
1
class Over < Binary
-
1
include Arel::AliasPredication
-
-
1
def initialize(left, right = nil)
-
super(left, right)
-
end
-
-
1
def operator; 'OVER' end
-
end
-
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class RightOuterJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class SelectCore < Arel::Nodes::Node
-
1
attr_accessor :top, :projections, :wheres, :groups, :windows
-
1
attr_accessor :having, :source, :set_quantifier
-
-
1
def initialize
-
60
super()
-
60
@source = JoinSource.new nil
-
60
@top = nil
-
-
# http://savage.net.au/SQL/sql-92.bnf.html#set%20quantifier
-
60
@set_quantifier = nil
-
60
@projections = []
-
60
@wheres = []
-
60
@groups = []
-
60
@having = nil
-
60
@windows = []
-
end
-
-
1
def from
-
@source.left
-
end
-
-
1
def from= value
-
@source.left = value
-
end
-
-
1
alias :froms= :from=
-
1
alias :froms :from
-
-
1
def initialize_copy other
-
super
-
@source = @source.clone if @source
-
@projections = @projections.clone
-
@wheres = @wheres.clone
-
@groups = @groups.clone
-
@having = @having.clone if @having
-
@windows = @windows.clone
-
end
-
-
1
def hash
-
[
-
@source, @top, @set_quantifier, @projections,
-
@wheres, @groups, @having, @windows
-
].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.source == other.source &&
-
self.top == other.top &&
-
self.set_quantifier == other.set_quantifier &&
-
self.projections == other.projections &&
-
self.wheres == other.wheres &&
-
self.groups == other.groups &&
-
self.having == other.having &&
-
self.windows == other.windows
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class SelectStatement < Arel::Nodes::Node
-
1
attr_reader :cores
-
1
attr_accessor :limit, :orders, :lock, :offset, :with
-
-
1
def initialize cores = [SelectCore.new]
-
60
super()
-
60
@cores = cores
-
60
@orders = []
-
60
@limit = nil
-
60
@lock = nil
-
60
@offset = nil
-
60
@with = nil
-
end
-
-
1
def initialize_copy other
-
super
-
@cores = @cores.map { |x| x.clone }
-
@orders = @orders.map { |x| x.clone }
-
end
-
-
1
def hash
-
[@cores, @orders, @limit, @lock, @offset, @with].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.cores == other.cores &&
-
self.orders == other.orders &&
-
self.limit == other.limit &&
-
self.lock == other.lock &&
-
self.offset == other.offset &&
-
self.with == other.with
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class SqlLiteral < String
-
1
include Arel::Expressions
-
1
include Arel::Predications
-
1
include Arel::AliasPredication
-
1
include Arel::OrderPredications
-
-
1
def encode_with(coder)
-
coder.scalar = self.to_s
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class StringJoin < Arel::Nodes::Join
-
1
def initialize left, right = nil
-
super
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class TableAlias < Arel::Nodes::Binary
-
1
alias :name :right
-
1
alias :relation :left
-
1
alias :table_alias :name
-
-
1
def [] name
-
Attribute.new(self, name)
-
end
-
-
1
def table_name
-
relation.respond_to?(:name) ? relation.name : name
-
end
-
-
1
def engine
-
relation.engine
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Distinct < Arel::Nodes::Node
-
1
def hash
-
self.class.hash
-
end
-
-
1
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class True < Arel::Nodes::Node
-
1
def hash
-
self.class.hash
-
end
-
-
1
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Unary < Arel::Nodes::Node
-
1
attr_accessor :expr
-
1
alias :value :expr
-
-
1
def initialize expr
-
21
super()
-
21
@expr = expr
-
end
-
-
1
def hash
-
@expr.hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.expr == other.expr
-
end
-
1
alias :== :eql?
-
end
-
-
%w{
-
Bin
-
Group
-
Having
-
Limit
-
Not
-
Offset
-
On
-
Ordering
-
Top
-
Lock
-
DistinctOn
-
1
}.each do |name|
-
11
const_set(name, Class.new(Unary))
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class UnqualifiedColumn < Arel::Nodes::Unary
-
1
alias :attribute :expr
-
1
alias :attribute= :expr=
-
-
1
def relation
-
@expr.relation
-
end
-
-
1
def column
-
@expr.column
-
end
-
-
1
def name
-
9
@expr.name
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class UpdateStatement < Arel::Nodes::Node
-
1
attr_accessor :relation, :wheres, :values, :orders, :limit
-
1
attr_accessor :key
-
-
1
def initialize
-
4
@relation = nil
-
4
@wheres = []
-
4
@values = []
-
4
@orders = []
-
4
@limit = nil
-
4
@key = nil
-
end
-
-
1
def initialize_copy other
-
super
-
@wheres = @wheres.clone
-
@values = @values.clone
-
end
-
-
1
def hash
-
[@relation, @wheres, @values, @orders, @limit, @key].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.relation == other.relation &&
-
self.wheres == other.wheres &&
-
self.values == other.values &&
-
self.orders == other.orders &&
-
self.limit == other.limit &&
-
self.key == other.key
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Values < Arel::Nodes::Binary
-
1
alias :expressions :left
-
1
alias :expressions= :left=
-
1
alias :columns :right
-
1
alias :columns= :right=
-
-
1
def initialize exprs, columns = []
-
25
super
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class With < Arel::Nodes::Unary
-
1
alias children expr
-
end
-
-
1
class WithRecursive < With; end
-
end
-
end
-
-
1
module Arel
-
1
module OrderPredications
-
-
1
def asc
-
Nodes::Ascending.new self
-
end
-
-
1
def desc
-
Nodes::Descending.new self
-
end
-
-
end
-
end
-
1
module Arel
-
1
module Predications
-
1
def not_eq other
-
Nodes::NotEqual.new self, quoted_node(other)
-
end
-
-
1
def not_eq_any others
-
grouping_any :not_eq, others
-
end
-
-
1
def not_eq_all others
-
grouping_all :not_eq, others
-
end
-
-
1
def eq other
-
11
Nodes::Equality.new self, quoted_node(other)
-
end
-
-
1
def eq_any others
-
grouping_any :eq, others
-
end
-
-
1
def eq_all others
-
grouping_all :eq, quoted_array(others)
-
end
-
-
1
def between other
-
if other.begin == -Float::INFINITY
-
if other.end == Float::INFINITY
-
not_in([])
-
elsif other.exclude_end?
-
lt(other.end)
-
else
-
lteq(other.end)
-
end
-
elsif other.end == Float::INFINITY
-
gteq(other.begin)
-
elsif other.exclude_end?
-
gteq(other.begin).and(lt(other.end))
-
else
-
left = quoted_node(other.begin)
-
right = quoted_node(other.end)
-
Nodes::Between.new(self, left.and(right))
-
end
-
end
-
-
1
def in other
-
case other
-
when Arel::SelectManager
-
Arel::Nodes::In.new(self, other.ast)
-
when Range
-
if $VERBOSE
-
warn <<-eowarn
-
Passing a range to `#in` is deprecated. Call `#between`, instead.
-
eowarn
-
end
-
between(other)
-
when Enumerable
-
Nodes::In.new self, quoted_array(other)
-
else
-
Nodes::In.new self, quoted_node(other)
-
end
-
end
-
-
1
def in_any others
-
grouping_any :in, others
-
end
-
-
1
def in_all others
-
grouping_all :in, others
-
end
-
-
1
def not_between other
-
if other.begin == -Float::INFINITY # The range begins with negative infinity
-
if other.end == Float::INFINITY
-
self.in([])
-
elsif other.exclude_end?
-
gteq(other.end)
-
else
-
gt(other.end)
-
end
-
elsif other.end == Float::INFINITY
-
lt(other.begin)
-
else
-
left = lt(other.begin)
-
right = if other.exclude_end?
-
gteq(other.end)
-
else
-
gt(other.end)
-
end
-
left.or(right)
-
end
-
end
-
-
1
def not_in other
-
case other
-
when Arel::SelectManager
-
Arel::Nodes::NotIn.new(self, other.ast)
-
when Range
-
if $VERBOSE
-
warn <<-eowarn
-
Passing a range to `#not_in` is deprecated. Call `#not_between`, instead.
-
eowarn
-
end
-
not_between(other)
-
when Enumerable
-
Nodes::NotIn.new self, quoted_array(other)
-
else
-
Nodes::NotIn.new self, quoted_node(other)
-
end
-
end
-
-
1
def not_in_any others
-
grouping_any :not_in, others
-
end
-
-
1
def not_in_all others
-
grouping_all :not_in, others
-
end
-
-
1
def matches other, escape = nil
-
Nodes::Matches.new self, quoted_node(other), escape
-
end
-
-
1
def matches_any others, escape = nil
-
grouping_any :matches, others, escape
-
end
-
-
1
def matches_all others, escape = nil
-
grouping_all :matches, others, escape
-
end
-
-
1
def does_not_match other, escape = nil
-
Nodes::DoesNotMatch.new self, quoted_node(other), escape
-
end
-
-
1
def does_not_match_any others, escape = nil
-
grouping_any :does_not_match, others, escape
-
end
-
-
1
def does_not_match_all others, escape = nil
-
grouping_all :does_not_match, others, escape
-
end
-
-
1
def gteq right
-
Nodes::GreaterThanOrEqual.new self, quoted_node(right)
-
end
-
-
1
def gteq_any others
-
grouping_any :gteq, others
-
end
-
-
1
def gteq_all others
-
grouping_all :gteq, others
-
end
-
-
1
def gt right
-
Nodes::GreaterThan.new self, quoted_node(right)
-
end
-
-
1
def gt_any others
-
grouping_any :gt, others
-
end
-
-
1
def gt_all others
-
grouping_all :gt, others
-
end
-
-
1
def lt right
-
Nodes::LessThan.new self, quoted_node(right)
-
end
-
-
1
def lt_any others
-
grouping_any :lt, others
-
end
-
-
1
def lt_all others
-
grouping_all :lt, others
-
end
-
-
1
def lteq right
-
Nodes::LessThanOrEqual.new self, quoted_node(right)
-
end
-
-
1
def lteq_any others
-
grouping_any :lteq, others
-
end
-
-
1
def lteq_all others
-
grouping_all :lteq, others
-
end
-
-
1
private
-
-
1
def grouping_any method_id, others, *extras
-
nodes = others.map {|expr| send(method_id, expr, *extras)}
-
Nodes::Grouping.new nodes.inject { |memo,node|
-
Nodes::Or.new(memo, node)
-
}
-
end
-
-
1
def grouping_all method_id, others, *extras
-
nodes = others.map {|expr| send(method_id, expr, *extras)}
-
Nodes::Grouping.new Nodes::And.new(nodes)
-
end
-
-
1
def quoted_node(other)
-
11
Nodes.build_quoted(other, self)
-
end
-
-
1
def quoted_array(others)
-
others.map { |v| quoted_node(v) }
-
end
-
end
-
end
-
1
require 'arel/collectors/sql_string'
-
-
1
module Arel
-
1
class SelectManager < Arel::TreeManager
-
1
include Arel::Crud
-
-
1
STRING_OR_SYMBOL_CLASS = [Symbol, String]
-
-
1
def initialize engine, table = nil
-
60
super(engine)
-
60
@ast = Nodes::SelectStatement.new
-
60
@ctx = @ast.cores.last
-
60
from table
-
end
-
-
1
def initialize_copy other
-
super
-
@ctx = @ast.cores.last
-
end
-
-
1
def limit
-
@ast.limit && @ast.limit.expr
-
end
-
1
alias :taken :limit
-
-
1
def constraints
-
3
@ctx.wheres
-
end
-
-
1
def offset
-
@ast.offset && @ast.offset.expr
-
end
-
-
1
def skip amount
-
if amount
-
@ast.offset = Nodes::Offset.new(amount)
-
else
-
@ast.offset = nil
-
end
-
self
-
end
-
1
alias :offset= :skip
-
-
###
-
# Produces an Arel::Nodes::Exists node
-
1
def exists
-
Arel::Nodes::Exists.new @ast
-
end
-
-
1
def as other
-
create_table_alias grouping(@ast), Nodes::SqlLiteral.new(other)
-
end
-
-
1
def lock locking = Arel.sql('FOR UPDATE')
-
case locking
-
when true
-
locking = Arel.sql('FOR UPDATE')
-
when Arel::Nodes::SqlLiteral
-
when String
-
locking = Arel.sql locking
-
end
-
-
@ast.lock = Nodes::Lock.new(locking)
-
self
-
end
-
-
1
def locked
-
23
@ast.lock
-
end
-
-
1
def on *exprs
-
@ctx.source.right.last.right = Nodes::On.new(collapse(exprs))
-
self
-
end
-
-
1
def group *columns
-
columns.each do |column|
-
# FIXME: backwards compat
-
column = Nodes::SqlLiteral.new(column) if String === column
-
column = Nodes::SqlLiteral.new(column.to_s) if Symbol === column
-
-
@ctx.groups.push Nodes::Group.new column
-
end
-
self
-
end
-
-
1
def from table
-
60
table = Nodes::SqlLiteral.new(table) if String === table
-
-
60
case table
-
when Nodes::Join
-
@ctx.source.right << table
-
else
-
60
@ctx.source.left = table
-
end
-
-
60
self
-
end
-
-
1
def froms
-
@ast.cores.map { |x| x.from }.compact
-
end
-
-
1
def join relation, klass = Nodes::InnerJoin
-
return self unless relation
-
-
case relation
-
when String, Nodes::SqlLiteral
-
raise if relation.empty?
-
klass = Nodes::StringJoin
-
end
-
-
@ctx.source.right << create_join(relation, nil, klass)
-
self
-
end
-
-
1
def outer_join relation
-
join(relation, Nodes::OuterJoin)
-
end
-
-
1
def having *exprs
-
@ctx.having = Nodes::Having.new(collapse(exprs, @ctx.having))
-
self
-
end
-
-
1
def window name
-
window = Nodes::NamedWindow.new(name)
-
@ctx.windows.push window
-
window
-
end
-
-
1
def project *projections
-
# FIXME: converting these to SQLLiterals is probably not good, but
-
# rails tests require it.
-
60
@ctx.projections.concat projections.map { |x|
-
60
STRING_OR_SYMBOL_CLASS.include?(x.class) ? Nodes::SqlLiteral.new(x.to_s) : x
-
}
-
60
self
-
end
-
-
1
def projections
-
@ctx.projections
-
end
-
-
1
def projections= projections
-
@ctx.projections = projections
-
end
-
-
1
def distinct(value = true)
-
60
if value
-
@ctx.set_quantifier = Arel::Nodes::Distinct.new
-
else
-
60
@ctx.set_quantifier = nil
-
end
-
60
self
-
end
-
-
1
def distinct_on(value)
-
if value
-
@ctx.set_quantifier = Arel::Nodes::DistinctOn.new(value)
-
else
-
@ctx.set_quantifier = nil
-
end
-
self
-
end
-
-
1
def order *expr
-
# FIXME: We SHOULD NOT be converting these to SqlLiteral automatically
-
17
@ast.orders.concat expr.map { |x|
-
17
STRING_OR_SYMBOL_CLASS.include?(x.class) ? Nodes::SqlLiteral.new(x.to_s) : x
-
}
-
17
self
-
end
-
-
1
def orders
-
@ast.orders
-
end
-
-
1
def where_sql
-
return if @ctx.wheres.empty?
-
-
viz = Visitors::WhereSql.new @engine.connection
-
Nodes::SqlLiteral.new viz.accept(@ctx, Collectors::SQLString.new).value
-
end
-
-
1
def union operation, other = nil
-
if other
-
node_class = Nodes.const_get("Union#{operation.to_s.capitalize}")
-
else
-
other = operation
-
node_class = Nodes::Union
-
end
-
-
node_class.new self.ast, other.ast
-
end
-
-
1
def intersect other
-
Nodes::Intersect.new ast, other.ast
-
end
-
-
1
def except other
-
Nodes::Except.new ast, other.ast
-
end
-
1
alias :minus :except
-
-
1
def with *subqueries
-
if subqueries.first.is_a? Symbol
-
node_class = Nodes.const_get("With#{subqueries.shift.to_s.capitalize}")
-
else
-
node_class = Nodes::With
-
end
-
@ast.with = node_class.new(subqueries.flatten)
-
-
self
-
end
-
-
1
def take limit
-
4
if limit
-
4
@ast.limit = Nodes::Limit.new(limit)
-
4
@ctx.top = Nodes::Top.new(limit)
-
else
-
@ast.limit = nil
-
@ctx.top = nil
-
end
-
4
self
-
end
-
1
alias limit= take
-
-
1
def join_sources
-
@ctx.source.right
-
end
-
-
1
def source
-
@ctx.source
-
end
-
-
1
class Row < Struct.new(:data) # :nodoc:
-
1
def id
-
data['id']
-
end
-
-
1
def method_missing(name, *args)
-
name = name.to_s
-
return data[name] if data.key?(name)
-
super
-
end
-
end
-
-
1
private
-
1
def collapse exprs, existing = nil
-
exprs = exprs.unshift(existing.expr) if existing
-
exprs = exprs.compact.map { |expr|
-
if String === expr
-
# FIXME: Don't do this automatically
-
Arel.sql(expr)
-
else
-
expr
-
end
-
}
-
-
if exprs.length == 1
-
exprs.first
-
else
-
create_and exprs
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
class Table
-
1
include Arel::Crud
-
1
include Arel::FactoryMethods
-
-
1
@engine = nil
-
2
class << self; attr_accessor :engine; end
-
-
1
attr_accessor :name, :engine, :aliases, :table_alias
-
-
# TableAlias and Table both have a #table_name which is the name of the underlying table
-
1
alias :table_name :name
-
-
1
def initialize name, engine = Table.engine
-
5
@name = name.to_s
-
5
@engine = engine
-
5
@columns = nil
-
5
@aliases = []
-
5
@table_alias = nil
-
5
@primary_key = nil
-
-
5
if Hash === engine
-
@engine = engine[:engine] || Table.engine
-
-
# Sometime AR sends an :as parameter to table, to let the table know
-
# that it is an Alias. We may want to override new, and return a
-
# TableAlias node?
-
@table_alias = engine[:as] unless engine[:as].to_s == @name
-
end
-
end
-
-
1
def primary_key
-
if $VERBOSE
-
warn <<-eowarn
-
primary_key (#{caller.first}) is deprecated and will be removed in Arel 4.0.0
-
eowarn
-
end
-
@primary_key ||= begin
-
primary_key_name = @engine.connection.primary_key(name)
-
# some tables might be without primary key
-
primary_key_name && self[primary_key_name]
-
end
-
end
-
-
1
def alias name = "#{self.name}_2"
-
Nodes::TableAlias.new(self, name).tap do |node|
-
@aliases << node
-
end
-
end
-
-
1
def from table
-
SelectManager.new(@engine, table)
-
end
-
-
1
def join relation, klass = Nodes::InnerJoin
-
return from(self) unless relation
-
-
case relation
-
when String, Nodes::SqlLiteral
-
raise if relation.empty?
-
klass = Nodes::StringJoin
-
end
-
-
from(self).join(relation, klass)
-
end
-
-
1
def outer_join relation
-
join(relation, Nodes::OuterJoin)
-
end
-
-
1
def group *columns
-
from(self).group(*columns)
-
end
-
-
1
def order *expr
-
from(self).order(*expr)
-
end
-
-
1
def where condition
-
from(self).where condition
-
end
-
-
1
def project *things
-
from(self).project(*things)
-
end
-
-
1
def take amount
-
from(self).take amount
-
end
-
-
1
def skip amount
-
from(self).skip amount
-
end
-
-
1
def having expr
-
from(self).having expr
-
end
-
-
1
def [] name
-
210
::Arel::Attribute.new self, name
-
end
-
-
1
def select_manager
-
SelectManager.new(@engine)
-
end
-
-
1
def insert_manager
-
InsertManager.new(@engine)
-
end
-
-
1
def update_manager
-
UpdateManager.new(@engine)
-
end
-
-
1
def delete_manager
-
DeleteManager.new(@engine)
-
end
-
-
1
def hash
-
# Perf note: aliases, table alias and engine is excluded from the hash
-
# aliases can have a loop back to this table breaking hashes in parent
-
# relations, for the vast majority of cases @name is unique to a query
-
150
@name.hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.name == other.name &&
-
self.engine == other.engine &&
-
self.aliases == other.aliases &&
-
self.table_alias == other.table_alias
-
end
-
1
alias :== :eql?
-
-
1
private
-
-
1
def attributes_for columns
-
return nil unless columns
-
-
columns.map do |column|
-
Attributes.for(column).new self, column.name.to_sym
-
end
-
end
-
-
end
-
end
-
1
require 'arel/collectors/sql_string'
-
-
1
module Arel
-
1
class TreeManager
-
1
include Arel::FactoryMethods
-
-
1
attr_reader :ast, :engine
-
-
1
attr_accessor :bind_values
-
-
1
def initialize engine
-
92
@engine = engine
-
92
@ctx = nil
-
92
@bind_values = []
-
end
-
-
1
def to_dot
-
collector = Arel::Collectors::PlainString.new
-
collector = Visitors::Dot.new.accept @ast, collector
-
collector.value
-
end
-
-
1
def visitor
-
engine.connection.visitor
-
end
-
-
1
def to_sql
-
collector = Arel::Collectors::SQLString.new
-
collector = visitor.accept @ast, collector
-
collector.value
-
end
-
-
1
def initialize_copy other
-
super
-
@ast = @ast.clone
-
end
-
-
1
def where expr
-
11
if Arel::TreeManager === expr
-
expr = expr.ast
-
end
-
11
@ctx.wheres << expr
-
11
self
-
end
-
end
-
end
-
1
module Arel
-
1
class UpdateManager < Arel::TreeManager
-
1
def initialize engine
-
4
super
-
4
@ast = Nodes::UpdateStatement.new
-
4
@ctx = @ast
-
end
-
-
1
def take limit
-
@ast.limit = Nodes::Limit.new(Nodes.build_quoted(limit)) if limit
-
self
-
end
-
-
1
def key= key
-
4
@ast.key = Nodes.build_quoted(key)
-
end
-
-
1
def key
-
@ast.key
-
end
-
-
1
def order *expr
-
4
@ast.orders = expr
-
4
self
-
end
-
-
###
-
# UPDATE +table+
-
1
def table table
-
4
@ast.relation = table
-
4
self
-
end
-
-
1
def wheres= exprs
-
4
@ast.wheres = exprs
-
end
-
-
1
def where expr
-
@ast.wheres << expr
-
self
-
end
-
-
1
def set values
-
4
if String === values
-
@ast.values = [values]
-
else
-
4
@ast.values = values.map { |column,value|
-
9
Nodes::Assignment.new(
-
Nodes::UnqualifiedColumn.new(column),
-
value
-
)
-
}
-
end
-
4
self
-
end
-
end
-
end
-
1
require 'arel/visitors/visitor'
-
1
require 'arel/visitors/depth_first'
-
1
require 'arel/visitors/to_sql'
-
1
require 'arel/visitors/sqlite'
-
1
require 'arel/visitors/postgresql'
-
1
require 'arel/visitors/mysql'
-
1
require 'arel/visitors/mssql'
-
1
require 'arel/visitors/oracle'
-
1
require 'arel/visitors/where_sql'
-
1
require 'arel/visitors/dot'
-
1
require 'arel/visitors/ibm_db'
-
1
require 'arel/visitors/informix'
-
-
1
module Arel
-
1
module Visitors
-
1
VISITORS = {
-
'postgresql' => Arel::Visitors::PostgreSQL,
-
'mysql' => Arel::Visitors::MySQL,
-
'mysql2' => Arel::Visitors::MySQL,
-
'mssql' => Arel::Visitors::MSSQL,
-
'sqlserver' => Arel::Visitors::MSSQL,
-
'oracle_enhanced' => Arel::Visitors::Oracle,
-
'sqlite' => Arel::Visitors::SQLite,
-
'sqlite3' => Arel::Visitors::SQLite,
-
'ibm_db' => Arel::Visitors::IBM_DB,
-
'informix' => Arel::Visitors::Informix,
-
}
-
-
1
ENGINE_VISITORS = Hash.new do |hash, engine|
-
pool = engine.connection_pool
-
adapter = pool.spec.config[:adapter]
-
hash[engine] = (VISITORS[adapter] || Visitors::ToSql).new(engine)
-
end
-
-
1
def self.visitor_for engine
-
ENGINE_VISITORS[engine]
-
end
-
2
class << self; alias :for :visitor_for; end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
module BindVisitor
-
1
def initialize target
-
@block = nil
-
super
-
end
-
-
1
def accept node, collector, &block
-
@block = block if block_given?
-
super
-
end
-
-
1
private
-
-
1
def visit_Arel_Nodes_Assignment o, collector
-
if o.right.is_a? Arel::Nodes::BindParam
-
collector = visit o.left, collector
-
collector << " = "
-
visit o.right, collector
-
else
-
super
-
end
-
end
-
-
1
def visit_Arel_Nodes_BindParam o, collector
-
if @block
-
val = @block.call
-
if String === val
-
collector << val
-
end
-
else
-
super
-
end
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Dot < Arel::Visitors::Visitor
-
1
class Node # :nodoc:
-
1
attr_accessor :name, :id, :fields
-
-
1
def initialize name, id, fields = []
-
@name = name
-
@id = id
-
@fields = fields
-
end
-
end
-
-
1
class Edge < Struct.new :name, :from, :to # :nodoc:
-
end
-
-
1
def initialize
-
super()
-
@nodes = []
-
@edges = []
-
@node_stack = []
-
@edge_stack = []
-
@seen = {}
-
end
-
-
1
def accept object, collector
-
visit object
-
collector << to_dot
-
end
-
-
1
private
-
-
1
def visit_Arel_Nodes_Ordering o
-
visit_edge o, "expr"
-
end
-
-
1
def visit_Arel_Nodes_TableAlias o
-
visit_edge o, "name"
-
visit_edge o, "relation"
-
end
-
-
1
def visit_Arel_Nodes_Count o
-
visit_edge o, "expressions"
-
visit_edge o, "distinct"
-
end
-
-
1
def visit_Arel_Nodes_Values o
-
visit_edge o, "expressions"
-
end
-
-
1
def visit_Arel_Nodes_StringJoin o
-
visit_edge o, "left"
-
end
-
-
1
def visit_Arel_Nodes_InnerJoin o
-
visit_edge o, "left"
-
visit_edge o, "right"
-
end
-
1
alias :visit_Arel_Nodes_FullOuterJoin :visit_Arel_Nodes_InnerJoin
-
1
alias :visit_Arel_Nodes_OuterJoin :visit_Arel_Nodes_InnerJoin
-
1
alias :visit_Arel_Nodes_RightOuterJoin :visit_Arel_Nodes_InnerJoin
-
-
1
def visit_Arel_Nodes_DeleteStatement o
-
visit_edge o, "relation"
-
visit_edge o, "wheres"
-
end
-
-
1
def unary o
-
visit_edge o, "expr"
-
end
-
1
alias :visit_Arel_Nodes_Group :unary
-
1
alias :visit_Arel_Nodes_Grouping :unary
-
1
alias :visit_Arel_Nodes_Having :unary
-
1
alias :visit_Arel_Nodes_Limit :unary
-
1
alias :visit_Arel_Nodes_Not :unary
-
1
alias :visit_Arel_Nodes_Offset :unary
-
1
alias :visit_Arel_Nodes_On :unary
-
1
alias :visit_Arel_Nodes_Top :unary
-
1
alias :visit_Arel_Nodes_UnqualifiedColumn :unary
-
1
alias :visit_Arel_Nodes_Preceding :unary
-
1
alias :visit_Arel_Nodes_Following :unary
-
1
alias :visit_Arel_Nodes_Rows :unary
-
1
alias :visit_Arel_Nodes_Range :unary
-
-
1
def window o
-
visit_edge o, "partitions"
-
visit_edge o, "orders"
-
visit_edge o, "framing"
-
end
-
1
alias :visit_Arel_Nodes_Window :window
-
-
1
def named_window o
-
visit_edge o, "partitions"
-
visit_edge o, "orders"
-
visit_edge o, "framing"
-
visit_edge o, "name"
-
end
-
1
alias :visit_Arel_Nodes_NamedWindow :named_window
-
-
1
def function o
-
visit_edge o, "expressions"
-
visit_edge o, "distinct"
-
visit_edge o, "alias"
-
end
-
1
alias :visit_Arel_Nodes_Exists :function
-
1
alias :visit_Arel_Nodes_Min :function
-
1
alias :visit_Arel_Nodes_Max :function
-
1
alias :visit_Arel_Nodes_Avg :function
-
1
alias :visit_Arel_Nodes_Sum :function
-
-
1
def extract o
-
visit_edge o, "expressions"
-
visit_edge o, "alias"
-
end
-
1
alias :visit_Arel_Nodes_Extract :extract
-
-
1
def visit_Arel_Nodes_NamedFunction o
-
visit_edge o, "name"
-
visit_edge o, "expressions"
-
visit_edge o, "distinct"
-
visit_edge o, "alias"
-
end
-
-
1
def visit_Arel_Nodes_InsertStatement o
-
visit_edge o, "relation"
-
visit_edge o, "columns"
-
visit_edge o, "values"
-
end
-
-
1
def visit_Arel_Nodes_SelectCore o
-
visit_edge o, "source"
-
visit_edge o, "projections"
-
visit_edge o, "wheres"
-
visit_edge o, "windows"
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o
-
visit_edge o, "cores"
-
visit_edge o, "limit"
-
visit_edge o, "orders"
-
visit_edge o, "offset"
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o
-
visit_edge o, "relation"
-
visit_edge o, "wheres"
-
visit_edge o, "values"
-
end
-
-
1
def visit_Arel_Table o
-
visit_edge o, "name"
-
end
-
-
1
def visit_Arel_Attribute o
-
visit_edge o, "relation"
-
visit_edge o, "name"
-
end
-
1
alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Float :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_String :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Time :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute
-
-
1
def nary o
-
o.children.each_with_index do |x,i|
-
edge(i) { visit x }
-
end
-
end
-
1
alias :visit_Arel_Nodes_And :nary
-
-
1
def binary o
-
visit_edge o, "left"
-
visit_edge o, "right"
-
end
-
1
alias :visit_Arel_Nodes_As :binary
-
1
alias :visit_Arel_Nodes_Assignment :binary
-
1
alias :visit_Arel_Nodes_Between :binary
-
1
alias :visit_Arel_Nodes_DoesNotMatch :binary
-
1
alias :visit_Arel_Nodes_Equality :binary
-
1
alias :visit_Arel_Nodes_GreaterThan :binary
-
1
alias :visit_Arel_Nodes_GreaterThanOrEqual :binary
-
1
alias :visit_Arel_Nodes_In :binary
-
1
alias :visit_Arel_Nodes_JoinSource :binary
-
1
alias :visit_Arel_Nodes_LessThan :binary
-
1
alias :visit_Arel_Nodes_LessThanOrEqual :binary
-
1
alias :visit_Arel_Nodes_Matches :binary
-
1
alias :visit_Arel_Nodes_NotEqual :binary
-
1
alias :visit_Arel_Nodes_NotIn :binary
-
1
alias :visit_Arel_Nodes_Or :binary
-
1
alias :visit_Arel_Nodes_Over :binary
-
-
1
def visit_String o
-
@node_stack.last.fields << o
-
end
-
1
alias :visit_Time :visit_String
-
1
alias :visit_Date :visit_String
-
1
alias :visit_DateTime :visit_String
-
1
alias :visit_NilClass :visit_String
-
1
alias :visit_TrueClass :visit_String
-
1
alias :visit_FalseClass :visit_String
-
1
alias :visit_Arel_Nodes_BindParam :visit_String
-
1
alias :visit_Integer :visit_String
-
1
alias :visit_Fixnum :visit_String
-
1
alias :visit_BigDecimal :visit_String
-
1
alias :visit_Float :visit_String
-
1
alias :visit_Symbol :visit_String
-
1
alias :visit_Arel_Nodes_SqlLiteral :visit_String
-
-
1
def visit_Hash o
-
o.each_with_index do |pair, i|
-
edge("pair_#{i}") { visit pair }
-
end
-
end
-
-
1
def visit_Array o
-
o.each_with_index do |x,i|
-
edge(i) { visit x }
-
end
-
end
-
1
alias :visit_Set :visit_Array
-
-
1
def visit_edge o, method
-
edge(method) { visit o.send(method) }
-
end
-
-
1
def visit o
-
if node = @seen[o.object_id]
-
@edge_stack.last.to = node
-
return
-
end
-
-
node = Node.new(o.class.name, o.object_id)
-
@seen[node.id] = node
-
@nodes << node
-
with_node node do
-
super
-
end
-
end
-
-
1
def edge name
-
edge = Edge.new(name, @node_stack.last)
-
@edge_stack.push edge
-
@edges << edge
-
yield
-
@edge_stack.pop
-
end
-
-
1
def with_node node
-
if edge = @edge_stack.last
-
edge.to = node
-
end
-
-
@node_stack.push node
-
yield
-
@node_stack.pop
-
end
-
-
1
def quote string
-
string.to_s.gsub('"', '\"')
-
end
-
-
1
def to_dot
-
"digraph \"Arel\" {\nnode [width=0.375,height=0.25,shape=record];\n" +
-
@nodes.map { |node|
-
label = "<f0>#{node.name}"
-
-
node.fields.each_with_index do |field, i|
-
label << "|<f#{i + 1}>#{quote field}"
-
end
-
-
"#{node.id} [label=\"#{label}\"];"
-
}.join("\n") + "\n" + @edges.map { |edge|
-
"#{edge.from.id} -> #{edge.to.id} [label=\"#{edge.name}\"];"
-
}.join("\n") + "\n}"
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class IBM_DB < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_Limit o, collector
-
collector << "FETCH FIRST "
-
collector = visit o.expr, collector
-
collector << " ROWS ONLY"
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Informix < Arel::Visitors::ToSql
-
1
private
-
1
def visit_Arel_Nodes_SelectStatement o, collector
-
collector << "SELECT "
-
collector = maybe_visit o.offset, collector
-
collector = maybe_visit o.limit, collector
-
collector = o.cores.inject(collector) { |c,x|
-
visit_Arel_Nodes_SelectCore x, c
-
}
-
if o.orders.any?
-
collector << "ORDER BY "
-
collector = inject_join o.orders, collector, ", "
-
end
-
collector = maybe_visit o.lock, collector
-
end
-
1
def visit_Arel_Nodes_SelectCore o, collector
-
collector = inject_join o.projections, collector, ", "
-
froms = false
-
if o.source && !o.source.empty?
-
froms = true
-
collector << " FROM "
-
collector = visit o.source, collector
-
end
-
-
if o.wheres.any?
-
collector << " WHERE "
-
collector = inject_join o.wheres, collector, " AND "
-
end
-
-
if o.groups.any?
-
collector << "GROUP BY "
-
collector = inject_join o.groups, collector, ", "
-
end
-
-
maybe_visit o.having, collector
-
end
-
1
def visit_Arel_Nodes_Offset o, collector
-
collector << "SKIP "
-
visit o.expr, collector
-
end
-
1
def visit_Arel_Nodes_Limit o, collector
-
collector << "FIRST "
-
visit o.expr, collector
-
collector << " "
-
end
-
end
-
end
-
end
-
-
1
module Arel
-
1
module Visitors
-
1
class MSSQL < Arel::Visitors::ToSql
-
1
RowNumber = Struct.new :children
-
-
1
private
-
-
# `top` wouldn't really work here. I.e. User.select("distinct first_name").limit(10) would generate
-
# "select top 10 distinct first_name from users", which is invalid query! it should be
-
# "select distinct top 10 first_name from users"
-
1
def visit_Arel_Nodes_Top o
-
""
-
end
-
-
1
def visit_Arel_Visitors_MSSQL_RowNumber o, collector
-
collector << "ROW_NUMBER() OVER (ORDER BY "
-
inject_join(o.children, collector, ', ') << ") as _row_num"
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o, collector
-
if !o.limit && !o.offset
-
return super
-
end
-
-
is_select_count = false
-
o.cores.each { |x|
-
core_order_by = row_num_literal determine_order_by(o.orders, x)
-
if select_count? x
-
x.projections = [core_order_by]
-
is_select_count = true
-
else
-
x.projections << core_order_by
-
end
-
}
-
-
if is_select_count
-
# fixme count distinct wouldn't work with limit or offset
-
collector << "SELECT COUNT(1) as count_id FROM ("
-
end
-
-
collector << "SELECT _t.* FROM ("
-
collector = o.cores.inject(collector) { |c,x|
-
visit_Arel_Nodes_SelectCore x, c
-
}
-
collector << ") as _t WHERE #{get_offset_limit_clause(o)}"
-
-
if is_select_count
-
collector << ") AS subquery"
-
else
-
collector
-
end
-
end
-
-
1
def get_offset_limit_clause o
-
first_row = o.offset ? o.offset.expr.to_i + 1 : 1
-
last_row = o.limit ? o.limit.expr.to_i - 1 + first_row : nil
-
if last_row
-
" _row_num BETWEEN #{first_row} AND #{last_row}"
-
else
-
" _row_num >= #{first_row}"
-
end
-
end
-
-
1
def determine_order_by orders, x
-
if orders.any?
-
orders
-
elsif x.groups.any?
-
x.groups
-
else
-
pk = find_left_table_pk(x.froms)
-
pk ? [pk] : []
-
end
-
end
-
-
1
def row_num_literal order_by
-
RowNumber.new order_by
-
end
-
-
1
def select_count? x
-
x.projections.length == 1 && Arel::Nodes::Count === x.projections.first
-
end
-
-
# FIXME raise exception of there is no pk?
-
# FIXME!! Table.primary_key will be deprecated. What is the replacement??
-
1
def find_left_table_pk o
-
return o.primary_key if o.instance_of? Arel::Table
-
find_left_table_pk o.left if o.kind_of? Arel::Nodes::Join
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class MySQL < Arel::Visitors::ToSql
-
1
private
-
1
def visit_Arel_Nodes_Union o, collector, suppress_parens = false
-
unless suppress_parens
-
collector << "( "
-
end
-
-
collector = case o.left
-
when Arel::Nodes::Union
-
visit_Arel_Nodes_Union o.left, collector, true
-
else
-
visit o.left, collector
-
end
-
-
collector << " UNION "
-
-
collector = case o.right
-
when Arel::Nodes::Union
-
visit_Arel_Nodes_Union o.right, collector, true
-
else
-
visit o.right, collector
-
end
-
-
if suppress_parens
-
collector
-
else
-
collector << " )"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Bin o, collector
-
collector << "BINARY "
-
visit o.expr, collector
-
end
-
-
###
-
# :'(
-
# http://dev.mysql.com/doc/refman/5.0/en/select.html#id3482214
-
1
def visit_Arel_Nodes_SelectStatement o, collector
-
if o.offset && !o.limit
-
o.limit = Arel::Nodes::Limit.new(18446744073709551615)
-
end
-
super
-
end
-
-
1
def visit_Arel_Nodes_SelectCore o, collector
-
o.froms ||= Arel.sql('DUAL')
-
super
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o, collector
-
collector << "UPDATE "
-
collector = visit o.relation, collector
-
-
unless o.values.empty?
-
collector << " SET "
-
collector = inject_join o.values, collector, ', '
-
end
-
-
unless o.wheres.empty?
-
collector << " WHERE "
-
collector = inject_join o.wheres, collector, ' AND '
-
end
-
-
unless o.orders.empty?
-
collector << " ORDER BY "
-
collector = inject_join o.orders, collector, ', '
-
end
-
-
maybe_visit o.limit, collector
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Oracle < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_SelectStatement o, collector
-
o = order_hacks(o)
-
-
# if need to select first records without ORDER BY and GROUP BY and without DISTINCT
-
# then can use simple ROWNUM in WHERE clause
-
if o.limit && o.orders.empty? && o.cores.first.groups.empty? && !o.offset && o.cores.first.set_quantifier.class.to_s !~ /Distinct/
-
o.cores.last.wheres.push Nodes::LessThanOrEqual.new(
-
Nodes::SqlLiteral.new('ROWNUM'), o.limit.expr
-
)
-
return super
-
end
-
-
if o.limit && o.offset
-
o = o.dup
-
limit = o.limit.expr
-
offset = o.offset
-
o.offset = nil
-
collector << "
-
SELECT * FROM (
-
SELECT raw_sql_.*, rownum raw_rnum_
-
FROM ("
-
-
collector = super(o, collector)
-
collector << ") raw_sql_
-
WHERE rownum <= #{offset.expr.to_i + limit}
-
)
-
WHERE "
-
return visit(offset, collector)
-
end
-
-
if o.limit
-
o = o.dup
-
limit = o.limit.expr
-
collector << "SELECT * FROM ("
-
collector = super(o, collector)
-
collector << ") WHERE ROWNUM <= "
-
return visit limit, collector
-
end
-
-
if o.offset
-
o = o.dup
-
offset = o.offset
-
o.offset = nil
-
collector << "SELECT * FROM (
-
SELECT raw_sql_.*, rownum raw_rnum_
-
FROM ("
-
collector = super(o, collector)
-
collector << ") raw_sql_
-
)
-
WHERE "
-
return visit offset, collector
-
end
-
-
super
-
end
-
-
1
def visit_Arel_Nodes_Limit o, collector
-
collector
-
end
-
-
1
def visit_Arel_Nodes_Offset o, collector
-
collector << "raw_rnum_ > "
-
visit o.expr, collector
-
end
-
-
1
def visit_Arel_Nodes_Except o, collector
-
collector << "( "
-
collector = infix_value o, collector, " MINUS "
-
collector << " )"
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o, collector
-
# Oracle does not allow ORDER BY/LIMIT in UPDATEs.
-
if o.orders.any? && o.limit.nil?
-
# However, there is no harm in silently eating the ORDER BY clause if no LIMIT has been provided,
-
# otherwise let the user deal with the error
-
o = o.dup
-
o.orders = []
-
end
-
-
super
-
end
-
-
###
-
# Hacks for the order clauses specific to Oracle
-
1
def order_hacks o
-
return o if o.orders.empty?
-
return o unless o.cores.any? do |core|
-
core.projections.any? do |projection|
-
/FIRST_VALUE/ === projection
-
end
-
end
-
# Previous version with join and split broke ORDER BY clause
-
# if it contained functions with several arguments (separated by ',').
-
#
-
# orders = o.orders.map { |x| visit x }.join(', ').split(',')
-
orders = o.orders.map do |x|
-
string = visit(x, Arel::Collectors::SQLString.new).value
-
if string.include?(',')
-
split_order_string(string)
-
else
-
string
-
end
-
end.flatten
-
o.orders = []
-
orders.each_with_index do |order, i|
-
o.orders <<
-
Nodes::SqlLiteral.new("alias_#{i}__#{' DESC' if /\bdesc$/i === order}")
-
end
-
o
-
end
-
-
# Split string by commas but count opening and closing brackets
-
# and ignore commas inside brackets.
-
1
def split_order_string(string)
-
array = []
-
i = 0
-
string.split(',').each do |part|
-
if array[i]
-
array[i] << ',' << part
-
else
-
# to ensure that array[i] will be String and not Arel::Nodes::SqlLiteral
-
array[i] = '' << part
-
end
-
i += 1 if array[i].count('(') == array[i].count(')')
-
end
-
array
-
end
-
-
1
def visit_Arel_Nodes_BindParam o, collector
-
collector.add_bind(o) { |i| ":a#{i}" }
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class PostgreSQL < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_Matches o, collector
-
infix_value o, collector, ' ILIKE '
-
end
-
-
1
def visit_Arel_Nodes_DoesNotMatch o, collector
-
infix_value o, collector, ' NOT ILIKE '
-
end
-
-
1
def visit_Arel_Nodes_Regexp o, collector
-
infix_value o, collector, ' ~ '
-
end
-
-
1
def visit_Arel_Nodes_NotRegexp o, collector
-
infix_value o, collector, ' !~ '
-
end
-
-
1
def visit_Arel_Nodes_DistinctOn o, collector
-
collector << "DISTINCT ON ( "
-
visit(o.expr, collector) << " )"
-
end
-
-
1
def visit_Arel_Nodes_BindParam o, collector
-
collector.add_bind(o) { |i| "$#{i}" }
-
end
-
end
-
end
-
end
-
1
require 'arel/visitors/visitor'
-
-
1
module Arel
-
1
module Visitors
-
1
class Reduce < Arel::Visitors::Visitor
-
1
def accept object, collector
-
60
visit object, collector
-
end
-
-
1
private
-
-
1
def visit object, collector
-
431
send dispatch[object.class], object, collector
-
rescue NoMethodError => e
-
raise e if respond_to?(dispatch[object.class], true)
-
superklass = object.class.ancestors.find { |klass|
-
respond_to?(dispatch[klass], true)
-
}
-
raise(TypeError, "Cannot visit #{object.class}") unless superklass
-
dispatch[object.class] = dispatch[superklass]
-
retry
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class SQLite < Arel::Visitors::ToSql
-
1
private
-
-
# Locks are not supported in SQLite
-
1
def visit_Arel_Nodes_Lock o, collector
-
collector
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o, collector
-
28
o.limit = Arel::Nodes::Limit.new(-1) if o.offset && !o.limit
-
28
super
-
end
-
end
-
end
-
end
-
1
require 'bigdecimal'
-
1
require 'date'
-
1
require 'arel/visitors/reduce'
-
-
1
module Arel
-
1
module Visitors
-
1
class ToSql < Arel::Visitors::Reduce
-
##
-
# This is some roflscale crazy stuff. I'm roflscaling this because
-
# building SQL queries is a hotspot. I will explain the roflscale so that
-
# others will not rm this code.
-
#
-
# In YARV, string literals in a method body will get duped when the byte
-
# code is executed. Let's take a look:
-
#
-
# > puts RubyVM::InstructionSequence.new('def foo; "bar"; end').disasm
-
#
-
# == disasm: <RubyVM::InstructionSequence:foo@<compiled>>=====
-
# 0000 trace 8
-
# 0002 trace 1
-
# 0004 putstring "bar"
-
# 0006 trace 16
-
# 0008 leave
-
#
-
# The `putstring` bytecode will dup the string and push it on the stack.
-
# In many cases in our SQL visitor, that string is never mutated, so there
-
# is no need to dup the literal.
-
#
-
# If we change to a constant lookup, the string will not be duped, and we
-
# can reduce the objects in our system:
-
#
-
# > puts RubyVM::InstructionSequence.new('BAR = "bar"; def foo; BAR; end').disasm
-
#
-
# == disasm: <RubyVM::InstructionSequence:foo@<compiled>>========
-
# 0000 trace 8
-
# 0002 trace 1
-
# 0004 getinlinecache 11, <ic:0>
-
# 0007 getconstant :BAR
-
# 0009 setinlinecache <ic:0>
-
# 0011 trace 16
-
# 0013 leave
-
#
-
# `getconstant` should be a hash lookup, and no object is duped when the
-
# value of the constant is pushed on the stack. Hence the crazy
-
# constants below.
-
#
-
# `matches` and `doesNotMatch` operate case-insensitively via Visitor subclasses
-
# specialized for specific databases when necessary.
-
#
-
-
1
WHERE = ' WHERE ' # :nodoc:
-
1
SPACE = ' ' # :nodoc:
-
1
COMMA = ', ' # :nodoc:
-
1
GROUP_BY = ' GROUP BY ' # :nodoc:
-
1
ORDER_BY = ' ORDER BY ' # :nodoc:
-
1
WINDOW = ' WINDOW ' # :nodoc:
-
1
AND = ' AND ' # :nodoc:
-
-
1
DISTINCT = 'DISTINCT' # :nodoc:
-
-
1
def initialize connection
-
1
super()
-
1
@connection = connection
-
end
-
-
1
def compile node, &block
-
accept(node, Arel::Collectors::SQLString.new, &block).value
-
end
-
-
1
private
-
-
1
def schema_cache
-
@connection.schema_cache
-
end
-
-
1
def visit_Arel_Nodes_DeleteStatement o, collector
-
3
collector << "DELETE FROM "
-
3
collector = visit o.relation, collector
-
3
if o.wheres.any?
-
3
collector << " WHERE "
-
3
inject_join o.wheres, collector, AND
-
else
-
collector
-
end
-
end
-
-
# FIXME: we should probably have a 2-pass visitor for this
-
1
def build_subselect key, o
-
stmt = Nodes::SelectStatement.new
-
core = stmt.cores.first
-
core.froms = o.relation
-
core.wheres = o.wheres
-
core.projections = [key]
-
stmt.limit = o.limit
-
stmt.orders = o.orders
-
stmt
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o, collector
-
4
if o.orders.empty? && o.limit.nil?
-
4
wheres = o.wheres
-
else
-
wheres = [Nodes::In.new(o.key, [build_subselect(o.key, o)])]
-
end
-
-
4
collector << "UPDATE "
-
4
collector = visit o.relation, collector
-
4
unless o.values.empty?
-
4
collector << " SET "
-
4
collector = inject_join o.values, collector, ", "
-
end
-
-
4
unless wheres.empty?
-
4
collector << " WHERE "
-
4
collector = inject_join wheres, collector, " AND "
-
end
-
-
4
collector
-
end
-
-
1
def visit_Arel_Nodes_InsertStatement o, collector
-
25
collector << "INSERT INTO "
-
25
collector = visit o.relation, collector
-
25
if o.columns.any?
-
collector << " (#{o.columns.map { |x|
-
130
quote_column_name x.name
-
25
}.join ', '})"
-
end
-
-
25
if o.values
-
25
maybe_visit o.values, collector
-
elsif o.select
-
maybe_visit o.select, collector
-
else
-
collector
-
end
-
end
-
-
1
def visit_Arel_Nodes_Exists o, collector
-
collector << "EXISTS ("
-
collector = visit(o.expressions, collector) << ")"
-
if o.alias
-
collector << " AS "
-
visit o.alias, collector
-
else
-
collector
-
end
-
end
-
-
1
def visit_Arel_Nodes_Casted o, collector
-
collector << quoted(o.val, o.attribute).to_s
-
end
-
-
1
def visit_Arel_Nodes_Quoted o, collector
-
collector << quoted(o.expr, nil).to_s
-
end
-
-
1
def visit_Arel_Nodes_True o, collector
-
collector << "TRUE"
-
end
-
-
1
def visit_Arel_Nodes_False o, collector
-
collector << "FALSE"
-
end
-
-
1
def table_exists? name
-
schema_cache.table_exists? name
-
end
-
-
1
def column_for attr
-
return unless attr
-
name = attr.name.to_s
-
table = attr.relation.table_name
-
-
return nil unless table_exists? table
-
-
column_cache(table)[name]
-
end
-
-
1
def column_cache(table)
-
schema_cache.columns_hash(table)
-
end
-
-
1
def visit_Arel_Nodes_Values o, collector
-
25
collector << "VALUES ("
-
-
25
len = o.expressions.length - 1
-
25
o.expressions.zip(o.columns).each_with_index { |(value, attr), i|
-
130
case value
-
when Nodes::SqlLiteral, Nodes::BindParam
-
130
collector = visit value, collector
-
else
-
collector << quote(value, attr && column_for(attr)).to_s
-
end
-
130
unless i == len
-
105
collector << ', '
-
end
-
}
-
-
25
collector << ")"
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o, collector
-
28
if o.with
-
collector = visit o.with, collector
-
collector << SPACE
-
end
-
-
28
collector = o.cores.inject(collector) { |c,x|
-
28
visit_Arel_Nodes_SelectCore(x, c)
-
}
-
-
28
unless o.orders.empty?
-
17
collector << SPACE
-
17
collector << ORDER_BY
-
17
len = o.orders.length - 1
-
17
o.orders.each_with_index { |x, i|
-
17
collector = visit(x, collector)
-
17
collector << COMMA unless len == i
-
}
-
end
-
-
28
collector = maybe_visit o.limit, collector
-
28
collector = maybe_visit o.offset, collector
-
28
collector = maybe_visit o.lock, collector
-
-
28
collector
-
end
-
-
1
def visit_Arel_Nodes_SelectCore o, collector
-
28
collector << "SELECT"
-
-
28
collector = maybe_visit o.top, collector
-
-
28
collector = maybe_visit o.set_quantifier, collector
-
-
28
unless o.projections.empty?
-
28
collector << SPACE
-
28
len = o.projections.length - 1
-
28
o.projections.each_with_index do |x, i|
-
28
collector = visit(x, collector)
-
28
collector << COMMA unless len == i
-
end
-
end
-
-
28
if o.source && !o.source.empty?
-
28
collector << " FROM "
-
28
collector = visit o.source, collector
-
end
-
-
28
unless o.wheres.empty?
-
4
collector << WHERE
-
4
len = o.wheres.length - 1
-
4
o.wheres.each_with_index do |x, i|
-
4
collector = visit(x, collector)
-
4
collector << AND unless len == i
-
end
-
end
-
-
28
unless o.groups.empty?
-
collector << GROUP_BY
-
len = o.groups.length - 1
-
o.groups.each_with_index do |x, i|
-
collector = visit(x, collector)
-
collector << COMMA unless len == i
-
end
-
end
-
-
28
collector = maybe_visit o.having, collector
-
-
28
unless o.windows.empty?
-
collector << WINDOW
-
len = o.windows.length - 1
-
o.windows.each_with_index do |x, i|
-
collector = visit(x, collector)
-
collector << COMMA unless len == i
-
end
-
end
-
-
28
collector
-
end
-
-
1
def visit_Arel_Nodes_Bin o, collector
-
visit o.expr, collector
-
end
-
-
1
def visit_Arel_Nodes_Distinct o, collector
-
collector << DISTINCT
-
end
-
-
1
def visit_Arel_Nodes_DistinctOn o, collector
-
raise NotImplementedError, 'DISTINCT ON not implemented for this db'
-
end
-
-
1
def visit_Arel_Nodes_With o, collector
-
collector << "WITH "
-
inject_join o.children, collector, ', '
-
end
-
-
1
def visit_Arel_Nodes_WithRecursive o, collector
-
collector << "WITH RECURSIVE "
-
inject_join o.children, collector, ', '
-
end
-
-
1
def visit_Arel_Nodes_Union o, collector
-
collector << "( "
-
infix_value(o, collector, " UNION ") << " )"
-
end
-
-
1
def visit_Arel_Nodes_UnionAll o, collector
-
collector << "( "
-
infix_value(o, collector, " UNION ALL ") << " )"
-
end
-
-
1
def visit_Arel_Nodes_Intersect o, collector
-
collector << "( "
-
infix_value(o, collector, " INTERSECT ") << " )"
-
end
-
-
1
def visit_Arel_Nodes_Except o, collector
-
collector << "( "
-
infix_value(o, collector, " EXCEPT ") << " )"
-
end
-
-
1
def visit_Arel_Nodes_NamedWindow o, collector
-
collector << quote_column_name(o.name)
-
collector << " AS "
-
visit_Arel_Nodes_Window o, collector
-
end
-
-
1
def visit_Arel_Nodes_Window o, collector
-
collector << "("
-
-
if o.partitions.any?
-
collector << "PARTITION BY "
-
collector = inject_join o.partitions, collector, ", "
-
end
-
-
if o.orders.any?
-
collector << ' ' if o.partitions.any?
-
collector << "ORDER BY "
-
collector = inject_join o.orders, collector, ", "
-
end
-
-
if o.framing
-
collector << ' ' if o.partitions.any? or o.orders.any?
-
collector = visit o.framing, collector
-
end
-
-
collector << ")"
-
end
-
-
1
def visit_Arel_Nodes_Rows o, collector
-
if o.expr
-
collector << "ROWS "
-
visit o.expr, collector
-
else
-
collector << "ROWS"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Range o, collector
-
if o.expr
-
collector << "RANGE "
-
visit o.expr, collector
-
else
-
collector << "RANGE"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Preceding o, collector
-
collector = if o.expr
-
visit o.expr, collector
-
else
-
collector << "UNBOUNDED"
-
end
-
-
collector << " PRECEDING"
-
end
-
-
1
def visit_Arel_Nodes_Following o, collector
-
collector = if o.expr
-
visit o.expr, collector
-
else
-
collector << "UNBOUNDED"
-
end
-
-
collector << " FOLLOWING"
-
end
-
-
1
def visit_Arel_Nodes_CurrentRow o, collector
-
collector << "CURRENT ROW"
-
end
-
-
1
def visit_Arel_Nodes_Over o, collector
-
case o.right
-
when nil
-
visit(o.left, collector) << " OVER ()"
-
when Arel::Nodes::SqlLiteral
-
infix_value o, collector, " OVER "
-
when String, Symbol
-
visit(o.left, collector) << " OVER #{quote_column_name o.right.to_s}"
-
else
-
infix_value o, collector, " OVER "
-
end
-
end
-
-
1
def visit_Arel_Nodes_Having o, collector
-
collector << "HAVING "
-
visit o.expr, collector
-
end
-
-
1
def visit_Arel_Nodes_Offset o, collector
-
collector << "OFFSET "
-
visit o.expr, collector
-
end
-
-
1
def visit_Arel_Nodes_Limit o, collector
-
4
collector << "LIMIT "
-
4
visit o.expr, collector
-
end
-
-
# FIXME: this does nothing on most databases, but does on MSSQL
-
1
def visit_Arel_Nodes_Top o, collector
-
4
collector
-
end
-
-
1
def visit_Arel_Nodes_Lock o, collector
-
visit o.expr, collector
-
end
-
-
1
def visit_Arel_Nodes_Grouping o, collector
-
if o.expr.is_a? Nodes::Grouping
-
visit(o.expr, collector)
-
else
-
collector << "("
-
visit(o.expr, collector) << ")"
-
end
-
end
-
-
1
def visit_Arel_SelectManager o, collector
-
collector << "(#{o.to_sql.rstrip})"
-
end
-
-
1
def visit_Arel_Nodes_Ascending o, collector
-
visit(o.expr, collector) << " ASC"
-
end
-
-
1
def visit_Arel_Nodes_Descending o, collector
-
visit(o.expr, collector) << " DESC"
-
end
-
-
1
def visit_Arel_Nodes_Group o, collector
-
visit o.expr, collector
-
end
-
-
1
def visit_Arel_Nodes_NamedFunction o, collector
-
collector << o.name
-
collector << "("
-
collector << "DISTINCT " if o.distinct
-
collector = inject_join(o.expressions, collector, ", ") << ")"
-
if o.alias
-
collector << " AS "
-
visit o.alias, collector
-
else
-
collector
-
end
-
end
-
-
1
def visit_Arel_Nodes_Extract o, collector
-
collector << "EXTRACT(#{o.field.to_s.upcase} FROM "
-
visit(o.expr, collector) << ")"
-
end
-
-
1
def visit_Arel_Nodes_Count o, collector
-
aggregate "COUNT", o, collector
-
end
-
-
1
def visit_Arel_Nodes_Sum o, collector
-
aggregate "SUM", o, collector
-
end
-
-
1
def visit_Arel_Nodes_Max o, collector
-
aggregate "MAX", o, collector
-
end
-
-
1
def visit_Arel_Nodes_Min o, collector
-
aggregate "MIN", o, collector
-
end
-
-
1
def visit_Arel_Nodes_Avg o, collector
-
aggregate "AVG", o, collector
-
end
-
-
1
def visit_Arel_Nodes_TableAlias o, collector
-
collector = visit o.relation, collector
-
collector << " "
-
collector << quote_table_name(o.name)
-
end
-
-
1
def visit_Arel_Nodes_Between o, collector
-
collector = visit o.left, collector
-
collector << " BETWEEN "
-
visit o.right, collector
-
end
-
-
1
def visit_Arel_Nodes_GreaterThanOrEqual o, collector
-
collector = visit o.left, collector
-
collector << " >= "
-
visit o.right, collector
-
end
-
-
1
def visit_Arel_Nodes_GreaterThan o, collector
-
collector = visit o.left, collector
-
collector << " > "
-
visit o.right, collector
-
end
-
-
1
def visit_Arel_Nodes_LessThanOrEqual o, collector
-
collector = visit o.left, collector
-
collector << " <= "
-
visit o.right, collector
-
end
-
-
1
def visit_Arel_Nodes_LessThan o, collector
-
collector = visit o.left, collector
-
collector << " < "
-
visit o.right, collector
-
end
-
-
1
def visit_Arel_Nodes_Matches o, collector
-
collector = visit o.left, collector
-
collector << " LIKE "
-
collector = visit o.right, collector
-
if o.escape
-
collector << ' ESCAPE '
-
visit o.escape, collector
-
else
-
collector
-
end
-
end
-
-
1
def visit_Arel_Nodes_DoesNotMatch o, collector
-
collector = visit o.left, collector
-
collector << " NOT LIKE "
-
collector = visit o.right, collector
-
if o.escape
-
collector << ' ESCAPE '
-
visit o.escape, collector
-
else
-
collector
-
end
-
end
-
-
1
def visit_Arel_Nodes_JoinSource o, collector
-
28
if o.left
-
28
collector = visit o.left, collector
-
end
-
28
if o.right.any?
-
collector << " " if o.left
-
collector = inject_join o.right, collector, ' '
-
end
-
28
collector
-
end
-
-
1
def visit_Arel_Nodes_Regexp o, collector
-
raise NotImplementedError, '~ not implemented for this db'
-
end
-
-
1
def visit_Arel_Nodes_NotRegexp o, collector
-
raise NotImplementedError, '!~ not implemented for this db'
-
end
-
-
1
def visit_Arel_Nodes_StringJoin o, collector
-
visit o.left, collector
-
end
-
-
1
def visit_Arel_Nodes_FullOuterJoin o, collector
-
collector << "FULL OUTER JOIN "
-
collector = visit o.left, collector
-
collector << SPACE
-
visit o.right, collector
-
end
-
-
1
def visit_Arel_Nodes_OuterJoin o, collector
-
collector << "LEFT OUTER JOIN "
-
collector = visit o.left, collector
-
collector << " "
-
visit o.right, collector
-
end
-
-
1
def visit_Arel_Nodes_RightOuterJoin o, collector
-
collector << "RIGHT OUTER JOIN "
-
collector = visit o.left, collector
-
collector << SPACE
-
visit o.right, collector
-
end
-
-
1
def visit_Arel_Nodes_InnerJoin o, collector
-
collector << "INNER JOIN "
-
collector = visit o.left, collector
-
if o.right
-
collector << SPACE
-
visit(o.right, collector)
-
else
-
collector
-
end
-
end
-
-
1
def visit_Arel_Nodes_On o, collector
-
collector << "ON "
-
visit o.expr, collector
-
end
-
-
1
def visit_Arel_Nodes_Not o, collector
-
collector << "NOT ("
-
visit(o.expr, collector) << ")"
-
end
-
-
1
def visit_Arel_Table o, collector
-
60
if o.table_alias
-
collector << "#{quote_table_name o.name} #{quote_table_name o.table_alias}"
-
else
-
60
collector << quote_table_name(o.name)
-
end
-
end
-
-
1
def visit_Arel_Nodes_In o, collector
-
if Array === o.right && o.right.empty?
-
collector << '1=0'
-
else
-
collector = visit o.left, collector
-
collector << " IN ("
-
visit(o.right, collector) << ")"
-
end
-
end
-
-
1
def visit_Arel_Nodes_NotIn o, collector
-
if Array === o.right && o.right.empty?
-
collector << '1=1'
-
else
-
collector = visit o.left, collector
-
collector << " NOT IN ("
-
collector = visit o.right, collector
-
collector << ")"
-
end
-
end
-
-
1
def visit_Arel_Nodes_And o, collector
-
11
inject_join o.children, collector, " AND "
-
end
-
-
1
def visit_Arel_Nodes_Or o, collector
-
collector = visit o.left, collector
-
collector << " OR "
-
visit o.right, collector
-
end
-
-
1
def visit_Arel_Nodes_Assignment o, collector
-
9
case o.right
-
when Arel::Nodes::UnqualifiedColumn, Arel::Attributes::Attribute, Arel::Nodes::BindParam
-
9
collector = visit o.left, collector
-
9
collector << " = "
-
9
visit o.right, collector
-
else
-
collector = visit o.left, collector
-
collector << " = "
-
collector << quote(o.right, column_for(o.left)).to_s
-
end
-
end
-
-
1
def visit_Arel_Nodes_Equality o, collector
-
11
right = o.right
-
-
11
collector = visit o.left, collector
-
-
11
if right.nil?
-
collector << " IS NULL"
-
else
-
11
collector << " = "
-
11
visit right, collector
-
end
-
end
-
-
1
def visit_Arel_Nodes_NotEqual o, collector
-
right = o.right
-
-
collector = visit o.left, collector
-
-
if right.nil?
-
collector << " IS NOT NULL"
-
else
-
collector << " != "
-
visit right, collector
-
end
-
end
-
-
1
def visit_Arel_Nodes_As o, collector
-
collector = visit o.left, collector
-
collector << " AS "
-
visit o.right, collector
-
end
-
-
1
def visit_Arel_Nodes_UnqualifiedColumn o, collector
-
9
collector << "#{quote_column_name o.name}"
-
9
collector
-
end
-
-
1
def visit_Arel_Attributes_Attribute o, collector
-
39
join_name = o.relation.table_alias || o.relation.name
-
39
collector << "#{quote_table_name join_name}.#{quote_column_name o.name}"
-
end
-
1
alias :visit_Arel_Attributes_Integer :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Float :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Decimal :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_String :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Time :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attributes_Attribute
-
-
22
def literal o, collector; collector << o.to_s; end
-
-
1
def visit_Arel_Nodes_BindParam o, collector
-
300
collector.add_bind(o) { "?" }
-
end
-
-
1
alias :visit_Arel_Nodes_SqlLiteral :literal
-
1
alias :visit_Bignum :literal
-
1
alias :visit_Fixnum :literal
-
1
alias :visit_Integer :literal
-
-
1
def quoted o, a
-
quote(o, column_for(a))
-
end
-
-
1
def unsupported o, collector
-
raise "unsupported: #{o.class.name}"
-
end
-
-
1
alias :visit_ActiveSupport_Multibyte_Chars :unsupported
-
1
alias :visit_ActiveSupport_StringInquirer :unsupported
-
1
alias :visit_BigDecimal :unsupported
-
1
alias :visit_Class :unsupported
-
1
alias :visit_Date :unsupported
-
1
alias :visit_DateTime :unsupported
-
1
alias :visit_FalseClass :unsupported
-
1
alias :visit_Float :unsupported
-
1
alias :visit_Hash :unsupported
-
1
alias :visit_NilClass :unsupported
-
1
alias :visit_String :unsupported
-
1
alias :visit_Symbol :unsupported
-
1
alias :visit_Time :unsupported
-
1
alias :visit_TrueClass :unsupported
-
-
1
def visit_Arel_Nodes_InfixOperation o, collector
-
collector = visit o.left, collector
-
collector << " #{o.operator} "
-
visit o.right, collector
-
end
-
-
1
alias :visit_Arel_Nodes_Addition :visit_Arel_Nodes_InfixOperation
-
1
alias :visit_Arel_Nodes_Subtraction :visit_Arel_Nodes_InfixOperation
-
1
alias :visit_Arel_Nodes_Multiplication :visit_Arel_Nodes_InfixOperation
-
1
alias :visit_Arel_Nodes_Division :visit_Arel_Nodes_InfixOperation
-
-
1
def visit_Array o, collector
-
inject_join o, collector, ", "
-
end
-
1
alias :visit_Set :visit_Array
-
-
1
def quote value, column = nil
-
return value if Arel::Nodes::SqlLiteral === value
-
@connection.quote value, column
-
end
-
-
1
def quote_table_name name
-
99
return name if Arel::Nodes::SqlLiteral === name
-
99
@connection.quote_table_name(name)
-
end
-
-
1
def quote_column_name name
-
178
return name if Arel::Nodes::SqlLiteral === name
-
150
@connection.quote_column_name(name)
-
end
-
-
1
def maybe_visit thing, collector
-
193
return collector unless thing
-
33
collector << " "
-
33
visit thing, collector
-
end
-
-
1
def inject_join list, collector, join_str
-
22
len = list.length - 1
-
22
list.each_with_index.inject(collector) { |c, (x,i)|
-
27
if i == len
-
22
visit x, c
-
else
-
5
visit(x, c) << join_str
-
end
-
}
-
end
-
-
1
def infix_value o, collector, value
-
collector = visit o.left, collector
-
collector << value
-
visit o.right, collector
-
end
-
-
1
def aggregate name, o, collector
-
collector << "#{name}("
-
if o.distinct
-
collector << "DISTINCT "
-
end
-
collector = inject_join(o.expressions, collector, ", ") << ")"
-
if o.alias
-
collector << " AS "
-
visit o.alias, collector
-
else
-
collector
-
end
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Visitor
-
1
def initialize
-
1
@dispatch = get_dispatch_cache
-
end
-
-
1
def accept object
-
visit object
-
end
-
-
1
private
-
-
1
def self.dispatch_cache
-
2
Hash.new do |hash, klass|
-
17
hash[klass] = "visit_#{(klass.name || '').gsub('::', '_')}"
-
end
-
end
-
-
1
def get_dispatch_cache
-
1
self.class.dispatch_cache
-
end
-
-
1
def dispatch
-
431
@dispatch
-
end
-
-
1
def visit object
-
send dispatch[object.class], object
-
rescue NoMethodError => e
-
raise e if respond_to?(dispatch[object.class], true)
-
superklass = object.class.ancestors.find { |klass|
-
respond_to?(dispatch[klass], true)
-
}
-
raise(TypeError, "Cannot visit #{object.class}") unless superklass
-
dispatch[object.class] = dispatch[superklass]
-
retry
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class WhereSql < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_SelectCore o, collector
-
collector << "WHERE "
-
inject_join o.wheres, collector, ' AND '
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module WindowPredications
-
-
1
def over(expr = nil)
-
Nodes::Over.new(self, expr)
-
end
-
-
end
-
end
-
1
require 'byebug/attacher'
-
#
-
# Main Container for all of Byebug's code
-
#
-
1
module Byebug
-
#
-
# Enters byebug right before (or right after if _before_ is false) return
-
# events occur. Before entering byebug the init script is read.
-
#
-
1
def self.attach
-
require 'byebug/core'
-
-
unless started?
-
self.mode = :attached
-
-
start
-
run_init_script
-
end
-
-
current_context.step_out(3, true)
-
end
-
end
-
-
#
-
# Adds a `byebug` method to the Kernel module.
-
#
-
# Dropping a `byebug` call anywhere in your code, you get a debug prompt.
-
#
-
1
module Kernel
-
1
def byebug
-
Byebug.attach
-
end
-
-
1
alias debugger byebug
-
end
-
1
require 'timeout'
-
1
require 'nokogiri'
-
1
require 'xpath'
-
-
1
module Capybara
-
1
class CapybaraError < StandardError; end
-
1
class DriverNotFoundError < CapybaraError; end
-
1
class FrozenInTime < CapybaraError; end
-
1
class ElementNotFound < CapybaraError; end
-
1
class ModalNotFound < CapybaraError; end
-
1
class Ambiguous < ElementNotFound; end
-
1
class ExpectationNotMet < ElementNotFound; end
-
1
class FileNotFound < CapybaraError; end
-
1
class UnselectNotAllowed < CapybaraError; end
-
1
class NotSupportedByDriverError < CapybaraError; end
-
1
class InfiniteRedirectError < CapybaraError; end
-
1
class ScopeError < CapybaraError; end
-
1
class WindowError < CapybaraError; end
-
1
class ReadOnlyElementError < CapybaraError; end
-
-
1
class << self
-
1
attr_accessor :asset_host, :app_host, :run_server, :default_host, :always_include_port
-
1
attr_accessor :server_port, :exact, :match, :exact_options, :visible_text_only
-
1
attr_accessor :default_selector, :default_wait_time, :ignore_hidden_elements
-
1
attr_accessor :save_and_open_page_path, :automatic_reload, :raise_server_errors
-
1
attr_writer :default_driver, :current_driver, :javascript_driver, :session_name, :server_host
-
1
attr_accessor :app
-
-
##
-
#
-
# Configure Capybara to suit your needs.
-
#
-
# Capybara.configure do |config|
-
# config.run_server = false
-
# config.app_host = 'http://www.google.com'
-
# end
-
#
-
# === Configurable options
-
#
-
# [app_host = String] The default host to use when giving a relative URL to visit
-
# [always_include_port = Boolean] Whether the Rack server's port should automatically be inserted into every visited URL (Default: false)
-
# [asset_host = String] Where dynamic assets are hosted - will be prepended to relative asset locations if present (Default: nil)
-
# [run_server = Boolean] Whether to start a Rack server for the given Rack app (Default: true)
-
# [default_selector = :css/:xpath] Methods which take a selector use the given type by default (Default: CSS)
-
# [default_wait_time = Integer] The number of seconds to wait for asynchronous processes to finish (Default: 2)
-
# [ignore_hidden_elements = Boolean] Whether to ignore hidden elements on the page (Default: true)
-
# [automatic_reload = Boolean] Whether to automatically reload elements as Capybara is waiting (Default: true)
-
# [save_and_open_page_path = String] Where to put pages saved through save_and_open_page (Default: Dir.pwd)
-
#
-
# === DSL Options
-
#
-
# when using capybara/dsl, the following options are also available:
-
#
-
# [default_driver = Symbol] The name of the driver to use by default. (Default: :rack_test)
-
# [javascript_driver = Symbol] The name of a driver to use for JavaScript enabled tests. (Default: :selenium)
-
#
-
1
def configure
-
1
yield self
-
end
-
-
##
-
#
-
# Register a new driver for Capybara.
-
#
-
# Capybara.register_driver :rack_test do |app|
-
# Capybara::Driver::RackTest.new(app)
-
# end
-
#
-
# @param [Symbol] name The name of the new driver
-
# @yield [app] This block takes a rack app and returns a Capybara driver
-
# @yieldparam [<Rack>] app The rack application that this driver runs agains. May be nil.
-
# @yieldreturn [Capybara::Driver::Base] A Capybara driver instance
-
#
-
1
def register_driver(name, &block)
-
3
drivers[name] = block
-
end
-
-
##
-
#
-
# Add a new selector to Capybara. Selectors can be used by various methods in Capybara
-
# to find certain elements on the page in a more convenient way. For example adding a
-
# selector to find certain table rows might look like this:
-
#
-
# Capybara.add_selector(:row) do
-
# xpath { |num| ".//tbody/tr[#{num}]" }
-
# end
-
#
-
# This makes it possible to use this selector in a variety of ways:
-
#
-
# find(:row, 3)
-
# page.find('table#myTable').find(:row, 3).text
-
# page.find('table#myTable').has_selector?(:row, 3)
-
# within(:row, 3) { expect(page).to have_content('$100.000') }
-
#
-
# Here is another example:
-
#
-
# Capybara.add_selector(:id) do
-
# xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }
-
# end
-
#
-
# Note that this particular selector already ships with Capybara.
-
#
-
# @param [Symbol] name The name of the selector to add
-
# @yield A block executed in the context of the new {Capybara::Selector}
-
#
-
1
def add_selector(name, &block)
-
15
Capybara::Selector.add(name, &block)
-
end
-
-
1
def drivers
-
5
@drivers ||= {}
-
end
-
-
##
-
#
-
# Register a proc that Capybara will call to run the Rack application.
-
#
-
# Capybara.server do |app, port|
-
# require 'rack/handler/mongrel'
-
# Rack::Handler::Mongrel.run(app, :Port => port)
-
# end
-
#
-
# By default, Capybara will try to run webrick.
-
#
-
# @yield [app, port] This block receives a rack app and port and should run a Rack handler
-
#
-
1
def server(&block)
-
1
if block_given?
-
1
@server = block
-
else
-
@server
-
end
-
end
-
-
##
-
#
-
# Wraps the given string, which should contain an HTML document or fragment
-
# in a {Capybara::Node::Simple} which exposes all {Capybara::Node::Matchers} and
-
# {Capybara::Node::Finders}. This allows you to query any string containing
-
# HTML in the exact same way you would query the current document in a Capybara
-
# session. For example:
-
#
-
# node = Capybara.string <<-HTML
-
# <ul>
-
# <li id="home">Home</li>
-
# <li id="projects">Projects</li>
-
# </ul>
-
# HTML
-
#
-
# node.find('#projects').text # => 'Projects'
-
# node.has_selector?('li#home', :text => 'Home')
-
# node.has_selector?(:projects)
-
# node.find('ul').find('li').text # => 'Home'
-
#
-
# @param [String] html An html fragment or document
-
# @return [Capybara::Node::Simple] A node which has Capybara's finders and matchers
-
#
-
1
def string(html)
-
Capybara::Node::Simple.new(html)
-
end
-
-
##
-
#
-
# Runs Capybara's default server for the given application and port
-
# under most circumstances you should not have to call this method
-
# manually.
-
#
-
# @param [Rack Application] app The rack application to run
-
# @param [Fixnum] port The port to run the application on
-
#
-
1
def run_default_server(app, port)
-
require 'rack/handler/webrick'
-
Rack::Handler::WEBrick.run(app, :Host => server_host, :Port => port, :AccessLog => [], :Logger => WEBrick::Log::new(nil, 0))
-
end
-
-
##
-
#
-
# @return [Symbol] The name of the driver to use by default
-
#
-
1
def default_driver
-
103
@default_driver || :rack_test
-
end
-
-
##
-
#
-
# @return [Symbol] The name of the driver currently in use
-
#
-
1
def current_driver
-
103
@current_driver || default_driver
-
end
-
1
alias_method :mode, :current_driver
-
-
##
-
#
-
# @return [Symbol] The name of the driver used when JavaScript is needed
-
#
-
1
def javascript_driver
-
@javascript_driver || :selenium
-
end
-
-
##
-
#
-
# Use the default driver as the current driver
-
#
-
1
def use_default_driver
-
18
@current_driver = nil
-
end
-
-
##
-
#
-
# Yield a block using a specific driver
-
#
-
1
def using_driver(driver)
-
previous_driver = Capybara.current_driver
-
Capybara.current_driver = driver
-
yield
-
ensure
-
@current_driver = previous_driver
-
end
-
-
##
-
#
-
# @return [String] The IP address bound by default server
-
#
-
1
def server_host
-
@server_host || '127.0.0.1'
-
end
-
-
##
-
#
-
# Yield a block using a specific wait time
-
#
-
1
def using_wait_time(seconds)
-
previous_wait_time = Capybara.default_wait_time
-
Capybara.default_wait_time = seconds
-
yield
-
ensure
-
Capybara.default_wait_time = previous_wait_time
-
end
-
-
##
-
#
-
# The current Capybara::Session based on what is set as Capybara.app and Capybara.current_driver
-
#
-
# @return [Capybara::Session] The currently used session
-
#
-
1
def current_session
-
102
session_pool["#{current_driver}:#{session_name}:#{app.object_id}"] ||= Capybara::Session.new(current_driver, app)
-
end
-
-
##
-
#
-
# Reset sessions, cleaning out the pool of sessions. This will remove any session information such
-
# as cookies.
-
#
-
1
def reset_sessions!
-
36
session_pool.each { |mode, session| session.reset! }
-
end
-
1
alias_method :reset!, :reset_sessions!
-
-
##
-
#
-
# The current session name.
-
#
-
# @return [Symbol] The name of the currently used session.
-
#
-
1
def session_name
-
102
@session_name ||= :default
-
end
-
-
##
-
#
-
# Yield a block using a specific session name.
-
#
-
1
def using_session(name)
-
self.session_name = name
-
yield
-
ensure
-
self.session_name = :default
-
end
-
-
##
-
#
-
# Parse raw html into a document using Nokogiri, and adjust textarea contents as defined by the spec.
-
#
-
# @param [String] html The raw html
-
# @return [Nokogiri::HTML::Document] HTML document
-
#
-
1
def HTML(html)
-
69
Nokogiri::HTML(html).tap do |document|
-
69
document.xpath('//textarea').each do |textarea|
-
textarea.content=textarea.content.sub(/\A\n/,'')
-
end
-
end
-
end
-
-
1
def included(base)
-
base.send(:include, Capybara::DSL)
-
warn "`include Capybara` is deprecated. Please use `include Capybara::DSL` instead."
-
end
-
-
1
def deprecate(method, alternate_method)
-
warn "DEPRECATED: ##{method} is deprecated, please use ##{alternate_method} instead"
-
end
-
-
1
private
-
-
1
def session_pool
-
120
@session_pool ||= {}
-
end
-
end
-
-
1
self.default_driver = nil
-
1
self.current_driver = nil
-
-
1
module Driver; end
-
1
module RackTest; end
-
1
module Selenium; end
-
-
1
require 'capybara/helpers'
-
1
require 'capybara/session'
-
1
require 'capybara/dsl'
-
1
require 'capybara/window'
-
1
require 'capybara/server'
-
1
require 'capybara/selector'
-
1
require 'capybara/result'
-
1
require 'capybara/version'
-
-
1
require 'capybara/queries/base_query'
-
1
require 'capybara/query'
-
1
require 'capybara/queries/text_query'
-
1
require 'capybara/queries/title_query'
-
-
1
require 'capybara/node/finders'
-
1
require 'capybara/node/matchers'
-
1
require 'capybara/node/actions'
-
1
require 'capybara/node/document_matchers'
-
1
require 'capybara/node/simple'
-
1
require 'capybara/node/base'
-
1
require 'capybara/node/element'
-
1
require 'capybara/node/document'
-
-
1
require 'capybara/driver/base'
-
1
require 'capybara/driver/node'
-
-
1
require 'capybara/rack_test/driver'
-
1
require 'capybara/rack_test/node'
-
1
require 'capybara/rack_test/form'
-
1
require 'capybara/rack_test/browser'
-
1
require 'capybara/rack_test/css_handlers.rb'
-
-
1
require 'capybara/selenium/node'
-
1
require 'capybara/selenium/driver'
-
end
-
-
1
Capybara.configure do |config|
-
1
config.always_include_port = false
-
1
config.run_server = true
-
1
config.server {|app, port| Capybara.run_default_server(app, port)}
-
1
config.default_selector = :css
-
1
config.default_wait_time = 2
-
1
config.ignore_hidden_elements = true
-
1
config.default_host = "http://www.example.com"
-
1
config.automatic_reload = true
-
1
config.match = :smart
-
1
config.exact = false
-
1
config.raise_server_errors = true
-
1
config.visible_text_only = false
-
end
-
-
1
Capybara.register_driver :rack_test do |app|
-
Capybara::RackTest::Driver.new(app)
-
end
-
-
1
Capybara.register_driver :selenium do |app|
-
Capybara::Selenium::Driver.new(app)
-
end
-
1
require 'capybara'
-
1
require 'capybara/rspec/matchers'
-
-
1
World(Capybara::DSL)
-
1
World(Capybara::RSpecMatchers)
-
-
1
After do
-
18
Capybara.reset_sessions!
-
end
-
-
1
Before do
-
18
Capybara.use_default_driver
-
end
-
-
1
Before '@javascript' do
-
Capybara.current_driver = Capybara.javascript_driver
-
end
-
-
1
Before do |scenario|
-
18
scenario.source_tag_names.each do |tag|
-
driver_name = tag.sub(/^@/, '').to_sym
-
if Capybara.drivers.has_key?(driver_name)
-
Capybara.current_driver = driver_name
-
end
-
end
-
end
-
1
class Capybara::Driver::Base
-
1
def current_url
-
raise NotImplementedError
-
end
-
-
1
def visit(path)
-
raise NotImplementedError
-
end
-
-
1
def find_xpath(query)
-
raise NotImplementedError
-
end
-
-
1
def find_css(query)
-
raise NotImplementedError
-
end
-
-
1
def html
-
raise NotImplementedError
-
end
-
-
1
def go_back
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#go_back'
-
end
-
-
1
def go_forward
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#go_forward'
-
end
-
-
1
def execute_script(script)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#execute_script'
-
end
-
-
1
def evaluate_script(script)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#evaluate_script'
-
end
-
-
1
def save_screenshot(path, options={})
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#save_screenshot'
-
end
-
-
1
def response_headers
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#response_headers'
-
end
-
-
1
def status_code
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#status_code'
-
end
-
-
1
def within_frame(frame_handle)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#within_frame'
-
end
-
-
1
def current_window_handle
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#current_window_handle'
-
end
-
-
1
def window_size(handle)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#window_size'
-
end
-
-
1
def resize_window_to(handle, width, height)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#resize_window_to'
-
end
-
-
1
def maximize_window(handle)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#maximize_current_window'
-
end
-
-
1
def close_window(handle)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#close_window'
-
end
-
-
1
def window_handles
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#window_handles'
-
end
-
-
1
def open_new_window
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#open_new_window'
-
end
-
-
1
def switch_to_window(handle)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#switch_to_window'
-
end
-
-
1
def within_window(locator)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#within_window'
-
end
-
-
1
def no_such_window_error
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#no_such_window_error'
-
end
-
-
-
##
-
#
-
# Execute the block, and then accept the modal opened.
-
# @param type [:alert, :confirm, :prompt]
-
# @option options [Numeric] :wait How long to wait for the modal to appear after executing the block.
-
# @option options [String, Regexp] :text Text to verify is in the message shown in the modal
-
# @option options [String] :with Text to fill in in the case of a prompt
-
# @return [String] the message shown in the modal
-
# @raise [Capybara::ModalNotFound] if modal dialog hasn't been found
-
#
-
1
def accept_modal(type, options={}, &blk)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#accept_modal'
-
end
-
-
##
-
#
-
# Execute the block, and then dismiss the modal opened.
-
# @param type [:alert, :confirm, :prompt]
-
# @option options [Numeric] :wait How long to wait for the modal to appear after executing the block.
-
# @option options [String, Regexp] :text Text to verify is in the message shown in the modal
-
# @return [String] the message shown in the modal
-
# @raise [Capybara::ModalNotFound] if modal dialog hasn't been found
-
#
-
1
def dismiss_modal(type, options={}, &blk)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#dismiss_modal'
-
end
-
-
1
def invalid_element_errors
-
[]
-
end
-
-
1
def wait?
-
false
-
end
-
-
1
def reset!
-
end
-
-
1
def needs_server?
-
1
false
-
end
-
end
-
1
module Capybara
-
1
module Driver
-
1
class Node
-
1
attr_reader :driver, :native
-
-
1
def initialize(driver, native)
-
1048
@driver = driver
-
1048
@native = native
-
end
-
-
1
def all_text
-
raise NotImplementedError
-
end
-
-
1
def visible_text
-
raise NotImplementedError
-
end
-
-
1
def [](name)
-
raise NotImplementedError
-
end
-
-
1
def value
-
raise NotImplementedError
-
end
-
-
# @param value String or Array. Array is only allowed if node has 'multiple' attribute
-
# @param options [Hash{}] Driver specific options for how to set a value on a node
-
1
def set(value, options={})
-
raise NotImplementedError
-
end
-
-
1
def select_option
-
raise NotImplementedError
-
end
-
-
1
def unselect_option
-
raise NotImplementedError
-
end
-
-
1
def click
-
raise NotImplementedError
-
end
-
-
1
def right_click
-
raise NotImplementedError
-
end
-
-
1
def double_click
-
raise NotImplementedError
-
end
-
-
1
def hover
-
raise NotImplementedError
-
end
-
-
1
def drag_to(element)
-
raise NotImplementedError
-
end
-
-
1
def tag_name
-
raise NotImplementedError
-
end
-
-
1
def visible?
-
raise NotImplementedError
-
end
-
-
1
def checked?
-
raise NotImplementedError
-
end
-
-
1
def selected?
-
raise NotImplementedError
-
end
-
-
1
def disabled?
-
raise NotImplementedError
-
end
-
-
1
def path
-
raise NotSupportedByDriverError, 'Capybara::Driver::Node#path'
-
end
-
-
1
def trigger(event)
-
raise NotSupportedByDriverError, 'Capybara::Driver::Node#trigger'
-
end
-
-
1
def inspect
-
%(#<#{self.class} tag="#{tag_name}" path="#{path}">)
-
rescue NotSupportedByDriverError
-
%(#<#{self.class} tag="#{tag_name}">)
-
end
-
-
1
def ==(other)
-
raise NotSupportedByDriverError, 'Capybara::Driver::Node#=='
-
end
-
end
-
end
-
end
-
1
require 'capybara'
-
-
1
module Capybara
-
1
module DSL
-
1
def self.included(base)
-
warn "including Capybara::DSL in the global scope is not recommended!" if base == Object
-
super
-
end
-
-
1
def self.extended(base)
-
19
warn "extending the main object with Capybara::DSL is not recommended!" if base == TOPLEVEL_BINDING.eval("self")
-
19
super
-
end
-
-
##
-
#
-
# Shortcut to working in a different session.
-
#
-
1
def using_session(name, &block)
-
Capybara.using_session(name, &block)
-
end
-
-
##
-
#
-
# Shortcut to using a different wait time.
-
#
-
1
def using_wait_time(seconds, &block)
-
Capybara.using_wait_time(seconds, &block)
-
end
-
-
##
-
#
-
# Shortcut to accessing the current session.
-
#
-
# class MyClass
-
# include Capybara::DSL
-
#
-
# def has_header?
-
# page.has_css?('h1')
-
# end
-
# end
-
#
-
# @return [Capybara::Session] The current session object
-
#
-
1
def page
-
102
Capybara.current_session
-
end
-
-
1
Session::DSL_METHODS.each do |method|
-
90
define_method method do |*args, &block|
-
74
page.send method, *args, &block
-
end
-
end
-
end
-
-
1
extend(Capybara::DSL)
-
end
-
# encoding: UTF-8
-
-
1
module Capybara
-
-
# @api private
-
1
module Helpers
-
1
extend self
-
-
##
-
#
-
# Normalizes whitespace space by stripping leading and trailing
-
# whitespace and replacing sequences of whitespace characters
-
# with a single space.
-
#
-
# @param [String] text Text to normalize
-
# @return [String] Normalized text
-
#
-
1
def normalize_whitespace(text)
-
70
text.to_s.gsub(/[[:space:]]+/, ' ').strip
-
end
-
-
##
-
#
-
# Escapes any characters that would have special meaning in a regexp
-
# if text is not a regexp
-
#
-
# @param [String] text Text to escape
-
# @return [String] Escaped text
-
#
-
1
def to_regexp(text)
-
14
text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(normalize_whitespace(text)))
-
end
-
-
##
-
#
-
# Injects a `<base>` tag into the given HTML code, pointing to
-
# `Capybara.asset_host`.
-
#
-
# @param [String] html HTML code to inject into
-
# @return [String] The modified HTML code
-
#
-
1
def inject_asset_host(html)
-
if Capybara.asset_host && Nokogiri::HTML(html).css("base").empty?
-
match = html.match(/<head[^<]*?>/)
-
html.clone.insert match.end(0), "<base href='#{Capybara.asset_host}' />"
-
else
-
html
-
end
-
end
-
-
##
-
#
-
# Checks if the given count matches the given count options.
-
# Defaults to true if no options are specified. If multiple
-
# options are provided, it tests that all conditions are met;
-
# however, if :count is supplied, all other options are ignored.
-
#
-
# @param [Integer] count The actual number. Should be coercible via Integer()
-
# @option [Range] between Count must be within the given range
-
# @option [Integer] count Count must be exactly this
-
# @option [Integer] maximum Count must be smaller than or equal to this value
-
# @option [Integer] minimum Count must be larger than or equal to this value
-
#
-
1
def matches_count?(count, options={})
-
32
return (Integer(options[:count]) == count) if options[:count]
-
32
return false if options[:maximum] && (Integer(options[:maximum]) < count)
-
32
return false if options[:minimum] && (Integer(options[:minimum]) > count)
-
32
return false if options[:between] && !(options[:between] === count)
-
32
return true
-
end
-
-
##
-
#
-
# Checks if a count of 0 is valid for the given options hash.
-
# Returns false if options hash does not specify any count options.
-
#
-
1
def expects_none?(options={})
-
105
if [:count, :maximum, :minimum, :between].any? { |k| options.has_key? k }
-
matches_count?(0,options)
-
else
-
21
false
-
end
-
end
-
-
##
-
#
-
# Generates a failure message given a description of the query and count
-
# options.
-
#
-
# @param [String] description Description of a query
-
# @option [Range] between Count should have been within the given range
-
# @option [Integer] count Count should have been exactly this
-
# @option [Integer] maximum Count should have been smaller than or equal to this value
-
# @option [Integer] minimum Count should have been larger than or equal to this value
-
#
-
1
def failure_message(description, options={})
-
message = "expected to find #{description}"
-
if options[:count]
-
message << " #{options[:count]} #{declension('time', 'times', options[:count])}"
-
elsif options[:between]
-
message << " between #{options[:between].first} and #{options[:between].last} times"
-
elsif options[:maximum]
-
message << " at most #{options[:maximum]} #{declension('time', 'times', options[:maximum])}"
-
elsif options[:minimum]
-
message << " at least #{options[:minimum]} #{declension('time', 'times', options[:minimum])}"
-
end
-
message
-
end
-
-
##
-
#
-
# A poor man's `pluralize`. Given two declensions, one singular and one
-
# plural, as well as a count, this will pick the correct declension. This
-
# way we can generate grammatically correct error message.
-
#
-
# @param [String] singular The singular form of the word
-
# @param [String] plural The plural form of the word
-
# @param [Integer] count The number of items
-
#
-
1
def declension(singular, plural, count)
-
if count == 1
-
singular
-
else
-
plural
-
end
-
end
-
end
-
end
-
1
module Capybara
-
1
module Node
-
1
module Actions
-
-
##
-
#
-
# Finds a button or link by id, text or value and clicks it. Also looks at image
-
# alt text inside the link.
-
#
-
# @param [String] locator Text, id or value of link or button
-
#
-
1
def click_link_or_button(locator, options={})
-
find(:link_or_button, locator, options).click
-
end
-
1
alias_method :click_on, :click_link_or_button
-
-
##
-
#
-
# Finds a link by id or text and clicks it. Also looks at image
-
# alt text inside the link.
-
#
-
# @param [String] locator Text or id of link
-
# @param options
-
# @option options [String] :href The value the href attribute must be
-
#
-
1
def click_link(locator, options={})
-
29
find(:link, locator, options).click
-
end
-
-
##
-
#
-
# Finds a button by id, text or value and clicks it.
-
#
-
# @param [String] locator Text, id or value of button
-
#
-
1
def click_button(locator, options={})
-
8
find(:button, locator, options).click
-
end
-
-
##
-
#
-
# Locate a text field or text area and fill it in with the given text
-
# The field can be found via its name, id or label text.
-
#
-
# page.fill_in 'Name', :with => 'Bob'
-
#
-
# @param [String] locator Which field to fill in
-
# @param [Hash] options
-
# @option options [String] :with The value to fill in - required
-
# @option options [Hash] :fill_options Driver specific options regarding how to fill fields
-
#
-
1
def fill_in(locator, options={})
-
14
raise "Must pass a hash containing 'with'" if not options.is_a?(Hash) or not options.has_key?(:with)
-
14
with = options.delete(:with)
-
14
fill_options = options.delete(:fill_options)
-
14
find(:fillable_field, locator, options).set(with, fill_options)
-
end
-
-
##
-
#
-
# Find a radio button and mark it as checked. The radio button can be found
-
# via name, id or label text.
-
#
-
# page.choose('Male')
-
#
-
# @param [String] locator Which radio button to choose
-
#
-
1
def choose(locator, options={})
-
find(:radio_button, locator, options).set(true)
-
end
-
-
##
-
#
-
# Find a check box and mark it as checked. The check box can be found
-
# via name, id or label text.
-
#
-
# page.check('German')
-
#
-
# @param [String] locator Which check box to check
-
#
-
1
def check(locator, options={})
-
find(:checkbox, locator, options).set(true)
-
end
-
-
##
-
#
-
# Find a check box and mark uncheck it. The check box can be found
-
# via name, id or label text.
-
#
-
# page.uncheck('German')
-
#
-
# @param [String] locator Which check box to uncheck
-
#
-
1
def uncheck(locator, options={})
-
find(:checkbox, locator, options).set(false)
-
end
-
-
##
-
#
-
# Find a select box on the page and select a particular option from it. If the select
-
# box is a multiple select, +select+ can be called multiple times to select more than
-
# one option. The select box can be found via its name, id or label text.
-
#
-
# page.select 'March', :from => 'Month'
-
#
-
# @param [String] value Which option to select
-
# @param [Hash{:from => String}] options The id, name or label of the select box
-
#
-
1
def select(value, options={})
-
1
if options.has_key?(:from)
-
1
from = options.delete(:from)
-
1
find(:select, from, options).find(:option, value, options).select_option
-
else
-
find(:option, value, options).select_option
-
end
-
end
-
-
##
-
#
-
# Find a select box on the page and unselect a particular option from it. If the select
-
# box is a multiple select, +unselect+ can be called multiple times to unselect more than
-
# one option. The select box can be found via its name, id or label text.
-
#
-
# page.unselect 'March', :from => 'Month'
-
#
-
# @param [String] value Which option to unselect
-
# @param [Hash{:from => String}] options The id, name or label of the select box
-
#
-
1
def unselect(value, options={})
-
if options.has_key?(:from)
-
from = options.delete(:from)
-
find(:select, from, options).find(:option, value, options).unselect_option
-
else
-
find(:option, value, options).unselect_option
-
end
-
end
-
-
##
-
#
-
# Find a file field on the page and attach a file given its path. The file field can
-
# be found via its name, id or label text.
-
#
-
# page.attach_file(locator, '/path/to/file.png')
-
#
-
# @param [String] locator Which field to attach the file to
-
# @param [String] path The path of the file that will be attached, or an array of paths
-
#
-
1
def attach_file(locator, path, options={})
-
Array(path).each do |p|
-
raise Capybara::FileNotFound, "cannot attach file, #{p} does not exist" unless File.exist?(p.to_s)
-
end
-
find(:file_field, locator, options).set(path)
-
end
-
end
-
end
-
end
-
1
module Capybara
-
1
module Node
-
-
##
-
#
-
# A {Capybara::Node::Base} represents either an element on a page through the subclass
-
# {Capybara::Node::Element} or a document through {Capybara::Node::Document}.
-
#
-
# Both types of Node share the same methods, used for interacting with the
-
# elements on the page. These methods are divided into three categories,
-
# finders, actions and matchers. These are found in the modules
-
# {Capybara::Node::Finders}, {Capybara::Node::Actions} and {Capybara::Node::Matchers}
-
# respectively.
-
#
-
# A {Capybara::Session} exposes all methods from {Capybara::Node::Document} directly:
-
#
-
# session = Capybara::Session.new(:rack_test, my_app)
-
# session.visit('/')
-
# session.fill_in('Foo', :with => 'Bar') # from Capybara::Node::Actions
-
# bar = session.find('#bar') # from Capybara::Node::Finders
-
# bar.select('Baz', :from => 'Quox') # from Capybara::Node::Actions
-
# session.has_css?('#foobar') # from Capybara::Node::Matchers
-
#
-
1
class Base
-
1
attr_reader :session, :base, :parent
-
-
1
include Capybara::Node::Finders
-
1
include Capybara::Node::Actions
-
1
include Capybara::Node::Matchers
-
-
1
def initialize(session, base)
-
82
@session = session
-
82
@base = base
-
end
-
-
# overridden in subclasses, e.g. Capybara::Node::Element
-
1
def reload
-
self
-
end
-
-
##
-
#
-
# This method is Capybara's primary defence against asynchronicity
-
# problems. It works by attempting to run a given block of code until it
-
# succeeds. The exact behaviour of this method depends on a number of
-
# factors. Basically there are certain exceptions which, when raised
-
# from the block, instead of bubbling up, are caught, and the block is
-
# re-run.
-
#
-
# Certain drivers, such as RackTest, have no support for asynchronous
-
# processes, these drivers run the block, and any error raised bubbles up
-
# immediately. This allows faster turn around in the case where an
-
# expectation fails.
-
#
-
# Only exceptions that are {Capybara::ElementNotFound} or any subclass
-
# thereof cause the block to be rerun. Drivers may specify additional
-
# exceptions which also cause reruns. This usually occurs when a node is
-
# manipulated which no longer exists on the page. For example, the
-
# Selenium driver specifies
-
# `Selenium::WebDriver::Error::ObsoleteElementError`.
-
#
-
# As long as any of these exceptions are thrown, the block is re-run,
-
# until a certain amount of time passes. The amount of time defaults to
-
# {Capybara.default_wait_time} and can be overridden through the `seconds`
-
# argument. This time is compared with the system time to see how much
-
# time has passed. If the return value of `Time.now` is stubbed out,
-
# Capybara will raise `Capybara::FrozenInTime`.
-
#
-
# @param [Integer] seconds Number of seconds to retry this block
-
# @param options [Hash]
-
# @option options [Array<Exception>] :errors (driver.invalid_element_errors +
-
# [Capybara::ElementNotFound]) exception types that cause the block to be rerun
-
# @return [Object] The result of the given block
-
# @raise [Capybara::FrozenInTime] If the return value of `Time.now` appears stuck
-
#
-
1
def synchronize(seconds=Capybara.default_wait_time, options = {})
-
377
start_time = Time.now
-
-
377
if session.synchronized
-
233
yield
-
else
-
144
session.synchronized = true
-
144
begin
-
144
yield
-
rescue => e
-
session.raise_server_error!
-
raise e unless driver.wait?
-
raise e unless catch_error?(e, options[:errors])
-
raise e if (Time.now - start_time) >= seconds
-
sleep(0.05)
-
raise Capybara::FrozenInTime, "time appears to be frozen, Capybara does not work with libraries which freeze time, consider using time travelling instead" if Time.now == start_time
-
reload if Capybara.automatic_reload
-
retry
-
ensure
-
144
session.synchronized = false
-
144
end
-
end
-
end
-
-
# @api private
-
1
def find_css(css)
-
7
base.find_css(css)
-
end
-
-
# @api private
-
1
def find_xpath(xpath)
-
87
base.find_xpath(xpath)
-
end
-
-
1
protected
-
-
1
def catch_error?(error, errors = nil)
-
errors ||= (driver.invalid_element_errors + [Capybara::ElementNotFound])
-
errors.any? do |type|
-
error.is_a?(type)
-
end
-
end
-
-
1
def driver
-
session.driver
-
end
-
end
-
end
-
end
-
1
module Capybara
-
1
module Node
-
-
##
-
#
-
# A {Capybara::Document} represents an HTML document. Any operation
-
# performed on it will be performed on the entire document.
-
#
-
# @see Capybara::Node
-
#
-
1
class Document < Base
-
1
include Capybara::Node::DocumentMatchers
-
-
1
def inspect
-
%(#<Capybara::Document>)
-
end
-
-
##
-
#
-
# @return [String] The text of the document
-
#
-
1
def text(type=nil)
-
14
find(:xpath, '/html').text(type)
-
end
-
-
1
def title
-
session.driver.title
-
end
-
end
-
end
-
end
-
1
module Capybara
-
1
module Node
-
1
module DocumentMatchers
-
##
-
# Asserts that the page has the given title.
-
#
-
# @!macro title_query_params
-
# @overload $0(string, options = {})
-
# @param string [String] The string that title should include
-
# @overload $0(regexp, options = {})
-
# @param regexp [Regexp] The regexp that title should match to
-
# @option options [Numeric] :wait (Capybara.default_wait_time) Time that Capybara will wait for title to eq/match given string/regexp argument
-
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
-
# @return [true]
-
#
-
1
def assert_title(title, options = {})
-
query = Capybara::Queries::TitleQuery.new(title, options)
-
synchronize(query.wait) do
-
unless query.resolves_for?(self)
-
raise Capybara::ExpectationNotMet, query.failure_message
-
end
-
end
-
return true
-
end
-
-
##
-
# Asserts that the page doesn't have the given title.
-
#
-
# @macro title_query_params
-
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
-
# @return [true]
-
#
-
1
def assert_no_title(title, options = {})
-
query = Capybara::Queries::TitleQuery.new(title, options)
-
synchronize(query.wait) do
-
if query.resolves_for?(self)
-
raise Capybara::ExpectationNotMet, query.negative_failure_message
-
end
-
end
-
return true
-
end
-
-
##
-
# Checks if the page has the given title.
-
#
-
# @macro title_query_params
-
# @return [Boolean]
-
#
-
1
def has_title?(title, options = {})
-
assert_title(title, options)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
-
##
-
# Checks if the page doesn't have the given title.
-
#
-
# @macro title_query_params
-
# @return [Boolean]
-
#
-
1
def has_no_title?(title, options = {})
-
assert_no_title(title, options)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
end
-
end
-
end
-
1
module Capybara
-
1
module Node
-
-
##
-
#
-
# A {Capybara::Element} represents a single element on the page. It is possible
-
# to interact with the contents of this element the same as with a document:
-
#
-
# session = Capybara::Session.new(:rack_test, my_app)
-
#
-
# bar = session.find('#bar') # from Capybara::Node::Finders
-
# bar.select('Baz', :from => 'Quox') # from Capybara::Node::Actions
-
#
-
# {Capybara::Element} also has access to HTML attributes and other properties of the
-
# element:
-
#
-
# bar.value
-
# bar.text
-
# bar[:title]
-
#
-
# @see Capybara::Node
-
#
-
1
class Element < Base
-
-
1
def initialize(session, base, parent, query)
-
81
super(session, base)
-
81
@parent = parent
-
81
@query = query
-
end
-
-
1
def allow_reload!
-
74
@allow_reload = true
-
end
-
-
##
-
#
-
# @return [Object] The native element from the driver, this allows access to driver specific methods
-
#
-
1
def native
-
synchronize { base.native }
-
end
-
-
##
-
#
-
# Retrieve the text of the element. If `Capybara.ignore_hidden_elements`
-
# is `true`, which it is by default, then this will return only text
-
# which is visible. The exact semantics of this may differ between
-
# drivers, but generally any text within elements with `display:none` is
-
# ignored. This behaviour can be overridden by passing `:all` to this
-
# method.
-
#
-
# @param [:all, :visible] type Whether to return only visible or all text
-
# @return [String] The text of the element
-
#
-
1
def text(type=nil)
-
28
type ||= :all unless Capybara.ignore_hidden_elements or Capybara.visible_text_only
-
28
synchronize do
-
28
if type == :all
-
base.all_text
-
else
-
28
base.visible_text
-
end
-
end
-
end
-
-
##
-
#
-
# Retrieve the given attribute
-
#
-
# element[:title] # => HTML title attribute
-
#
-
# @param [Symbol] attribute The attribute to retrieve
-
# @return [String] The value of the attribute
-
#
-
1
def [](attribute)
-
synchronize { base[attribute] }
-
end
-
-
##
-
#
-
# @return [String] The value of the form element
-
#
-
1
def value
-
synchronize { base.value }
-
end
-
-
##
-
#
-
# Set the value of the form element to the given value.
-
#
-
# @param [String] value The new value
-
# @param [Hash{}] options Driver specific options for how to set the value
-
#
-
1
def set(value, options={})
-
14
options ||= {}
-
-
14
driver_supports_options = (base.method(:set).arity != 1)
-
-
14
unless options.empty? || driver_supports_options
-
warn "Options passed to Capybara::Node#set but the driver doesn't support them"
-
end
-
-
14
synchronize do
-
14
if driver_supports_options
-
base.set(value, options)
-
else
-
14
base.set(value)
-
end
-
end
-
end
-
-
##
-
#
-
# Select this node if is an option element inside a select tag
-
#
-
1
def select_option
-
2
synchronize { base.select_option }
-
end
-
-
##
-
#
-
# Unselect this node if is an option element inside a multiple select tag
-
#
-
1
def unselect_option
-
synchronize { base.unselect_option }
-
end
-
-
##
-
#
-
# Click the Element
-
#
-
1
def click
-
74
synchronize { base.click }
-
end
-
-
##
-
#
-
# Right Click the Element
-
#
-
1
def right_click
-
synchronize { base.right_click }
-
end
-
-
##
-
#
-
# Double Click the Element
-
#
-
1
def double_click
-
synchronize { base.double_click }
-
end
-
-
##
-
#
-
# Hover on the Element
-
#
-
1
def hover
-
synchronize { base.hover }
-
end
-
-
##
-
#
-
# @return [String] The tag name of the element
-
#
-
1
def tag_name
-
synchronize { base.tag_name }
-
end
-
-
##
-
#
-
# Whether or not the element is visible. Not all drivers support CSS, so
-
# the result may be inaccurate.
-
#
-
# @return [Boolean] Whether the element is visible
-
#
-
1
def visible?
-
148
synchronize { base.visible? }
-
end
-
-
##
-
#
-
# Whether or not the element is checked.
-
#
-
# @return [Boolean] Whether the element is checked
-
#
-
1
def checked?
-
synchronize { base.checked? }
-
end
-
-
##
-
#
-
# Whether or not the element is selected.
-
#
-
# @return [Boolean] Whether the element is selected
-
#
-
1
def selected?
-
synchronize { base.selected? }
-
end
-
-
##
-
#
-
# Whether or not the element is disabled.
-
#
-
# @return [Boolean] Whether the element is disabled
-
#
-
1
def disabled?
-
46
synchronize { base.disabled? }
-
end
-
-
##
-
#
-
# An XPath expression describing where on the page the element can be found
-
#
-
# @return [String] An XPath expression
-
#
-
1
def path
-
synchronize { base.path }
-
end
-
-
##
-
#
-
# Trigger any event on the current element, for example mouseover or focus
-
# events. Does not work in Selenium.
-
#
-
# @param [String] event The name of the event to trigger
-
#
-
1
def trigger(event)
-
synchronize { base.trigger(event) }
-
end
-
-
##
-
#
-
# Drag the element to the given other element.
-
#
-
# source = page.find('#foo')
-
# target = page.find('#bar')
-
# source.drag_to(target)
-
#
-
# @param [Capybara::Element] node The element to drag to
-
#
-
1
def drag_to(node)
-
synchronize { base.drag_to(node.base) }
-
end
-
-
1
def reload
-
if @allow_reload
-
begin
-
reloaded = parent.reload.first(@query.name, @query.locator, @query.options)
-
@base = reloaded.base if reloaded
-
rescue => e
-
raise e unless catch_error?(e)
-
end
-
end
-
self
-
end
-
-
1
def inspect
-
%(#<Capybara::Element tag="#{tag_name}" path="#{path}">)
-
rescue NotSupportedByDriverError
-
%(#<Capybara::Element tag="#{tag_name}">)
-
end
-
end
-
end
-
end
-
1
module Capybara
-
1
module Node
-
1
module Finders
-
-
##
-
#
-
# Find an {Capybara::Element} based on the given arguments. +find+ will raise an error if the element
-
# is not found.
-
#
-
# If the driver is capable of executing JavaScript, +find+ will wait for a set amount of time
-
# and continuously retry finding the element until either the element is found or the time
-
# expires. The length of time +find+ will wait is controlled through {Capybara.default_wait_time}
-
# and defaults to 2 seconds.
-
#
-
# +find+ takes the same options as +all+.
-
#
-
# page.find('#foo').find('.bar')
-
# page.find(:xpath, '//div[contains(., "bar")]')
-
# page.find('li', :text => 'Quox').click_link('Delete')
-
#
-
# @param (see Capybara::Node::Finders#all)
-
# @option options [Boolean] match The matching strategy to use.
-
# @option options [false, Numeric] wait How long to wait for the element to appear.
-
#
-
# @return [Capybara::Element] The found element
-
# @raise [Capybara::ElementNotFound] If the element can't be found before time expires
-
#
-
1
def find(*args)
-
74
query = Capybara::Query.new(*args)
-
synchronize(query.wait) do
-
74
if query.match == :smart or query.match == :prefer_exact
-
74
result = query.resolve_for(self, true)
-
74
result = query.resolve_for(self, false) if result.size == 0 && !query.exact?
-
else
-
result = query.resolve_for(self)
-
end
-
74
if query.match == :one or query.match == :smart and result.size > 1
-
raise Capybara::Ambiguous.new("Ambiguous match, found #{result.size} elements matching #{query.description}")
-
end
-
74
if result.size == 0
-
raise Capybara::ElementNotFound.new("Unable to find #{query.description}")
-
end
-
74
result.first
-
74
end.tap(&:allow_reload!)
-
end
-
-
##
-
#
-
# Find a form field on the page. The field can be found by its name, id or label text.
-
#
-
# @param [String] locator Which field to find
-
# @return [Capybara::Element] The found element
-
#
-
1
def find_field(locator, options={})
-
find(:field, locator, options)
-
end
-
1
alias_method :field_labeled, :find_field
-
-
##
-
#
-
# Find a link on the page. The link can be found by its id or text.
-
#
-
# @param [String] locator Which link to find
-
# @return [Capybara::Element] The found element
-
#
-
1
def find_link(locator, options={})
-
find(:link, locator, options)
-
end
-
-
##
-
#
-
# Find a button on the page. The button can be found by its id, name or value.
-
#
-
# @param [String] locator Which button to find
-
# @return [Capybara::Element] The found element
-
#
-
1
def find_button(locator, options={})
-
find(:button, locator, options)
-
end
-
-
##
-
#
-
# Find a element on the page, given its id.
-
#
-
# @param [String] id Which element to find
-
# @return [Capybara::Element] The found element
-
#
-
1
def find_by_id(id, options={})
-
find(:id, id, options)
-
end
-
-
##
-
#
-
# Find all elements on the page matching the given selector
-
# and options.
-
#
-
# Both XPath and CSS expressions are supported, but Capybara
-
# does not try to automatically distinguish between them. The
-
# following statements are equivalent:
-
#
-
# page.all(:css, 'a#person_123')
-
# page.all(:xpath, '//a[@id="person_123"]')
-
#
-
#
-
# If the type of selector is left out, Capybara uses
-
# {Capybara.default_selector}. It's set to :css by default.
-
#
-
# page.all("a#person_123")
-
#
-
# Capybara.default_selector = :xpath
-
# page.all('//a[@id="person_123"]')
-
#
-
# The set of found elements can further be restricted by specifying
-
# options. It's possible to select elements by their text or visibility:
-
#
-
# page.all('a', :text => 'Home')
-
# page.all('#menu li', :visible => true)
-
#
-
# By default if no elements are found, an empty array is returned;
-
# however, expectations can be set on the number of elements to be
-
# found using:
-
#
-
# page.assert_selector('p#foo', :count => 4)
-
# page.assert_selector('p#foo', :maximum => 10)
-
# page.assert_selector('p#foo', :minimum => 1)
-
# page.assert_selector('p#foo', :between => 1..10)
-
#
-
# See {Capybara::Helpers#matches_count?} for additional information about
-
# count matching.
-
#
-
# @overload all([kind], locator, options)
-
# @param [:css, :xpath] kind The type of selector
-
# @param [String] locator The selector
-
# @option options [String, Regexp] text Only find elements which contain this text or match this regexp
-
# @option options [Boolean] visible Only find elements that are visible on the page. Setting this to false
-
# finds invisible _and_ visible elements.
-
# @option options [Integer] count Exact number of matches that are expected to be found
-
# @option options [Integer] maximum Maximum number of matches that are expected to be found
-
# @option options [Integer] minimum Minimum number of matches that are expected to be found
-
# @option options [Range] between Number of matches found must be within the given range
-
# @option options [Boolean] exact Control whether `is` expressions in the given XPath match exactly or partially
-
# @return [Capybara::Result] A collection of found elements
-
#
-
1
def all(*args)
-
query = Capybara::Query.new(*args)
-
synchronize(query.wait) do
-
result = query.resolve_for(self)
-
raise Capybara::ExpectationNotMet, result.failure_message unless result.matches_count?
-
result
-
end
-
end
-
-
##
-
#
-
# Find the first element on the page matching the given selector
-
# and options, or nil if no element matches.
-
#
-
# @overload first([kind], locator, options)
-
# @param [:css, :xpath] kind The type of selector
-
# @param [String] locator The selector
-
# @param [Hash] options Additional options; see {#all}
-
# @return [Capybara::Element] The found element or nil
-
#
-
1
def first(*args)
-
all(*args).first
-
end
-
end
-
end
-
end
-
1
module Capybara
-
1
module Node
-
1
module Matchers
-
-
##
-
#
-
# Checks if a given selector is on the page or current node.
-
#
-
# page.has_selector?('p#foo')
-
# page.has_selector?(:xpath, './/p[@id="foo"]')
-
# page.has_selector?(:foo)
-
#
-
# By default it will check if the expression occurs at least once,
-
# but a different number can be specified.
-
#
-
# page.has_selector?('p.foo', :count => 4)
-
#
-
# This will check if the expression occurs exactly 4 times.
-
#
-
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
-
# such as :text and :visible.
-
#
-
# page.has_selector?('li', :text => 'Horse', :visible => true)
-
#
-
# has_selector? can also accept XPath expressions generated by the
-
# XPath gem:
-
#
-
# page.has_selector?(:xpath, XPath.descendant(:p))
-
#
-
# @param (see Capybara::Node::Finders#all)
-
# @param args
-
# @option args [Integer] :count (nil) Number of times the text should occur
-
# @option args [Integer] :minimum (nil) Minimum number of times the text should occur
-
# @option args [Integer] :maximum (nil) Maximum number of times the text should occur
-
# @option args [Range] :between (nil) Range of times that should contain number of times text occurs
-
# @return [Boolean] If the expression exists
-
#
-
1
def has_selector?(*args)
-
assert_selector(*args)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
-
##
-
#
-
# Checks if a given selector is not on the page or current node.
-
# Usage is identical to Capybara::Node::Matchers#has_selector?
-
#
-
# @param (see Capybara::Node::Finders#has_selector?)
-
# @return [Boolean]
-
#
-
1
def has_no_selector?(*args)
-
assert_no_selector(*args)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
-
##
-
#
-
# Asserts that a given selector is on the page or current node.
-
#
-
# page.assert_selector('p#foo')
-
# page.assert_selector(:xpath, './/p[@id="foo"]')
-
# page.assert_selector(:foo)
-
#
-
# By default it will check if the expression occurs at least once,
-
# but a different number can be specified.
-
#
-
# page.assert_selector('p#foo', :count => 4)
-
#
-
# This will check if the expression occurs exactly 4 times. See
-
# {Capybara::Node::Finders#all} for other available result size options.
-
#
-
# If a :count of 0 is specified, it will behave like {#assert_no_selector};
-
# however, use of that method is preferred over this one.
-
#
-
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
-
# such as :text and :visible.
-
#
-
# page.assert_selector('li', :text => 'Horse', :visible => true)
-
#
-
# `assert_selector` can also accept XPath expressions generated by the
-
# XPath gem:
-
#
-
# page.assert_selector(:xpath, XPath.descendant(:p))
-
#
-
# @param (see Capybara::Node::Finders#all)
-
# @option options [Integer] :count (nil) Number of times the expression should occur
-
# @raise [Capybara::ExpectationNotMet] If the selector does not exist
-
#
-
1
def assert_selector(*args)
-
query = Capybara::Query.new(*args)
-
synchronize(query.wait) do
-
result = query.resolve_for(self)
-
matches_count = Capybara::Helpers.matches_count?(result.size, query.options)
-
unless matches_count && ((result.size > 0) || Capybara::Helpers.expects_none?(query.options))
-
raise Capybara::ExpectationNotMet, result.failure_message
-
end
-
end
-
return true
-
end
-
-
##
-
#
-
# Asserts that a given selector is not on the page or current node.
-
# Usage is identical to Capybara::Node::Matchers#assert_selector
-
#
-
# Query options such as :count, :minimum, :maximum, and :between are
-
# considered to be an integral part of the selector. This will return
-
# true, for example, if a page contains 4 anchors but the query expects 5:
-
#
-
# page.assert_no_selector('a', :minimum => 1) # Found, raises Capybara::ExpectationNotMet
-
# page.assert_no_selector('a', :count => 4) # Found, raises Capybara::ExpectationNotMet
-
# page.assert_no_selector('a', :count => 5) # Not Found, returns true
-
#
-
# @param (see Capybara::Node::Finders#assert_selector)
-
# @raise [Capybara::ExpectationNotMet] If the selector exists
-
#
-
1
def assert_no_selector(*args)
-
18
query = Capybara::Query.new(*args)
-
18
synchronize(query.wait) do
-
18
result = query.resolve_for(self)
-
18
matches_count = Capybara::Helpers.matches_count?(result.size, query.options)
-
18
if matches_count && ((result.size > 0) || Capybara::Helpers.expects_none?(query.options))
-
raise Capybara::ExpectationNotMet, result.negative_failure_message
-
end
-
end
-
18
return true
-
end
-
1
alias_method :refute_selector, :assert_no_selector
-
-
##
-
#
-
# Checks if a given XPath expression is on the page or current node.
-
#
-
# page.has_xpath?('.//p[@id="foo"]')
-
#
-
# By default it will check if the expression occurs at least once,
-
# but a different number can be specified.
-
#
-
# page.has_xpath?('.//p[@id="foo"]', :count => 4)
-
#
-
# This will check if the expression occurs exactly 4 times.
-
#
-
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
-
# such as :text and :visible.
-
#
-
# page.has_xpath?('.//li', :text => 'Horse', :visible => true)
-
#
-
# has_xpath? can also accept XPath expressions generate by the
-
# XPath gem:
-
#
-
# xpath = XPath.generate { |x| x.descendant(:p) }
-
# page.has_xpath?(xpath)
-
#
-
# @param [String] path An XPath expression
-
# @param options (see Capybara::Node::Finders#all)
-
# @option options [Integer] :count (nil) Number of times the expression should occur
-
# @return [Boolean] If the expression exists
-
#
-
1
def has_xpath?(path, options={})
-
has_selector?(:xpath, path, options)
-
end
-
-
##
-
#
-
# Checks if a given XPath expression is not on the page or current node.
-
# Usage is identical to Capybara::Node::Matchers#has_xpath?
-
#
-
# @param (see Capybara::Node::Finders#has_xpath?)
-
# @return [Boolean]
-
#
-
1
def has_no_xpath?(path, options={})
-
has_no_selector?(:xpath, path, options)
-
end
-
-
##
-
#
-
# Checks if a given CSS selector is on the page or current node.
-
#
-
# page.has_css?('p#foo')
-
#
-
# By default it will check if the selector occurs at least once,
-
# but a different number can be specified.
-
#
-
# page.has_css?('p#foo', :count => 4)
-
#
-
# This will check if the selector occurs exactly 4 times.
-
#
-
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
-
# such as :text and :visible.
-
#
-
# page.has_css?('li', :text => 'Horse', :visible => true)
-
#
-
# @param [String] path A CSS selector
-
# @param options (see Capybara::Node::Finders#all)
-
# @option options [Integer] :count (nil) Number of times the selector should occur
-
# @return [Boolean] If the selector exists
-
#
-
1
def has_css?(path, options={})
-
has_selector?(:css, path, options)
-
end
-
-
##
-
#
-
# Checks if a given CSS selector is not on the page or current node.
-
# Usage is identical to Capybara::Node::Matchers#has_css?
-
#
-
# @param (see Capybara::Node::Finders#has_css?)
-
# @return [Boolean]
-
#
-
1
def has_no_css?(path, options={})
-
has_no_selector?(:css, path, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has a link with the given
-
# text or id.
-
#
-
# @param [String] locator The text or id of a link to check for
-
# @param options
-
# @option options [String] :href The value the href attribute must be
-
# @return [Boolean] Whether it exists
-
#
-
1
def has_link?(locator, options={})
-
has_selector?(:link, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has no link with the given
-
# text or id.
-
#
-
# @param (see Capybara::Node::Finders#has_link?)
-
# @return [Boolean] Whether it doesn't exist
-
#
-
1
def has_no_link?(locator, options={})
-
has_no_selector?(:link, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has a button with the given
-
# text, value or id.
-
#
-
# @param [String] locator The text, value or id of a button to check for
-
# @return [Boolean] Whether it exists
-
#
-
1
def has_button?(locator, options={})
-
has_selector?(:button, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has no button with the given
-
# text, value or id.
-
#
-
# @param [String] locator The text, value or id of a button to check for
-
# @return [Boolean] Whether it doesn't exist
-
#
-
1
def has_no_button?(locator, options={})
-
has_no_selector?(:button, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has a form field with the given
-
# label, name or id.
-
#
-
# For text fields and other textual fields, such as textareas and
-
# HTML5 email/url/etc. fields, it's possible to specify a :with
-
# option to specify the text the field should contain:
-
#
-
# page.has_field?('Name', :with => 'Jonas')
-
#
-
# It is also possible to filter by the field type attribute:
-
#
-
# page.has_field?('Email', :type => 'email')
-
#
-
# Note: 'textarea' and 'select' are valid type values, matching the associated tag names.
-
#
-
# @param [String] locator The label, name or id of a field to check for
-
# @option options [String] :with The text content of the field
-
# @option options [String] :type The type attribute of the field
-
# @return [Boolean] Whether it exists
-
#
-
1
def has_field?(locator, options={})
-
has_selector?(:field, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has no form field with the given
-
# label, name or id. See {Capybara::Node::Matchers#has_field?}.
-
#
-
# @param [String] locator The label, name or id of a field to check for
-
# @option options [String] :with The text content of the field
-
# @option options [String] :type The type attribute of the field
-
# @return [Boolean] Whether it doesn't exist
-
#
-
1
def has_no_field?(locator, options={})
-
has_no_selector?(:field, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has a radio button or
-
# checkbox with the given label, value or id, that is currently
-
# checked.
-
#
-
# @param [String] locator The label, name or id of a checked field
-
# @return [Boolean] Whether it exists
-
#
-
1
def has_checked_field?(locator, options={})
-
has_selector?(:field, locator, options.merge(:checked => true))
-
end
-
-
##
-
#
-
# Checks if the page or current node has no radio button or
-
# checkbox with the given label, value or id, that is currently
-
# checked.
-
#
-
# @param [String] locator The label, name or id of a checked field
-
# @return [Boolean] Whether it doesn't exist
-
#
-
1
def has_no_checked_field?(locator, options={})
-
has_no_selector?(:field, locator, options.merge(:checked => true))
-
end
-
-
##
-
#
-
# Checks if the page or current node has a radio button or
-
# checkbox with the given label, value or id, that is currently
-
# unchecked.
-
#
-
# @param [String] locator The label, name or id of an unchecked field
-
# @return [Boolean] Whether it exists
-
#
-
1
def has_unchecked_field?(locator, options={})
-
has_selector?(:field, locator, options.merge(:unchecked => true))
-
end
-
-
##
-
#
-
# Checks if the page or current node has no radio button or
-
# checkbox with the given label, value or id, that is currently
-
# unchecked.
-
#
-
# @param [String] locator The label, name or id of an unchecked field
-
# @return [Boolean] Whether it doesn't exist
-
#
-
1
def has_no_unchecked_field?(locator, options={})
-
has_no_selector?(:field, locator, options.merge(:unchecked => true))
-
end
-
-
##
-
#
-
# Checks if the page or current node has a select field with the
-
# given label, name or id.
-
#
-
# It can be specified which option should currently be selected:
-
#
-
# page.has_select?('Language', :selected => 'German')
-
#
-
# For multiple select boxes, several options may be specified:
-
#
-
# page.has_select?('Language', :selected => ['English', 'German'])
-
#
-
# It's also possible to check if the exact set of options exists for
-
# this select box:
-
#
-
# page.has_select?('Language', :options => ['English', 'German', 'Spanish'])
-
#
-
# You can also check for a partial set of options:
-
#
-
# page.has_select?('Language', :with_options => ['English', 'German'])
-
#
-
# @param [String] locator The label, name or id of a select box
-
# @option options [Array] :options Options which should be contained in this select box
-
# @option options [Array] :with_options Partial set of options which should be contained in this select box
-
# @option options [String, Array] :selected Options which should be selected
-
# @return [Boolean] Whether it exists
-
#
-
1
def has_select?(locator, options={})
-
has_selector?(:select, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has no select field with the
-
# given label, name or id. See {Capybara::Node::Matchers#has_select?}.
-
#
-
# @param (see Capybara::Node::Matchers#has_select?)
-
# @return [Boolean] Whether it doesn't exist
-
#
-
1
def has_no_select?(locator, options={})
-
has_no_selector?(:select, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has a table with the given id
-
# or caption:
-
#
-
# page.has_table?('People')
-
#
-
# @param [String] locator The id or caption of a table
-
# @return [Boolean] Whether it exist
-
#
-
1
def has_table?(locator, options={})
-
has_selector?(:table, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has no table with the given id
-
# or caption. See {Capybara::Node::Matchers#has_table?}.
-
#
-
# @param (see Capybara::Node::Matchers#has_table?)
-
# @return [Boolean] Whether it doesn't exist
-
#
-
1
def has_no_table?(locator, options={})
-
has_no_selector?(:table, locator, options)
-
end
-
-
##
-
# Asserts that the page or current node has the given text content,
-
# ignoring any HTML tags.
-
#
-
# @!macro text_query_params
-
# @overload $0(type, text, options = {})
-
# @param [:all, :visible] type Whether to check for only visible or all text
-
# @param [String, Regexp] text The string/regexp to check for. If it's a string, text is expected to include it. If it's a regexp, text is expected to match it.
-
# @option options [Integer] :count (nil) Number of times the text is expected to occur
-
# @option options [Integer] :minimum (nil) Minimum number of times the text is expected to occur
-
# @option options [Integer] :maximum (nil) Maximum number of times the text is expected to occur
-
# @option options [Range] :between (nil) Range of times that is expected to contain number of times text occurs
-
# @option options [Numeric] :wait (Capybara.default_wait_time) Time that Capybara will wait for text to eq/match given string/regexp argument
-
# @overload $0(text, options = {})
-
# @param [String, Regexp] text The string/regexp to check for. If it's a string, text is expected to include it. If it's a regexp, text is expected to match it.
-
# @option options [Integer] :count (nil) Number of times the text is expected to occur
-
# @option options [Integer] :minimum (nil) Minimum number of times the text is expected to occur
-
# @option options [Integer] :maximum (nil) Maximum number of times the text is expected to occur
-
# @option options [Range] :between (nil) Range of times that is expected to contain number of times text occurs
-
# @option options [Numeric] :wait (Capybara.default_wait_time) Time that Capybara will wait for text to eq/match given string/regexp argument
-
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
-
# @return [true]
-
#
-
1
def assert_text(*args)
-
11
query = Capybara::Queries::TextQuery.new(*args)
-
11
synchronize(query.wait) do
-
11
count = query.resolve_for(self)
-
11
matches_count = Capybara::Helpers.matches_count?(count, query.options)
-
11
unless matches_count && ((count > 0) || Capybara::Helpers.expects_none?(query.options))
-
raise Capybara::ExpectationNotMet, query.failure_message
-
end
-
end
-
11
return true
-
end
-
-
##
-
# Asserts that the page or current node doesn't have the given text content,
-
# ignoring any HTML tags.
-
#
-
# @macro text_query_params
-
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
-
# @return [true]
-
#
-
1
def assert_no_text(*args)
-
3
query = Capybara::Queries::TextQuery.new(*args)
-
3
synchronize(query.wait) do
-
3
count = query.resolve_for(self)
-
3
matches_count = Capybara::Helpers.matches_count?(count, query.options)
-
3
if matches_count && ((count > 0) || Capybara::Helpers.expects_none?(query.options))
-
raise Capybara::ExpectationNotMet, query.negative_failure_message
-
end
-
end
-
3
return true
-
end
-
-
##
-
# Checks if the page or current node has the given text content,
-
# ignoring any HTML tags.
-
#
-
# Whitespaces are normalized in both node's text and passed text parameter.
-
# Note that whitespace isn't normalized in passed regexp as normalizing whitespace
-
# in regexp isn't easy and doesn't seem to be worth it.
-
#
-
# By default it will check if the text occurs at least once,
-
# but a different number can be specified.
-
#
-
# page.has_text?('lorem ipsum', between: 2..4)
-
#
-
# This will check if the text occurs from 2 to 4 times.
-
#
-
# @macro text_query_params
-
# @return [Boolean] Whether it exists
-
#
-
1
def has_text?(*args)
-
assert_text(*args)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
1
alias_method :has_content?, :has_text?
-
-
##
-
# Checks if the page or current node does not have the given text
-
# content, ignoring any HTML tags and normalizing whitespace.
-
#
-
# @macro text_query_params
-
# @return [Boolean] Whether it doesn't exist
-
#
-
1
def has_no_text?(*args)
-
3
assert_no_text(*args)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
1
alias_method :has_no_content?, :has_no_text?
-
-
1
def ==(other)
-
self.eql?(other) || (other.respond_to?(:base) && base == other.base)
-
end
-
end
-
end
-
end
-
1
module Capybara
-
# @api private
-
1
module Queries
-
1
class BaseQuery
-
1
COUNT_KEYS = [:count, :minimum, :maximum, :between]
-
-
1
attr_reader :options
-
-
1
def wait
-
106
if @options.has_key?(:wait)
-
@options[:wait] || 0
-
else
-
106
Capybara.default_wait_time
-
end
-
end
-
-
1
private
-
-
1
def assert_valid_keys
-
106
invalid_keys = @options.keys - valid_keys
-
106
unless invalid_keys.empty?
-
invalid_names = invalid_keys.map(&:inspect).join(", ")
-
valid_names = valid_keys.map(&:inspect).join(", ")
-
raise ArgumentError, "invalid keys #{invalid_names}, should be one of #{valid_names}"
-
end
-
end
-
end
-
end
-
end
-
1
module Capybara
-
# @api private
-
1
module Queries
-
1
class TextQuery < BaseQuery
-
1
def initialize(*args)
-
14
@type = args.shift if args.first.is_a?(Symbol) || args.first.nil?
-
14
@expected_text, @options = args
-
14
unless @expected_text.is_a?(Regexp)
-
14
@expected_text = Capybara::Helpers.normalize_whitespace(@expected_text)
-
end
-
14
@search_regexp = Capybara::Helpers.to_regexp(@expected_text)
-
14
@options ||= {}
-
14
assert_valid_keys
-
-
# this is needed to not break existing tests that may use keys supported by `Query` but not supported by `TextQuery`
-
# can be removed in next minor version (> 2.4)
-
14
invalid_keys = @options.keys - (COUNT_KEYS + [:wait])
-
14
unless invalid_keys.empty?
-
invalid_names = invalid_keys.map(&:inspect).join(", ")
-
valid_names = valid_keys.map(&:inspect).join(", ")
-
warn "invalid keys #{invalid_names}, should be one of #{valid_names}"
-
end
-
end
-
-
1
def resolve_for(node)
-
14
@actual_text = Capybara::Helpers.normalize_whitespace(node.text(@type))
-
14
@count = @actual_text.scan(@search_regexp).size
-
end
-
-
1
def failure_message
-
description =
-
if @expected_text.is_a?(Regexp)
-
"text matching #{@expected_text.inspect}"
-
else
-
"text #{@expected_text.inspect}"
-
end
-
-
message = Capybara::Helpers.failure_message(description, @options)
-
unless (COUNT_KEYS & @options.keys).empty?
-
message << " but found #{@count} #{Capybara::Helpers.declension('time', 'times', @count)}"
-
end
-
message << " in #{@actual_text.inspect}"
-
end
-
-
1
def negative_failure_message
-
failure_message.sub(/(to find)/, 'not \1')
-
end
-
-
1
private
-
-
1
def valid_keys
-
14
Capybara::Query::VALID_KEYS # can be changed to COUNT_KEYS + [:wait] in next minor version (> 2.4)
-
end
-
end
-
end
-
end
-
1
module Capybara
-
# @api private
-
1
module Queries
-
1
class TitleQuery < BaseQuery
-
1
def initialize(expected_title, options = {})
-
@expected_title = expected_title
-
@options = options
-
unless @expected_title.is_a?(Regexp)
-
@expected_title = Capybara::Helpers.normalize_whitespace(@expected_title)
-
end
-
@search_regexp = Capybara::Helpers.to_regexp(@expected_title)
-
assert_valid_keys
-
end
-
-
1
def resolves_for?(node)
-
@actual_title = node.title
-
@actual_title.match(@search_regexp)
-
end
-
-
1
def failure_message
-
failure_message_helper
-
end
-
-
1
def negative_failure_message
-
failure_message_helper(' not')
-
end
-
-
1
private
-
-
1
def failure_message_helper(negated = '')
-
verb = (@expected_title.is_a?(Regexp))? 'match' : 'include'
-
"expected #{@actual_title.inspect}#{negated} to #{verb} #{@expected_title.inspect}"
-
end
-
-
1
def valid_keys
-
[:wait]
-
end
-
end
-
end
-
end
-
1
module Capybara
-
# @deprecated This class and its methods are not supposed to be used by users of Capybara's public API.
-
# It may be removed in future versions of Capybara.
-
1
class Query < Queries::BaseQuery
-
1
attr_accessor :selector, :locator, :options, :expression, :find, :negative
-
-
1
VALID_KEYS = [:text, :visible, :between, :count, :maximum, :minimum, :exact, :match, :wait]
-
1
VALID_MATCH = [:first, :smart, :prefer_exact, :one]
-
-
1
def initialize(*args)
-
92
@options = if args.last.is_a?(Hash) then args.pop.dup else {} end
-
-
92
if args[0].is_a?(Symbol)
-
85
@selector = Selector.all[args[0]]
-
85
@locator = args[1]
-
else
-
112
@selector = Selector.all.values.find { |s| s.match?(args[0]) }
-
7
@locator = args[0]
-
end
-
92
@selector ||= Selector.all[Capybara.default_selector]
-
-
# for compatibility with Capybara 2.0
-
92
if Capybara.exact_options and @selector == Selector.all[:option]
-
@options[:exact] = true
-
end
-
-
92
@expression = @selector.call(@locator)
-
92
assert_valid_keys
-
end
-
-
1
def name; selector.name; end
-
1
def label; selector.label or selector.name; end
-
-
1
def description
-
@description = "#{label} #{locator.inspect}"
-
@description << " with text #{options[:text].inspect}" if options[:text]
-
@description << selector.description(options)
-
@description
-
end
-
-
1
def matches_filters?(node)
-
81
if options[:text]
-
14
regexp = options[:text].is_a?(Regexp) ? options[:text] : Regexp.escape(options[:text].to_s)
-
14
return false if not node.text(visible).match(regexp)
-
end
-
74
case visible
-
74
when :visible then return false unless node.visible?
-
when :hidden then return false if node.visible?
-
end
-
74
selector.custom_filters.each do |name, filter|
-
55
if options.has_key?(name)
-
return false unless filter.matches?(node, options[name])
-
elsif filter.default?
-
23
return false unless filter.matches?(node, filter.default)
-
end
-
end
-
end
-
-
1
def visible
-
88
if options.has_key?(:visible)
-
case @options[:visible]
-
when true then :visible
-
when false then :all
-
else @options[:visible]
-
end
-
else
-
88
if Capybara.ignore_hidden_elements
-
88
:visible
-
else
-
:all
-
end
-
end
-
end
-
-
1
def exact?
-
20
if options.has_key?(:exact)
-
@options[:exact]
-
else
-
20
Capybara.exact
-
end
-
end
-
-
1
def match
-
314
if options.has_key?(:match)
-
@options[:match]
-
else
-
314
Capybara.match
-
end
-
end
-
-
1
def xpath(exact=nil)
-
87
exact = self.exact? if exact == nil
-
87
if @expression.respond_to?(:to_xpath) and exact
-
53
@expression.to_xpath(:exact)
-
else
-
34
@expression.to_s
-
end
-
end
-
-
1
def css
-
7
@expression
-
end
-
-
# @api private
-
1
def resolve_for(node, exact = nil)
-
94
node.synchronize do
-
94
children = if selector.format == :css
-
7
node.find_css(self.css)
-
else
-
87
node.find_xpath(self.xpath(exact))
-
end.map do |child|
-
81
if node.is_a?(Capybara::Node::Base)
-
81
Capybara::Node::Element.new(node.session, child, node, self)
-
else
-
Capybara::Node::Simple.new(child)
-
end
-
end
-
94
Capybara::Result.new(children, self)
-
end
-
end
-
-
1
private
-
-
1
def valid_keys
-
92
COUNT_KEYS + [:text, :visible, :exact, :match, :wait] + @selector.custom_filters.keys
-
end
-
-
1
def assert_valid_keys
-
92
super
-
92
unless VALID_MATCH.include?(match)
-
raise ArgumentError, "invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(", ")}"
-
end
-
end
-
end
-
end
-
1
class Capybara::RackTest::Browser
-
1
include ::Rack::Test::Methods
-
-
1
attr_reader :driver
-
1
attr_accessor :current_host
-
-
1
def initialize(driver)
-
19
@driver = driver
-
end
-
-
1
def app
-
19
driver.app
-
end
-
-
1
def options
-
92
driver.options
-
end
-
-
1
def visit(path, attributes = {})
-
18
reset_host!
-
18
process_and_follow_redirects(:get, path, attributes)
-
end
-
-
1
def submit(method, path, attributes)
-
11
path = request_path if not path or path.empty?
-
11
process_and_follow_redirects(method, path, attributes, {'HTTP_REFERER' => current_url})
-
end
-
-
1
def follow(method, path, attributes = {})
-
26
return if path.gsub(/^#{request_path}/, '').start_with?('#')
-
26
process_and_follow_redirects(method, path, attributes, {'HTTP_REFERER' => current_url})
-
end
-
-
1
def process_and_follow_redirects(method, path, attributes = {}, env = {})
-
55
process(method, path, attributes, env)
-
55
if driver.follow_redirects?
-
55
driver.redirect_limit.times do
-
275
process(:get, last_response["Location"], {}, env) if last_response.redirect?
-
end
-
55
raise Capybara::InfiniteRedirectError, "redirected more than #{driver.redirect_limit} times, check for infinite redirects." if last_response.redirect?
-
end
-
end
-
-
1
def process(method, path, attributes = {}, env = {})
-
66
new_uri = URI.parse(path)
-
66
method.downcase! unless method.is_a? Symbol
-
-
66
new_uri.path = request_path if path.start_with?("?")
-
66
new_uri.path = "/" if new_uri.path.empty?
-
66
new_uri.path = request_path.sub(%r(/[^/]*$), '/') + new_uri.path unless new_uri.path.start_with?('/')
-
66
new_uri.scheme ||= @current_scheme
-
66
new_uri.host ||= @current_host
-
66
new_uri.port ||= @current_port unless new_uri.default_port == @current_port
-
-
66
@current_scheme = new_uri.scheme
-
66
@current_host = new_uri.host
-
66
@current_port = new_uri.port
-
-
66
reset_cache!
-
66
send(method, new_uri.to_s, attributes, env.merge(options[:headers] || {}))
-
end
-
-
1
def current_url
-
41
last_request.url
-
rescue Rack::Test::Error
-
""
-
end
-
-
1
def reset_host!
-
36
uri = URI.parse(Capybara.app_host || Capybara.default_host)
-
36
@current_scheme = uri.scheme
-
36
@current_host = uri.host
-
36
@current_port = uri.port
-
end
-
-
1
def reset_cache!
-
66
@dom = nil
-
end
-
-
1
def dom
-
86
@dom ||= Capybara::HTML(html)
-
end
-
-
1
def find(format, selector)
-
if format==:css
-
7
dom.css(selector, Capybara::RackTest::CSSHandlers.new)
-
else
-
79
dom.xpath(selector)
-
159
end.map { |node| Capybara::RackTest::Node.new(self, node) }
-
end
-
-
1
def html
-
69
last_response.body
-
rescue Rack::Test::Error
-
18
""
-
end
-
-
1
def title
-
dom.xpath("//title").text
-
end
-
-
1
protected
-
-
1
def build_rack_mock_session
-
19
reset_host! unless current_host
-
19
Rack::MockSession.new(app, current_host)
-
end
-
-
1
def request_path
-
26
last_request.path
-
rescue Rack::Test::Error
-
"/"
-
end
-
end
-
1
class Capybara::RackTest::CSSHandlers < BasicObject
-
1
include ::Kernel
-
-
1
def disabled list
-
list.find_all { |node| node.has_attribute? 'disabled' }
-
end
-
1
def enabled list
-
list.find_all { |node| !node.has_attribute? 'disabled' }
-
end
-
end
-
1
require 'rack/test'
-
1
require 'rack/utils'
-
1
require 'mime/types'
-
1
require 'nokogiri'
-
1
require 'cgi'
-
-
1
class Capybara::RackTest::Driver < Capybara::Driver::Base
-
1
DEFAULT_OPTIONS = {
-
:respect_data_method => false,
-
:follow_redirects => true,
-
:redirect_limit => 5
-
}
-
1
attr_reader :app, :options
-
-
1
def initialize(app, options={})
-
1
raise ArgumentError, "rack-test requires a rack application, but none was given" unless app
-
1
@app = app
-
1
@options = DEFAULT_OPTIONS.merge(options)
-
end
-
-
1
def browser
-
108
@browser ||= Capybara::RackTest::Browser.new(self)
-
end
-
-
1
def follow_redirects?
-
55
@options[:follow_redirects]
-
end
-
-
1
def redirect_limit
-
55
@options[:redirect_limit]
-
end
-
-
1
def response
-
browser.last_response
-
end
-
-
1
def request
-
browser.last_request
-
end
-
-
1
def visit(path, attributes = {})
-
18
browser.visit(path, attributes)
-
end
-
-
1
def submit(method, path, attributes)
-
browser.submit(method, path, attributes)
-
end
-
-
1
def follow(method, path, attributes = {})
-
browser.follow(method, path, attributes)
-
end
-
-
1
def current_url
-
4
browser.current_url
-
end
-
-
1
def response_headers
-
response.headers
-
end
-
-
1
def status_code
-
response.status
-
end
-
-
1
def find_xpath(selector)
-
79
browser.find(:xpath, selector)
-
end
-
-
1
def find_css(selector)
-
7
browser.find(:css,selector)
-
end
-
-
1
def html
-
browser.html
-
end
-
-
1
def dom
-
browser.dom
-
end
-
-
1
def title
-
browser.title
-
end
-
-
1
def reset!
-
18
@browser = nil
-
end
-
-
1
def get(*args, &block); browser.get(*args, &block); end
-
1
def post(*args, &block); browser.post(*args, &block); end
-
1
def put(*args, &block); browser.put(*args, &block); end
-
1
def delete(*args, &block); browser.delete(*args, &block); end
-
1
def header(key, value); browser.header(key, value); end
-
end
-
1
class Capybara::RackTest::Form < Capybara::RackTest::Node
-
# This only needs to inherit from Rack::Test::UploadedFile because Rack::Test checks for
-
# the class specifically when determining whether to construct the request as multipart.
-
# That check should be based solely on the form element's 'enctype' attribute value,
-
# which should probably be provided to Rack::Test in its non-GET request methods.
-
1
class NilUploadedFile < Rack::Test::UploadedFile
-
1
def initialize
-
@empty_file = Tempfile.new("nil_uploaded_file")
-
@empty_file.close
-
end
-
-
1
def original_filename; ""; end
-
1
def content_type; "application/octet-stream"; end
-
1
def path; @empty_file.path; end
-
end
-
-
1
def params(button)
-
11
params = {}
-
-
11
form_element_types=[:input, :select, :textarea]
-
11
form_elements_xpath=XPath.generate do |x|
-
11
xpath=x.descendant(*form_element_types).where(~x.attr(:form))
-
11
xpath=xpath.union(x.anywhere(*form_element_types).where(x.attr(:form) == native[:id])) if native[:id]
-
11
xpath.where(~x.attr(:disabled))
-
end.to_s
-
-
11
native.xpath(form_elements_xpath).map do |field|
-
53
case field.name
-
when 'input'
-
43
if %w(radio checkbox).include? field['type']
-
if field['checked']
-
node=Capybara::RackTest::Node.new(self.driver, field)
-
merge_param!(params, field['name'].to_s, node.value.to_s)
-
end
-
elsif %w(submit image).include? field['type']
-
# TO DO identify the click button here (in document order, rather
-
# than leaving until the end of the params)
-
elsif field['type'] =='file'
-
if multipart?
-
file = \
-
if (value = field['value']).to_s.empty?
-
NilUploadedFile.new
-
else
-
content_type = MIME::Types.type_for(value).first.to_s
-
Rack::Test::UploadedFile.new(value, content_type)
-
end
-
merge_param!(params, field['name'].to_s, file)
-
else
-
merge_param!(params, field['name'].to_s, File.basename(field['value'].to_s))
-
end
-
else
-
35
merge_param!(params, field['name'].to_s, field['value'].to_s)
-
end
-
when 'select'
-
10
if field['multiple'] == 'multiple'
-
options = field.xpath(".//option[@selected]")
-
options.each do |option|
-
merge_param!(params, field['name'].to_s, (option['value'] || option.text).to_s)
-
end
-
else
-
10
option = field.xpath(".//option[@selected]").first
-
10
option ||= field.xpath('.//option').first
-
10
merge_param!(params, field['name'].to_s, (option['value'] || option.text).to_s) if option
-
end
-
when 'textarea'
-
merge_param!(params, field['name'].to_s, field.text.to_s.gsub(/\n/, "\r\n"))
-
end
-
end
-
11
merge_param!(params, button[:name], button[:value] || "") if button[:name]
-
11
params
-
end
-
-
1
def submit(button)
-
11
action = (button && button['formaction']) || native['action']
-
11
driver.submit(method, action.to_s, params(button))
-
end
-
-
1
def multipart?
-
self[:enctype] == "multipart/form-data"
-
end
-
-
1
private
-
-
1
def method
-
11
self[:method] =~ /post/i ? :post : :get
-
end
-
-
1
def merge_param!(params, key, value)
-
53
Rack::Utils.normalize_params(params, key, value)
-
end
-
end
-
1
require 'capybara'
-
1
require 'capybara/dsl'
-
-
1
Capybara.app = Rack::Builder.new do
-
1
map "/" do
-
1
if Gem::Version.new(Rails.version) >= Gem::Version.new("3.0")
-
1
run Rails.application
-
else # Rails 2
-
use Rails::Rack::Static
-
run ActionController::Dispatcher.new
-
end
-
end
-
end.to_app
-
-
1
Capybara.save_and_open_page_path = Rails.root.join('tmp/capybara')
-
-
# Override default rack_test driver to respect data-method attributes.
-
1
Capybara.register_driver :rack_test do |app|
-
1
Capybara::RackTest::Driver.new(app, :respect_data_method => true)
-
end
-
1
require 'forwardable'
-
-
1
module Capybara
-
-
##
-
# A {Capybara::Result} represents a collection of {Capybara::Element} on the page. It is possible to interact with this
-
# collection similar to an Array because it implements Enumerable and offers the following Array methods through delegation:
-
#
-
# * []
-
# * each()
-
# * at()
-
# * size()
-
# * count()
-
# * length()
-
# * first()
-
# * last()
-
# * empty?()
-
#
-
# @see Capybara::Element
-
#
-
1
class Result
-
1
include Enumerable
-
1
extend Forwardable
-
-
1
def initialize(elements, query)
-
94
@elements = elements
-
175
@result = elements.select { |node| query.matches_filters?(node) }
-
94
@rest = @elements - @result
-
94
@query = query
-
end
-
-
1
def_delegators :@result, :each, :[], :at, :size, :count, :length,
-
:first, :last, :values_at, :empty?, :inspect, :sample, :index
-
-
1
def matches_count?
-
Capybara::Helpers.matches_count?(@result.size, @query.options)
-
end
-
-
1
def failure_message
-
message = Capybara::Helpers.failure_message(@query.description, @query.options)
-
if count > 0
-
message << ", found #{count} #{Capybara::Helpers.declension("match", "matches", count)}: " << @result.map(&:text).map(&:inspect).join(", ")
-
else
-
message << " but there were no matches"
-
end
-
unless @rest.empty?
-
elements = @rest.map(&:text).map(&:inspect).join(", ")
-
message << ". Also found " << elements << ", which matched the selector but not all filters."
-
end
-
message
-
end
-
-
1
def negative_failure_message
-
failure_message.sub(/(to find)/, 'not \1')
-
end
-
end
-
end
-
1
module Capybara
-
1
module RSpecMatchers
-
1
class Matcher
-
1
include ::RSpec::Matchers::Composable if defined?(::RSpec::Expectations::Version) && RSpec::Expectations::Version::STRING.to_f >= 3.0
-
-
1
def wrap(actual)
-
11
if actual.respond_to?("has_selector?")
-
11
actual
-
else
-
Capybara.string(actual.to_s)
-
end
-
end
-
end
-
-
1
class HaveSelector < Matcher
-
1
attr_reader :failure_message, :failure_message_when_negated
-
-
1
def initialize(*args)
-
@args = args
-
end
-
-
1
def matches?(actual)
-
wrap(actual).assert_selector(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message = e.message
-
return false
-
end
-
-
1
def does_not_match?(actual)
-
wrap(actual).assert_no_selector(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message_when_negated = e.message
-
return false
-
end
-
-
1
def description
-
"have #{query.description}"
-
end
-
-
1
def query
-
@query ||= Capybara::Query.new(*@args)
-
end
-
-
# RSpec 2 compatibility:
-
1
alias_method :failure_message_for_should, :failure_message
-
1
alias_method :failure_message_for_should_not, :failure_message_when_negated
-
end
-
-
1
class HaveText < Matcher
-
1
attr_reader :type, :content, :options
-
-
1
attr_reader :failure_message, :failure_message_when_negated
-
-
1
def initialize(*args)
-
11
@args = args.dup
-
-
# are set just for backwards compatability
-
11
@type = args.shift if args.first.is_a?(Symbol)
-
11
@content = args.shift
-
11
@options = (args.first.is_a?(Hash))? args.first : {}
-
end
-
-
1
def matches?(actual)
-
11
wrap(actual).assert_text(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message = e.message
-
return false
-
end
-
-
1
def does_not_match?(actual)
-
wrap(actual).assert_no_text(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message_when_negated = e.message
-
return false
-
end
-
-
1
def description
-
"text #{format(content)}"
-
end
-
-
1
def format(content)
-
content = Capybara::Helpers.normalize_whitespace(content) unless content.is_a? Regexp
-
content.inspect
-
end
-
-
# RSpec 2 compatibility:
-
1
alias_method :failure_message_for_should, :failure_message
-
1
alias_method :failure_message_for_should_not, :failure_message_when_negated
-
end
-
-
1
class HaveTitle < Matcher
-
1
attr_reader :title
-
-
1
attr_reader :failure_message, :failure_message_when_negated
-
-
1
def initialize(*args)
-
@args = args
-
-
# are set just for backwards compatability
-
@title = args.first
-
end
-
-
1
def matches?(actual)
-
wrap(actual).assert_title(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message = e.message
-
return false
-
end
-
-
1
def does_not_match?(actual)
-
wrap(actual).assert_no_title(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message_when_negated = e.message
-
return false
-
end
-
-
1
def description
-
"have title #{title.inspect}"
-
end
-
-
# RSpec 2 compatibility:
-
1
alias_method :failure_message_for_should, :failure_message
-
1
alias_method :failure_message_for_should_not, :failure_message_when_negated
-
end
-
-
1
class BecomeClosed
-
1
def initialize(options)
-
@wait_time = Capybara::Query.new(options).wait
-
end
-
-
1
def matches?(window)
-
@window = window
-
start_time = Time.now
-
while window.exists?
-
return false if (Time.now - start_time) > @wait_time
-
sleep 0.05
-
end
-
true
-
end
-
-
1
def failure_message
-
"expected #{@window.inspect} to become closed after #{@wait_time} seconds"
-
end
-
-
1
def failure_message_when_negated
-
"expected #{@window.inspect} not to become closed after #{@wait_time} seconds"
-
end
-
-
# RSpec 2 compatibility:
-
1
alias_method :failure_message_for_should, :failure_message
-
1
alias_method :failure_message_for_should_not, :failure_message_when_negated
-
end
-
-
1
def have_selector(*args)
-
HaveSelector.new(*args)
-
end
-
-
1
def have_xpath(xpath, options={})
-
HaveSelector.new(:xpath, xpath, options)
-
end
-
-
1
def have_css(css, options={})
-
HaveSelector.new(:css, css, options)
-
end
-
-
1
def have_text(*args)
-
11
HaveText.new(*args)
-
end
-
1
alias_method :have_content, :have_text
-
-
1
def have_title(title, options = {})
-
HaveTitle.new(title, options)
-
end
-
-
1
def have_link(locator, options={})
-
HaveSelector.new(:link, locator, options)
-
end
-
-
1
def have_button(locator, options={})
-
HaveSelector.new(:button, locator, options)
-
end
-
-
1
def have_field(locator, options={})
-
HaveSelector.new(:field, locator, options)
-
end
-
-
1
def have_checked_field(locator, options={})
-
HaveSelector.new(:field, locator, options.merge(:checked => true))
-
end
-
-
1
def have_unchecked_field(locator, options={})
-
HaveSelector.new(:field, locator, options.merge(:unchecked => true))
-
end
-
-
1
def have_select(locator, options={})
-
HaveSelector.new(:select, locator, options)
-
end
-
-
1
def have_table(locator, options={})
-
HaveSelector.new(:table, locator, options)
-
end
-
-
##
-
# Wait for window to become closed.
-
# @example
-
# expect(window).to become_closed(wait: 0.8)
-
# @param options [Hash] optional param
-
# @option options [Numeric] :wait (Capybara.default_wait_time) wait time
-
1
def become_closed(options = {})
-
BecomeClosed.new(options)
-
end
-
end
-
end
-
1
module Capybara
-
1
class Selector
-
1
class Filter
-
1
def initialize(name, block, options={})
-
22
@name = name
-
22
@block = block
-
22
@options = options
-
22
@options[:valid_values] = [true,false] if options[:boolean]
-
end
-
-
1
def default?
-
55
@options.has_key?(:default)
-
end
-
-
1
def default
-
23
@options[:default]
-
end
-
-
1
def matches?(node, value)
-
23
if @options.has_key?(:valid_values) && !Array(@options[:valid_values]).include?(value)
-
warn "Invalid value #{value.inspect} passed to filter #{@name}"
-
end
-
23
@block.call(node, value)
-
end
-
end
-
-
1
attr_reader :name, :custom_filters, :format
-
-
1
class << self
-
1
def all
-
114
@selectors ||= {}
-
end
-
-
1
def add(name, &block)
-
15
all[name.to_sym] = Capybara::Selector.new(name.to_sym, &block)
-
end
-
-
1
def remove(name)
-
all.delete(name.to_sym)
-
end
-
end
-
-
1
def initialize(name, &block)
-
15
@name = name
-
15
@custom_filters = {}
-
15
@match = nil
-
15
@label = nil
-
15
@failure_message = nil
-
15
@description = nil
-
15
instance_eval(&block)
-
end
-
-
1
def xpath(&block)
-
14
@format = :xpath
-
14
@xpath = block if block
-
14
@xpath
-
end
-
-
# Same as xpath, but wrap in XPath.css().
-
1
def css(&block)
-
1
@format = :css
-
1
@css = block if block
-
1
@css
-
end
-
-
1
def match(&block)
-
@match = block if block
-
@match
-
end
-
-
1
def label(label=nil)
-
5
@label = label if label
-
5
@label
-
end
-
-
1
def description(options={})
-
(@description && @description.call(options)).to_s
-
end
-
-
1
def call(locator)
-
92
if @format==:css
-
7
@css.call(locator)
-
else
-
85
@xpath.call(locator)
-
end
-
end
-
-
1
def match?(locator)
-
105
@match and @match.call(locator)
-
end
-
-
1
def filter(name, options={}, &block)
-
22
@custom_filters[name] = Filter.new(name, block, options)
-
end
-
-
1
def describe &block
-
9
@description = block
-
end
-
end
-
end
-
-
1
Capybara.add_selector(:xpath) do
-
33
xpath { |xpath| xpath }
-
end
-
-
1
Capybara.add_selector(:css) do
-
8
css { |css| css }
-
end
-
-
1
Capybara.add_selector(:id) do
-
1
xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }
-
end
-
-
1
Capybara.add_selector(:field) do
-
1
xpath { |locator| XPath::HTML.field(locator) }
-
1
filter(:checked, boolean: true) { |node, value| not(value ^ node.checked?) }
-
1
filter(:unchecked, boolean: true) { |node, value| (value ^ node.checked?) }
-
1
filter(:disabled, default: false, boolean: true) { |node, value| not(value ^ node.disabled?) }
-
1
filter(:with) { |node, with| node.value == with.to_s }
-
1
filter(:type) do |node, type|
-
if ['textarea', 'select'].include?(type)
-
node.tag_name == type
-
else
-
node[:type] == type
-
end
-
end
-
1
describe do |options|
-
desc, states = "", []
-
desc << " of type #{options[:type].inspect}" if options[:type]
-
desc << " with value #{options[:with].to_s.inspect}" if options.has_key?(:with)
-
states << 'checked' if options[:checked] || (options.has_key?(:unchecked) && !options[:unchecked])
-
states << 'not checked' if options[:unchecked] || (options.has_key?(:checked) && !options[:checked])
-
states << 'disabled' if options[:disabled]
-
desc << " that is #{states.join(' and ')}" unless states.empty?
-
desc
-
end
-
end
-
-
1
Capybara.add_selector(:fieldset) do
-
1
xpath { |locator| XPath::HTML.fieldset(locator) }
-
end
-
-
1
Capybara.add_selector(:link_or_button) do
-
1
label "link or button"
-
1
xpath { |locator| XPath::HTML.link_or_button(locator) }
-
1
filter(:disabled, default: false, boolean: true) { |node, value| node.tag_name == "a" or not(value ^ node.disabled?) }
-
1
describe { |options| " that is disabled" if options[:disabled] }
-
end
-
-
1
Capybara.add_selector(:link) do
-
30
xpath { |locator| XPath::HTML.link(locator) }
-
1
filter(:href) do |node, href|
-
node.first(:xpath, XPath.axis(:self)[XPath.attr(:href).equals(href.to_s)])
-
end
-
1
describe { |options| " with href #{options[:href].inspect}" if options[:href] }
-
end
-
-
1
Capybara.add_selector(:button) do
-
9
xpath { |locator| XPath::HTML.button(locator) }
-
9
filter(:disabled, default: false, boolean: true) { |node, value| not(value ^ node.disabled?) }
-
1
describe { |options| " that is disabled" if options[:disabled] }
-
end
-
-
1
Capybara.add_selector(:fillable_field) do
-
1
label "field"
-
15
xpath { |locator| XPath::HTML.fillable_field(locator) }
-
15
filter(:disabled, default: false, boolean: true) { |node, value| not(value ^ node.disabled?) }
-
1
describe { |options| " that is disabled" if options[:disabled] }
-
end
-
-
1
Capybara.add_selector(:radio_button) do
-
1
label "radio button"
-
1
xpath { |locator| XPath::HTML.radio_button(locator) }
-
1
filter(:checked, boolean: true) { |node, value| not(value ^ node.checked?) }
-
1
filter(:unchecked, boolean: true) { |node, value| (value ^ node.checked?) }
-
1
filter(:option) { |node, value| node.value == value.to_s }
-
1
filter(:disabled, default: false, boolean: true) { |node, value| not(value ^ node.disabled?) }
-
1
describe do |options|
-
desc, states = "", []
-
desc << " with value #{options[:option].inspect}" if options[:option]
-
states << 'checked' if options[:checked] || (options.has_key?(:unchecked) && !options[:unchecked])
-
states << 'not checked' if options[:unchecked] || (options.has_key?(:checked) && !options[:checked])
-
states << 'disabled' if options[:disabled]
-
desc << " that is #{states.join(' and ')}" unless states.empty?
-
desc
-
end
-
end
-
-
1
Capybara.add_selector(:checkbox) do
-
1
xpath { |locator| XPath::HTML.checkbox(locator) }
-
1
filter(:checked, boolean: true) { |node, value| not(value ^ node.checked?) }
-
1
filter(:unchecked, boolean: true) { |node, value| (value ^ node.checked?) }
-
1
filter(:option) { |node, value| node.value == value.to_s }
-
1
filter(:disabled, default: false, boolean: true) { |node, value| not(value ^ node.disabled?) }
-
1
describe do |options|
-
desc, states = "", []
-
desc << " with value #{options[:option].inspect}" if options[:option]
-
states << 'checked' if options[:checked] || (options.has_key?(:unchecked) && !options[:unchecked])
-
states << 'not checked' if options[:unchecked] || (options.has_key?(:checked) && !options[:checked])
-
states << 'disabled' if options[:disabled]
-
desc << " that is #{states.join(' and ')}" unless states.empty?
-
desc
-
end
-
end
-
-
1
Capybara.add_selector(:select) do
-
1
label "select box"
-
2
xpath { |locator| XPath::HTML.select(locator) }
-
1
filter(:options) do |node, options|
-
actual = node.all(:xpath, './/option').map { |option| option.text }
-
options.sort == actual.sort
-
end
-
1
filter(:with_options) { |node, options| options.all? { |option| node.first(:option, option) } }
-
1
filter(:selected) do |node, selected|
-
actual = node.all(:xpath, './/option').select { |option| option.selected? }.map { |option| option.text }
-
[selected].flatten.sort == actual.sort
-
end
-
2
filter(:disabled, default: false, boolean: true) { |node, value| not(value ^ node.disabled?) }
-
1
describe do |options|
-
desc = ""
-
desc << " with options #{options[:options].inspect}" if options[:options]
-
desc << " with at least options #{options[:with_options].inspect}" if options[:with_options]
-
desc << " with #{options[:selected].inspect} selected" if options[:selected]
-
desc << " that is disabled" if options[:disabled]
-
desc
-
end
-
end
-
-
1
Capybara.add_selector(:option) do
-
2
xpath { |locator| XPath::HTML.option(locator) }
-
end
-
-
1
Capybara.add_selector(:file_field) do
-
1
label "file field"
-
1
xpath { |locator| XPath::HTML.file_field(locator) }
-
1
filter(:disabled, default: false, boolean: true) { |node, value| not(value ^ node.disabled?) }
-
1
describe { |options| " that is disabled" if options[:disabled] }
-
end
-
-
1
Capybara.add_selector(:table) do
-
1
xpath { |locator| XPath::HTML.table(locator) }
-
end
-
1
require "uri"
-
-
1
class Capybara::Selenium::Driver < Capybara::Driver::Base
-
1
DEFAULT_OPTIONS = {
-
:browser => :firefox
-
}
-
1
SPECIAL_OPTIONS = [:browser]
-
-
1
attr_reader :app, :options
-
-
1
def browser
-
unless @browser
-
@browser = Selenium::WebDriver.for(options[:browser], options.reject { |key,val| SPECIAL_OPTIONS.include?(key) })
-
-
main = Process.pid
-
at_exit do
-
# Store the exit status of the test run since it goes away after calling the at_exit proc...
-
@exit_status = $!.status if $!.is_a?(SystemExit)
-
quit if Process.pid == main
-
exit @exit_status if @exit_status # Force exit with stored status
-
end
-
end
-
@browser
-
end
-
-
1
def initialize(app, options={})
-
begin
-
require 'selenium-webdriver'
-
rescue LoadError => e
-
if e.message =~ /selenium-webdriver/
-
raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler."
-
else
-
raise e
-
end
-
end
-
-
@app = app
-
@browser = nil
-
@exit_status = nil
-
@frame_handles = {}
-
@options = DEFAULT_OPTIONS.merge(options)
-
end
-
-
1
def visit(path)
-
browser.navigate.to(path)
-
end
-
-
1
def go_back
-
browser.navigate.back
-
end
-
-
1
def go_forward
-
browser.navigate.forward
-
end
-
-
1
def html
-
browser.page_source
-
end
-
-
1
def title
-
browser.title
-
end
-
-
1
def current_url
-
browser.current_url
-
end
-
-
1
def find_xpath(selector)
-
browser.find_elements(:xpath, selector).map { |node| Capybara::Selenium::Node.new(self, node) }
-
end
-
-
1
def find_css(selector)
-
browser.find_elements(:css, selector).map { |node| Capybara::Selenium::Node.new(self, node) }
-
end
-
-
1
def wait?; true; end
-
1
def needs_server?; true; end
-
-
1
def execute_script(script)
-
browser.execute_script script
-
end
-
-
1
def evaluate_script(script)
-
browser.execute_script "return #{script}"
-
end
-
-
1
def save_screenshot(path, options={})
-
browser.save_screenshot(path)
-
end
-
-
1
def reset!
-
# Use instance variable directly so we avoid starting the browser just to reset the session
-
if @browser
-
begin
-
begin @browser.manage.delete_all_cookies
-
rescue Selenium::WebDriver::Error::UnhandledError
-
# delete_all_cookies fails when we've previously gone
-
# to about:blank, so we rescue this error and do nothing
-
# instead.
-
end
-
@browser.navigate.to("about:blank")
-
rescue Selenium::WebDriver::Error::UnhandledAlertError
-
# This error is thrown if an unhandled alert is on the page
-
# Firefox appears to automatically dismiss this alert, chrome does not
-
# We'll try to accept it
-
begin
-
@browser.switch_to.alert.accept
-
rescue Selenium::WebDriver::Error::NoAlertPresentError
-
# The alert is now gone - nothing to do
-
end
-
# try cleaning up the browser again
-
retry
-
end
-
end
-
end
-
-
##
-
#
-
# Webdriver supports frame name, id, index(zero-based) or {Capybara::Element} to find iframe
-
#
-
# @overload within_frame(index)
-
# @param [Integer] index index of a frame
-
# @overload within_frame(name_or_id)
-
# @param [String] name_or_id name or id of a frame
-
# @overload within_frame(element)
-
# @param [Capybara::Node::Base] a_node frame element
-
#
-
1
def within_frame(frame_handle)
-
@frame_handles[browser.window_handle] ||= []
-
frame_handle = frame_handle.native if frame_handle.is_a?(Capybara::Node::Base)
-
@frame_handles[browser.window_handle] << frame_handle
-
a=browser.switch_to.frame(frame_handle)
-
yield
-
ensure
-
# There doesnt appear to be any way in Webdriver to move back to a parent frame
-
# other than going back to the root and then reiterating down
-
@frame_handles[browser.window_handle].pop
-
browser.switch_to.default_content
-
@frame_handles[browser.window_handle].each { |fh| browser.switch_to.frame(fh) }
-
end
-
-
1
def current_window_handle
-
browser.window_handle
-
end
-
-
1
def window_size(handle)
-
within_given_window(handle) do
-
size = browser.manage.window.size
-
[size.width, size.height]
-
end
-
end
-
-
1
def resize_window_to(handle, width, height)
-
within_given_window(handle) do
-
browser.manage.window.resize_to(width, height)
-
end
-
end
-
-
1
def maximize_window(handle)
-
within_given_window(handle) do
-
browser.manage.window.maximize
-
end
-
sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405
-
end
-
-
1
def close_window(handle)
-
within_given_window(handle) do
-
browser.close
-
end
-
end
-
-
1
def window_handles
-
browser.window_handles
-
end
-
-
1
def open_new_window
-
browser.execute_script('window.open();')
-
end
-
-
1
def switch_to_window(handle)
-
browser.switch_to.window handle
-
end
-
-
# @api private
-
1
def find_window(locator)
-
handles = browser.window_handles
-
return locator if handles.include? locator
-
-
original_handle = browser.window_handle
-
handles.each do |handle|
-
switch_to_window(handle)
-
if (locator == browser.execute_script("return window.name") ||
-
browser.title.include?(locator) ||
-
browser.current_url.include?(locator))
-
switch_to_window(original_handle)
-
return handle
-
end
-
end
-
raise Capybara::ElementNotFound, "Could not find a window identified by #{locator}"
-
end
-
-
1
def within_window(locator)
-
handle = find_window(locator)
-
browser.switch_to.window(handle) { yield }
-
end
-
-
1
def accept_modal(type, options={}, &blk)
-
yield if block_given?
-
modal = find_modal(options)
-
modal.send_keys options[:with] if options[:with]
-
message = modal.text
-
modal.accept
-
message
-
end
-
-
1
def dismiss_modal(type, options={}, &blk)
-
yield if block_given?
-
modal = find_modal(options)
-
message = modal.text
-
modal.dismiss
-
message
-
end
-
-
1
def quit
-
@browser.quit if @browser
-
rescue Errno::ECONNREFUSED
-
# Browser must have already gone
-
ensure
-
@browser = nil
-
end
-
-
1
def invalid_element_errors
-
[Selenium::WebDriver::Error::StaleElementReferenceError, Selenium::WebDriver::Error::UnhandledError, Selenium::WebDriver::Error::ElementNotVisibleError]
-
end
-
-
1
def no_such_window_error
-
Selenium::WebDriver::Error::NoSuchWindowError
-
end
-
-
1
private
-
-
1
def within_given_window(handle)
-
original_handle = self.current_window_handle
-
if handle == original_handle
-
yield
-
else
-
switch_to_window(handle)
-
result = yield
-
switch_to_window(original_handle)
-
result
-
end
-
end
-
-
1
def find_modal(options={})
-
# Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time
-
# Actual wait time may be longer than specified
-
wait = Selenium::WebDriver::Wait.new(
-
timeout: (options[:wait] || Capybara.default_wait_time),
-
ignore: Selenium::WebDriver::Error::NoAlertPresentError)
-
begin
-
modal = wait.until do
-
alert = @browser.switch_to.alert
-
regexp = options[:text].is_a?(Regexp) ? options[:text] : Regexp.escape(options[:text].to_s)
-
alert.text.match(regexp) ? alert : nil
-
end
-
rescue Selenium::WebDriver::Error::TimeOutError
-
raise Capybara::ModalNotFound.new("Unable to find modal dialog#{" with #{options[:text]}" if options[:text]}")
-
end
-
end
-
-
end
-
1
class Capybara::Selenium::Node < Capybara::Driver::Node
-
1
def visible_text
-
# Selenium doesn't normalize Unicode whitespace.
-
Capybara::Helpers.normalize_whitespace(native.text)
-
end
-
-
1
def all_text
-
text = driver.browser.execute_script("return arguments[0].textContent", native)
-
Capybara::Helpers.normalize_whitespace(text)
-
end
-
-
1
def [](name)
-
native.attribute(name.to_s)
-
rescue Selenium::WebDriver::Error::WebDriverError
-
nil
-
end
-
-
1
def value
-
if tag_name == "select" and self[:multiple] and not self[:multiple] == "false"
-
native.find_elements(:xpath, ".//option").select { |n| n.selected? }.map { |n| n[:value] || n.text }
-
else
-
native[:value]
-
end
-
end
-
-
1
def set(value)
-
tag_name = self.tag_name
-
type = self[:type]
-
if (Array === value) && !self[:multiple]
-
raise ArgumentError.new "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}"
-
end
-
if tag_name == 'input' and type == 'radio'
-
click
-
elsif tag_name == 'input' and type == 'checkbox'
-
click if value ^ native.attribute('checked').to_s.eql?("true")
-
elsif tag_name == 'input' and type == 'file'
-
path_names = value.to_s.empty? ? [] : value
-
native.send_keys(*path_names)
-
elsif tag_name == 'textarea' or tag_name == 'input'
-
if self[:readonly]
-
warn "Attempt to set readonly element with value: #{value} \n *This will raise an exception in a future version of Capybara"
-
elsif value.to_s.empty?
-
native.clear
-
else
-
#script can change a readonly element which user input cannot, so dont execute if readonly
-
driver.browser.execute_script "arguments[0].value = ''", native
-
native.send_keys(value.to_s)
-
end
-
elsif native.attribute('isContentEditable')
-
#ensure we are focused on the element
-
script = <<-JS
-
var range = document.createRange();
-
range.selectNodeContents(arguments[0]);
-
window.getSelection().addRange(range);
-
JS
-
driver.browser.execute_script script, native
-
native.send_keys(value.to_s)
-
end
-
end
-
-
1
def select_option
-
native.click unless selected?
-
end
-
-
1
def unselect_option
-
if select_node['multiple'] != 'multiple' and select_node['multiple'] != 'true'
-
raise Capybara::UnselectNotAllowed, "Cannot unselect option from single select box."
-
end
-
native.click if selected?
-
end
-
-
1
def click
-
native.click
-
end
-
-
1
def right_click
-
driver.browser.action.context_click(native).perform
-
end
-
-
1
def double_click
-
driver.browser.action.double_click(native).perform
-
end
-
-
1
def hover
-
driver.browser.action.move_to(native).perform
-
end
-
-
1
def drag_to(element)
-
driver.browser.action.drag_and_drop(native, element.native).perform
-
end
-
-
1
def tag_name
-
native.tag_name.downcase
-
end
-
-
1
def visible?
-
displayed = native.displayed?
-
displayed and displayed != "false"
-
end
-
-
1
def selected?
-
selected = native.selected?
-
selected and selected != "false"
-
end
-
-
1
def disabled?
-
!native.enabled?
-
end
-
-
1
alias :checked? :selected?
-
-
1
def find_xpath(locator)
-
native.find_elements(:xpath, locator).map { |n| self.class.new(driver, n) }
-
end
-
-
1
def find_css(locator)
-
native.find_elements(:css, locator).map { |n| self.class.new(driver, n) }
-
end
-
-
1
def ==(other)
-
native == other.native
-
end
-
-
1
private
-
-
# a reference to the select node if this is an option node
-
1
def select_node
-
find_xpath('./ancestor::select').first
-
end
-
end
-
1
require 'uri'
-
1
require 'net/http'
-
1
require 'rack'
-
-
1
module Capybara
-
1
class Server
-
1
class Middleware
-
1
attr_accessor :error
-
-
1
def initialize(app)
-
@app = app
-
end
-
-
1
def call(env)
-
if env["PATH_INFO"] == "/__identify__"
-
[200, {}, [@app.object_id.to_s]]
-
else
-
begin
-
@app.call(env)
-
rescue StandardError => e
-
@error = e unless @error
-
raise e
-
end
-
end
-
end
-
end
-
-
1
class << self
-
1
def ports
-
@ports ||= {}
-
end
-
end
-
-
1
attr_reader :app, :port, :host
-
-
1
def initialize(app, port=Capybara.server_port, host=Capybara.server_host)
-
@app = app
-
@middleware = Middleware.new(@app)
-
@server_thread = nil # suppress warnings
-
@host, @port = host, port
-
@port ||= Capybara::Server.ports[@app.object_id]
-
@port ||= find_available_port
-
end
-
-
1
def reset_error!
-
@middleware.error = nil
-
end
-
-
1
def error
-
@middleware.error
-
end
-
-
1
def responsive?
-
return false if @server_thread && @server_thread.join(0)
-
-
res = Net::HTTP.start(host, @port) { |http| http.get('/__identify__') }
-
-
if res.is_a?(Net::HTTPSuccess) or res.is_a?(Net::HTTPRedirection)
-
return res.body == @app.object_id.to_s
-
end
-
rescue SystemCallError
-
return false
-
end
-
-
1
def boot
-
unless responsive?
-
Capybara::Server.ports[@app.object_id] = @port
-
-
@server_thread = Thread.new do
-
Capybara.server.call(@middleware, @port)
-
end
-
-
Timeout.timeout(60) { @server_thread.join(0.1) until responsive? }
-
end
-
rescue Timeout::Error
-
raise "Rack application timed out during boot"
-
else
-
self
-
end
-
-
1
private
-
-
1
def find_available_port
-
server = TCPServer.new('127.0.0.1', 0)
-
server.addr[1]
-
ensure
-
server.close if server
-
end
-
-
end
-
end
-
1
module Capybara
-
-
##
-
#
-
# The Session class represents a single user's interaction with the system. The Session can use
-
# any of the underlying drivers. A session can be initialized manually like this:
-
#
-
# session = Capybara::Session.new(:culerity, MyRackApp)
-
#
-
# The application given as the second argument is optional. When running Capybara against an external
-
# page, you might want to leave it out:
-
#
-
# session = Capybara::Session.new(:culerity)
-
# session.visit('http://www.google.com')
-
#
-
# Session provides a number of methods for controlling the navigation of the page, such as +visit+,
-
# +current_path, and so on. It also delegate a number of methods to a Capybara::Document, representing
-
# the current HTML document. This allows interaction:
-
#
-
# session.fill_in('q', :with => 'Capybara')
-
# session.click_button('Search')
-
# expect(session).to have_content('Capybara')
-
#
-
# When using capybara/dsl, the Session is initialized automatically for you.
-
#
-
1
class Session
-
1
NODE_METHODS = [
-
:all, :first, :attach_file, :text, :check, :choose,
-
:click_link_or_button, :click_button, :click_link, :field_labeled,
-
:fill_in, :find, :find_button, :find_by_id, :find_field, :find_link,
-
:has_content?, :has_text?, :has_css?, :has_no_content?, :has_no_text?,
-
:has_no_css?, :has_no_xpath?, :resolve, :has_xpath?, :select, :uncheck,
-
:has_link?, :has_no_link?, :has_button?, :has_no_button?, :has_field?,
-
:has_no_field?, :has_checked_field?, :has_unchecked_field?,
-
:has_no_table?, :has_table?, :unselect, :has_select?, :has_no_select?,
-
:has_selector?, :has_no_selector?, :click_on, :has_no_checked_field?,
-
:has_no_unchecked_field?, :query, :assert_selector, :assert_no_selector,
-
:refute_selector, :assert_text, :assert_no_text
-
]
-
# @api private
-
1
DOCUMENT_METHODS = [
-
:title, :assert_title, :assert_no_title, :has_title?, :has_no_title?
-
]
-
1
SESSION_METHODS = [
-
:body, :html, :source, :current_url, :current_host, :current_path,
-
:execute_script, :evaluate_script, :visit, :go_back, :go_forward,
-
:within, :within_fieldset, :within_table, :within_frame, :current_window,
-
:windows, :open_new_window, :switch_to_window, :within_window, :window_opened_by,
-
:save_page, :save_and_open_page, :save_screenshot,
-
:save_and_open_screenshot, :reset_session!, :response_headers,
-
:status_code, :current_scope
-
] + DOCUMENT_METHODS
-
1
MODAL_METHODS = [
-
:accept_alert, :accept_confirm, :dismiss_confirm, :accept_prompt,
-
:dismiss_prompt
-
]
-
1
DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS
-
-
1
attr_reader :mode, :app, :server
-
1
attr_accessor :synchronized
-
-
1
def initialize(mode, app=nil)
-
1
@mode = mode
-
1
@app = app
-
1
if Capybara.run_server and @app and driver.needs_server?
-
@server = Capybara::Server.new(@app).boot
-
else
-
1
@server = nil
-
end
-
1
@touched = false
-
end
-
-
1
def driver
-
@driver ||= begin
-
1
unless Capybara.drivers.has_key?(mode)
-
other_drivers = Capybara.drivers.keys.map { |key| key.inspect }
-
raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}"
-
end
-
1
Capybara.drivers[mode].call(app)
-
42
end
-
end
-
-
##
-
#
-
# Reset the session (i.e. remove cookies and navigate to blank page)
-
#
-
# This method does not:
-
#
-
# * accept modal dialogs if they are present (Selenium driver now does, others may not)
-
# * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc.
-
# * modify state of the driver/underlying browser in any other way
-
#
-
# as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps.
-
#
-
# If you want to do anything from the list above on a general basis you can:
-
#
-
# * write RSpec/Cucumber/etc. after hook
-
# * monkeypatch this method
-
# * use Ruby's `prepend` method
-
#
-
1
def reset!
-
18
if @touched
-
18
driver.reset!
-
18
assert_no_selector :xpath, "/html/body/*"
-
18
@touched = false
-
end
-
18
raise_server_error!
-
end
-
1
alias_method :cleanup!, :reset!
-
1
alias_method :reset_session!, :reset!
-
-
##
-
#
-
# Raise errors encountered in the server
-
#
-
1
def raise_server_error!
-
36
raise @server.error if Capybara.raise_server_errors and @server and @server.error
-
ensure
-
36
@server.reset_error! if @server
-
end
-
-
##
-
#
-
# Returns a hash of response headers. Not supported by all drivers (e.g. Selenium)
-
#
-
# @return [Hash{String => String}] A hash of response headers.
-
#
-
1
def response_headers
-
driver.response_headers
-
end
-
-
##
-
#
-
# Returns the current HTTP status code as an Integer. Not supported by all drivers (e.g. Selenium)
-
#
-
# @return [Integer] Current HTTP status code
-
#
-
1
def status_code
-
driver.status_code
-
end
-
-
##
-
#
-
# @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript).
-
#
-
1
def html
-
driver.html
-
end
-
1
alias_method :body, :html
-
1
alias_method :source, :html
-
-
##
-
#
-
# @return [String] Path of the current page, without any domain information
-
#
-
1
def current_path
-
path = URI.parse(current_url).path
-
path if path and not path.empty?
-
end
-
-
##
-
#
-
# @return [String] Host of the current page
-
#
-
1
def current_host
-
uri = URI.parse(current_url)
-
"#{uri.scheme}://#{uri.host}" if uri.host
-
end
-
-
##
-
#
-
# @return [String] Fully qualified URL of the current page
-
#
-
1
def current_url
-
4
driver.current_url
-
end
-
-
##
-
#
-
# Navigate to the given URL. The URL can either be a relative URL or an absolute URL
-
# The behaviour of either depends on the driver.
-
#
-
# session.visit('/foo')
-
# session.visit('http://google.com')
-
#
-
# For drivers which can run against an external application, such as the selenium driver
-
# giving an absolute URL will navigate to that page. This allows testing applications
-
# running on remote servers. For these drivers, setting {Capybara.app_host} will make the
-
# remote server the default. For example:
-
#
-
# Capybara.app_host = 'http://google.com'
-
# session.visit('/') # visits the google homepage
-
#
-
# If {Capybara.always_include_port} is set to true and this session is running against
-
# a rack application, then the port that the rack application is running on will automatically
-
# be inserted into the URL. Supposing the app is running on port `4567`, doing something like:
-
#
-
# visit("http://google.com/test")
-
#
-
# Will actually navigate to `http://google.com:4567/test`.
-
#
-
# @param [#to_s] url The URL to navigate to. The parameter will be cast to a String.
-
#
-
1
def visit(url)
-
18
raise_server_error!
-
-
18
url = url.to_s
-
18
@touched = true
-
-
18
url_relative = URI.parse(url).scheme.nil?
-
-
18
if url_relative && Capybara.app_host
-
url = Capybara.app_host + url
-
url_relative = false
-
end
-
-
18
if @server
-
url = "http://#{@server.host}:#{@server.port}" + url if url_relative
-
-
if Capybara.always_include_port
-
uri = URI.parse(url)
-
uri.port = @server.port if uri.port == uri.default_port
-
url = uri.to_s
-
end
-
end
-
-
18
driver.visit(url)
-
end
-
-
##
-
#
-
# Move back a single entry in the browser's history.
-
#
-
1
def go_back
-
driver.go_back
-
end
-
-
##
-
#
-
# Move forward a single entry in the browser's history.
-
#
-
1
def go_forward
-
driver.go_forward
-
end
-
-
##
-
#
-
# Executes the given block within the context of a node. `within` takes the
-
# same options as `find`, as well as a block. For the duration of the
-
# block, any command to Capybara will be handled as though it were scoped
-
# to the given element.
-
#
-
# within(:xpath, '//div[@id="delivery-address"]') do
-
# fill_in('Street', :with => '12 Main Street')
-
# end
-
#
-
# Just as with `find`, if multiple elements match the selector given to
-
# `within`, an error will be raised, and just as with `find`, this
-
# behaviour can be controlled through the `:match` and `:exact` options.
-
#
-
# It is possible to omit the first parameter, in that case, the selector is
-
# assumed to be of the type set in Capybara.default_selector.
-
#
-
# within('div#delivery-address') do
-
# fill_in('Street', :with => '12 Main Street')
-
# end
-
#
-
# Note that a lot of uses of `within` can be replaced more succinctly with
-
# chaining:
-
#
-
# find('div#delivery-address').fill_in('Street', :with => '12 Main Street')
-
#
-
# @overload within(*find_args)
-
# @param (see Capybara::Node::Finders#all)
-
#
-
# @overload within(a_node)
-
# @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated
-
#
-
# @raise [Capybara::ElementNotFound] If the scope can't be found before time expires
-
#
-
1
def within(*args)
-
new_scope = if args.first.is_a?(Capybara::Node::Base) then args.first else find(*args) end
-
begin
-
scopes.push(new_scope)
-
yield
-
ensure
-
scopes.pop
-
end
-
end
-
-
##
-
#
-
# Execute the given block within the a specific fieldset given the id or legend of that fieldset.
-
#
-
# @param [String] locator Id or legend of the fieldset
-
#
-
1
def within_fieldset(locator)
-
within :fieldset, locator do
-
yield
-
end
-
end
-
-
##
-
#
-
# Execute the given block within the a specific table given the id or caption of that table.
-
#
-
# @param [String] locator Id or caption of the table
-
#
-
1
def within_table(locator)
-
within :table, locator do
-
yield
-
end
-
end
-
-
##
-
#
-
# Execute the given block within the given iframe using given frame name or index.
-
# May be supported by not all drivers. Drivers that support it, may provide additional options.
-
#
-
# @overload within_frame(index)
-
# @param [Integer] index index of a frame
-
# @overload within_frame(name)
-
# @param [String] name name of a frame
-
#
-
1
def within_frame(frame_handle)
-
scopes.push(nil)
-
driver.within_frame(frame_handle) do
-
yield
-
end
-
ensure
-
scopes.pop
-
end
-
-
##
-
# @return [Capybara::Window] current window
-
#
-
1
def current_window
-
Window.new(self, driver.current_window_handle)
-
end
-
-
##
-
# Get all opened windows.
-
# The order of windows in returned array is not defined.
-
# The driver may sort windows by their creation time but it's not required.
-
#
-
# @return [Array<Capybara::Window>] an array of all windows
-
#
-
1
def windows
-
driver.window_handles.map do |handle|
-
Window.new(self, handle)
-
end
-
end
-
-
##
-
# Open new window.
-
# Current window doesn't change as the result of this call.
-
# It should be switched to explicitly.
-
#
-
# @return [Capybara::Window] window that has been opened
-
#
-
1
def open_new_window
-
window_opened_by do
-
driver.open_new_window
-
end
-
end
-
-
##
-
# @overload switch_to_window(&block)
-
# Switches to the first window for which given block returns a value other than false or nil.
-
# If window that matches block can't be found, the window will be switched back and `WindowError` will be raised.
-
# @example
-
# window = switch_to_window { title == 'Page title' }
-
# @raise [Capybara::WindowError] if no window matches given block
-
# @overload switch_to_window(window)
-
# @param window [Capybara::Window] window that should be switched to
-
# @raise [Capybara::Driver::Base#no_such_window_error] if unexistent (e.g. closed) window was passed
-
#
-
# @return [Capybara::Window] window that has been switched to
-
# @raise [Capybara::ScopeError] if this method is invoked inside `within`,
-
# `within_frame` or `within_window` methods
-
# @raise [ArgumentError] if both or neither arguments were provided
-
#
-
1
def switch_to_window(window = nil)
-
block_given = block_given?
-
if window && block_given
-
raise ArgumentError, "`switch_to_window` can take either a block or a window, not both"
-
elsif !window && !block_given
-
raise ArgumentError, "`switch_to_window`: either window or block should be provided"
-
elsif scopes.size > 1
-
raise Capybara::ScopeError, "`switch_to_window` is not supposed to be invoked from "\
-
"`within`'s, `within_frame`'s' or `within_window`'s' block."
-
end
-
-
if window
-
driver.switch_to_window(window.handle)
-
window
-
else
-
original_window_handle = driver.current_window_handle
-
begin
-
driver.window_handles.each do |handle|
-
driver.switch_to_window handle
-
if yield
-
return Window.new(self, handle)
-
end
-
end
-
rescue => e
-
driver.switch_to_window(original_window_handle)
-
raise e
-
else
-
driver.switch_to_window(original_window_handle)
-
raise Capybara::WindowError, "Could not find a window matching block/lambda"
-
end
-
end
-
end
-
-
##
-
# This method does the following:
-
#
-
# 1. Switches to the given window (it can be located by window instance/lambda/string).
-
# 2. Executes the given block (within window located at previous step).
-
# 3. Switches back (this step will be invoked even if exception will happen at second step)
-
#
-
# @overload within_window(window) { do_something }
-
# @param window [Capybara::Window] instance of `Capybara::Window` class
-
# that will be switched to
-
# @raise [driver#no_such_window_error] if unexistent (e.g. closed) window was passed
-
# @overload within_window(proc_or_lambda) { do_something }
-
# @param lambda [Proc] lambda. First window for which lambda
-
# returns a value other than false or nil will be switched to.
-
# @example
-
# within_window(->{ page.title == 'Page title' }) { click_button 'Submit' }
-
# @raise [Capybara::WindowError] if no window matching lambda was found
-
# @overload within_window(string) { do_something }
-
# @deprecated Pass window or lambda instead
-
# @param [String] handle, name, url or title of the window
-
#
-
# @raise [Capybara::ScopeError] if this method is invoked inside `within`,
-
# `within_frame` or `within_window` methods
-
# @return value returned by the block
-
#
-
1
def within_window(window_or_handle)
-
if window_or_handle.instance_of?(Capybara::Window)
-
original = current_window
-
switch_to_window(window_or_handle) unless original == window_or_handle
-
scopes << nil
-
begin
-
yield
-
ensure
-
@scopes.pop
-
switch_to_window(original) unless original == window_or_handle
-
end
-
elsif window_or_handle.is_a?(Proc)
-
original = current_window
-
switch_to_window { window_or_handle.call }
-
scopes << nil
-
begin
-
yield
-
ensure
-
@scopes.pop
-
switch_to_window(original)
-
end
-
else
-
offending_line = caller.first
-
file_line = offending_line.match(/^(.+?):(\d+)/)[0]
-
warn "DEPRECATION WARNING: Passing string argument to #within_window is deprecated. "\
-
"Pass window object or lambda. (called from #{file_line})"
-
begin
-
scopes << nil
-
driver.within_window(window_or_handle) { yield }
-
ensure
-
@scopes.pop
-
end
-
end
-
end
-
-
##
-
# Get the window that has been opened by the passed block.
-
# It will wait for it to be opened (in the same way as other Capybara methods wait).
-
# It's better to use this method than `windows.last`
-
# {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}
-
#
-
# @param options [Hash]
-
# @option options [Numeric] :wait (Capybara.default_wait_time) wait time
-
# @return [Capybara::Window] the window that has been opened within a block
-
# @raise [Capybara::WindowError] if block passed to window hasn't opened window
-
# or opened more than one window
-
#
-
1
def window_opened_by(options = {}, &block)
-
old_handles = driver.window_handles
-
block.call
-
-
wait_time = Capybara::Query.new(options).wait
-
document.synchronize(wait_time, errors: [Capybara::WindowError]) do
-
opened_handles = (driver.window_handles - old_handles)
-
if opened_handles.size != 1
-
raise Capybara::WindowError, "block passed to #window_opened_by "\
-
"opened #{opened_handles.size} windows instead of 1"
-
end
-
Window.new(self, opened_handles.first)
-
end
-
end
-
-
##
-
#
-
# Execute the given script, not returning a result. This is useful for scripts that return
-
# complex objects, such as jQuery statements. +execute_script+ should be used over
-
# +evaluate_script+ whenever possible.
-
#
-
# @param [String] script A string of JavaScript to execute
-
#
-
1
def execute_script(script)
-
@touched = true
-
driver.execute_script(script)
-
end
-
-
##
-
#
-
# Evaluate the given JavaScript and return the result. Be careful when using this with
-
# scripts that return complex objects, such as jQuery statements. +execute_script+ might
-
# be a better alternative.
-
#
-
# @param [String] script A string of JavaScript to evaluate
-
# @return [Object] The result of the evaluated JavaScript (may be driver specific)
-
#
-
1
def evaluate_script(script)
-
@touched = true
-
driver.evaluate_script(script)
-
end
-
-
##
-
#
-
# Execute the block, accepting a alert.
-
#
-
# @!macro modal_params
-
# @overload $0(text, options = {}, &blk)
-
# @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched
-
# @overload $0(options = {}, &blk)
-
# @option options [Numeric] :wait How long to wait for the modal to appear after executing the block.
-
# @return [String] the message shown in the modal
-
# @raise [Capybara::ModalNotFound] if modal dialog hasn't been found
-
#
-
1
def accept_alert(text_or_options=nil, options={}, &blk)
-
if text_or_options.is_a? Hash
-
options=text_or_options
-
else
-
options[:text]=text_or_options
-
end
-
-
driver.accept_modal(:alert, options, &blk)
-
end
-
-
##
-
#
-
# Execute the block, accepting a confirm.
-
#
-
# @macro modal_params
-
#
-
1
def accept_confirm(text_or_options=nil, options={}, &blk)
-
if text_or_options.is_a? Hash
-
options=text_or_options
-
else
-
options[:text]=text_or_options
-
end
-
-
driver.accept_modal(:confirm, options, &blk)
-
end
-
-
##
-
#
-
# Execute the block, dismissing a confirm.
-
#
-
# @macro modal_params
-
#
-
1
def dismiss_confirm(text_or_options=nil, options={}, &blk)
-
if text_or_options.is_a? Hash
-
options=text_or_options
-
else
-
options[:text]=text_or_options
-
end
-
-
driver.dismiss_modal(:confirm, options, &blk)
-
end
-
-
##
-
#
-
# Execute the block, accepting a prompt, optionally responding to the prompt.
-
#
-
# @macro modal_params
-
# @option options [String] :with Response to provide to the prompt
-
#
-
1
def accept_prompt(text_or_options=nil, options={}, &blk)
-
if text_or_options.is_a? Hash
-
options=text_or_options
-
else
-
options[:text]=text_or_options
-
end
-
-
driver.accept_modal(:prompt, options, &blk)
-
end
-
-
##
-
#
-
# Execute the block, dismissing a prompt.
-
#
-
# @macro modal_params
-
#
-
1
def dismiss_prompt(text_or_options=nil, options={}, &blk)
-
if text_or_options.is_a? Hash
-
options=text_or_options
-
else
-
options[:text]=text_or_options
-
end
-
-
driver.dismiss_modal(:prompt, options, &blk)
-
end
-
-
##
-
#
-
# Save a snapshot of the page.
-
#
-
# @param [String] path The path to where it should be saved [optional]
-
#
-
1
def save_page(path=nil)
-
path ||= default_path('html')
-
-
FileUtils.mkdir_p(File.dirname(path))
-
-
File.open(path,'wb') { |f| f.write(Capybara::Helpers.inject_asset_host(body)) }
-
path
-
end
-
-
##
-
#
-
# Save a snapshot of the page and open it in a browser for inspection
-
#
-
# @param [String] file_name The path to where it should be saved [optional]
-
#
-
1
def save_and_open_page(file_name=nil)
-
file_name = save_page(file_name)
-
open_file(file_name)
-
end
-
-
##
-
#
-
# Save a screenshot of page
-
#
-
# @param [String] path A string of image path
-
# @option [Hash] options Options for saving screenshot
-
1
def save_screenshot(path, options={})
-
path ||= default_path('png')
-
-
FileUtils.mkdir_p(File.dirname(path))
-
-
driver.save_screenshot(path, options)
-
path
-
end
-
-
##
-
#
-
# Save a screenshot of the page and open it for inspection
-
#
-
# @param [String] file_name The path to where it should be saved [optional]
-
#
-
1
def save_and_open_screenshot(file_name=nil)
-
file_name = save_screenshot(file_name)
-
open_file(file_name)
-
end
-
-
1
def document
-
84
@document ||= Capybara::Node::Document.new(self, driver)
-
end
-
-
1
NODE_METHODS.each do |method|
-
51
define_method method do |*args, &block|
-
84
@touched = true
-
84
current_scope.send(method, *args, &block)
-
end
-
end
-
-
1
DOCUMENT_METHODS.each do |method|
-
5
define_method method do |*args, &block|
-
document.send(method, *args, &block)
-
end
-
end
-
-
1
def inspect
-
%(#<Capybara::Session>)
-
end
-
-
1
def current_scope
-
84
scopes.last || document
-
end
-
-
1
private
-
-
1
def open_file(file_name)
-
begin
-
require "launchy"
-
Launchy.open(file_name)
-
rescue LoadError
-
warn "File saved to #{file_name}."
-
warn "Please install the launchy gem to open the file automatically."
-
end
-
end
-
-
1
def default_path(extension)
-
timestamp = Time.new.strftime("%Y%m%d%H%M%S")
-
path = "capybara-#{timestamp}#{rand(10**10)}.#{extension}"
-
File.expand_path(path, Capybara.save_and_open_page_path)
-
end
-
-
1
def scopes
-
84
@scopes ||= [nil]
-
end
-
end
-
end
-
1
module Capybara
-
1
VERSION = '2.4.4'
-
end
-
1
module Capybara
-
##
-
# The Window class represents a browser window.
-
#
-
# You can get an instance of the class by calling either of:
-
#
-
# * {Capybara::Session#windows}
-
# * {Capybara::Session#current_window}
-
# * {Capybara::Session#window_opened_by}
-
# * {Capybara::Session#switch_to_window}
-
#
-
# Note that some drivers (e.g. Selenium) support getting size of/resizing/closing only
-
# current window. So if you invoke such method for:
-
#
-
# * window that is current, Capybara will make 2 Selenium method invocations
-
# (get handle of current window + get size/resize/close).
-
# * window that is not current, Capybara will make 4 Selenium method invocations
-
# (get handle of current window + switch to given handle + get size/resize/close + switch to original handle)
-
#
-
1
class Window
-
# @return [String] a string that uniquely identifies window within session
-
1
attr_reader :handle
-
-
# @return [Capybara::Session] session that this window belongs to
-
1
attr_reader :session
-
-
# @api private
-
1
def initialize(session, handle)
-
@session = session
-
@driver = session.driver
-
@handle = handle
-
end
-
-
##
-
# @return [Boolean] whether the window is not closed
-
1
def exists?
-
@driver.window_handles.include?(@handle)
-
end
-
-
##
-
# @return [Boolean] whether the window is closed
-
1
def closed?
-
!exists?
-
end
-
-
##
-
# @return [Boolean] whether this window is the window in which commands are being executed
-
1
def current?
-
@driver.current_window_handle == @handle
-
rescue @driver.no_such_window_error
-
false
-
end
-
-
##
-
# Close window.
-
#
-
# If this method was called for window that is current, then after calling this method
-
# future invocations of other Capybara methods should raise
-
# `session.driver.no_such_window_error` until another window will be switched to.
-
#
-
# @!macro about_current
-
# If this method was called for window that is not current, then after calling this method
-
# current window shouldn remain the same as it was before calling this method.
-
#
-
1
def close
-
@driver.close_window(handle)
-
end
-
-
##
-
# Get window size.
-
#
-
# @macro about_current
-
# @return [Array<(Fixnum, Fixnum)>] an array with width and height
-
#
-
1
def size
-
@driver.window_size(handle)
-
end
-
-
##
-
# Resize window.
-
#
-
# @macro about_current
-
# @param width [String] the new window width in pixels
-
# @param height [String] the new window height in pixels
-
#
-
1
def resize_to(width, height)
-
@driver.resize_window_to(handle, width, height)
-
end
-
-
##
-
# Maximize window.
-
#
-
# If a particular driver (e.g. headless driver) doesn't have concept of maximizing it
-
# may not support this method.
-
#
-
# @macro about_current
-
#
-
1
def maximize
-
@driver.maximize_window(handle)
-
end
-
-
1
def eql?(other)
-
other.kind_of?(self.class) && @session == other.session && @handle == other.handle
-
end
-
1
alias_method :==, :eql?
-
-
1
def hash
-
@session.hash ^ @handle.hash
-
end
-
-
1
def inspect
-
"#<Window @handle=#{@handle.inspect}>"
-
end
-
-
1
private
-
-
1
def raise_unless_current(what)
-
unless current?
-
raise Capybara::WindowError, "#{what} not current window is not possible."
-
end
-
end
-
end
-
end
-
1
require 'coffee-script'
-
1
require 'coffee/rails/engine'
-
1
require 'coffee/rails/template_handler'
-
1
require 'coffee/rails/version'
-
1
require 'rails/engine'
-
-
1
module Coffee
-
1
module Rails
-
1
class Engine < ::Rails::Engine
-
1
config.app_generators.javascript_engine :coffee
-
-
1
if config.respond_to?(:annotations)
-
config.annotations.register_extensions("coffee") { |annotation| /#\s*(#{annotation}):?\s*(.*)$/ }
-
end
-
end
-
end
-
end
-
1
module Coffee
-
1
module Rails
-
1
class TemplateHandler
-
1
def self.erb_handler
-
@@erb_handler ||= ActionView::Template.registered_template_handler(:erb)
-
end
-
-
1
def self.call(template)
-
compiled_source = erb_handler.call(template)
-
"CoffeeScript.compile(begin;#{compiled_source};end)"
-
end
-
end
-
end
-
end
-
-
1
ActiveSupport.on_load(:action_view) do
-
1
ActionView::Template.register_template_handler :coffee, Coffee::Rails::TemplateHandler
-
end
-
1
module Coffee
-
1
module Rails
-
1
VERSION = "4.1.1"
-
end
-
end
-
1
require 'coffee_script'
-
1
require 'execjs'
-
1
require 'coffee_script/source'
-
-
1
module CoffeeScript
-
1
Error = ExecJS::Error
-
1
EngineError = ExecJS::RuntimeError
-
1
CompilationError = ExecJS::ProgramError
-
-
1
module Source
-
1
def self.path
-
1
@path ||= ENV['COFFEESCRIPT_SOURCE_PATH'] || bundled_path
-
end
-
-
1
def self.path=(path)
-
@contents = @version = @bare_option = @context = nil
-
@path = path
-
end
-
-
1
COMPILE_FUNCTION_SOURCE = <<-JS
-
;function compile(script, options) {
-
try {
-
return CoffeeScript.compile(script, options);
-
} catch (err) {
-
if (err instanceof SyntaxError && err.location) {
-
throw new SyntaxError([
-
err.filename || "[stdin]",
-
err.location.first_line + 1,
-
err.location.first_column + 1
-
].join(":") + ": " + err.message)
-
} else {
-
throw err;
-
}
-
}
-
}
-
JS
-
-
1
def self.contents
-
1
@contents ||= File.read(path) + COMPILE_FUNCTION_SOURCE
-
end
-
-
1
def self.version
-
1
@version ||= contents[/CoffeeScript Compiler v([\d.]+)/, 1]
-
end
-
-
1
def self.bare_option
-
@bare_option ||= contents.match(/noWrap/) ? 'noWrap' : 'bare'
-
end
-
-
1
def self.context
-
@context ||= ExecJS.compile(contents)
-
end
-
end
-
-
1
class << self
-
1
def engine
-
end
-
-
1
def engine=(engine)
-
end
-
-
1
def version
-
Source.version
-
end
-
-
# Compile a script (String or IO) to JavaScript.
-
1
def compile(script, options = {})
-
script = script.read if script.respond_to?(:read)
-
-
if options.key?(:bare)
-
elsif options.key?(:no_wrap)
-
options[:bare] = options[:no_wrap]
-
else
-
options[:bare] = false
-
end
-
-
# Stringify keys
-
options = options.inject({}) { |h, (k, v)| h[k.to_s] = v; h }
-
Source.context.call("compile", script, options)
-
end
-
end
-
end
-
1
module CoffeeScript
-
1
module Source
-
1
def self.bundled_path
-
1
File.expand_path("../coffee-script.js", __FILE__)
-
end
-
end
-
end
-
1
require 'concurrent/version'
-
1
require 'concurrent/constants'
-
1
require 'concurrent/errors'
-
1
require 'concurrent/configuration'
-
-
1
require 'concurrent/atomics'
-
1
require 'concurrent/executors'
-
1
require 'concurrent/synchronization'
-
-
1
require 'concurrent/atomic/atomic_reference'
-
1
require 'concurrent/agent'
-
1
require 'concurrent/atom'
-
1
require 'concurrent/array'
-
1
require 'concurrent/hash'
-
1
require 'concurrent/map'
-
1
require 'concurrent/tuple'
-
1
require 'concurrent/async'
-
1
require 'concurrent/dataflow'
-
1
require 'concurrent/delay'
-
1
require 'concurrent/exchanger'
-
1
require 'concurrent/future'
-
1
require 'concurrent/immutable_struct'
-
1
require 'concurrent/ivar'
-
1
require 'concurrent/maybe'
-
1
require 'concurrent/mutable_struct'
-
1
require 'concurrent/mvar'
-
1
require 'concurrent/promise'
-
1
require 'concurrent/scheduled_task'
-
1
require 'concurrent/settable_struct'
-
1
require 'concurrent/timer_task'
-
1
require 'concurrent/tvar'
-
-
1
require 'concurrent/thread_safe/synchronized_delegator'
-
1
require 'concurrent/thread_safe/util'
-
-
1
require 'concurrent/options'
-
-
# @!macro [new] internal_implementation_note
-
#
-
# @note **Private Implementation:** This abstraction is a private, internal
-
# implementation detail. It should never be used directly.
-
-
# @!macro [new] monotonic_clock_warning
-
#
-
# @note Time calculations one all platforms and languages are sensitive to
-
# changes to the system clock. To alleviate the potential problems
-
# associated with changing the system clock while an application is running,
-
# most modern operating systems provide a monotonic clock that operates
-
# independently of the system clock. A monotonic clock cannot be used to
-
# determine human-friendly clock times. A monotonic clock is used exclusively
-
# for calculating time intervals. Not all Ruby platforms provide access to an
-
# operating system monotonic clock. On these platforms a pure-Ruby monotonic
-
# clock will be used as a fallback. An operating system monotonic clock is both
-
# faster and more reliable than the pure-Ruby implementation. The pure-Ruby
-
# implementation should be fast and reliable enough for most non-realtime
-
# operations. At this time the common Ruby platforms that provide access to an
-
# operating system monotonic clock are MRI 2.1 and above and JRuby (all versions).
-
#
-
# @see http://linux.die.net/man/3/clock_gettime Linux clock_gettime(3)
-
-
# @!macro [new] copy_options
-
#
-
# ## Copy Options
-
#
-
# Object references in Ruby are mutable. This can lead to serious
-
# problems when the {#value} of an object is a mutable reference. Which
-
# is always the case unless the value is a `Fixnum`, `Symbol`, or similar
-
# "primitive" data type. Each instance can be configured with a few
-
# options that can help protect the program from potentially dangerous
-
# operations. Each of these options can be optionally set when the object
-
# instance is created:
-
#
-
# * `:dup_on_deref` When true the object will call the `#dup` method on
-
# the `value` object every time the `#value` method is called
-
# (default: false)
-
# * `:freeze_on_deref` When true the object will call the `#freeze`
-
# method on the `value` object every time the `#value` method is called
-
# (default: false)
-
# * `:copy_on_deref` When given a `Proc` object the `Proc` will be run
-
# every time the `#value` method is called. The `Proc` will be given
-
# the current `value` as its only argument and the result returned by
-
# the block will be the return value of the `#value` call. When `nil`
-
# this option will be ignored (default: nil)
-
#
-
# When multiple deref options are set the order of operations is strictly defined.
-
# The order of deref operations is:
-
# * `:copy_on_deref`
-
# * `:dup_on_deref`
-
# * `:freeze_on_deref`
-
#
-
# Because of this ordering there is no need to `#freeze` an object created by a
-
# provided `:copy_on_deref` block. Simply set `:freeze_on_deref` to `true`.
-
# Setting both `:dup_on_deref` to `true` and `:freeze_on_deref` to `true` is
-
# as close to the behavior of a "pure" functional language (like Erlang, Clojure,
-
# or Haskell) as we are likely to get in Ruby.
-
-
# @!macro [attach] deref_options
-
#
-
# @option opts [Boolean] :dup_on_deref (false) Call `#dup` before
-
# returning the data from {#value}
-
# @option opts [Boolean] :freeze_on_deref (false) Call `#freeze` before
-
# returning the data from {#value}
-
# @option opts [Proc] :copy_on_deref (nil) When calling the {#value}
-
# method, call the given proc passing the internal value as the sole
-
# argument then return the new value returned from the proc.
-
-
# @!macro [attach] executor_and_deref_options
-
#
-
# @param [Hash] opts the options used to define the behavior at update and deref
-
# and to specify the executor on which to perform actions
-
# @option opts [Executor] :executor when set use the given `Executor` instance.
-
# Three special values are also supported: `:task` returns the global task pool,
-
# `:operation` returns the global operation pool, and `:immediate` returns a new
-
# `ImmediateExecutor` object.
-
# @!macro deref_options
-
-
# Modern concurrency tools for Ruby. Inspired by Erlang, Clojure, Scala, Haskell,
-
# F#, C#, Java, and classic concurrency patterns.
-
#
-
# The design goals of this gem are:
-
#
-
# * Stay true to the spirit of the languages providing inspiration
-
# * But implement in a way that makes sense for Ruby
-
# * Keep the semantics as idiomatic Ruby as possible
-
# * Support features that make sense in Ruby
-
# * Exclude features that don't make sense in Ruby
-
# * Be small, lean, and loosely coupled
-
1
module Concurrent
-
-
end
-
1
require 'concurrent/configuration'
-
1
require 'concurrent/atomic/atomic_reference'
-
1
require 'concurrent/atomic/thread_local_var'
-
1
require 'concurrent/collection/copy_on_write_observer_set'
-
1
require 'concurrent/concern/observable'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# `Agent` is inspired by Clojure's [agent](http://clojure.org/agents)
-
# function. An agent is a shared, mutable variable providing independent,
-
# uncoordinated, *asynchronous* change of individual values. Best used when
-
# the value will undergo frequent, complex updates. Suitable when the result
-
# of an update does not need to be known immediately. `Agent` is (mostly)
-
# functionally equivalent to Clojure's agent, except where the runtime
-
# prevents parity.
-
#
-
# Agents are reactive, not autonomous - there is no imperative message loop
-
# and no blocking receive. The state of an Agent should be itself immutable
-
# and the `#value` of an Agent is always immediately available for reading by
-
# any thread without any messages, i.e. observation does not require
-
# cooperation or coordination.
-
#
-
# Agent action dispatches are made using the various `#send` methods. These
-
# methods always return immediately. At some point later, in another thread,
-
# the following will happen:
-
#
-
# 1. The given `action` will be applied to the state of the Agent and the
-
# `args`, if any were supplied.
-
# 2. The return value of `action` will be passed to the validator lambda,
-
# if one has been set on the Agent.
-
# 3. If the validator succeeds or if no validator was given, the return value
-
# of the given `action` will become the new `#value` of the Agent. See
-
# `#initialize` for details.
-
# 4. If any observers were added to the Agent, they will be notified. See
-
# `#add_observer` for details.
-
# 5. If during the `action` execution any other dispatches are made (directly
-
# or indirectly), they will be held until after the `#value` of the Agent
-
# has been changed.
-
#
-
# If any exceptions are thrown by an action function, no nested dispatches
-
# will occur, and the exception will be cached in the Agent itself. When an
-
# Agent has errors cached, any subsequent interactions will immediately throw
-
# an exception, until the agent's errors are cleared. Agent errors can be
-
# examined with `#error` and the agent restarted with `#restart`.
-
#
-
# The actions of all Agents get interleaved amongst threads in a thread pool.
-
# At any point in time, at most one action for each Agent is being executed.
-
# Actions dispatched to an agent from another single agent or thread will
-
# occur in the order they were sent, potentially interleaved with actions
-
# dispatched to the same agent from other sources. The `#send` method should
-
# be used for actions that are CPU limited, while the `#send_off` method is
-
# appropriate for actions that may block on IO.
-
#
-
# Unlike in Clojure, `Agent` cannot participate in `Concurrent::TVar` transactions.
-
#
-
# ## Example
-
#
-
# ```
-
# def next_fibonacci(set = nil)
-
# return [0, 1] if set.nil?
-
# set + [set[-2..-1].reduce{|sum,x| sum + x }]
-
# end
-
#
-
# # create an agent with an initial value
-
# agent = Concurrent::Agent.new(next_fibonacci)
-
#
-
# # send a few update requests
-
# 5.times do
-
# agent.send{|set| next_fibonacci(set) }
-
# end
-
#
-
# # wait for them to complete
-
# agent.await
-
#
-
# # get the current value
-
# agent.value #=> [0, 1, 1, 2, 3, 5, 8]
-
# ```
-
#
-
# ## Observation
-
#
-
# Agents support observers through the {Concurrent::Observable} mixin module.
-
# Notification of observers occurs every time an action dispatch returns and
-
# the new value is successfully validated. Observation will *not* occur if the
-
# action raises an exception, if validation fails, or when a {#restart} occurs.
-
#
-
# When notified the observer will receive three arguments: `time`, `old_value`,
-
# and `new_value`. The `time` argument is the time at which the value change
-
# occurred. The `old_value` is the value of the Agent when the action began
-
# processing. The `new_value` is the value to which the Agent was set when the
-
# action completed. Note that `old_value` and `new_value` may be the same.
-
# This is not an error. It simply means that the action returned the same
-
# value.
-
#
-
# ## Nested Actions
-
#
-
# It is possible for an Agent action to post further actions back to itself.
-
# The nested actions will be enqueued normally then processed *after* the
-
# outer action completes, in the order they were sent, possibly interleaved
-
# with action dispatches from other threads. Nested actions never deadlock
-
# with one another and a failure in a nested action will never affect the
-
# outer action.
-
#
-
# Nested actions can be called using the Agent reference from the enclosing
-
# scope or by passing the reference in as a "send" argument. Nested actions
-
# cannot be post using `self` from within the action block/proc/lambda; `self`
-
# in this context will not reference the Agent. The preferred method for
-
# dispatching nested actions is to pass the Agent as an argument. This allows
-
# Ruby to more effectively manage the closing scope.
-
#
-
# Prefer this:
-
#
-
# ```
-
# agent = Concurrent::Agent.new(0)
-
# agent.send(agent) do |value, this|
-
# this.send {|v| v + 42 }
-
# 3.14
-
# end
-
# agent.value #=> 45.14
-
# ```
-
#
-
# Over this:
-
#
-
# ```
-
# agent = Concurrent::Agent.new(0)
-
# agent.send do |value|
-
# agent.send {|v| v + 42 }
-
# 3.14
-
# end
-
# ```
-
#
-
# @!macro [new] agent_await_warning
-
#
-
# **NOTE** Never, *under any circumstances*, call any of the "await" methods
-
# ({#await}, {#await_for}, {#await_for!}, and {#wait}) from within an action
-
# block/proc/lambda. The call will block the Agent and will always fail.
-
# Calling either {#await} or {#wait} (with a timeout of `nil`) will
-
# hopelessly deadlock the Agent with no possibility of recovery.
-
#
-
# @!macro thread_safe_variable_comparison
-
#
-
# @see http://clojure.org/Agents Clojure Agents
-
# @see http://clojure.org/state Values and Change - Clojure's approach to Identity and State
-
1
class Agent < Synchronization::LockableObject
-
1
include Concern::Observable
-
-
1
ERROR_MODES = [:continue, :fail].freeze
-
1
private_constant :ERROR_MODES
-
-
1
AWAIT_FLAG = Object.new
-
1
private_constant :AWAIT_FLAG
-
-
1
AWAIT_ACTION = ->(value, latch) { latch.count_down; AWAIT_FLAG }
-
1
private_constant :AWAIT_ACTION
-
-
1
DEFAULT_ERROR_HANDLER = ->(agent, error) { nil }
-
1
private_constant :DEFAULT_ERROR_HANDLER
-
-
1
DEFAULT_VALIDATOR = ->(value) { true }
-
1
private_constant :DEFAULT_VALIDATOR
-
-
1
Job = Struct.new(:action, :args, :executor, :caller)
-
1
private_constant :Job
-
-
# Raised during action processing or any other time in an Agent's lifecycle.
-
1
class Error < StandardError
-
1
def initialize(message = nil)
-
message ||= 'agent must be restarted before jobs can post'
-
super(message)
-
end
-
end
-
-
# Raised when a new value obtained during action processing or at `#restart`
-
# fails validation.
-
1
class ValidationError < Error
-
1
def initialize(message = nil)
-
message ||= 'invalid value'
-
super(message)
-
end
-
end
-
-
# The error mode this Agent is operating in. See {#initialize} for details.
-
1
attr_reader :error_mode
-
-
# Create a new `Agent` with the given initial value and options.
-
#
-
# The `:validator` option must be `nil` or a side-effect free proc/lambda
-
# which takes one argument. On any intended value change the validator, if
-
# provided, will be called. If the new value is invalid the validator should
-
# return `false` or raise an error.
-
#
-
# The `:error_handler` option must be `nil` or a proc/lambda which takes two
-
# arguments. When an action raises an error or validation fails, either by
-
# returning false or raising an error, the error handler will be called. The
-
# arguments to the error handler will be a reference to the agent itself and
-
# the error object which was raised.
-
#
-
# The `:error_mode` may be either `:continue` (the default if an error
-
# handler is given) or `:fail` (the default if error handler nil or not
-
# given).
-
#
-
# If an action being run by the agent throws an error or doesn't pass
-
# validation the error handler, if present, will be called. After the
-
# handler executes if the error mode is `:continue` the Agent will continue
-
# as if neither the action that caused the error nor the error itself ever
-
# happened.
-
#
-
# If the mode is `:fail` the Agent will become {#failed?} and will stop
-
# accepting new action dispatches. Any previously queued actions will be
-
# held until {#restart} is called. The {#value} method will still work,
-
# returning the value of the Agent before the error.
-
#
-
# @param [Object] initial the initial value
-
# @param [Hash] opts the configuration options
-
#
-
# @option opts [Symbol] :error_mode either `:continue` or `:fail`
-
# @option opts [nil, Proc] :error_handler the (optional) error handler
-
# @option opts [nil, Proc] :validator the (optional) validation procedure
-
1
def initialize(initial, opts = {})
-
super()
-
synchronize { ns_initialize(initial, opts) }
-
end
-
-
# The current value (state) of the Agent, irrespective of any pending or
-
# in-progress actions. The value is always available and is non-blocking.
-
#
-
# @return [Object] the current value
-
1
def value
-
@current.value # TODO (pitr 12-Sep-2015): broken unsafe read?
-
end
-
-
1
alias_method :deref, :value
-
-
# When {#failed?} and {#error_mode} is `:fail`, returns the error object
-
# which caused the failure, else `nil`. When {#error_mode} is `:continue`
-
# will *always* return `nil`.
-
#
-
# @return [nil, Error] the error which caused the failure when {#failed?}
-
1
def error
-
@error.value
-
end
-
-
1
alias_method :reason, :error
-
-
# @!macro [attach] agent_send
-
#
-
# Dispatches an action to the Agent and returns immediately. Subsequently,
-
# in a thread from a thread pool, the {#value} will be set to the return
-
# value of the action. Action dispatches are only allowed when the Agent
-
# is not {#failed?}.
-
#
-
# The action must be a block/proc/lambda which takes 1 or more arguments.
-
# The first argument is the current {#value} of the Agent. Any arguments
-
# passed to the send method via the `args` parameter will be passed to the
-
# action as the remaining arguments. The action must return the new value
-
# of the Agent.
-
#
-
# * {#send} and {#send!} should be used for actions that are CPU limited
-
# * {#send_off}, {#send_off!}, and {#<<} are appropriate for actions that
-
# may block on IO
-
# * {#send_via} and {#send_via!} are used when a specific executor is to
-
# be used for the action
-
#
-
# @param [Array<Object>] args zero or more arguments to be passed to
-
# the action
-
# @param [Proc] action the action dispatch to be enqueued
-
#
-
# @yield [agent, value, *args] process the old value and return the new
-
# @yieldparam [Object] value the current {#value} of the Agent
-
# @yieldparam [Array<Object>] args zero or more arguments to pass to the
-
# action
-
# @yieldreturn [Object] the new value of the Agent
-
#
-
# @!macro [attach] send_return
-
# @return [Boolean] true if the action is successfully enqueued, false if
-
# the Agent is {#failed?}
-
1
def send(*args, &action)
-
enqueue_action_job(action, args, Concurrent.global_fast_executor)
-
end
-
-
# @!macro agent_send
-
#
-
# @!macro [attach] send_bang_return_and_raise
-
# @return [Boolean] true if the action is successfully enqueued
-
# @raise [Concurrent::Agent::Error] if the Agent is {#failed?}
-
1
def send!(*args, &action)
-
raise Error.new unless send(*args, &action)
-
true
-
end
-
-
# @!macro agent_send
-
# @!macro send_return
-
1
def send_off(*args, &action)
-
enqueue_action_job(action, args, Concurrent.global_io_executor)
-
end
-
-
1
alias_method :post, :send_off
-
-
# @!macro agent_send
-
# @!macro send_bang_return_and_raise
-
1
def send_off!(*args, &action)
-
raise Error.new unless send_off(*args, &action)
-
true
-
end
-
-
# @!macro agent_send
-
# @!macro send_return
-
# @param [Concurrent::ExecutorService] executor the executor on which the
-
# action is to be dispatched
-
1
def send_via(executor, *args, &action)
-
enqueue_action_job(action, args, executor)
-
end
-
-
# @!macro agent_send
-
# @!macro send_bang_return_and_raise
-
# @param [Concurrent::ExecutorService] executor the executor on which the
-
# action is to be dispatched
-
1
def send_via!(executor, *args, &action)
-
raise Error.new unless send_via(executor, *args, &action)
-
true
-
end
-
-
# Dispatches an action to the Agent and returns immediately. Subsequently,
-
# in a thread from a thread pool, the {#value} will be set to the return
-
# value of the action. Appropriate for actions that may block on IO.
-
#
-
# @param [Proc] action the action dispatch to be enqueued
-
# @return [Concurrent::Agent] self
-
# @see {#send_off}
-
1
def <<(action)
-
send_off(&action)
-
self
-
end
-
-
# Blocks the current thread (indefinitely!) until all actions dispatched
-
# thus far, from this thread or nested by the Agent, have occurred. Will
-
# block when {#failed?}. Will never return if a failed Agent is {#restart}
-
# with `:clear_actions` true.
-
#
-
# Returns a reference to `self` to support method chaining:
-
#
-
# ```
-
# current_value = agent.await.value
-
# ```
-
#
-
# @return [Boolean] self
-
#
-
# @!macro agent_await_warning
-
1
def await
-
wait(nil)
-
self
-
end
-
-
# Blocks the current thread until all actions dispatched thus far, from this
-
# thread or nested by the Agent, have occurred, or the timeout (in seconds)
-
# has elapsed.
-
#
-
# @param [Float] timeout the maximum number of seconds to wait
-
# @return [Boolean] true if all actions complete before timeout else false
-
#
-
# @!macro agent_await_warning
-
1
def await_for(timeout)
-
wait(timeout.to_f)
-
end
-
-
# Blocks the current thread until all actions dispatched thus far, from this
-
# thread or nested by the Agent, have occurred, or the timeout (in seconds)
-
# has elapsed.
-
#
-
# @param [Float] timeout the maximum number of seconds to wait
-
# @return [Boolean] true if all actions complete before timeout
-
#
-
# @raise [Concurrent::TimeoutError] when timout is reached
-
#
-
# @!macro agent_await_warning
-
1
def await_for!(timeout)
-
raise Concurrent::TimeoutError unless wait(timeout.to_f)
-
true
-
end
-
-
# Blocks the current thread until all actions dispatched thus far, from this
-
# thread or nested by the Agent, have occurred, or the timeout (in seconds)
-
# has elapsed. Will block indefinitely when timeout is nil or not given.
-
#
-
# Provided mainly for consistency with other classes in this library. Prefer
-
# the various `await` methods instead.
-
#
-
# @param [Float] timeout the maximum number of seconds to wait
-
# @return [Boolean] true if all actions complete before timeout else false
-
#
-
# @!macro agent_await_warning
-
1
def wait(timeout = nil)
-
latch = Concurrent::CountDownLatch.new(1)
-
enqueue_await_job(latch)
-
latch.wait(timeout)
-
end
-
-
# Is the Agent in a failed state?
-
#
-
# @see {#restart}
-
1
def failed?
-
!@error.value.nil?
-
end
-
-
1
alias_method :stopped?, :failed?
-
-
# When an Agent is {#failed?}, changes the Agent {#value} to `new_value`
-
# then un-fails the Agent so that action dispatches are allowed again. If
-
# the `:clear_actions` option is give and true, any actions queued on the
-
# Agent that were being held while it was failed will be discarded,
-
# otherwise those held actions will proceed. The `new_value` must pass the
-
# validator if any, or `restart` will raise an exception and the Agent will
-
# remain failed with its old {#value} and {#error}. Observers, if any, will
-
# not be notified of the new state.
-
#
-
# @param [Object] new_value the new value for the Agent once restarted
-
# @param [Hash] opts the configuration options
-
# @option opts [Symbol] :clear_actions true if all enqueued but unprocessed
-
# actions should be discarded on restart, else false (default: false)
-
# @return [Boolean] true
-
#
-
# @raise [Concurrent:AgentError] when not failed
-
1
def restart(new_value, opts = {})
-
clear_actions = opts.fetch(:clear_actions, false)
-
synchronize do
-
raise Error.new('agent is not failed') unless failed?
-
raise ValidationError unless ns_validate(new_value)
-
@current.value = new_value
-
@error.value = nil
-
@queue.clear if clear_actions
-
ns_post_next_job unless @queue.empty?
-
end
-
true
-
end
-
-
1
class << self
-
-
# Blocks the current thread (indefinitely!) until all actions dispatched
-
# thus far to all the given Agents, from this thread or nested by the
-
# given Agents, have occurred. Will block when any of the agents are
-
# failed. Will never return if a failed Agent is restart with
-
# `:clear_actions` true.
-
#
-
# @param [Array<Concurrent::Agent>] agents the Agents on which to wait
-
# @return [Boolean] true
-
#
-
# @!macro agent_await_warning
-
1
def await(*agents)
-
agents.each { |agent| agent.await }
-
true
-
end
-
-
# Blocks the current thread until all actions dispatched thus far to all
-
# the given Agents, from this thread or nested by the given Agents, have
-
# occurred, or the timeout (in seconds) has elapsed.
-
#
-
# @param [Float] timeout the maximum number of seconds to wait
-
# @param [Array<Concurrent::Agent>] agents the Agents on which to wait
-
# @return [Boolean] true if all actions complete before timeout else false
-
#
-
# @!macro agent_await_warning
-
1
def await_for(timeout, *agents)
-
end_at = Concurrent.monotonic_time + timeout.to_f
-
ok = agents.length.times do |i|
-
break false if (delay = end_at - Concurrent.monotonic_time) < 0
-
break false unless agents[i].await_for(delay)
-
end
-
!!ok
-
end
-
-
# Blocks the current thread until all actions dispatched thus far to all
-
# the given Agents, from this thread or nested by the given Agents, have
-
# occurred, or the timeout (in seconds) has elapsed.
-
#
-
# @param [Float] timeout the maximum number of seconds to wait
-
# @param [Array<Concurrent::Agent>] agents the Agents on which to wait
-
# @return [Boolean] true if all actions complete before timeout
-
#
-
# @raise [Concurrent::TimeoutError] when timout is reached
-
# @!macro agent_await_warning
-
1
def await_for!(timeout, *agents)
-
raise Concurrent::TimeoutError unless await_for(timeout, *agents)
-
true
-
end
-
end
-
-
1
private
-
-
1
def ns_initialize(initial, opts)
-
@error_mode = opts[:error_mode]
-
@error_handler = opts[:error_handler]
-
-
if @error_mode && !ERROR_MODES.include?(@error_mode)
-
raise ArgumentError.new('unrecognized error mode')
-
elsif @error_mode.nil?
-
@error_mode = @error_handler ? :continue : :fail
-
end
-
-
@error_handler ||= DEFAULT_ERROR_HANDLER
-
@validator = opts.fetch(:validator, DEFAULT_VALIDATOR)
-
@current = Concurrent::AtomicReference.new(initial)
-
@error = Concurrent::AtomicReference.new(nil)
-
@caller = Concurrent::ThreadLocalVar.new(nil)
-
@queue = []
-
-
self.observers = Collection::CopyOnNotifyObserverSet.new
-
end
-
-
1
def enqueue_action_job(action, args, executor)
-
raise ArgumentError.new('no action given') unless action
-
job = Job.new(action, args, executor, @caller.value || Thread.current.object_id)
-
synchronize { ns_enqueue_job(job) }
-
end
-
-
1
def enqueue_await_job(latch)
-
synchronize do
-
if (index = ns_find_last_job_for_thread)
-
job = Job.new(AWAIT_ACTION, [latch], Concurrent.global_immediate_executor,
-
Thread.current.object_id)
-
ns_enqueue_job(job, index+1)
-
else
-
latch.count_down
-
true
-
end
-
end
-
end
-
-
1
def ns_enqueue_job(job, index = nil)
-
# a non-nil index means this is an await job
-
return false if index.nil? && failed?
-
index ||= @queue.length
-
@queue.insert(index, job)
-
# if this is the only job, post to executor
-
ns_post_next_job if @queue.length == 1
-
true
-
end
-
-
1
def ns_post_next_job
-
@queue.first.executor.post { execute_next_job }
-
end
-
-
1
def execute_next_job
-
job = synchronize { @queue.first }
-
old_value = @current.value
-
-
@caller.value = job.caller # for nested actions
-
new_value = job.action.call(old_value, *job.args)
-
@caller.value = nil
-
-
return if new_value == AWAIT_FLAG
-
-
if ns_validate(new_value)
-
@current.value = new_value
-
observers.notify_observers(Time.now, old_value, new_value)
-
else
-
handle_error(ValidationError.new)
-
end
-
rescue => error
-
handle_error(error)
-
ensure
-
synchronize do
-
@queue.shift
-
unless failed? || @queue.empty?
-
ns_post_next_job
-
end
-
end
-
end
-
-
1
def ns_validate(value)
-
@validator.call(value)
-
rescue
-
false
-
end
-
-
1
def handle_error(error)
-
# stop new jobs from posting
-
@error.value = error if @error_mode == :fail
-
@error_handler.call(self, error)
-
rescue
-
# do nothing
-
end
-
-
1
def ns_find_last_job_for_thread
-
@queue.rindex { |job| job.caller == Thread.current.object_id }
-
end
-
end
-
end
-
1
require 'concurrent/utility/engine'
-
1
require 'concurrent/thread_safe/util'
-
-
1
module Concurrent
-
1
if Concurrent.on_cruby?
-
-
# Because MRI never runs code in parallel, the existing
-
# non-thread-safe structures should usually work fine.
-
-
# @!macro [attach] concurrent_array
-
#
-
# A thread-safe subclass of Array. This version locks against the object
-
# itself for every method call, ensuring only one thread can be reading
-
# or writing at a time. This includes iteration methods like `#each`.
-
#
-
# @see http://ruby-doc.org/core-2.2.0/Array.html Ruby standard library `Array`
-
1
class Array < ::Array;
-
end
-
-
elsif Concurrent.on_jruby?
-
require 'jruby/synchronized'
-
-
# @!macro concurrent_array
-
class Array < ::Array
-
include JRuby::Synchronized
-
end
-
-
elsif Concurrent.on_rbx? || Concurrent.on_truffle?
-
require 'monitor'
-
require 'concurrent/thread_safe/util/array_hash_rbx'
-
-
# @!macro concurrent_array
-
class Array < ::Array
-
end
-
-
ThreadSafe::Util.make_synchronized_on_rbx Array
-
end
-
end
-
-
1
require 'concurrent/configuration'
-
1
require 'concurrent/ivar'
-
1
require 'concurrent/synchronization/lockable_object'
-
-
1
module Concurrent
-
-
# A mixin module that provides simple asynchronous behavior to a class,
-
# turning it into a simple actor. Loosely based on Erlang's
-
# [gen_server](http://www.erlang.org/doc/man/gen_server.html), but without
-
# supervision or linking.
-
#
-
# A more feature-rich {Concurrent::Actor} is also available when the
-
# capabilities of `Async` are too limited.
-
#
-
# ```cucumber
-
# Feature:
-
# As a stateful, plain old Ruby class
-
# I want safe, asynchronous behavior
-
# So my long-running methods don't block the main thread
-
# ```
-
#
-
# The `Async` module is a way to mix simple yet powerful asynchronous
-
# capabilities into any plain old Ruby object or class, turning each object
-
# into a simple Actor. Method calls are processed on a background thread. The
-
# caller is free to perform other actions while processing occurs in the
-
# background.
-
#
-
# Method calls to the asynchronous object are made via two proxy methods:
-
# `async` (alias `cast`) and `await` (alias `call`). These proxy methods post
-
# the method call to the object's background thread and return a "future"
-
# which will eventually contain the result of the method call.
-
#
-
# This behavior is loosely patterned after Erlang's `gen_server` behavior.
-
# When an Erlang module implements the `gen_server` behavior it becomes
-
# inherently asynchronous. The `start` or `start_link` function spawns a
-
# process (similar to a thread but much more lightweight and efficient) and
-
# returns the ID of the process. Using the process ID, other processes can
-
# send messages to the `gen_server` via the `cast` and `call` methods. Unlike
-
# Erlang's `gen_server`, however, `Async` classes do not support linking or
-
# supervision trees.
-
#
-
# ## Basic Usage
-
#
-
# When this module is mixed into a class, objects of the class become inherently
-
# asynchronous. Each object gets its own background thread on which to post
-
# asynchronous method calls. Asynchronous method calls are executed in the
-
# background one at a time in the order they are received.
-
#
-
# To create an asynchronous class, simply mix in the `Concurrent::Async` module:
-
#
-
# ```
-
# class Hello
-
# include Concurrent::Async
-
#
-
# def hello(name)
-
# "Hello, #{name}!"
-
# end
-
# end
-
# ```
-
#
-
# When defining a constructor it is critical that the first line be a call to
-
# `super` with no arguments. The `super` method initializes the background
-
# thread and other asynchronous components.
-
#
-
# ```
-
# class BackgroundLogger
-
# include Concurrent::Async
-
#
-
# def initialize(level)
-
# super()
-
# @logger = Logger.new(STDOUT)
-
# @logger.level = level
-
# end
-
#
-
# def info(msg)
-
# @logger.info(msg)
-
# end
-
# end
-
# ```
-
#
-
# Mixing this module into a class provides each object two proxy methods:
-
# `async` and `await`. These methods are thread safe with respect to the
-
# enclosing object. The former proxy allows methods to be called
-
# asynchronously by posting to the object's internal thread. The latter proxy
-
# allows a method to be called synchronously but does so safely with respect
-
# to any pending asynchronous method calls and ensures proper ordering. Both
-
# methods return a {Concurrent::IVar} which can be inspected for the result
-
# of the proxied method call. Calling a method with `async` will return a
-
# `:pending` `IVar` whereas `await` will return a `:complete` `IVar`.
-
#
-
# ```
-
# class Echo
-
# include Concurrent::Async
-
#
-
# def echo(msg)
-
# print "#{msg}\n"
-
# end
-
# end
-
#
-
# horn = Echo.new
-
# horn.echo('zero') # synchronous, not thread-safe
-
# # returns the actual return value of the method
-
#
-
# horn.async.echo('one') # asynchronous, non-blocking, thread-safe
-
# # returns an IVar in the :pending state
-
#
-
# horn.await.echo('two') # synchronous, blocking, thread-safe
-
# # returns an IVar in the :complete state
-
# ```
-
#
-
# ## Let It Fail
-
#
-
# The `async` and `await` proxy methods have built-in error protection based
-
# on Erlang's famous "let it fail" philosophy. Instance methods should not be
-
# programmed defensively. When an exception is raised by a delegated method
-
# the proxy will rescue the exception, expose it to the caller as the `reason`
-
# attribute of the returned future, then process the next method call.
-
#
-
# ## Calling Methods Internally
-
#
-
# External method calls should *always* use the `async` and `await` proxy
-
# methods. When one method calls another method, the `async` proxy should
-
# rarely be used and the `await` proxy should *never* be used.
-
#
-
# When an object calls one of its own methods using the `await` proxy the
-
# second call will be enqueued *behind* the currently running method call.
-
# Any attempt to wait on the result will fail as the second call will never
-
# run until after the current call completes.
-
#
-
# Calling a method using the `await` proxy from within a method that was
-
# itself called using `async` or `await` will irreversibly deadlock the
-
# object. Do *not* do this, ever.
-
#
-
# ## Instance Variables and Attribute Accessors
-
#
-
# Instance variables do not need to be thread-safe so long as they are private.
-
# Asynchronous method calls are processed in the order they are received and
-
# are processed one at a time. Therefore private instance variables can only
-
# be accessed by one thread at a time. This is inherently thread-safe.
-
#
-
# When using private instance variables within asynchronous methods, the best
-
# practice is to read the instance variable into a local variable at the start
-
# of the method then update the instance variable at the *end* of the method.
-
# This way, should an exception be raised during method execution the internal
-
# state of the object will not have been changed.
-
#
-
# ### Reader Attributes
-
#
-
# The use of `attr_reader` is discouraged. Internal state exposed externally,
-
# when necessary, should be done through accessor methods. The instance
-
# variables exposed by these methods *must* be thread-safe, or they must be
-
# called using the `async` and `await` proxy methods. These two approaches are
-
# subtly different.
-
#
-
# When internal state is accessed via the `async` and `await` proxy methods,
-
# the returned value represents the object's state *at the time the call is
-
# processed*, which may *not* be the state of the object at the time the call
-
# is made.
-
#
-
# To get the state *at the current* time, irrespective of an enqueued method
-
# calls, a reader method must be called directly. This is inherently unsafe
-
# unless the instance variable is itself thread-safe, preferrably using one
-
# of the thread-safe classes within this library. Because the thread-safe
-
# classes within this library are internally-locking or non-locking, they can
-
# be safely used from within asynchronous methods without causing deadlocks.
-
#
-
# Generally speaking, the best practice is to *not* expose internal state via
-
# reader methods. The best practice is to simply use the method's return value.
-
#
-
# ### Writer Attributes
-
#
-
# Writer attributes should never be used with asynchronous classes. Changing
-
# the state externally, even when done in the thread-safe way, is not logically
-
# consistent. Changes to state need to be timed with respect to all asynchronous
-
# method calls which my be in-process or enqueued. The only safe practice is to
-
# pass all necessary data to each method as arguments and let the method update
-
# the internal state as necessary.
-
#
-
# ## Class Constants, Variables, and Methods
-
#
-
# ### Class Constants
-
#
-
# Class constants do not need to be thread-safe. Since they are read-only and
-
# immutable they may be safely read both externally and from within
-
# asynchronous methods.
-
#
-
# ### Class Variables
-
#
-
# Class variables should be avoided. Class variables represent shared state.
-
# Shared state is anathema to concurrency. Should there be a need to share
-
# state using class variables they *must* be thread-safe, preferrably
-
# using the thread-safe classes within this library. When updating class
-
# variables, never assign a new value/object to the variable itself. Assignment
-
# is not thread-safe in Ruby. Instead, use the thread-safe update functions
-
# of the variable itself to change the value.
-
#
-
# The best practice is to *never* use class variables with `Async` classes.
-
#
-
# ### Class Methods
-
#
-
# Class methods which are pure functions are safe. Class methods which modify
-
# class variables should be avoided, for all the reasons listed above.
-
#
-
# ## An Important Note About Thread Safe Guarantees
-
#
-
# > Thread safe guarantees can only be made when asynchronous method calls
-
# > are not mixed with direct method calls. Use only direct method calls
-
# > when the object is used exclusively on a single thread. Use only
-
# > `async` and `await` when the object is shared between threads. Once you
-
# > call a method using `async` or `await`, you should no longer call methods
-
# > directly on the object. Use `async` and `await` exclusively from then on.
-
#
-
# @example
-
#
-
# class Echo
-
# include Concurrent::Async
-
#
-
# def echo(msg)
-
# print "#{msg}\n"
-
# end
-
# end
-
#
-
# horn = Echo.new
-
# horn.echo('zero') # synchronous, not thread-safe
-
# # returns the actual return value of the method
-
#
-
# horn.async.echo('one') # asynchronous, non-blocking, thread-safe
-
# # returns an IVar in the :pending state
-
#
-
# horn.await.echo('two') # synchronous, blocking, thread-safe
-
# # returns an IVar in the :complete state
-
#
-
# @see Concurrent::Actor
-
# @see https://en.wikipedia.org/wiki/Actor_model "Actor Model" at Wikipedia
-
# @see http://www.erlang.org/doc/man/gen_server.html Erlang gen_server
-
# @see http://c2.com/cgi/wiki?LetItCrash "Let It Crash" at http://c2.com/
-
1
module Async
-
-
# @!method self.new(*args, &block)
-
#
-
# Instanciate a new object and ensure proper initialization of the
-
# synchronization mechanisms.
-
#
-
# @param [Array<Object>] args Zero or more arguments to be passed to the
-
# object's initializer.
-
# @param [Proc] block Optional block to pass to the object's initializer.
-
# @return [Object] A properly initialized object of the asynchronous class.
-
-
# Check for the presence of a method on an object and determine if a given
-
# set of arguments matches the required arity.
-
#
-
# @param [Object] obj the object to check against
-
# @param [Symbol] method the method to check the object for
-
# @param [Array] args zero or more arguments for the arity check
-
#
-
# @raise [NameError] the object does not respond to `method` method
-
# @raise [ArgumentError] the given `args` do not match the arity of `method`
-
#
-
# @note This check is imperfect because of the way Ruby reports the arity of
-
# methods with a variable number of arguments. It is possible to determine
-
# if too few arguments are given but impossible to determine if too many
-
# arguments are given. This check may also fail to recognize dynamic behavior
-
# of the object, such as methods simulated with `method_missing`.
-
#
-
# @see http://www.ruby-doc.org/core-2.1.1/Method.html#method-i-arity Method#arity
-
# @see http://ruby-doc.org/core-2.1.0/Object.html#method-i-respond_to-3F Object#respond_to?
-
# @see http://www.ruby-doc.org/core-2.1.0/BasicObject.html#method-i-method_missing BasicObject#method_missing
-
#
-
# @!visibility private
-
1
def self.validate_argc(obj, method, *args)
-
argc = args.length
-
arity = obj.method(method).arity
-
-
if arity >= 0 && argc != arity
-
raise ArgumentError.new("wrong number of arguments (#{argc} for #{arity})")
-
elsif arity < 0 && (arity = (arity + 1).abs) > argc
-
raise ArgumentError.new("wrong number of arguments (#{argc} for #{arity}..*)")
-
end
-
end
-
-
# @!visibility private
-
1
def self.included(base)
-
base.singleton_class.send(:alias_method, :original_new, :new)
-
base.extend(ClassMethods)
-
super(base)
-
end
-
-
# @!visibility private
-
1
module ClassMethods
-
1
def new(*args, &block)
-
obj = original_new(*args, &block)
-
obj.send(:init_synchronization)
-
obj
-
end
-
end
-
1
private_constant :ClassMethods
-
-
# Delegates asynchronous, thread-safe method calls to the wrapped object.
-
#
-
# @!visibility private
-
1
class AsyncDelegator < Synchronization::LockableObject
-
1
safe_initialization!
-
-
# Create a new delegator object wrapping the given delegate.
-
#
-
# @param [Object] delegate the object to wrap and delegate method calls to
-
1
def initialize(delegate)
-
super()
-
@delegate = delegate
-
@queue = []
-
@executor = Concurrent.global_io_executor
-
end
-
-
# Delegates method calls to the wrapped object.
-
#
-
# @param [Symbol] method the method being called
-
# @param [Array] args zero or more arguments to the method
-
#
-
# @return [IVar] the result of the method call
-
#
-
# @raise [NameError] the object does not respond to `method` method
-
# @raise [ArgumentError] the given `args` do not match the arity of `method`
-
1
def method_missing(method, *args, &block)
-
super unless @delegate.respond_to?(method)
-
Async::validate_argc(@delegate, method, *args)
-
-
ivar = Concurrent::IVar.new
-
synchronize do
-
@queue.push [ivar, method, args, block]
-
@executor.post { perform } if @queue.length == 1
-
end
-
-
ivar
-
end
-
-
# Perform all enqueued tasks.
-
#
-
# This method must be called from within the executor. It must not be
-
# called while already running. It will loop until the queue is empty.
-
1
def perform
-
loop do
-
ivar, method, args, block = synchronize { @queue.first }
-
break unless ivar # queue is empty
-
-
begin
-
ivar.set(@delegate.send(method, *args, &block))
-
rescue => error
-
ivar.fail(error)
-
end
-
-
synchronize do
-
@queue.shift
-
return if @queue.empty?
-
end
-
end
-
end
-
end
-
1
private_constant :AsyncDelegator
-
-
# Delegates synchronous, thread-safe method calls to the wrapped object.
-
#
-
# @!visibility private
-
1
class AwaitDelegator
-
-
# Create a new delegator object wrapping the given delegate.
-
#
-
# @param [AsyncDelegator] delegate the object to wrap and delegate method calls to
-
1
def initialize(delegate)
-
@delegate = delegate
-
end
-
-
# Delegates method calls to the wrapped object.
-
#
-
# @param [Symbol] method the method being called
-
# @param [Array] args zero or more arguments to the method
-
#
-
# @return [IVar] the result of the method call
-
#
-
# @raise [NameError] the object does not respond to `method` method
-
# @raise [ArgumentError] the given `args` do not match the arity of `method`
-
1
def method_missing(method, *args, &block)
-
ivar = @delegate.send(method, *args, &block)
-
ivar.wait
-
ivar
-
end
-
end
-
1
private_constant :AwaitDelegator
-
-
# Causes the chained method call to be performed asynchronously on the
-
# object's thread. The delegated method will return a future in the
-
# `:pending` state and the method call will have been scheduled on the
-
# object's thread. The final disposition of the method call can be obtained
-
# by inspecting the returned future.
-
#
-
# @!macro [attach] async_thread_safety_warning
-
# @note The method call is guaranteed to be thread safe with respect to
-
# all other method calls against the same object that are called with
-
# either `async` or `await`. The mutable nature of Ruby references
-
# (and object orientation in general) prevent any other thread safety
-
# guarantees. Do NOT mix direct method calls with delegated method calls.
-
# Use *only* delegated method calls when sharing the object between threads.
-
#
-
# @return [Concurrent::IVar] the pending result of the asynchronous operation
-
#
-
# @raise [NameError] the object does not respond to the requested method
-
# @raise [ArgumentError] the given `args` do not match the arity of
-
# the requested method
-
1
def async
-
@__async_delegator__
-
end
-
1
alias_method :cast, :async
-
-
# Causes the chained method call to be performed synchronously on the
-
# current thread. The delegated will return a future in either the
-
# `:fulfilled` or `:rejected` state and the delegated method will have
-
# completed. The final disposition of the delegated method can be obtained
-
# by inspecting the returned future.
-
#
-
# @!macro async_thread_safety_warning
-
#
-
# @return [Concurrent::IVar] the completed result of the synchronous operation
-
#
-
# @raise [NameError] the object does not respond to the requested method
-
# @raise [ArgumentError] the given `args` do not match the arity of the
-
# requested method
-
1
def await
-
@__await_delegator__
-
end
-
1
alias_method :call, :await
-
-
# Initialize the internal serializer and other stnchronization mechanisms.
-
#
-
# @note This method *must* be called immediately upon object construction.
-
# This is the only way thread-safe initialization can be guaranteed.
-
#
-
# @!visibility private
-
1
def init_synchronization
-
return self if @__async_initialized__
-
@__async_initialized__ = true
-
@__async_delegator__ = AsyncDelegator.new(self)
-
@__await_delegator__ = AwaitDelegator.new(@__async_delegator__)
-
self
-
end
-
end
-
end
-
1
require 'concurrent/atomic/atomic_reference'
-
1
require 'concurrent/collection/copy_on_notify_observer_set'
-
1
require 'concurrent/concern/observable'
-
1
require 'concurrent/synchronization'
-
-
# @!macro [new] thread_safe_variable_comparison
-
#
-
# ## Thread-safe Variable Classes
-
#
-
# Each of the thread-safe variable classes is designed to solve a different
-
# problem. In general:
-
#
-
# * *{Concurrent::Agent}:* Shared, mutable variable providing independent,
-
# uncoordinated, *asynchronous* change of individual values. Best used when
-
# the value will undergo frequent, complex updates. Suitable when the result
-
# of an update does not need to be known immediately.
-
# * *{Concurrent::Atom}:* Shared, mutable variable providing independent,
-
# uncoordinated, *synchronous* change of individual values. Best used when
-
# the value will undergo frequent reads but only occasional, though complex,
-
# updates. Suitable when the result of an update must be known immediately.
-
# * *{Concurrent::AtomicReference}:* A simple object reference that can be
-
# atomically. Updates are synchronous but fast. Best used when updates a
-
# simple set operations. Not suitable when updates are complex.
-
# {Concurrent::AtomicBoolean} and {Concurrent::AtomicFixnum} are similar
-
# but optimized for the given data type.
-
# * *{Concurrent::Exchanger}:* Shared, stateless synchronization point. Used
-
# when two or more threads need to exchange data. The threads will pair then
-
# block on each other until the exchange is complete.
-
# * *{Concurrent::MVar}:* Shared synchronization point. Used when one thread
-
# must give a value to another, which must take the value. The threads will
-
# block on each other until the exchange is complete.
-
# * *{Concurrent::ThreadLocalVar}:* Shared, mutable, isolated variable which
-
# holds a different value for each thread which has access. Often used as
-
# an instance variable in objects which must maintain different state
-
# for different threads.
-
# * *{Concurrent::TVar}:* Shared, mutable variables which provide
-
# *coordinated*, *synchronous*, change of *many* stated. Used when multiple
-
# value must change together, in an all-or-nothing transaction.
-
-
-
1
module Concurrent
-
-
# Atoms provide a way to manage shared, synchronous, independent state.
-
#
-
# An atom is initialized with an initial value and an optional validation
-
# proc. At any time the value of the atom can be synchronously and safely
-
# changed. If a validator is given at construction then any new value
-
# will be checked against the validator and will be rejected if the
-
# validator returns false or raises an exception.
-
#
-
# There are two ways to change the value of an atom: {#compare_and_set} and
-
# {#swap}. The former will set the new value if and only if it validates and
-
# the current value matches the new value. The latter will atomically set the
-
# new value to the result of running the given block if and only if that
-
# value validates.
-
#
-
# ## Example
-
#
-
# ```
-
# def next_fibonacci(set = nil)
-
# return [0, 1] if set.nil?
-
# set + [set[-2..-1].reduce{|sum,x| sum + x }]
-
# end
-
#
-
# # create an atom with an initial value
-
# atom = Concurrent::Atom.new(next_fibonacci)
-
#
-
# # send a few update requests
-
# 5.times do
-
# atom.swap{|set| next_fibonacci(set) }
-
# end
-
#
-
# # get the current value
-
# atom.value #=> [0, 1, 1, 2, 3, 5, 8]
-
# ```
-
#
-
# ## Observation
-
#
-
# Atoms support observers through the {Concurrent::Observable} mixin module.
-
# Notification of observers occurs every time the value of the Atom changes.
-
# When notified the observer will receive three arguments: `time`, `old_value`,
-
# and `new_value`. The `time` argument is the time at which the value change
-
# occurred. The `old_value` is the value of the Atom when the change began
-
# The `new_value` is the value to which the Atom was set when the change
-
# completed. Note that `old_value` and `new_value` may be the same. This is
-
# not an error. It simply means that the change operation returned the same
-
# value.
-
#
-
# Unlike in Clojure, `Atom` cannot participate in {Concurrent::TVar} transactions.
-
#
-
# @!macro thread_safe_variable_comparison
-
#
-
# @see http://clojure.org/atoms Clojure Atoms
-
# @see http://clojure.org/state Values and Change - Clojure's approach to Identity and State
-
1
class Atom < Synchronization::Object
-
1
include Concern::Observable
-
-
1
safe_initialization!
-
1
private(*attr_atomic(:value))
-
1
public :value
-
-
# Create a new atom with the given initial value.
-
#
-
# @param [Object] value The initial value
-
# @param [Hash] opts The options used to configure the atom
-
# @option opts [Proc] :validator (nil) Optional proc used to validate new
-
# values. It must accept one and only one argument which will be the
-
# intended new value. The validator will return true if the new value
-
# is acceptable else return false (preferrably) or raise an exception.
-
#
-
# @!macro deref_options
-
#
-
# @raise [ArgumentError] if the validator is not a `Proc` (when given)
-
1
def initialize(value, opts = {})
-
super()
-
@Validator = opts.fetch(:validator, -> v { true })
-
self.observers = Collection::CopyOnNotifyObserverSet.new
-
self.value = value
-
end
-
-
# @!method value
-
# The current value of the atom.
-
#
-
# @return [Object] The current value.
-
-
1
alias_method :deref, :value
-
-
# Atomically swaps the value of atom using the given block. The current
-
# value will be passed to the block, as will any arguments passed as
-
# arguments to the function. The new value will be validated against the
-
# (optional) validator proc given at construction. If validation fails the
-
# value will not be changed.
-
#
-
# Internally, {#swap} reads the current value, applies the block to it, and
-
# attempts to compare-and-set it in. Since another thread may have changed
-
# the value in the intervening time, it may have to retry, and does so in a
-
# spin loop. The net effect is that the value will always be the result of
-
# the application of the supplied block to a current value, atomically.
-
# However, because the block might be called multiple times, it must be free
-
# of side effects.
-
#
-
# @note The given block may be called multiple times, and thus should be free
-
# of side effects.
-
#
-
# @param [Object] args Zero or more arguments passed to the block.
-
#
-
# @yield [value, args] Calculates a new value for the atom based on the
-
# current value and any supplied arguments.
-
# @yieldparam value [Object] The current value of the atom.
-
# @yieldparam args [Object] All arguments passed to the function, in order.
-
# @yieldreturn [Object] The intended new value of the atom.
-
#
-
# @return [Object] The final value of the atom after all operations and
-
# validations are complete.
-
#
-
# @raise [ArgumentError] When no block is given.
-
1
def swap(*args)
-
raise ArgumentError.new('no block given') unless block_given?
-
-
loop do
-
old_value = value
-
new_value = yield(old_value, *args)
-
begin
-
break old_value unless valid?(new_value)
-
break new_value if compare_and_set(old_value, new_value)
-
rescue
-
break old_value
-
end
-
end
-
end
-
-
# Atomically sets the value of atom to the new value if and only if the
-
# current value of the atom is identical to the old value and the new
-
# value successfully validates against the (optional) validator given
-
# at construction.
-
#
-
# @param [Object] old_value The expected current value.
-
# @param [Object] new_value The intended new value.
-
#
-
# @return [Boolean] True if the value is changed else false.
-
1
def compare_and_set(old_value, new_value)
-
if valid?(new_value) && compare_and_set_value(old_value, new_value)
-
observers.notify_observers(Time.now, old_value, new_value)
-
true
-
else
-
false
-
end
-
end
-
-
# Atomically sets the value of atom to the new value without regard for the
-
# current value so long as the new value successfully validates against the
-
# (optional) validator given at construction.
-
#
-
# @param [Object] new_value The intended new value.
-
#
-
# @return [Object] The final value of the atom after all operations and
-
# validations are complete.
-
1
def reset(new_value)
-
old_value = value
-
if valid?(new_value)
-
self.value = new_value
-
observers.notify_observers(Time.now, old_value, new_value)
-
new_value
-
else
-
old_value
-
end
-
end
-
-
1
private
-
-
# Is the new value valid?
-
#
-
# @param [Object] new_value The intended new value.
-
# @return [Boolean] false if the validator function returns false or raises
-
# an exception else true
-
1
def valid?(new_value)
-
@Validator.call(new_value)
-
rescue
-
false
-
end
-
end
-
end
-
1
require 'concurrent/constants'
-
-
1
module Concurrent
-
-
# @!macro thread_local_var
-
# @!macro internal_implementation_note
-
# @!visibility private
-
1
class AbstractThreadLocalVar
-
-
# @!macro thread_local_var_method_initialize
-
1
def initialize(default = nil, &default_block)
-
if default && block_given?
-
raise ArgumentError, "Cannot use both value and block as default value"
-
end
-
-
if block_given?
-
@default_block = default_block
-
@default = nil
-
else
-
@default_block = nil
-
@default = default
-
end
-
-
allocate_storage
-
end
-
-
# @!macro thread_local_var_method_get
-
1
def value
-
raise NotImplementedError
-
end
-
-
# @!macro thread_local_var_method_set
-
1
def value=(value)
-
raise NotImplementedError
-
end
-
-
# @!macro thread_local_var_method_bind
-
1
def bind(value, &block)
-
if block_given?
-
old_value = self.value
-
begin
-
self.value = value
-
yield
-
ensure
-
self.value = old_value
-
end
-
end
-
end
-
-
1
protected
-
-
# @!visibility private
-
1
def allocate_storage
-
raise NotImplementedError
-
end
-
-
# @!visibility private
-
1
def default
-
if @default_block
-
self.value = @default_block.call
-
else
-
@default
-
end
-
end
-
end
-
end
-
1
require 'concurrent/synchronization'
-
1
require 'concurrent/utility/engine'
-
1
require 'concurrent/atomic_reference/concurrent_update_error'
-
1
require 'concurrent/atomic_reference/mutex_atomic'
-
-
1
begin
-
# force fallback impl with FORCE_ATOMIC_FALLBACK=1
-
1
if /[^0fF]/ =~ ENV['FORCE_ATOMIC_FALLBACK']
-
ruby_engine = 'mutex_atomic'
-
else
-
1
ruby_engine = Concurrent.ruby_engine
-
end
-
-
1
require "concurrent/atomic_reference/#{ruby_engine}"
-
rescue LoadError
-
#warn 'Compiled extensions not installed, pure Ruby Atomic will be used.'
-
end
-
-
1
if defined? Concurrent::JavaAtomicReference
-
-
# @!macro atomic_reference
-
class Concurrent::AtomicReference < Concurrent::JavaAtomicReference
-
end
-
-
elsif defined? Concurrent::RbxAtomicReference
-
-
# @!macro atomic_reference
-
class Concurrent::AtomicReference < Concurrent::RbxAtomicReference
-
end
-
-
elsif defined? Concurrent::CAtomicReference
-
-
# @!macro atomic_reference
-
class Concurrent::AtomicReference < Concurrent::CAtomicReference
-
end
-
-
else
-
-
# @!macro atomic_reference
-
1
class Concurrent::AtomicReference < Concurrent::MutexAtomicReference
-
end
-
end
-
-
1
class Concurrent::AtomicReference
-
# @return [String] Short string representation.
-
1
def to_s
-
format '<#%s:0x%x value:%s>', self.class, object_id << 1, get
-
end
-
-
1
alias_method :inspect, :to_s
-
end
-
1
require 'concurrent/atomic/mutex_count_down_latch'
-
1
require 'concurrent/atomic/java_count_down_latch'
-
1
require 'concurrent/utility/engine'
-
-
1
module Concurrent
-
-
###################################################################
-
-
# @!macro [new] count_down_latch_method_initialize
-
#
-
# Create a new `CountDownLatch` with the initial `count`.
-
#
-
# @param [new] count the initial count
-
#
-
# @raise [ArgumentError] if `count` is not an integer or is less than zero
-
-
# @!macro [new] count_down_latch_method_wait
-
#
-
# Block on the latch until the counter reaches zero or until `timeout` is reached.
-
#
-
# @param [Fixnum] timeout the number of seconds to wait for the counter or `nil`
-
# to block indefinitely
-
# @return [Boolean] `true` if the `count` reaches zero else false on `timeout`
-
-
# @!macro [new] count_down_latch_method_count_down
-
#
-
# Signal the latch to decrement the counter. Will signal all blocked threads when
-
# the `count` reaches zero.
-
-
# @!macro [attach] count_down_latch_method_count
-
#
-
# The current value of the counter.
-
#
-
# @return [Fixnum] the current value of the counter
-
-
###################################################################
-
-
# @!macro [new] count_down_latch_public_api
-
#
-
# @!method initialize(count = 1)
-
# @!macro count_down_latch_method_initialize
-
#
-
# @!method wait(timeout = nil)
-
# @!macro count_down_latch_method_wait
-
#
-
# @!method count_down
-
# @!macro count_down_latch_method_count_down
-
#
-
# @!method count
-
# @!macro count_down_latch_method_count
-
-
###################################################################
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
CountDownLatchImplementation = case
-
when Concurrent.on_jruby?
-
JavaCountDownLatch
-
else
-
1
MutexCountDownLatch
-
end
-
1
private_constant :CountDownLatchImplementation
-
-
# @!macro [attach] count_down_latch
-
#
-
# A synchronization object that allows one thread to wait on multiple other threads.
-
# The thread that will wait creates a `CountDownLatch` and sets the initial value
-
# (normally equal to the number of other threads). The initiating thread passes the
-
# latch to the other threads then waits for the other threads by calling the `#wait`
-
# method. Each of the other threads calls `#count_down` when done with its work.
-
# When the latch counter reaches zero the waiting thread is unblocked and continues
-
# with its work. A `CountDownLatch` can be used only once. Its value cannot be reset.
-
#
-
# @!macro count_down_latch_public_api
-
# @example Waiter and Decrementer
-
# latch = Concurrent::CountDownLatch.new(3)
-
#
-
# waiter = Thread.new do
-
# latch.wait()
-
# puts ("Waiter released")
-
# end
-
#
-
# decrementer = Thread.new do
-
# sleep(1)
-
# latch.count_down
-
# puts latch.count
-
#
-
# sleep(1)
-
# latch.count_down
-
# puts latch.count
-
#
-
# sleep(1)
-
# latch.count_down
-
# puts latch.count
-
# end
-
#
-
# [waiter, decrementer].each(&:join)
-
1
class CountDownLatch < CountDownLatchImplementation
-
end
-
end
-
1
require 'concurrent/synchronization'
-
1
require 'concurrent/utility/native_integer'
-
-
1
module Concurrent
-
-
# A synchronization aid that allows a set of threads to all wait for each
-
# other to reach a common barrier point.
-
# @example
-
# barrier = Concurrent::CyclicBarrier.new(3)
-
# jobs = Array.new(3) { |i| -> { sleep i; p done: i } }
-
# process = -> (i) do
-
# # waiting to start at the same time
-
# barrier.wait
-
# # execute job
-
# jobs[i].call
-
# # wait for others to finish
-
# barrier.wait
-
# end
-
# threads = 2.times.map do |i|
-
# Thread.new(i, &process)
-
# end
-
#
-
# # use main as well
-
# process.call 2
-
#
-
# # here we can be sure that all jobs are processed
-
1
class CyclicBarrier < Synchronization::LockableObject
-
-
# @!visibility private
-
1
Generation = Struct.new(:status)
-
1
private_constant :Generation
-
-
# Create a new `CyclicBarrier` that waits for `parties` threads
-
#
-
# @param [Fixnum] parties the number of parties
-
# @yield an optional block that will be executed that will be executed after
-
# the last thread arrives and before the others are released
-
#
-
# @raise [ArgumentError] if `parties` is not an integer or is less than zero
-
1
def initialize(parties, &block)
-
Utility::NativeInteger.ensure_integer_and_bounds parties
-
Utility::NativeInteger.ensure_positive_and_no_zero parties
-
-
super(&nil)
-
synchronize { ns_initialize parties, &block }
-
end
-
-
# @return [Fixnum] the number of threads needed to pass the barrier
-
1
def parties
-
synchronize { @parties }
-
end
-
-
# @return [Fixnum] the number of threads currently waiting on the barrier
-
1
def number_waiting
-
synchronize { @number_waiting }
-
end
-
-
# Blocks on the barrier until the number of waiting threads is equal to
-
# `parties` or until `timeout` is reached or `reset` is called
-
# If a block has been passed to the constructor, it will be executed once by
-
# the last arrived thread before releasing the others
-
# @param [Fixnum] timeout the number of seconds to wait for the counter or
-
# `nil` to block indefinitely
-
# @return [Boolean] `true` if the `count` reaches zero else false on
-
# `timeout` or on `reset` or if the barrier is broken
-
1
def wait(timeout = nil)
-
synchronize do
-
-
return false unless @generation.status == :waiting
-
-
@number_waiting += 1
-
-
if @number_waiting == @parties
-
@action.call if @action
-
ns_generation_done @generation, :fulfilled
-
true
-
else
-
generation = @generation
-
if ns_wait_until(timeout) { generation.status != :waiting }
-
generation.status == :fulfilled
-
else
-
ns_generation_done generation, :broken, false
-
false
-
end
-
end
-
end
-
end
-
-
# resets the barrier to its initial state
-
# If there is at least one waiting thread, it will be woken up, the `wait`
-
# method will return false and the barrier will be broken
-
# If the barrier is broken, this method restores it to the original state
-
#
-
# @return [nil]
-
1
def reset
-
synchronize { ns_generation_done @generation, :reset }
-
end
-
-
# A barrier can be broken when:
-
# - a thread called the `reset` method while at least one other thread was waiting
-
# - at least one thread timed out on `wait` method
-
#
-
# A broken barrier can be restored using `reset` it's safer to create a new one
-
# @return [Boolean] true if the barrier is broken otherwise false
-
1
def broken?
-
synchronize { @generation.status != :waiting }
-
end
-
-
1
protected
-
-
1
def ns_generation_done(generation, status, continue = true)
-
generation.status = status
-
ns_next_generation if continue
-
ns_broadcast
-
end
-
-
1
def ns_next_generation
-
@generation = Generation.new(:waiting)
-
@number_waiting = 0
-
end
-
-
1
def ns_initialize(parties, &block)
-
@parties = parties
-
@action = block
-
ns_next_generation
-
end
-
end
-
end
-
1
if Concurrent.on_jruby?
-
-
module Concurrent
-
-
# @!macro count_down_latch
-
# @!visibility private
-
# @!macro internal_implementation_note
-
class JavaCountDownLatch
-
-
# @!macro count_down_latch_method_initialize
-
def initialize(count = 1)
-
unless count.is_a?(Fixnum) && count >= 0
-
raise ArgumentError.new('count must be in integer greater than or equal zero')
-
end
-
@latch = java.util.concurrent.CountDownLatch.new(count)
-
end
-
-
# @!macro count_down_latch_method_wait
-
def wait(timeout = nil)
-
if timeout.nil?
-
@latch.await
-
true
-
else
-
@latch.await(1000 * timeout, java.util.concurrent.TimeUnit::MILLISECONDS)
-
end
-
end
-
-
# @!macro count_down_latch_method_count_down
-
def count_down
-
@latch.countDown
-
end
-
-
# @!macro count_down_latch_method_count
-
def count
-
@latch.getCount
-
end
-
end
-
end
-
end
-
1
require 'concurrent/atomic/abstract_thread_local_var'
-
-
1
if Concurrent.on_jruby?
-
-
module Concurrent
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
class JavaThreadLocalVar < AbstractThreadLocalVar
-
-
# @!macro thread_local_var_method_get
-
def value
-
value = @var.get
-
-
if value.nil?
-
default
-
elsif value == NULL
-
nil
-
else
-
value
-
end
-
end
-
-
# @!macro thread_local_var_method_set
-
def value=(value)
-
@var.set(value)
-
end
-
-
protected
-
-
# @!visibility private
-
def allocate_storage
-
@var = java.lang.ThreadLocal.new
-
end
-
end
-
end
-
end
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# @!macro atomic_boolean
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class MutexAtomicBoolean < Synchronization::LockableObject
-
-
# @!macro atomic_boolean_method_initialize
-
1
def initialize(initial = false)
-
super()
-
synchronize { ns_initialize(initial) }
-
end
-
-
# @!macro atomic_boolean_method_value_get
-
1
def value
-
synchronize { @value }
-
end
-
-
# @!macro atomic_boolean_method_value_set
-
1
def value=(value)
-
synchronize { @value = !!value }
-
end
-
-
# @!macro atomic_boolean_method_true_question
-
1
def true?
-
synchronize { @value }
-
end
-
-
# @!macro atomic_boolean_method_false_question
-
1
def false?
-
synchronize { !@value }
-
end
-
-
# @!macro atomic_boolean_method_make_true
-
1
def make_true
-
synchronize { ns_make_value(true) }
-
end
-
-
# @!macro atomic_boolean_method_make_false
-
1
def make_false
-
synchronize { ns_make_value(false) }
-
end
-
-
1
protected
-
-
# @!visibility private
-
1
def ns_initialize(initial)
-
@value = !!initial
-
end
-
-
# @!visibility private
-
1
def ns_make_value(value)
-
old = @value
-
@value = value
-
old != @value
-
end
-
end
-
end
-
1
require 'concurrent/synchronization'
-
1
require 'concurrent/utility/native_integer'
-
-
1
module Concurrent
-
-
# @!macro atomic_fixnum
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class MutexAtomicFixnum < Synchronization::LockableObject
-
-
# @!macro atomic_fixnum_method_initialize
-
1
def initialize(initial = 0)
-
super()
-
synchronize { ns_initialize(initial) }
-
end
-
-
# @!macro atomic_fixnum_method_value_get
-
1
def value
-
synchronize { @value }
-
end
-
-
# @!macro atomic_fixnum_method_value_set
-
1
def value=(value)
-
synchronize { ns_set(value) }
-
end
-
-
# @!macro atomic_fixnum_method_increment
-
1
def increment(delta = 1)
-
synchronize { ns_set(@value + delta.to_i) }
-
end
-
-
1
alias_method :up, :increment
-
-
# @!macro atomic_fixnum_method_decrement
-
1
def decrement(delta = 1)
-
synchronize { ns_set(@value - delta.to_i) }
-
end
-
-
1
alias_method :down, :decrement
-
-
# @!macro atomic_fixnum_method_compare_and_set
-
1
def compare_and_set(expect, update)
-
synchronize do
-
if @value == expect.to_i
-
@value = update.to_i
-
true
-
else
-
false
-
end
-
end
-
end
-
-
# @!macro atomic_fixnum_method_update
-
1
def update
-
synchronize do
-
@value = yield @value
-
end
-
end
-
-
1
protected
-
-
# @!visibility private
-
1
def ns_initialize(initial)
-
ns_set(initial)
-
end
-
-
1
private
-
-
# @!visibility private
-
1
def ns_set(value)
-
Utility::NativeInteger.ensure_integer_and_bounds value
-
@value = value
-
end
-
end
-
end
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# @!macro count_down_latch
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class MutexCountDownLatch < Synchronization::LockableObject
-
-
# @!macro count_down_latch_method_initialize
-
1
def initialize(count = 1)
-
Utility::NativeInteger.ensure_integer_and_bounds count
-
Utility::NativeInteger.ensure_positive count
-
-
super()
-
synchronize { ns_initialize count }
-
end
-
-
# @!macro count_down_latch_method_wait
-
1
def wait(timeout = nil)
-
synchronize { ns_wait_until(timeout) { @count == 0 } }
-
end
-
-
# @!macro count_down_latch_method_count_down
-
1
def count_down
-
synchronize do
-
@count -= 1 if @count > 0
-
ns_broadcast if @count == 0
-
end
-
end
-
-
# @!macro count_down_latch_method_count
-
1
def count
-
synchronize { @count }
-
end
-
-
1
protected
-
-
1
def ns_initialize(count)
-
@count = count
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'concurrent/atomic/atomic_fixnum'
-
1
require 'concurrent/errors'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# Ruby read-write lock implementation
-
#
-
# Allows any number of concurrent readers, but only one concurrent writer
-
# (And if the "write" lock is taken, any readers who come along will have to wait)
-
#
-
# If readers are already active when a writer comes along, the writer will wait for
-
# all the readers to finish before going ahead.
-
# Any additional readers that come when the writer is already waiting, will also
-
# wait (so writers are not starved).
-
#
-
# This implementation is based on `java.util.concurrent.ReentrantReadWriteLock`.
-
#
-
# @example
-
# lock = Concurrent::ReadWriteLock.new
-
# lock.with_read_lock { data.retrieve }
-
# lock.with_write_lock { data.modify! }
-
#
-
# @note Do **not** try to acquire the write lock while already holding a read lock
-
# **or** try to acquire the write lock while you already have it.
-
# This will lead to deadlock
-
#
-
# @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html java.util.concurrent.ReentrantReadWriteLock
-
1
class ReadWriteLock < Synchronization::Object
-
-
# @!visibility private
-
1
WAITING_WRITER = 1 << 15
-
-
# @!visibility private
-
1
RUNNING_WRITER = 1 << 29
-
-
# @!visibility private
-
1
MAX_READERS = WAITING_WRITER - 1
-
-
# @!visibility private
-
1
MAX_WRITERS = RUNNING_WRITER - MAX_READERS - 1
-
-
1
safe_initialization!
-
-
# Implementation notes:
-
# A goal is to make the uncontended path for both readers/writers lock-free
-
# Only if there is reader-writer or writer-writer contention, should locks be used
-
# Internal state is represented by a single integer ("counter"), and updated
-
# using atomic compare-and-swap operations
-
# When the counter is 0, the lock is free
-
# Each reader increments the counter by 1 when acquiring a read lock
-
# (and decrements by 1 when releasing the read lock)
-
# The counter is increased by (1 << 15) for each writer waiting to acquire the
-
# write lock, and by (1 << 29) if the write lock is taken
-
-
# Create a new `ReadWriteLock` in the unlocked state.
-
1
def initialize
-
super()
-
@Counter = AtomicFixnum.new(0) # single integer which represents lock state
-
@ReadLock = Synchronization::Lock.new
-
@WriteLock = Synchronization::Lock.new
-
end
-
-
# Execute a block operation within a read lock.
-
#
-
# @yield the task to be performed within the lock.
-
#
-
# @return [Object] the result of the block operation.
-
#
-
# @raise [ArgumentError] when no block is given.
-
# @raise [Concurrent::ResourceLimitError] if the maximum number of readers
-
# is exceeded.
-
1
def with_read_lock
-
raise ArgumentError.new('no block given') unless block_given?
-
acquire_read_lock
-
begin
-
yield
-
ensure
-
release_read_lock
-
end
-
end
-
-
# Execute a block operation within a write lock.
-
#
-
# @yield the task to be performed within the lock.
-
#
-
# @return [Object] the result of the block operation.
-
#
-
# @raise [ArgumentError] when no block is given.
-
# @raise [Concurrent::ResourceLimitError] if the maximum number of readers
-
# is exceeded.
-
1
def with_write_lock
-
raise ArgumentError.new('no block given') unless block_given?
-
acquire_write_lock
-
begin
-
yield
-
ensure
-
release_write_lock
-
end
-
end
-
-
# Acquire a read lock. If a write lock has been acquired will block until
-
# it is released. Will not block if other read locks have been acquired.
-
#
-
# @return [Boolean] true if the lock is successfully acquired
-
#
-
# @raise [Concurrent::ResourceLimitError] if the maximum number of readers
-
# is exceeded.
-
1
def acquire_read_lock
-
while true
-
c = @Counter.value
-
raise ResourceLimitError.new('Too many reader threads') if max_readers?(c)
-
-
# If a writer is waiting when we first queue up, we need to wait
-
if waiting_writer?(c)
-
@ReadLock.wait_until { !waiting_writer? }
-
-
# after a reader has waited once, they are allowed to "barge" ahead of waiting writers
-
# but if a writer is *running*, the reader still needs to wait (naturally)
-
while true
-
c = @Counter.value
-
if running_writer?(c)
-
@ReadLock.wait_until { !running_writer? }
-
else
-
return if @Counter.compare_and_set(c, c+1)
-
end
-
end
-
else
-
break if @Counter.compare_and_set(c, c+1)
-
end
-
end
-
true
-
end
-
-
# Release a previously acquired read lock.
-
#
-
# @return [Boolean] true if the lock is successfully released
-
1
def release_read_lock
-
while true
-
c = @Counter.value
-
if @Counter.compare_and_set(c, c-1)
-
# If one or more writers were waiting, and we were the last reader, wake a writer up
-
if waiting_writer?(c) && running_readers(c) == 1
-
@WriteLock.signal
-
end
-
break
-
end
-
end
-
true
-
end
-
-
# Acquire a write lock. Will block and wait for all active readers and writers.
-
#
-
# @return [Boolean] true if the lock is successfully acquired
-
#
-
# @raise [Concurrent::ResourceLimitError] if the maximum number of writers
-
# is exceeded.
-
1
def acquire_write_lock
-
while true
-
c = @Counter.value
-
raise ResourceLimitError.new('Too many writer threads') if max_writers?(c)
-
-
if c == 0 # no readers OR writers running
-
# if we successfully swap the RUNNING_WRITER bit on, then we can go ahead
-
break if @Counter.compare_and_set(0, RUNNING_WRITER)
-
elsif @Counter.compare_and_set(c, c+WAITING_WRITER)
-
while true
-
# Now we have successfully incremented, so no more readers will be able to increment
-
# (they will wait instead)
-
# However, readers OR writers could decrement right here, OR another writer could increment
-
@WriteLock.wait_until do
-
# So we have to do another check inside the synchronized section
-
# If a writer OR reader is running, then go to sleep
-
c = @Counter.value
-
!running_writer?(c) && !running_readers?(c)
-
end
-
-
# We just came out of a wait
-
# If we successfully turn the RUNNING_WRITER bit on with an atomic swap,
-
# Then we are OK to stop waiting and go ahead
-
# Otherwise go back and wait again
-
c = @Counter.value
-
break if !running_writer?(c) && !running_readers?(c) && @Counter.compare_and_set(c, c+RUNNING_WRITER-WAITING_WRITER)
-
end
-
break
-
end
-
end
-
true
-
end
-
-
# Release a previously acquired write lock.
-
#
-
# @return [Boolean] true if the lock is successfully released
-
1
def release_write_lock
-
c = @Counter.update { |counter| counter-RUNNING_WRITER }
-
@ReadLock.broadcast
-
@WriteLock.signal if waiting_writers(c) > 0
-
true
-
end
-
-
# Queries if the write lock is held by any thread.
-
#
-
# @return [Boolean] true if the write lock is held else false`
-
1
def write_locked?
-
@Counter.value >= RUNNING_WRITER
-
end
-
-
# Queries whether any threads are waiting to acquire the read or write lock.
-
#
-
# @return [Boolean] true if any threads are waiting for a lock else false
-
1
def has_waiters?
-
waiting_writer?(@Counter.value)
-
end
-
-
1
private
-
-
# @!visibility private
-
1
def running_readers(c = @Counter.value)
-
c & MAX_READERS
-
end
-
-
# @!visibility private
-
1
def running_readers?(c = @Counter.value)
-
(c & MAX_READERS) > 0
-
end
-
-
# @!visibility private
-
1
def running_writer?(c = @Counter.value)
-
c >= RUNNING_WRITER
-
end
-
-
# @!visibility private
-
1
def waiting_writers(c = @Counter.value)
-
(c & MAX_WRITERS) / WAITING_WRITER
-
end
-
-
# @!visibility private
-
1
def waiting_writer?(c = @Counter.value)
-
c >= WAITING_WRITER
-
end
-
-
# @!visibility private
-
1
def max_readers?(c = @Counter.value)
-
(c & MAX_READERS) == MAX_READERS
-
end
-
-
# @!visibility private
-
1
def max_writers?(c = @Counter.value)
-
(c & MAX_WRITERS) == MAX_WRITERS
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'concurrent/atomic/atomic_reference'
-
1
require 'concurrent/errors'
-
1
require 'concurrent/synchronization'
-
1
require 'concurrent/atomic/thread_local_var'
-
-
1
module Concurrent
-
-
# Re-entrant read-write lock implementation
-
#
-
# Allows any number of concurrent readers, but only one concurrent writer
-
# (And while the "write" lock is taken, no read locks can be obtained either.
-
# Hence, the write lock can also be called an "exclusive" lock.)
-
#
-
# If another thread has taken a read lock, any thread which wants a write lock
-
# will block until all the readers release their locks. However, once a thread
-
# starts waiting to obtain a write lock, any additional readers that come along
-
# will also wait (so writers are not starved).
-
#
-
# A thread can acquire both a read and write lock at the same time. A thread can
-
# also acquire a read lock OR a write lock more than once. Only when the read (or
-
# write) lock is released as many times as it was acquired, will the thread
-
# actually let it go, allowing other threads which might have been waiting
-
# to proceed.
-
#
-
# If both read and write locks are acquired by the same thread, it is not strictly
-
# necessary to release them in the same order they were acquired. In other words,
-
# the following code is legal:
-
#
-
# @example
-
# lock = Concurrent::ReentrantReadWriteLock.new
-
# lock.acquire_write_lock
-
# lock.acquire_read_lock
-
# lock.release_write_lock
-
# # At this point, the current thread is holding only a read lock, not a write
-
# # lock. So other threads can take read locks, but not a write lock.
-
# lock.release_read_lock
-
# # Now the current thread is not holding either a read or write lock, so
-
# # another thread could potentially acquire a write lock.
-
#
-
# This implementation was inspired by `java.util.concurrent.ReentrantReadWriteLock`.
-
#
-
# @example
-
# lock = Concurrent::ReentrantReadWriteLock.new
-
# lock.with_read_lock { data.retrieve }
-
# lock.with_write_lock { data.modify! }
-
#
-
# @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html java.util.concurrent.ReentrantReadWriteLock
-
1
class ReentrantReadWriteLock < Synchronization::Object
-
-
# Implementation notes:
-
#
-
# A goal is to make the uncontended path for both readers/writers mutex-free
-
# Only if there is reader-writer or writer-writer contention, should mutexes be used
-
# Otherwise, a single CAS operation is all we need to acquire/release a lock
-
#
-
# Internal state is represented by a single integer ("counter"), and updated
-
# using atomic compare-and-swap operations
-
# When the counter is 0, the lock is free
-
# Each thread which has one OR MORE read locks increments the counter by 1
-
# (and decrements by 1 when releasing the read lock)
-
# The counter is increased by (1 << 15) for each writer waiting to acquire the
-
# write lock, and by (1 << 29) if the write lock is taken
-
#
-
# Additionally, each thread uses a thread-local variable to count how many times
-
# it has acquired a read lock, AND how many times it has acquired a write lock.
-
# It uses a similar trick; an increment of 1 means a read lock was taken, and
-
# an increment of (1 << 15) means a write lock was taken
-
# This is what makes re-entrancy possible
-
#
-
# 2 rules are followed to ensure good liveness properties:
-
# 1) Once a writer has queued up and is waiting for a write lock, no other thread
-
# can take a lock without waiting
-
# 2) When a write lock is released, readers are given the "first chance" to wake
-
# up and acquire a read lock
-
# Following these rules means readers and writers tend to "take turns", so neither
-
# can starve the other, even under heavy contention
-
-
# @!visibility private
-
1
READER_BITS = 15
-
# @!visibility private
-
1
WRITER_BITS = 14
-
-
# Used with @Counter:
-
# @!visibility private
-
1
WAITING_WRITER = 1 << READER_BITS
-
# @!visibility private
-
1
RUNNING_WRITER = 1 << (READER_BITS + WRITER_BITS)
-
# @!visibility private
-
1
MAX_READERS = WAITING_WRITER - 1
-
# @!visibility private
-
1
MAX_WRITERS = RUNNING_WRITER - MAX_READERS - 1
-
-
# Used with @HeldCount:
-
# @!visibility private
-
1
WRITE_LOCK_HELD = 1 << READER_BITS
-
# @!visibility private
-
1
READ_LOCK_MASK = WRITE_LOCK_HELD - 1
-
# @!visibility private
-
1
WRITE_LOCK_MASK = MAX_WRITERS
-
-
1
safe_initialization!
-
-
# Create a new `ReentrantReadWriteLock` in the unlocked state.
-
1
def initialize
-
super()
-
@Counter = AtomicFixnum.new(0) # single integer which represents lock state
-
@ReadQueue = Synchronization::Lock.new # used to queue waiting readers
-
@WriteQueue = Synchronization::Lock.new # used to queue waiting writers
-
@HeldCount = ThreadLocalVar.new(0) # indicates # of R & W locks held by this thread
-
end
-
-
# Execute a block operation within a read lock.
-
#
-
# @yield the task to be performed within the lock.
-
#
-
# @return [Object] the result of the block operation.
-
#
-
# @raise [ArgumentError] when no block is given.
-
# @raise [Concurrent::ResourceLimitError] if the maximum number of readers
-
# is exceeded.
-
1
def with_read_lock
-
raise ArgumentError.new('no block given') unless block_given?
-
acquire_read_lock
-
begin
-
yield
-
ensure
-
release_read_lock
-
end
-
end
-
-
# Execute a block operation within a write lock.
-
#
-
# @yield the task to be performed within the lock.
-
#
-
# @return [Object] the result of the block operation.
-
#
-
# @raise [ArgumentError] when no block is given.
-
# @raise [Concurrent::ResourceLimitError] if the maximum number of readers
-
# is exceeded.
-
1
def with_write_lock
-
raise ArgumentError.new('no block given') unless block_given?
-
acquire_write_lock
-
begin
-
yield
-
ensure
-
release_write_lock
-
end
-
end
-
-
# Acquire a read lock. If a write lock is held by another thread, will block
-
# until it is released.
-
#
-
# @return [Boolean] true if the lock is successfully acquired
-
#
-
# @raise [Concurrent::ResourceLimitError] if the maximum number of readers
-
# is exceeded.
-
1
def acquire_read_lock
-
if (held = @HeldCount.value) > 0
-
# If we already have a lock, there's no need to wait
-
if held & READ_LOCK_MASK == 0
-
# But we do need to update the counter, if we were holding a write
-
# lock but not a read lock
-
@Counter.update { |c| c + 1 }
-
end
-
@HeldCount.value = held + 1
-
return true
-
end
-
-
while true
-
c = @Counter.value
-
raise ResourceLimitError.new('Too many reader threads') if max_readers?(c)
-
-
# If a writer is waiting OR running when we first queue up, we need to wait
-
if waiting_or_running_writer?(c)
-
# Before going to sleep, check again with the ReadQueue mutex held
-
@ReadQueue.synchronize do
-
@ReadQueue.ns_wait if waiting_or_running_writer?
-
end
-
# Note: the above 'synchronize' block could have used #wait_until,
-
# but that waits repeatedly in a loop, checking the wait condition
-
# each time it wakes up (to protect against spurious wakeups)
-
# But we are already in a loop, which is only broken when we successfully
-
# acquire the lock! So we don't care about spurious wakeups, and would
-
# rather not pay the extra overhead of using #wait_until
-
-
# After a reader has waited once, they are allowed to "barge" ahead of waiting writers
-
# But if a writer is *running*, the reader still needs to wait (naturally)
-
while true
-
c = @Counter.value
-
if running_writer?(c)
-
@ReadQueue.synchronize do
-
@ReadQueue.ns_wait if running_writer?
-
end
-
elsif @Counter.compare_and_set(c, c+1)
-
@HeldCount.value = held + 1
-
return true
-
end
-
end
-
elsif @Counter.compare_and_set(c, c+1)
-
@HeldCount.value = held + 1
-
return true
-
end
-
end
-
end
-
-
# Try to acquire a read lock and return true if we succeed. If it cannot be
-
# acquired immediately, return false.
-
#
-
# @return [Boolean] true if the lock is successfully acquired
-
1
def try_read_lock
-
if (held = @HeldCount.value) > 0
-
if held & READ_LOCK_MASK == 0
-
# If we hold a write lock, but not a read lock...
-
@Counter.update { |c| c + 1 }
-
end
-
@HeldCount.value = held + 1
-
return true
-
else
-
c = @Counter.value
-
if !waiting_or_running_writer?(c) && @Counter.compare_and_set(c, c+1)
-
@HeldCount.value = held + 1
-
return true
-
end
-
end
-
false
-
end
-
-
# Release a previously acquired read lock.
-
#
-
# @return [Boolean] true if the lock is successfully released
-
1
def release_read_lock
-
held = @HeldCount.value = @HeldCount.value - 1
-
rlocks_held = held & READ_LOCK_MASK
-
if rlocks_held == 0
-
c = @Counter.update { |counter| counter - 1 }
-
# If one or more writers were waiting, and we were the last reader, wake a writer up
-
if waiting_or_running_writer?(c) && running_readers(c) == 0
-
@WriteQueue.signal
-
end
-
elsif rlocks_held == READ_LOCK_MASK
-
raise IllegalOperationError, "Cannot release a read lock which is not held"
-
end
-
true
-
end
-
-
# Acquire a write lock. Will block and wait for all active readers and writers.
-
#
-
# @return [Boolean] true if the lock is successfully acquired
-
#
-
# @raise [Concurrent::ResourceLimitError] if the maximum number of writers
-
# is exceeded.
-
1
def acquire_write_lock
-
if (held = @HeldCount.value) >= WRITE_LOCK_HELD
-
# if we already have a write (exclusive) lock, there's no need to wait
-
@HeldCount.value = held + WRITE_LOCK_HELD
-
return true
-
end
-
-
while true
-
c = @Counter.value
-
raise ResourceLimitError.new('Too many writer threads') if max_writers?(c)
-
-
# To go ahead and take the lock without waiting, there must be no writer
-
# running right now, AND no writers who came before us still waiting to
-
# acquire the lock
-
# Additionally, if any read locks have been taken, we must hold all of them
-
if c == held
-
# If we successfully swap the RUNNING_WRITER bit on, then we can go ahead
-
if @Counter.compare_and_set(c, c+RUNNING_WRITER)
-
@HeldCount.value = held + WRITE_LOCK_HELD
-
return true
-
end
-
elsif @Counter.compare_and_set(c, c+WAITING_WRITER)
-
while true
-
# Now we have successfully incremented, so no more readers will be able to increment
-
# (they will wait instead)
-
# However, readers OR writers could decrement right here
-
@WriteQueue.synchronize do
-
# So we have to do another check inside the synchronized section
-
# If a writer OR another reader is running, then go to sleep
-
c = @Counter.value
-
@WriteQueue.ns_wait if running_writer?(c) || running_readers(c) != held
-
end
-
# Note: if you are thinking of replacing the above 'synchronize' block
-
# with #wait_until, read the comment in #acquire_read_lock first!
-
-
# We just came out of a wait
-
# If we successfully turn the RUNNING_WRITER bit on with an atomic swap,
-
# then we are OK to stop waiting and go ahead
-
# Otherwise go back and wait again
-
c = @Counter.value
-
if !running_writer?(c) &&
-
running_readers(c) == held &&
-
@Counter.compare_and_set(c, c+RUNNING_WRITER-WAITING_WRITER)
-
@HeldCount.value = held + WRITE_LOCK_HELD
-
return true
-
end
-
end
-
end
-
end
-
end
-
-
# Try to acquire a write lock and return true if we succeed. If it cannot be
-
# acquired immediately, return false.
-
#
-
# @return [Boolean] true if the lock is successfully acquired
-
1
def try_write_lock
-
if (held = @HeldCount.value) >= WRITE_LOCK_HELD
-
@HeldCount.value = held + WRITE_LOCK_HELD
-
return true
-
else
-
c = @Counter.value
-
if !waiting_or_running_writer?(c) &&
-
running_readers(c) == held &&
-
@Counter.compare_and_set(c, c+RUNNING_WRITER)
-
@HeldCount.value = held + WRITE_LOCK_HELD
-
return true
-
end
-
end
-
false
-
end
-
-
# Release a previously acquired write lock.
-
#
-
# @return [Boolean] true if the lock is successfully released
-
1
def release_write_lock
-
held = @HeldCount.value = @HeldCount.value - WRITE_LOCK_HELD
-
wlocks_held = held & WRITE_LOCK_MASK
-
if wlocks_held == 0
-
c = @Counter.update { |counter| counter - RUNNING_WRITER }
-
@ReadQueue.broadcast
-
@WriteQueue.signal if waiting_writers(c) > 0
-
elsif wlocks_held == WRITE_LOCK_MASK
-
raise IllegalOperationError, "Cannot release a write lock which is not held"
-
end
-
true
-
end
-
-
1
private
-
-
# @!visibility private
-
1
def running_readers(c = @Counter.value)
-
c & MAX_READERS
-
end
-
-
# @!visibility private
-
1
def running_readers?(c = @Counter.value)
-
(c & MAX_READERS) > 0
-
end
-
-
# @!visibility private
-
1
def running_writer?(c = @Counter.value)
-
c >= RUNNING_WRITER
-
end
-
-
# @!visibility private
-
1
def waiting_writers(c = @Counter.value)
-
(c & MAX_WRITERS) >> READER_BITS
-
end
-
-
# @!visibility private
-
1
def waiting_or_running_writer?(c = @Counter.value)
-
c >= WAITING_WRITER
-
end
-
-
# @!visibility private
-
1
def max_readers?(c = @Counter.value)
-
(c & MAX_READERS) == MAX_READERS
-
end
-
-
# @!visibility private
-
1
def max_writers?(c = @Counter.value)
-
(c & MAX_WRITERS) == MAX_WRITERS
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'concurrent/atomic/abstract_thread_local_var'
-
-
1
module Concurrent
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class RubyThreadLocalVar < AbstractThreadLocalVar
-
-
# Each thread has a (lazily initialized) array of thread-local variable values
-
# Each time a new thread-local var is created, we allocate an "index" for it
-
# For example, if the allocated index is 1, that means slot #1 in EVERY
-
# thread's thread-local array will be used for the value of that TLV
-
#
-
# The good thing about using a per-THREAD structure to hold values, rather
-
# than a per-TLV structure, is that no synchronization is needed when
-
# reading and writing those values (since the structure is only ever
-
# accessed by a single thread)
-
#
-
# Of course, when a TLV is GC'd, 1) we need to recover its index for use
-
# by other new TLVs (otherwise the thread-local arrays could get bigger
-
# and bigger with time), and 2) we need to null out all the references
-
# held in the now-unused slots (both to avoid blocking GC of those objects,
-
# and also to prevent "stale" values from being passed on to a new TLV
-
# when the index is reused)
-
# Because we need to null out freed slots, we need to keep references to
-
# ALL the thread-local arrays -- ARRAYS is for that
-
# But when a Thread is GC'd, we need to drop the reference to its thread-local
-
# array, so we don't leak memory
-
-
# @!visibility private
-
1
FREE = []
-
1
LOCK = Mutex.new
-
1
ARRAYS = {} # used as a hash set
-
1
@@next = 0
-
1
private_constant :FREE, :LOCK, :ARRAYS
-
-
# @!macro thread_local_var_method_get
-
1
def value
-
if array = get_threadlocal_array
-
value = array[@index]
-
if value.nil?
-
default
-
elsif value.equal?(NULL)
-
nil
-
else
-
value
-
end
-
else
-
default
-
end
-
end
-
-
# @!macro thread_local_var_method_set
-
1
def value=(value)
-
me = Thread.current
-
# We could keep the thread-local arrays in a hash, keyed by Thread
-
# But why? That would require locking
-
# Using Ruby's built-in thread-local storage is faster
-
unless array = get_threadlocal_array(me)
-
array = set_threadlocal_array([], me)
-
LOCK.synchronize { ARRAYS[array.object_id] = array }
-
ObjectSpace.define_finalizer(me, self.class.thread_finalizer(array))
-
end
-
array[@index] = (value.nil? ? NULL : value)
-
value
-
end
-
-
1
protected
-
-
# @!visibility private
-
1
def allocate_storage
-
@index = LOCK.synchronize do
-
FREE.pop || begin
-
result = @@next
-
@@next += 1
-
result
-
end
-
end
-
ObjectSpace.define_finalizer(self, self.class.threadlocal_finalizer(@index))
-
end
-
-
# @!visibility private
-
1
def self.threadlocal_finalizer(index)
-
proc do
-
Thread.new do # avoid error: can't be called from trap context
-
LOCK.synchronize do
-
FREE.push(index)
-
# The cost of GC'ing a TLV is linear in the number of threads using TLVs
-
# But that is natural! More threads means more storage is used per TLV
-
# So naturally more CPU time is required to free more storage
-
ARRAYS.each_value do |array|
-
array[index] = nil
-
end
-
end
-
end
-
end
-
end
-
-
# @!visibility private
-
1
def self.thread_finalizer(array)
-
proc do
-
Thread.new do # avoid error: can't be called from trap context
-
LOCK.synchronize do
-
# The thread which used this thread-local array is now gone
-
# So don't hold onto a reference to the array (thus blocking GC)
-
ARRAYS.delete(array.object_id)
-
end
-
end
-
end
-
end
-
-
1
private
-
-
1
if Thread.instance_methods.include?(:thread_variable_get)
-
-
1
def get_threadlocal_array(thread = Thread.current)
-
thread.thread_variable_get(:__threadlocal_array__)
-
end
-
-
1
def set_threadlocal_array(array, thread = Thread.current)
-
thread.thread_variable_set(:__threadlocal_array__, array)
-
end
-
-
else
-
-
def get_threadlocal_array(thread = Thread.current)
-
thread[:__threadlocal_array__]
-
end
-
-
def set_threadlocal_array(array, thread = Thread.current)
-
thread[:__threadlocal_array__] = array
-
end
-
end
-
-
# This exists only for use in testing
-
# @!visibility private
-
1
def value_for(thread)
-
if array = get_threadlocal_array(thread)
-
value = array[@index]
-
if value.nil?
-
default_for(thread)
-
elsif value.equal?(NULL)
-
nil
-
else
-
value
-
end
-
else
-
default_for(thread)
-
end
-
end
-
-
1
def default_for(thread)
-
if @default_block
-
raise "Cannot use default_for with default block"
-
else
-
@default
-
end
-
end
-
end
-
end
-
1
require 'concurrent/atomic/mutex_semaphore'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
###################################################################
-
-
# @!macro [new] semaphore_method_initialize
-
#
-
# Create a new `Semaphore` with the initial `count`.
-
#
-
# @param [Fixnum] count the initial count
-
#
-
# @raise [ArgumentError] if `count` is not an integer or is less than zero
-
-
# @!macro [new] semaphore_method_acquire
-
#
-
# Acquires the given number of permits from this semaphore,
-
# blocking until all are available.
-
#
-
# @param [Fixnum] permits Number of permits to acquire
-
#
-
# @raise [ArgumentError] if `permits` is not an integer or is less than
-
# one
-
#
-
# @return [nil]
-
-
# @!macro [new] semaphore_method_available_permits
-
#
-
# Returns the current number of permits available in this semaphore.
-
#
-
# @return [Integer]
-
-
# @!macro [new] semaphore_method_drain_permits
-
#
-
# Acquires and returns all permits that are immediately available.
-
#
-
# @return [Integer]
-
-
# @!macro [new] semaphore_method_try_acquire
-
#
-
# Acquires the given number of permits from this semaphore,
-
# only if all are available at the time of invocation or within
-
# `timeout` interval
-
#
-
# @param [Fixnum] permits the number of permits to acquire
-
#
-
# @param [Fixnum] timeout the number of seconds to wait for the counter
-
# or `nil` to return immediately
-
#
-
# @raise [ArgumentError] if `permits` is not an integer or is less than
-
# one
-
#
-
# @return [Boolean] `false` if no permits are available, `true` when
-
# acquired a permit
-
-
# @!macro [new] semaphore_method_release
-
#
-
# Releases the given number of permits, returning them to the semaphore.
-
#
-
# @param [Fixnum] permits Number of permits to return to the semaphore.
-
#
-
# @raise [ArgumentError] if `permits` is not a number or is less than one
-
#
-
# @return [nil]
-
-
###################################################################
-
-
# @!macro [new] semaphore_public_api
-
#
-
# @!method initialize(count)
-
# @!macro semaphore_method_initialize
-
#
-
# @!method acquire(permits = 1)
-
# @!macro semaphore_method_acquire
-
#
-
# @!method available_permits
-
# @!macro semaphore_method_available_permits
-
#
-
# @!method drain_permits
-
# @!macro semaphore_method_drain_permits
-
#
-
# @!method try_acquire(permits = 1, timeout = nil)
-
# @!macro semaphore_method_try_acquire
-
#
-
# @!method release(permits = 1)
-
# @!macro semaphore_method_release
-
-
###################################################################
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
SemaphoreImplementation = case
-
when defined?(JavaSemaphore)
-
JavaSemaphore
-
else
-
1
MutexSemaphore
-
end
-
1
private_constant :SemaphoreImplementation
-
-
# @!macro [attach] semaphore
-
#
-
# A counting semaphore. Conceptually, a semaphore maintains a set of
-
# permits. Each {#acquire} blocks if necessary until a permit is
-
# available, and then takes it. Each {#release} adds a permit, potentially
-
# releasing a blocking acquirer.
-
# However, no actual permit objects are used; the Semaphore just keeps a
-
# count of the number available and acts accordingly.
-
#
-
# @!macro semaphore_public_api
-
# @example
-
# semaphore = Concurrent::Semaphore.new(2)
-
#
-
# t1 = Thread.new do
-
# semaphore.acquire
-
# puts "Thread 1 acquired semaphore"
-
# end
-
#
-
# t2 = Thread.new do
-
# semaphore.acquire
-
# puts "Thread 2 acquired semaphore"
-
# end
-
#
-
# t3 = Thread.new do
-
# semaphore.acquire
-
# puts "Thread 3 acquired semaphore"
-
# end
-
#
-
# t4 = Thread.new do
-
# sleep(2)
-
# puts "Thread 4 releasing semaphore"
-
# semaphore.release
-
# end
-
#
-
# [t1, t2, t3, t4].each(&:join)
-
#
-
# # prints:
-
# # Thread 3 acquired semaphore
-
# # Thread 2 acquired semaphore
-
# # Thread 4 releasing semaphore
-
# # Thread 1 acquired semaphore
-
#
-
1
class Semaphore < SemaphoreImplementation
-
end
-
end
-
1
module Concurrent
-
-
# @!macro atomic_reference
-
1
class ConcurrentUpdateError < ThreadError
-
# frozen pre-allocated backtrace to speed ConcurrentUpdateError
-
1
CONC_UP_ERR_BACKTRACE = ['backtrace elided; set verbose to enable'].freeze
-
end
-
end
-
1
require 'concurrent/atomic_reference/concurrent_update_error'
-
-
1
module Concurrent
-
-
# Define update methods that use direct paths
-
#
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
module AtomicDirectUpdate
-
-
# @!macro [attach] atomic_reference_method_update
-
#
-
# Pass the current value to the given block, replacing it
-
# with the block's result. May retry if the value changes
-
# during the block's execution.
-
#
-
# @yield [Object] Calculate a new value for the atomic reference using
-
# given (old) value
-
# @yieldparam [Object] old_value the starting value of the atomic reference
-
#
-
# @return [Object] the new value
-
1
def update
-
true until compare_and_set(old_value = get, new_value = yield(old_value))
-
new_value
-
end
-
-
# @!macro [attach] atomic_reference_method_try_update
-
#
-
# Pass the current value to the given block, replacing it
-
# with the block's result. Return nil if the update fails.
-
#
-
# @yield [Object] Calculate a new value for the atomic reference using
-
# given (old) value
-
# @yieldparam [Object] old_value the starting value of the atomic reference
-
#
-
# @note This method was altered to avoid raising an exception by default.
-
# Instead, this method now returns `nil` in case of failure. For more info,
-
# please see: https://github.com/ruby-concurrency/concurrent-ruby/pull/336
-
#
-
# @return [Object] the new value, or nil if update failed
-
1
def try_update
-
old_value = get
-
new_value = yield old_value
-
-
return unless compare_and_set old_value, new_value
-
-
new_value
-
end
-
-
# @!macro [attach] atomic_reference_method_try_update!
-
#
-
# Pass the current value to the given block, replacing it
-
# with the block's result. Raise an exception if the update
-
# fails.
-
#
-
# @yield [Object] Calculate a new value for the atomic reference using
-
# given (old) value
-
# @yieldparam [Object] old_value the starting value of the atomic reference
-
#
-
# @note This behavior mimics the behavior of the original
-
# `AtomicReference#try_update` API. The reason this was changed was to
-
# avoid raising exceptions (which are inherently slow) by default. For more
-
# info: https://github.com/ruby-concurrency/concurrent-ruby/pull/336
-
#
-
# @return [Object] the new value
-
#
-
# @raise [Concurrent::ConcurrentUpdateError] if the update fails
-
1
def try_update!
-
old_value = get
-
new_value = yield old_value
-
unless compare_and_set(old_value, new_value)
-
if $VERBOSE
-
raise ConcurrentUpdateError, "Update failed"
-
else
-
raise ConcurrentUpdateError, "Update failed", ConcurrentUpdateError::CONC_UP_ERR_BACKTRACE
-
end
-
end
-
new_value
-
end
-
end
-
end
-
1
require 'concurrent/synchronization'
-
1
require 'concurrent/atomic_reference/direct_update'
-
1
require 'concurrent/atomic_reference/numeric_cas_wrapper'
-
-
1
module Concurrent
-
-
# @!macro atomic_reference
-
#
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class MutexAtomicReference < Synchronization::LockableObject
-
1
include Concurrent::AtomicDirectUpdate
-
1
include Concurrent::AtomicNumericCompareAndSetWrapper
-
-
# @!macro atomic_reference_method_initialize
-
1
def initialize(value = nil)
-
1
super()
-
2
synchronize { ns_initialize(value) }
-
end
-
-
# @!macro atomic_reference_method_get
-
1
def get
-
synchronize { @value }
-
end
-
1
alias_method :value, :get
-
-
# @!macro atomic_reference_method_set
-
1
def set(new_value)
-
synchronize { @value = new_value }
-
end
-
1
alias_method :value=, :set
-
-
# @!macro atomic_reference_method_get_and_set
-
1
def get_and_set(new_value)
-
synchronize do
-
old_value = @value
-
@value = new_value
-
old_value
-
end
-
end
-
1
alias_method :swap, :get_and_set
-
-
# @!macro atomic_reference_method_compare_and_set
-
1
def _compare_and_set(old_value, new_value)
-
synchronize do
-
if @value.equal? old_value
-
@value = new_value
-
true
-
else
-
false
-
end
-
end
-
end
-
-
1
protected
-
-
1
def ns_initialize(value)
-
1
@value = value
-
end
-
end
-
end
-
1
module Concurrent
-
-
# Special "compare and set" handling of numeric values.
-
#
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
module AtomicNumericCompareAndSetWrapper
-
-
# @!macro atomic_reference_method_compare_and_set
-
1
def compare_and_set(old_value, new_value)
-
if old_value.kind_of? Numeric
-
while true
-
old = get
-
-
return false unless old.kind_of? Numeric
-
-
return false unless old == old_value
-
-
result = _compare_and_set(old, new_value)
-
return result if result
-
end
-
else
-
_compare_and_set(old_value, new_value)
-
end
-
end
-
1
alias_method :compare_and_swap, :compare_and_set
-
end
-
end
-
1
if defined? Concurrent::CAtomicReference
-
require 'concurrent/synchronization'
-
require 'concurrent/atomic_reference/direct_update'
-
require 'concurrent/atomic_reference/numeric_cas_wrapper'
-
-
module Concurrent
-
-
# @!macro atomic_reference
-
#
-
# @!visibility private
-
# @!macro internal_implementation_note
-
class CAtomicReference
-
include Concurrent::AtomicDirectUpdate
-
include Concurrent::AtomicNumericCompareAndSetWrapper
-
-
# @!method initialize
-
# @!macro atomic_reference_method_initialize
-
-
# @!method get
-
# @!macro atomic_reference_method_get
-
-
# @!method set
-
# @!macro atomic_reference_method_set
-
-
# @!method get_and_set
-
# @!macro atomic_reference_method_get_and_set
-
-
# @!method _compare_and_set
-
# @!macro atomic_reference_method_compare_and_set
-
end
-
end
-
end
-
# @!macro [new] atomic_reference
-
#
-
# An object reference that may be updated atomically. All read and write
-
# operations have java volatile semantic.
-
#
-
# @!macro thread_safe_variable_comparison
-
#
-
# @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicReference.html
-
# @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html
-
#
-
# @!method initialize
-
# @!macro [new] atomic_reference_method_initialize
-
# @param [Object] value The initial value.
-
#
-
# @!method get
-
# @!macro [new] atomic_reference_method_get
-
# Gets the current value.
-
# @return [Object] the current value
-
#
-
# @!method set
-
# @!macro [new] atomic_reference_method_set
-
# Sets to the given value.
-
# @param [Object] new_value the new value
-
# @return [Object] the new value
-
#
-
# @!method get_and_set
-
# @!macro [new] atomic_reference_method_get_and_set
-
# Atomically sets to the given value and returns the old value.
-
# @param [Object] new_value the new value
-
# @return [Object] the old value
-
#
-
# @!method compare_and_set
-
# @!macro [new] atomic_reference_method_compare_and_set
-
#
-
# Atomically sets the value to the given updated value if
-
# the current value == the expected value.
-
#
-
# @param [Object] old_value the expected value
-
# @param [Object] new_value the new value
-
#
-
# @return [Boolean] `true` if successful. A `false` return indicates
-
# that the actual value was not equal to the expected value.
-
-
1
require 'concurrent/atomic/atomic_reference'
-
1
require 'concurrent/atomic/atomic_boolean'
-
1
require 'concurrent/atomic/atomic_fixnum'
-
1
require 'concurrent/atomic/cyclic_barrier'
-
1
require 'concurrent/atomic/count_down_latch'
-
1
require 'concurrent/atomic/event'
-
1
require 'concurrent/atomic/read_write_lock'
-
1
require 'concurrent/atomic/reentrant_read_write_lock'
-
1
require 'concurrent/atomic/semaphore'
-
1
require 'concurrent/atomic/thread_local_var'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
1
module Collection
-
-
# A thread safe observer set implemented using copy-on-read approach:
-
# observers are added and removed from a thread safe collection; every time
-
# a notification is required the internal data structure is copied to
-
# prevent concurrency issues
-
#
-
# @api private
-
1
class CopyOnNotifyObserverSet < Synchronization::LockableObject
-
-
1
def initialize
-
super()
-
synchronize { ns_initialize }
-
end
-
-
# @!macro observable_add_observer
-
1
def add_observer(observer = nil, func = :update, &block)
-
if observer.nil? && block.nil?
-
raise ArgumentError, 'should pass observer as a first argument or block'
-
elsif observer && block
-
raise ArgumentError.new('cannot provide both an observer and a block')
-
end
-
-
if block
-
observer = block
-
func = :call
-
end
-
-
synchronize do
-
@observers[observer] = func
-
observer
-
end
-
end
-
-
# @!macro observable_delete_observer
-
1
def delete_observer(observer)
-
synchronize do
-
@observers.delete(observer)
-
observer
-
end
-
end
-
-
# @!macro observable_delete_observers
-
1
def delete_observers
-
synchronize do
-
@observers.clear
-
self
-
end
-
end
-
-
# @!macro observable_count_observers
-
1
def count_observers
-
synchronize { @observers.count }
-
end
-
-
# Notifies all registered observers with optional args
-
# @param [Object] args arguments to be passed to each observer
-
# @return [CopyOnWriteObserverSet] self
-
1
def notify_observers(*args, &block)
-
observers = duplicate_observers
-
notify_to(observers, *args, &block)
-
self
-
end
-
-
# Notifies all registered observers with optional args and deletes them.
-
#
-
# @param [Object] args arguments to be passed to each observer
-
# @return [CopyOnWriteObserverSet] self
-
1
def notify_and_delete_observers(*args, &block)
-
observers = duplicate_and_clear_observers
-
notify_to(observers, *args, &block)
-
self
-
end
-
-
1
protected
-
-
1
def ns_initialize
-
@observers = {}
-
end
-
-
1
private
-
-
1
def duplicate_and_clear_observers
-
synchronize do
-
observers = @observers.dup
-
@observers.clear
-
observers
-
end
-
end
-
-
1
def duplicate_observers
-
synchronize { @observers.dup }
-
end
-
-
1
def notify_to(observers, *args)
-
raise ArgumentError.new('cannot give arguments and a block') if block_given? && !args.empty?
-
observers.each do |observer, function|
-
args = yield if block_given?
-
observer.send(function, *args)
-
end
-
end
-
end
-
end
-
end
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
1
module Collection
-
-
# A thread safe observer set implemented using copy-on-write approach:
-
# every time an observer is added or removed the whole internal data structure is
-
# duplicated and replaced with a new one.
-
#
-
# @api private
-
1
class CopyOnWriteObserverSet < Synchronization::LockableObject
-
-
1
def initialize
-
super()
-
synchronize { ns_initialize }
-
end
-
-
# @!macro observable_add_observer
-
1
def add_observer(observer = nil, func = :update, &block)
-
if observer.nil? && block.nil?
-
raise ArgumentError, 'should pass observer as a first argument or block'
-
elsif observer && block
-
raise ArgumentError.new('cannot provide both an observer and a block')
-
end
-
-
if block
-
observer = block
-
func = :call
-
end
-
-
synchronize do
-
new_observers = @observers.dup
-
new_observers[observer] = func
-
@observers = new_observers
-
observer
-
end
-
end
-
-
# @!macro observable_delete_observer
-
1
def delete_observer(observer)
-
synchronize do
-
new_observers = @observers.dup
-
new_observers.delete(observer)
-
@observers = new_observers
-
observer
-
end
-
end
-
-
# @!macro observable_delete_observers
-
1
def delete_observers
-
self.observers = {}
-
self
-
end
-
-
# @!macro observable_count_observers
-
1
def count_observers
-
observers.count
-
end
-
-
# Notifies all registered observers with optional args
-
# @param [Object] args arguments to be passed to each observer
-
# @return [CopyOnWriteObserverSet] self
-
1
def notify_observers(*args, &block)
-
notify_to(observers, *args, &block)
-
self
-
end
-
-
# Notifies all registered observers with optional args and deletes them.
-
#
-
# @param [Object] args arguments to be passed to each observer
-
# @return [CopyOnWriteObserverSet] self
-
1
def notify_and_delete_observers(*args, &block)
-
old = clear_observers_and_return_old
-
notify_to(old, *args, &block)
-
self
-
end
-
-
1
protected
-
-
1
def ns_initialize
-
@observers = {}
-
end
-
-
1
private
-
-
1
def notify_to(observers, *args)
-
raise ArgumentError.new('cannot give arguments and a block') if block_given? && !args.empty?
-
observers.each do |observer, function|
-
args = yield if block_given?
-
observer.send(function, *args)
-
end
-
end
-
-
1
def observers
-
synchronize { @observers }
-
end
-
-
1
def observers=(new_set)
-
synchronize { @observers = new_set }
-
end
-
-
1
def clear_observers_and_return_old
-
synchronize do
-
old_observers = @observers
-
@observers = {}
-
old_observers
-
end
-
end
-
end
-
end
-
end
-
1
if Concurrent.on_jruby?
-
-
module Concurrent
-
module Collection
-
-
-
# @!macro priority_queue
-
#
-
# @!visibility private
-
# @!macro internal_implementation_note
-
class JavaNonConcurrentPriorityQueue
-
-
# @!macro priority_queue_method_initialize
-
def initialize(opts = {})
-
order = opts.fetch(:order, :max)
-
if [:min, :low].include?(order)
-
@queue = java.util.PriorityQueue.new(11) # 11 is the default initial capacity
-
else
-
@queue = java.util.PriorityQueue.new(11, java.util.Collections.reverseOrder())
-
end
-
end
-
-
# @!macro priority_queue_method_clear
-
def clear
-
@queue.clear
-
true
-
end
-
-
# @!macro priority_queue_method_delete
-
def delete(item)
-
found = false
-
while @queue.remove(item) do
-
found = true
-
end
-
found
-
end
-
-
# @!macro priority_queue_method_empty
-
def empty?
-
@queue.size == 0
-
end
-
-
# @!macro priority_queue_method_include
-
def include?(item)
-
@queue.contains(item)
-
end
-
alias_method :has_priority?, :include?
-
-
# @!macro priority_queue_method_length
-
def length
-
@queue.size
-
end
-
alias_method :size, :length
-
-
# @!macro priority_queue_method_peek
-
def peek
-
@queue.peek
-
end
-
-
# @!macro priority_queue_method_pop
-
def pop
-
@queue.poll
-
end
-
alias_method :deq, :pop
-
alias_method :shift, :pop
-
-
# @!macro priority_queue_method_push
-
def push(item)
-
raise ArgumentError.new('cannot enqueue nil') if item.nil?
-
@queue.add(item)
-
end
-
alias_method :<<, :push
-
alias_method :enq, :push
-
-
# @!macro priority_queue_method_from_list
-
def self.from_list(list, opts = {})
-
queue = new(opts)
-
list.each{|item| queue << item }
-
queue
-
end
-
end
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'concurrent/collection/map/non_concurrent_map_backend'
-
-
1
module Concurrent
-
-
# @!visibility private
-
1
module Collection
-
-
# @!visibility private
-
1
class MriMapBackend < NonConcurrentMapBackend
-
-
1
def initialize(options = nil)
-
super(options)
-
@write_lock = Mutex.new
-
end
-
-
1
def []=(key, value)
-
@write_lock.synchronize { super }
-
end
-
-
1
def compute_if_absent(key)
-
if stored_value = _get(key) # fast non-blocking path for the most likely case
-
stored_value
-
else
-
@write_lock.synchronize { super }
-
end
-
end
-
-
1
def compute_if_present(key)
-
@write_lock.synchronize { super }
-
end
-
-
1
def compute(key)
-
@write_lock.synchronize { super }
-
end
-
-
1
def merge_pair(key, value)
-
@write_lock.synchronize { super }
-
end
-
-
1
def replace_pair(key, old_value, new_value)
-
@write_lock.synchronize { super }
-
end
-
-
1
def replace_if_exists(key, new_value)
-
@write_lock.synchronize { super }
-
end
-
-
1
def get_and_set(key, value)
-
@write_lock.synchronize { super }
-
end
-
-
1
def delete(key)
-
@write_lock.synchronize { super }
-
end
-
-
1
def delete_pair(key, value)
-
@write_lock.synchronize { super }
-
end
-
-
1
def clear
-
@write_lock.synchronize { super }
-
end
-
end
-
end
-
end
-
1
require 'concurrent/constants'
-
-
1
module Concurrent
-
-
# @!visibility private
-
1
module Collection
-
-
# @!visibility private
-
1
class NonConcurrentMapBackend
-
-
# WARNING: all public methods of the class must operate on the @backend
-
# directly without calling each other. This is important because of the
-
# SynchronizedMapBackend which uses a non-reentrant mutex for perfomance
-
# reasons.
-
1
def initialize(options = nil)
-
@backend = {}
-
end
-
-
1
def [](key)
-
@backend[key]
-
end
-
-
1
def []=(key, value)
-
@backend[key] = value
-
end
-
-
1
def compute_if_absent(key)
-
if NULL != (stored_value = @backend.fetch(key, NULL))
-
stored_value
-
else
-
@backend[key] = yield
-
end
-
end
-
-
1
def replace_pair(key, old_value, new_value)
-
if pair?(key, old_value)
-
@backend[key] = new_value
-
true
-
else
-
false
-
end
-
end
-
-
1
def replace_if_exists(key, new_value)
-
if NULL != (stored_value = @backend.fetch(key, NULL))
-
@backend[key] = new_value
-
stored_value
-
end
-
end
-
-
1
def compute_if_present(key)
-
if NULL != (stored_value = @backend.fetch(key, NULL))
-
store_computed_value(key, yield(stored_value))
-
end
-
end
-
-
1
def compute(key)
-
store_computed_value(key, yield(@backend[key]))
-
end
-
-
1
def merge_pair(key, value)
-
if NULL == (stored_value = @backend.fetch(key, NULL))
-
@backend[key] = value
-
else
-
store_computed_value(key, yield(stored_value))
-
end
-
end
-
-
1
def get_and_set(key, value)
-
stored_value = @backend[key]
-
@backend[key] = value
-
stored_value
-
end
-
-
1
def key?(key)
-
@backend.key?(key)
-
end
-
-
1
def delete(key)
-
@backend.delete(key)
-
end
-
-
1
def delete_pair(key, value)
-
if pair?(key, value)
-
@backend.delete(key)
-
true
-
else
-
false
-
end
-
end
-
-
1
def clear
-
@backend.clear
-
self
-
end
-
-
1
def each_pair
-
return enum_for :each_pair unless block_given?
-
dupped_backend.each_pair do |k, v|
-
yield k, v
-
end
-
self
-
end
-
-
1
def size
-
@backend.size
-
end
-
-
1
def get_or_default(key, default_value)
-
@backend.fetch(key, default_value)
-
end
-
-
1
alias_method :_get, :[]
-
1
alias_method :_set, :[]=
-
1
private :_get, :_set
-
1
private
-
1
def initialize_copy(other)
-
super
-
@backend = {}
-
self
-
end
-
-
1
def dupped_backend
-
@backend.dup
-
end
-
-
1
def pair?(key, expected_value)
-
NULL != (stored_value = @backend.fetch(key, NULL)) && expected_value.equal?(stored_value)
-
end
-
-
1
def store_computed_value(key, new_value)
-
if new_value.nil?
-
@backend.delete(key)
-
nil
-
else
-
@backend[key] = new_value
-
end
-
end
-
end
-
end
-
end
-
1
require 'concurrent/collection/java_non_concurrent_priority_queue'
-
1
require 'concurrent/collection/ruby_non_concurrent_priority_queue'
-
1
require 'concurrent/utility/engine'
-
-
1
module Concurrent
-
1
module Collection
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
NonConcurrentPriorityQueueImplementation = case
-
when Concurrent.on_jruby?
-
JavaNonConcurrentPriorityQueue
-
else
-
1
RubyNonConcurrentPriorityQueue
-
end
-
1
private_constant :NonConcurrentPriorityQueueImplementation
-
-
# @!macro [attach] priority_queue
-
#
-
# A queue collection in which the elements are sorted based on their
-
# comparison (spaceship) operator `<=>`. Items are added to the queue
-
# at a position relative to their priority. On removal the element
-
# with the "highest" priority is removed. By default the sort order is
-
# from highest to lowest, but a lowest-to-highest sort order can be
-
# set on construction.
-
#
-
# The API is based on the `Queue` class from the Ruby standard library.
-
#
-
# The pure Ruby implementation, `RubyNonConcurrentPriorityQueue` uses a heap algorithm
-
# stored in an array. The algorithm is based on the work of Robert Sedgewick
-
# and Kevin Wayne.
-
#
-
# The JRuby native implementation is a thin wrapper around the standard
-
# library `java.util.NonConcurrentPriorityQueue`.
-
#
-
# When running under JRuby the class `NonConcurrentPriorityQueue` extends `JavaNonConcurrentPriorityQueue`.
-
# When running under all other interpreters it extends `RubyNonConcurrentPriorityQueue`.
-
#
-
# @note This implementation is *not* thread safe.
-
#
-
# @see http://en.wikipedia.org/wiki/Priority_queue
-
# @see http://ruby-doc.org/stdlib-2.0.0/libdoc/thread/rdoc/Queue.html
-
#
-
# @see http://algs4.cs.princeton.edu/24pq/index.php#2.6
-
# @see http://algs4.cs.princeton.edu/24pq/MaxPQ.java.html
-
#
-
# @see http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
-
#
-
# @!visibility private
-
1
class NonConcurrentPriorityQueue < NonConcurrentPriorityQueueImplementation
-
-
1
alias_method :has_priority?, :include?
-
-
1
alias_method :size, :length
-
-
1
alias_method :deq, :pop
-
1
alias_method :shift, :pop
-
-
1
alias_method :<<, :push
-
1
alias_method :enq, :push
-
-
# @!method initialize(opts = {})
-
# @!macro [new] priority_queue_method_initialize
-
#
-
# Create a new priority queue with no items.
-
#
-
# @param [Hash] opts the options for creating the queue
-
# @option opts [Symbol] :order (:max) dictates the order in which items are
-
# stored: from highest to lowest when `:max` or `:high`; from lowest to
-
# highest when `:min` or `:low`
-
-
# @!method clear
-
# @!macro [new] priority_queue_method_clear
-
#
-
# Removes all of the elements from this priority queue.
-
-
# @!method delete(item)
-
# @!macro [new] priority_queue_method_delete
-
#
-
# Deletes all items from `self` that are equal to `item`.
-
#
-
# @param [Object] item the item to be removed from the queue
-
# @return [Object] true if the item is found else false
-
-
# @!method empty?
-
# @!macro [new] priority_queue_method_empty
-
#
-
# Returns `true` if `self` contains no elements.
-
#
-
# @return [Boolean] true if there are no items in the queue else false
-
-
# @!method include?(item)
-
# @!macro [new] priority_queue_method_include
-
#
-
# Returns `true` if the given item is present in `self` (that is, if any
-
# element == `item`), otherwise returns false.
-
#
-
# @param [Object] item the item to search for
-
#
-
# @return [Boolean] true if the item is found else false
-
-
# @!method length
-
# @!macro [new] priority_queue_method_length
-
#
-
# The current length of the queue.
-
#
-
# @return [Fixnum] the number of items in the queue
-
-
# @!method peek
-
# @!macro [new] priority_queue_method_peek
-
#
-
# Retrieves, but does not remove, the head of this queue, or returns `nil`
-
# if this queue is empty.
-
#
-
# @return [Object] the head of the queue or `nil` when empty
-
-
# @!method pop
-
# @!macro [new] priority_queue_method_pop
-
#
-
# Retrieves and removes the head of this queue, or returns `nil` if this
-
# queue is empty.
-
#
-
# @return [Object] the head of the queue or `nil` when empty
-
-
# @!method push(item)
-
# @!macro [new] priority_queue_method_push
-
#
-
# Inserts the specified element into this priority queue.
-
#
-
# @param [Object] item the item to insert onto the queue
-
-
# @!method self.from_list(list, opts = {})
-
# @!macro [new] priority_queue_method_from_list
-
#
-
# Create a new priority queue from the given list.
-
#
-
# @param [Enumerable] list the list to build the queue from
-
# @param [Hash] opts the options for creating the queue
-
#
-
# @return [NonConcurrentPriorityQueue] the newly created and populated queue
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Collection
-
-
# @!macro priority_queue
-
#
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class RubyNonConcurrentPriorityQueue
-
-
# @!macro priority_queue_method_initialize
-
1
def initialize(opts = {})
-
order = opts.fetch(:order, :max)
-
@comparator = [:min, :low].include?(order) ? -1 : 1
-
clear
-
end
-
-
# @!macro priority_queue_method_clear
-
1
def clear
-
@queue = [nil]
-
@length = 0
-
true
-
end
-
-
# @!macro priority_queue_method_delete
-
1
def delete(item)
-
return false if empty?
-
original_length = @length
-
k = 1
-
while k <= @length
-
if @queue[k] == item
-
swap(k, @length)
-
@length -= 1
-
sink(k)
-
@queue.pop
-
else
-
k += 1
-
end
-
end
-
@length != original_length
-
end
-
-
# @!macro priority_queue_method_empty
-
1
def empty?
-
size == 0
-
end
-
-
# @!macro priority_queue_method_include
-
1
def include?(item)
-
@queue.include?(item)
-
end
-
1
alias_method :has_priority?, :include?
-
-
# @!macro priority_queue_method_length
-
1
def length
-
@length
-
end
-
1
alias_method :size, :length
-
-
# @!macro priority_queue_method_peek
-
1
def peek
-
empty? ? nil : @queue[1]
-
end
-
-
# @!macro priority_queue_method_pop
-
1
def pop
-
return nil if empty?
-
max = @queue[1]
-
swap(1, @length)
-
@length -= 1
-
sink(1)
-
@queue.pop
-
max
-
end
-
1
alias_method :deq, :pop
-
1
alias_method :shift, :pop
-
-
# @!macro priority_queue_method_push
-
1
def push(item)
-
raise ArgumentError.new('cannot enqueue nil') if item.nil?
-
@length += 1
-
@queue << item
-
swim(@length)
-
true
-
end
-
1
alias_method :<<, :push
-
1
alias_method :enq, :push
-
-
# @!macro priority_queue_method_from_list
-
1
def self.from_list(list, opts = {})
-
queue = new(opts)
-
list.each{|item| queue << item }
-
queue
-
end
-
-
1
private
-
-
# Exchange the values at the given indexes within the internal array.
-
#
-
# @param [Integer] x the first index to swap
-
# @param [Integer] y the second index to swap
-
#
-
# @!visibility private
-
1
def swap(x, y)
-
temp = @queue[x]
-
@queue[x] = @queue[y]
-
@queue[y] = temp
-
end
-
-
# Are the items at the given indexes ordered based on the priority
-
# order specified at construction?
-
#
-
# @param [Integer] x the first index from which to retrieve a comparable value
-
# @param [Integer] y the second index from which to retrieve a comparable value
-
#
-
# @return [Boolean] true if the two elements are in the correct priority order
-
# else false
-
#
-
# @!visibility private
-
1
def ordered?(x, y)
-
(@queue[x] <=> @queue[y]) == @comparator
-
end
-
-
# Percolate down to maintain heap invariant.
-
#
-
# @param [Integer] k the index at which to start the percolation
-
#
-
# @!visibility private
-
1
def sink(k)
-
while (j = (2 * k)) <= @length do
-
j += 1 if j < @length && ! ordered?(j, j+1)
-
break if ordered?(k, j)
-
swap(k, j)
-
k = j
-
end
-
end
-
-
# Percolate up to maintain heap invariant.
-
#
-
# @param [Integer] k the index at which to start the percolation
-
#
-
# @!visibility private
-
1
def swim(k)
-
while k > 1 && ! ordered?(k/2, k) do
-
swap(k, k/2)
-
k = k/2
-
end
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Concern
-
-
# Object references in Ruby are mutable. This can lead to serious problems when
-
# the `#value` of a concurrent object is a mutable reference. Which is always the
-
# case unless the value is a `Fixnum`, `Symbol`, or similar "primitive" data type.
-
# Most classes in this library that expose a `#value` getter method do so using the
-
# `Dereferenceable` mixin module.
-
#
-
# @!macro copy_options
-
1
module Dereferenceable
-
# NOTE: This module is going away in 2.0. In the mean time we need it to
-
# play nicely with the synchronization layer. This means that the
-
# including class SHOULD be synchronized and it MUST implement a
-
# `#synchronize` method. Not doing so will lead to runtime errors.
-
-
# Return the value this object represents after applying the options specified
-
# by the `#set_deref_options` method.
-
#
-
# @return [Object] the current value of the object
-
1
def value
-
synchronize { apply_deref_options(@value) }
-
end
-
1
alias_method :deref, :value
-
-
1
protected
-
-
# Set the internal value of this object
-
#
-
# @param [Object] value the new value
-
1
def value=(value)
-
synchronize{ @value = value }
-
end
-
-
# @!macro [attach] dereferenceable_set_deref_options
-
# Set the options which define the operations #value performs before
-
# returning data to the caller (dereferencing).
-
#
-
# @note Most classes that include this module will call `#set_deref_options`
-
# from within the constructor, thus allowing these options to be set at
-
# object creation.
-
#
-
# @param [Hash] opts the options defining dereference behavior.
-
# @option opts [String] :dup_on_deref (false) call `#dup` before returning the data
-
# @option opts [String] :freeze_on_deref (false) call `#freeze` before returning the data
-
# @option opts [String] :copy_on_deref (nil) call the given `Proc` passing
-
# the internal value and returning the value returned from the proc
-
1
def set_deref_options(opts = {})
-
10
synchronize{ ns_set_deref_options(opts) }
-
end
-
-
# @!macro dereferenceable_set_deref_options
-
# @!visibility private
-
1
def ns_set_deref_options(opts)
-
5
@dup_on_deref = opts[:dup_on_deref] || opts[:dup]
-
5
@freeze_on_deref = opts[:freeze_on_deref] || opts[:freeze]
-
5
@copy_on_deref = opts[:copy_on_deref] || opts[:copy]
-
5
@do_nothing_on_deref = !(@dup_on_deref || @freeze_on_deref || @copy_on_deref)
-
nil
-
end
-
-
# @!visibility private
-
1
def apply_deref_options(value)
-
return nil if value.nil?
-
return value if @do_nothing_on_deref
-
value = @copy_on_deref.call(value) if @copy_on_deref
-
value = value.dup if @dup_on_deref
-
value = value.freeze if @freeze_on_deref
-
value
-
end
-
end
-
end
-
end
-
1
require 'logger'
-
-
1
module Concurrent
-
1
module Concern
-
-
# Include where logging is needed
-
#
-
# @!visibility private
-
1
module Logging
-
1
include Logger::Severity
-
-
# Logs through {Concurrent.global_logger}, it can be overridden by setting @logger
-
# @param [Integer] level one of Logger::Severity constants
-
# @param [String] progname e.g. a path of an Actor
-
# @param [String, nil] message when nil block is used to generate the message
-
# @yieldreturn [String] a message
-
1
def log(level, progname, message = nil, &block)
-
#NOTE: Cannot require 'concurrent/configuration' above due to circular references.
-
# Assume that the gem has been initialized if we've gotten this far.
-
(@logger || Concurrent.global_logger).call level, progname, message, &block
-
rescue => error
-
$stderr.puts "`Concurrent.configuration.logger` failed to log #{[level, progname, message, block]}\n" +
-
"#{error.message} (#{error.class})\n#{error.backtrace.join "\n"}"
-
end
-
end
-
end
-
end
-
1
require 'concurrent/collection/copy_on_notify_observer_set'
-
1
require 'concurrent/collection/copy_on_write_observer_set'
-
-
1
module Concurrent
-
1
module Concern
-
-
# The [observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) is one
-
# of the most useful design patterns.
-
#
-
# The workflow is very simple:
-
# - an `observer` can register itself to a `subject` via a callback
-
# - many `observers` can be registered to the same `subject`
-
# - the `subject` notifies all registered observers when its status changes
-
# - an `observer` can deregister itself when is no more interested to receive
-
# event notifications
-
#
-
# In a single threaded environment the whole pattern is very easy: the
-
# `subject` can use a simple data structure to manage all its subscribed
-
# `observer`s and every `observer` can react directly to every event without
-
# caring about synchronization.
-
#
-
# In a multi threaded environment things are more complex. The `subject` must
-
# synchronize the access to its data structure and to do so currently we're
-
# using two specialized ObserverSet: {Concurrent::Concern::CopyOnWriteObserverSet}
-
# and {Concurrent::Concern::CopyOnNotifyObserverSet}.
-
#
-
# When implementing and `observer` there's a very important rule to remember:
-
# **there are no guarantees about the thread that will execute the callback**
-
#
-
# Let's take this example
-
# ```
-
# class Observer
-
# def initialize
-
# @count = 0
-
# end
-
#
-
# def update
-
# @count += 1
-
# end
-
# end
-
#
-
# obs = Observer.new
-
# [obj1, obj2, obj3, obj4].each { |o| o.add_observer(obs) }
-
# # execute [obj1, obj2, obj3, obj4]
-
# ```
-
#
-
# `obs` is wrong because the variable `@count` can be accessed by different
-
# threads at the same time, so it should be synchronized (using either a Mutex
-
# or an AtomicFixum)
-
1
module Observable
-
-
# @!macro [attach] observable_add_observer
-
#
-
# Adds an observer to this set. If a block is passed, the observer will be
-
# created by this method and no other params should be passed.
-
#
-
# @param [Object] observer the observer to add
-
# @param [Symbol] func the function to call on the observer during notification.
-
# Default is :update
-
# @return [Object] the added observer
-
1
def add_observer(observer = nil, func = :update, &block)
-
observers.add_observer(observer, func, &block)
-
end
-
-
# As `#add_observer` but can be used for chaining.
-
#
-
# @param [Object] observer the observer to add
-
# @param [Symbol] func the function to call on the observer during notification.
-
# @return [Observable] self
-
1
def with_observer(observer = nil, func = :update, &block)
-
add_observer(observer, func, &block)
-
self
-
end
-
-
# @!macro [attach] observable_delete_observer
-
#
-
# Remove `observer` as an observer on this object so that it will no
-
# longer receive notifications.
-
#
-
# @param [Object] observer the observer to remove
-
# @return [Object] the deleted observer
-
1
def delete_observer(observer)
-
observers.delete_observer(observer)
-
end
-
-
# @!macro [attach] observable_delete_observers
-
#
-
# Remove all observers associated with this object.
-
#
-
# @return [Observable] self
-
1
def delete_observers
-
observers.delete_observers
-
self
-
end
-
-
# @!macro [attach] observable_count_observers
-
#
-
# Return the number of observers associated with this object.
-
#
-
# @return [Integer] the observers count
-
1
def count_observers
-
observers.count_observers
-
end
-
-
1
protected
-
-
1
attr_accessor :observers
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'concurrent/delay'
-
1
require 'concurrent/errors'
-
1
require 'concurrent/atomic/atomic_reference'
-
1
require 'concurrent/concern/logging'
-
1
require 'concurrent/executor/immediate_executor'
-
1
require 'concurrent/utility/at_exit'
-
1
require 'concurrent/utility/processor_counter'
-
-
1
module Concurrent
-
1
extend Concern::Logging
-
-
1
autoload :Options, 'concurrent/options'
-
1
autoload :TimerSet, 'concurrent/executor/timer_set'
-
1
autoload :ThreadPoolExecutor, 'concurrent/executor/thread_pool_executor'
-
-
# @return [Logger] Logger with provided level and output.
-
1
def self.create_simple_logger(level = Logger::FATAL, output = $stderr)
-
# TODO (pitr-ch 24-Dec-2016): figure out why it had to be replaced, stdlogger was deadlocking
-
1
lambda do |severity, progname, message = nil, &block|
-
return false if severity < level
-
-
message = block ? block.call : message
-
formatted_message = case message
-
when String
-
message
-
when Exception
-
format "%s (%s)\n%s",
-
message.message, message.class, (message.backtrace || []).join("\n")
-
else
-
message.inspect
-
end
-
-
output.print format "[%s] %5s -- %s: %s\n",
-
Time.now.strftime('%Y-%m-%d %H:%M:%S.%L'),
-
Logger::SEV_LABEL[severity],
-
progname,
-
formatted_message
-
true
-
end
-
end
-
-
# Use logger created by #create_simple_logger to log concurrent-ruby messages.
-
1
def self.use_simple_logger(level = Logger::FATAL, output = $stderr)
-
Concurrent.global_logger = create_simple_logger level, output
-
end
-
-
# @return [Logger] Logger with provided level and output.
-
# @deprecated
-
1
def self.create_stdlib_logger(level = Logger::FATAL, output = $stderr)
-
logger = Logger.new(output)
-
logger.level = level
-
logger.formatter = lambda do |severity, datetime, progname, msg|
-
formatted_message = case msg
-
when String
-
msg
-
when Exception
-
format "%s (%s)\n%s",
-
msg.message, msg.class, (msg.backtrace || []).join("\n")
-
else
-
msg.inspect
-
end
-
format "[%s] %5s -- %s: %s\n",
-
datetime.strftime('%Y-%m-%d %H:%M:%S.%L'),
-
severity,
-
progname,
-
formatted_message
-
end
-
-
lambda do |loglevel, progname, message = nil, &block|
-
logger.add loglevel, message, progname, &block
-
end
-
end
-
-
# Use logger created by #create_stdlib_logger to log concurrent-ruby messages.
-
# @deprecated
-
1
def self.use_stdlib_logger(level = Logger::FATAL, output = $stderr)
-
Concurrent.global_logger = create_stdlib_logger level, output
-
end
-
-
# TODO (pitr-ch 27-Dec-2016): remove deadlocking stdlib_logger methods
-
-
# Suppresses all output when used for logging.
-
1
NULL_LOGGER = lambda { |level, progname, message = nil, &block| }
-
-
# @!visibility private
-
1
GLOBAL_LOGGER = AtomicReference.new(create_simple_logger(Logger::WARN))
-
1
private_constant :GLOBAL_LOGGER
-
-
1
def self.global_logger
-
GLOBAL_LOGGER.value
-
end
-
-
1
def self.global_logger=(value)
-
GLOBAL_LOGGER.value = value
-
end
-
-
# @!visibility private
-
1
GLOBAL_FAST_EXECUTOR = Delay.new { Concurrent.new_fast_executor(auto_terminate: true) }
-
1
private_constant :GLOBAL_FAST_EXECUTOR
-
-
# @!visibility private
-
1
GLOBAL_IO_EXECUTOR = Delay.new { Concurrent.new_io_executor(auto_terminate: true) }
-
1
private_constant :GLOBAL_IO_EXECUTOR
-
-
# @!visibility private
-
1
GLOBAL_TIMER_SET = Delay.new { TimerSet.new(auto_terminate: true) }
-
1
private_constant :GLOBAL_TIMER_SET
-
-
# @!visibility private
-
1
GLOBAL_IMMEDIATE_EXECUTOR = ImmediateExecutor.new
-
1
private_constant :GLOBAL_IMMEDIATE_EXECUTOR
-
-
# Disables AtExit handlers including pool auto-termination handlers.
-
# When disabled it will be the application programmer's responsibility
-
# to ensure that the handlers are shutdown properly prior to application
-
# exit by calling {AtExit.run} method.
-
#
-
# @note this option should be needed only because of `at_exit` ordering
-
# issues which may arise when running some of the testing frameworks.
-
# E.g. Minitest's test-suite runs itself in `at_exit` callback which
-
# executes after the pools are already terminated. Then auto termination
-
# needs to be disabled and called manually after test-suite ends.
-
# @note This method should *never* be called
-
# from within a gem. It should *only* be used from within the main
-
# application and even then it should be used only when necessary.
-
# @see AtExit
-
1
def self.disable_at_exit_handlers!
-
AtExit.enabled = false
-
end
-
-
# Global thread pool optimized for short, fast *operations*.
-
#
-
# @return [ThreadPoolExecutor] the thread pool
-
1
def self.global_fast_executor
-
GLOBAL_FAST_EXECUTOR.value
-
end
-
-
# Global thread pool optimized for long, blocking (IO) *tasks*.
-
#
-
# @return [ThreadPoolExecutor] the thread pool
-
1
def self.global_io_executor
-
GLOBAL_IO_EXECUTOR.value
-
end
-
-
1
def self.global_immediate_executor
-
GLOBAL_IMMEDIATE_EXECUTOR
-
end
-
-
# Global thread pool user for global *timers*.
-
#
-
# @return [Concurrent::TimerSet] the thread pool
-
1
def self.global_timer_set
-
GLOBAL_TIMER_SET.value
-
end
-
-
# General access point to global executors.
-
# @param [Symbol, Executor] executor_identifier symbols:
-
# - :fast - {Concurrent.global_fast_executor}
-
# - :io - {Concurrent.global_io_executor}
-
# - :immediate - {Concurrent.global_immediate_executor}
-
# @return [Executor]
-
1
def self.executor(executor_identifier)
-
Options.executor(executor_identifier)
-
end
-
-
1
def self.new_fast_executor(opts = {})
-
FixedThreadPool.new(
-
[2, Concurrent.processor_count].max,
-
auto_terminate: opts.fetch(:auto_terminate, true),
-
idletime: 60, # 1 minute
-
max_queue: 0, # unlimited
-
fallback_policy: :abort # shouldn't matter -- 0 max queue
-
)
-
end
-
-
1
def self.new_io_executor(opts = {})
-
ThreadPoolExecutor.new(
-
min_threads: [2, Concurrent.processor_count].max,
-
max_threads: ThreadPoolExecutor::DEFAULT_MAX_POOL_SIZE,
-
# max_threads: 1000,
-
auto_terminate: opts.fetch(:auto_terminate, true),
-
idletime: 60, # 1 minute
-
max_queue: 0, # unlimited
-
fallback_policy: :abort # shouldn't matter -- 0 max queue
-
)
-
end
-
end
-
1
module Concurrent
-
-
# Various classes within allows for +nil+ values to be stored,
-
# so a special +NULL+ token is required to indicate the "nil-ness".
-
# @!visibility private
-
1
NULL = Object.new
-
-
end
-
1
require 'concurrent/future'
-
1
require 'concurrent/atomic/atomic_fixnum'
-
-
1
module Concurrent
-
-
# @!visibility private
-
1
class DependencyCounter # :nodoc:
-
-
1
def initialize(count, &block)
-
@counter = AtomicFixnum.new(count)
-
@block = block
-
end
-
-
1
def update(time, value, reason)
-
if @counter.decrement == 0
-
@block.call
-
end
-
end
-
end
-
-
# {include:file:doc/dataflow.md}
-
#
-
# @param [Future] inputs zero or more `Future` operations that this dataflow depends upon
-
#
-
# @yield The operation to perform once all the dependencies are met
-
# @yieldparam [Future] inputs each of the `Future` inputs to the dataflow
-
# @yieldreturn [Object] the result of the block operation
-
#
-
# @return [Object] the result of all the operations
-
#
-
# @raise [ArgumentError] if no block is given
-
# @raise [ArgumentError] if any of the inputs are not `IVar`s
-
1
def dataflow(*inputs, &block)
-
dataflow_with(Concurrent.global_io_executor, *inputs, &block)
-
end
-
1
module_function :dataflow
-
-
1
def dataflow_with(executor, *inputs, &block)
-
call_dataflow(:value, executor, *inputs, &block)
-
end
-
1
module_function :dataflow_with
-
-
1
def dataflow!(*inputs, &block)
-
dataflow_with!(Concurrent.global_io_executor, *inputs, &block)
-
end
-
1
module_function :dataflow!
-
-
1
def dataflow_with!(executor, *inputs, &block)
-
call_dataflow(:value!, executor, *inputs, &block)
-
end
-
1
module_function :dataflow_with!
-
-
1
private
-
-
1
def call_dataflow(method, executor, *inputs, &block)
-
raise ArgumentError.new('an executor must be provided') if executor.nil?
-
raise ArgumentError.new('no block given') unless block_given?
-
unless inputs.all? { |input| input.is_a? IVar }
-
raise ArgumentError.new("Not all dependencies are IVars.\nDependencies: #{ inputs.inspect }")
-
end
-
-
result = Future.new(executor: executor) do
-
values = inputs.map { |input| input.send(method) }
-
block.call(*values)
-
end
-
-
if inputs.empty?
-
result.execute
-
else
-
counter = DependencyCounter.new(inputs.size) { result.execute }
-
-
inputs.each do |input|
-
input.add_observer counter
-
end
-
end
-
-
result
-
end
-
1
module_function :call_dataflow
-
end
-
1
require 'thread'
-
1
require 'concurrent/concern/obligation'
-
1
require 'concurrent/executor/immediate_executor'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# This file has circular require issues. It must be autoloaded here.
-
1
autoload :Options, 'concurrent/options'
-
-
# Lazy evaluation of a block yielding an immutable result. Useful for
-
# expensive operations that may never be needed. It may be non-blocking,
-
# supports the `Concern::Obligation` interface, and accepts the injection of
-
# custom executor upon which to execute the block. Processing of
-
# block will be deferred until the first time `#value` is called.
-
# At that time the caller can choose to return immediately and let
-
# the block execute asynchronously, block indefinitely, or block
-
# with a timeout.
-
#
-
# When a `Delay` is created its state is set to `pending`. The value and
-
# reason are both `nil`. The first time the `#value` method is called the
-
# enclosed opration will be run and the calling thread will block. Other
-
# threads attempting to call `#value` will block as well. Once the operation
-
# is complete the *value* will be set to the result of the operation or the
-
# *reason* will be set to the raised exception, as appropriate. All threads
-
# blocked on `#value` will return. Subsequent calls to `#value` will immediately
-
# return the cached value. The operation will only be run once. This means that
-
# any side effects created by the operation will only happen once as well.
-
#
-
# `Delay` includes the `Concurrent::Concern::Dereferenceable` mixin to support thread
-
# safety of the reference returned by `#value`.
-
#
-
# @!macro copy_options
-
#
-
# @!macro [attach] delay_note_regarding_blocking
-
# @note The default behavior of `Delay` is to block indefinitely when
-
# calling either `value` or `wait`, executing the delayed operation on
-
# the current thread. This makes the `timeout` value completely
-
# irrelevant. To enable non-blocking behavior, use the `executor`
-
# constructor option. This will cause the delayed operation to be
-
# execute on the given executor, allowing the call to timeout.
-
#
-
# @see Concurrent::Concern::Dereferenceable
-
1
class Delay < Synchronization::LockableObject
-
1
include Concern::Obligation
-
-
# NOTE: Because the global thread pools are lazy-loaded with these objects
-
# there is a performance hit every time we post a new task to one of these
-
# thread pools. Subsequently it is critical that `Delay` perform as fast
-
# as possible post-completion. This class has been highly optimized using
-
# the benchmark script `examples/lazy_and_delay.rb`. Do NOT attempt to
-
# DRY-up this class or perform other refactoring with running the
-
# benchmarks and ensuring that performance is not negatively impacted.
-
-
# Create a new `Delay` in the `:pending` state.
-
#
-
# @!macro executor_and_deref_options
-
#
-
# @yield the delayed operation to perform
-
#
-
# @raise [ArgumentError] if no block is given
-
1
def initialize(opts = {}, &block)
-
5
raise ArgumentError.new('no block given') unless block_given?
-
5
super(&nil)
-
10
synchronize { ns_initialize(opts, &block) }
-
end
-
-
# Return the value this object represents after applying the options
-
# specified by the `#set_deref_options` method. If the delayed operation
-
# raised an exception this method will return nil. The execption object
-
# can be accessed via the `#reason` method.
-
#
-
# @param [Numeric] timeout the maximum number of seconds to wait
-
# @return [Object] the current value of the object
-
#
-
# @!macro delay_note_regarding_blocking
-
1
def value(timeout = nil)
-
if @executor # TODO (pitr 12-Sep-2015): broken unsafe read?
-
super
-
else
-
# this function has been optimized for performance and
-
# should not be modified without running new benchmarks
-
synchronize do
-
execute = @computing = true unless @computing
-
if execute
-
begin
-
set_state(true, @task.call, nil)
-
rescue => ex
-
set_state(false, nil, ex)
-
end
-
end
-
end
-
if @do_nothing_on_deref
-
@value
-
else
-
apply_deref_options(@value)
-
end
-
end
-
end
-
-
# Return the value this object represents after applying the options
-
# specified by the `#set_deref_options` method. If the delayed operation
-
# raised an exception, this method will raise that exception (even when)
-
# the operation has already been executed).
-
#
-
# @param [Numeric] timeout the maximum number of seconds to wait
-
# @return [Object] the current value of the object
-
# @raise [Exception] when `#rejected?` raises `#reason`
-
#
-
# @!macro delay_note_regarding_blocking
-
1
def value!(timeout = nil)
-
if @executor
-
super
-
else
-
result = value
-
raise @reason if @reason
-
result
-
end
-
end
-
-
# Return the value this object represents after applying the options
-
# specified by the `#set_deref_options` method.
-
#
-
# @param [Integer] timeout (nil) the maximum number of seconds to wait for
-
# the value to be computed. When `nil` the caller will block indefinitely.
-
#
-
# @return [Object] self
-
#
-
# @!macro delay_note_regarding_blocking
-
1
def wait(timeout = nil)
-
if @executor
-
execute_task_once
-
super(timeout)
-
else
-
value
-
end
-
self
-
end
-
-
# Reconfigures the block returning the value if still `#incomplete?`
-
#
-
# @yield the delayed operation to perform
-
# @return [true, false] if success
-
1
def reconfigure(&block)
-
synchronize do
-
raise ArgumentError.new('no block given') unless block_given?
-
unless @computing
-
@task = block
-
true
-
else
-
false
-
end
-
end
-
end
-
-
1
protected
-
-
1
def ns_initialize(opts, &block)
-
5
init_obligation
-
5
set_deref_options(opts)
-
5
@executor = opts[:executor]
-
-
5
@task = block
-
5
@state = :pending
-
5
@computing = false
-
end
-
-
1
private
-
-
# @!visibility private
-
1
def execute_task_once # :nodoc:
-
# this function has been optimized for performance and
-
# should not be modified without running new benchmarks
-
execute = task = nil
-
synchronize do
-
execute = @computing = true unless @computing
-
task = @task
-
end
-
-
if execute
-
executor = Options.executor_from_options(executor: @executor)
-
executor.post do
-
begin
-
result = task.call
-
success = true
-
rescue => ex
-
reason = ex
-
end
-
synchronize do
-
set_state(success, result, reason)
-
event.set
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
-
1
Error = Class.new(StandardError)
-
-
# Raised when errors occur during configuration.
-
1
ConfigurationError = Class.new(Error)
-
-
# Raised when an asynchronous operation is cancelled before execution.
-
1
CancelledOperationError = Class.new(Error)
-
-
# Raised when a lifecycle method (such as `stop`) is called in an improper
-
# sequence or when the object is in an inappropriate state.
-
1
LifecycleError = Class.new(Error)
-
-
# Raised when an attempt is made to violate an immutability guarantee.
-
1
ImmutabilityError = Class.new(Error)
-
-
# Raised when an operation is attempted which is not legal given the
-
# receiver's current state
-
1
IllegalOperationError = Class.new(Error)
-
-
# Raised when an object's methods are called when it has not been
-
# properly initialized.
-
1
InitializationError = Class.new(Error)
-
-
# Raised when an object with a start/stop lifecycle has been started an
-
# excessive number of times. Often used in conjunction with a restart
-
# policy or strategy.
-
1
MaxRestartFrequencyError = Class.new(Error)
-
-
# Raised when an attempt is made to modify an immutable object
-
# (such as an `IVar`) after its final state has been set.
-
1
class MultipleAssignmentError < Error
-
1
attr_reader :inspection_data
-
-
1
def initialize(message = nil, inspection_data = nil)
-
@inspection_data = inspection_data
-
super message
-
end
-
-
1
def inspect
-
format '%s %s>', super[0..-2], @inspection_data.inspect
-
end
-
end
-
-
# Raised by an `Executor` when it is unable to process a given task,
-
# possibly because of a reject policy or other internal error.
-
1
RejectedExecutionError = Class.new(Error)
-
-
# Raised when any finite resource, such as a lock counter, exceeds its
-
# maximum limit/threshold.
-
1
ResourceLimitError = Class.new(Error)
-
-
# Raised when an operation times out.
-
1
TimeoutError = Class.new(Error)
-
-
# Aggregates multiple exceptions.
-
1
class MultipleErrors < Error
-
1
attr_reader :errors
-
-
1
def initialize(errors, message = "#{errors.size} errors")
-
@errors = errors
-
super [*message,
-
*errors.map { |e| [format('%s (%s)', e.message, e.class), *e.backtrace] }.flatten(1)
-
].join("\n")
-
end
-
end
-
-
end
-
1
require 'concurrent/constants'
-
1
require 'concurrent/errors'
-
1
require 'concurrent/maybe'
-
1
require 'concurrent/atomic/atomic_reference'
-
1
require 'concurrent/atomic/count_down_latch'
-
1
require 'concurrent/utility/engine'
-
1
require 'concurrent/utility/monotonic_time'
-
-
1
module Concurrent
-
-
# @!macro [attach] exchanger
-
#
-
# A synchronization point at which threads can pair and swap elements within
-
# pairs. Each thread presents some object on entry to the exchange method,
-
# matches with a partner thread, and receives its partner's object on return.
-
#
-
# @!macro thread_safe_variable_comparison
-
#
-
# This implementation is very simple, using only a single slot for each
-
# exchanger (unlike more advanced implementations which use an "arena").
-
# This approach will work perfectly fine when there are only a few threads
-
# accessing a single `Exchanger`. Beyond a handful of threads the performance
-
# will degrade rapidly due to contention on the single slot, but the algorithm
-
# will remain correct.
-
#
-
# @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Exchanger.html java.util.concurrent.Exchanger
-
#
-
# @!macro edge_warning
-
#
-
# @example
-
#
-
# exchanger = Concurrent::Exchanger.new
-
#
-
# threads = [
-
# Thread.new { puts "first: " << exchanger.exchange('foo', 1) }, #=> "first: bar"
-
# Thread.new { puts "second: " << exchanger.exchange('bar', 1) } #=> "second: foo"
-
# ]
-
# threads.each {|t| t.join(2) }
-
#
-
# @!visibility private
-
1
class AbstractExchanger < Synchronization::Object
-
-
# @!visibility private
-
1
CANCEL = Object.new
-
1
private_constant :CANCEL
-
-
# @!macro [attach] exchanger_method_initialize
-
1
def initialize
-
super
-
end
-
-
# @!macro [attach] exchanger_method_do_exchange
-
#
-
# Waits for another thread to arrive at this exchange point (unless the
-
# current thread is interrupted), and then transfers the given object to
-
# it, receiving its object in return. The timeout value indicates the
-
# approximate number of seconds the method should block while waiting
-
# for the exchange. When the timeout value is `nil` the method will
-
# block indefinitely.
-
#
-
# @param [Object] value the value to exchange with another thread
-
# @param [Numeric, nil] timeout in seconds, `nil` blocks indefinitely
-
#
-
# @!macro [attach] exchanger_method_exchange
-
#
-
# In some edge cases when a `timeout` is given a return value of `nil` may be
-
# ambiguous. Specifically, if `nil` is a valid value in the exchange it will
-
# be impossible to tell whether `nil` is the actual return value or if it
-
# signifies timeout. When `nil` is a valid value in the exchange consider
-
# using {#exchange!} or {#try_exchange} instead.
-
#
-
# @return [Object] the value exchanged by the other thread or `nil` on timeout
-
1
def exchange(value, timeout = nil)
-
(value = do_exchange(value, timeout)) == CANCEL ? nil : value
-
end
-
-
# @!macro exchanger_method_do_exchange
-
#
-
# @!macro [attach] exchanger_method_exchange_bang
-
#
-
# On timeout a {Concurrent::TimeoutError} exception will be raised.
-
#
-
# @return [Object] the value exchanged by the other thread
-
# @raise [Concurrent::TimeoutError] on timeout
-
1
def exchange!(value, timeout = nil)
-
if (value = do_exchange(value, timeout)) == CANCEL
-
raise Concurrent::TimeoutError
-
else
-
value
-
end
-
end
-
-
# @!macro exchanger_method_do_exchange
-
#
-
# @!macro [attach] exchanger_method_try_exchange
-
#
-
# The return value will be a {Concurrent::Maybe} set to `Just` on success or
-
# `Nothing` on timeout.
-
#
-
# @return [Concurrent::Maybe] on success a `Just` maybe will be returned with
-
# the item exchanged by the other thread as `#value`; on timeout a
-
# `Nothing` maybe will be returned with {Concurrent::TimeoutError} as `#reason`
-
#
-
# @example
-
#
-
# exchanger = Concurrent::Exchanger.new
-
#
-
# result = exchanger.exchange(:foo, 0.5)
-
#
-
# if result.just?
-
# puts result.value #=> :bar
-
# else
-
# puts 'timeout'
-
# end
-
1
def try_exchange(value, timeout = nil)
-
if (value = do_exchange(value, timeout)) == CANCEL
-
Concurrent::Maybe.nothing(Concurrent::TimeoutError)
-
else
-
Concurrent::Maybe.just(value)
-
end
-
end
-
-
1
private
-
-
# @!macro exchanger_method_do_exchange
-
#
-
# @return [Object, CANCEL] the value exchanged by the other thread; {CANCEL} on timeout
-
1
def do_exchange(value, timeout)
-
raise NotImplementedError
-
end
-
end
-
-
# @!macro exchanger
-
# @!macro internal_implementation_note
-
# @!visibility private
-
1
class RubyExchanger < AbstractExchanger
-
# A simplified version of java.util.concurrent.Exchanger written by
-
# Doug Lea, Bill Scherer, and Michael Scott with assistance from members
-
# of JCP JSR-166 Expert Group and released to the public domain. It does
-
# not include the arena or the multi-processor spin loops.
-
# http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/Exchanger.java
-
-
1
safe_initialization!
-
-
1
class Node < Concurrent::Synchronization::Object
-
1
attr_atomic :value
-
1
safe_initialization!
-
-
1
def initialize(item)
-
super()
-
@Item = item
-
@Latch = Concurrent::CountDownLatch.new
-
self.value = nil
-
end
-
-
1
def latch
-
@Latch
-
end
-
-
1
def item
-
@Item
-
end
-
end
-
1
private_constant :Node
-
-
# @!macro exchanger_method_initialize
-
1
def initialize
-
super
-
end
-
-
1
private
-
-
1
attr_atomic(:slot)
-
-
# @!macro exchanger_method_do_exchange
-
#
-
# @return [Object, CANCEL] the value exchanged by the other thread; {CANCEL} on timeout
-
1
def do_exchange(value, timeout)
-
-
# ALGORITHM
-
#
-
# From the original Java version:
-
#
-
# > The basic idea is to maintain a "slot", which is a reference to
-
# > a Node containing both an Item to offer and a "hole" waiting to
-
# > get filled in. If an incoming "occupying" thread sees that the
-
# > slot is null, it CAS'es (compareAndSets) a Node there and waits
-
# > for another to invoke exchange. That second "fulfilling" thread
-
# > sees that the slot is non-null, and so CASes it back to null,
-
# > also exchanging items by CASing the hole, plus waking up the
-
# > occupying thread if it is blocked. In each case CAS'es may
-
# > fail because a slot at first appears non-null but is null upon
-
# > CAS, or vice-versa. So threads may need to retry these
-
# > actions.
-
#
-
# This version:
-
#
-
# An exchange occurs between an "occupier" thread and a "fulfiller" thread.
-
# The "slot" is used to setup this interaction. The first thread in the
-
# exchange puts itself into the slot (occupies) and waits for a fulfiller.
-
# The second thread removes the occupier from the slot and attempts to
-
# perform the exchange. Removing the occupier also frees the slot for
-
# another occupier/fulfiller pair.
-
#
-
# Because the occupier and the fulfiller are operating independently and
-
# because there may be contention with other threads, any failed operation
-
# indicates contention. Both the occupier and the fulfiller operate within
-
# spin loops. Any failed actions along the happy path will cause the thread
-
# to repeat the loop and try again.
-
#
-
# When a timeout value is given the thread must be cognizant of time spent
-
# in the spin loop. The remaining time is checked every loop. When the time
-
# runs out the thread will exit.
-
#
-
# A "node" is the data structure used to perform the exchange. Only the
-
# occupier's node is necessary. It's the node used for the exchange.
-
# Each node has an "item," a "hole" (self), and a "latch." The item is the
-
# node's initial value. It never changes. It's what the fulfiller returns on
-
# success. The occupier's hole is where the fulfiller put its item. It's the
-
# item that the occupier returns on success. The latch is used for synchronization.
-
# Becuase a thread may act as either an occupier or fulfiller (or possibly
-
# both in periods of high contention) every thread creates a node when
-
# the exchange method is first called.
-
#
-
# The following steps occur within the spin loop. If any actions fail
-
# the thread will loop and try again, so long as there is time remaining.
-
# If time runs out the thread will return CANCEL.
-
#
-
# Check the slot for an occupier:
-
#
-
# * If the slot is empty try to occupy
-
# * If the slot is full try to fulfill
-
#
-
# Attempt to occupy:
-
#
-
# * Attempt to CAS myself into the slot
-
# * Go to sleep and wait to be woken by a fulfiller
-
# * If the sleep is successful then the fulfiller completed its happy path
-
# - Return the value from my hole (the value given by the fulfiller)
-
# * When the sleep fails (time ran out) attempt to cancel the operation
-
# - Attempt to CAS myself out of the hole
-
# - If successful there is no contention
-
# - Return CANCEL
-
# - On failure, I am competing with a fulfiller
-
# - Attempt to CAS my hole to CANCEL
-
# - On success
-
# - Let the fulfiller deal with my cancel
-
# - Return CANCEL
-
# - On failure the fulfiller has completed its happy path
-
# - Return th value from my hole (the fulfiller's value)
-
#
-
# Attempt to fulfill:
-
#
-
# * Attempt to CAS the occupier out of the slot
-
# - On failure loop again
-
# * Attempt to CAS my item into the occupier's hole
-
# - On failure the occupier is trying to cancel
-
# - Loop again
-
# - On success we are on the happy path
-
# - Wake the sleeping occupier
-
# - Return the occupier's item
-
-
value = NULL if value.nil? # The sentinel allows nil to be a valid value
-
me = Node.new(value) # create my node in case I need to occupy
-
end_at = Concurrent.monotonic_time + timeout.to_f # The time to give up
-
-
result = loop do
-
other = slot
-
if other && compare_and_set_slot(other, nil)
-
# try to fulfill
-
if other.compare_and_set_value(nil, value)
-
# happy path
-
other.latch.count_down
-
break other.item
-
end
-
elsif other.nil? && compare_and_set_slot(nil, me)
-
# try to occupy
-
timeout = end_at - Concurrent.monotonic_time if timeout
-
if me.latch.wait(timeout)
-
# happy path
-
break me.value
-
else
-
# attempt to remove myself from the slot
-
if compare_and_set_slot(me, nil)
-
break CANCEL
-
elsif !me.compare_and_set_value(nil, CANCEL)
-
# I've failed to block the fulfiller
-
break me.value
-
end
-
end
-
end
-
break CANCEL if timeout && Concurrent.monotonic_time >= end_at
-
end
-
-
result == NULL ? nil : result
-
end
-
end
-
-
1
if Concurrent.on_jruby?
-
-
# @!macro exchanger
-
# @!macro internal_implementation_note
-
# @!visibility private
-
class JavaExchanger < AbstractExchanger
-
-
# @!macro exchanger_method_initialize
-
def initialize
-
@exchanger = java.util.concurrent.Exchanger.new
-
end
-
-
private
-
-
# @!macro exchanger_method_do_exchange
-
#
-
# @return [Object, CANCEL] the value exchanged by the other thread; {CANCEL} on timeout
-
def do_exchange(value, timeout)
-
if timeout.nil?
-
@exchanger.exchange(value)
-
else
-
@exchanger.exchange(value, 1000 * timeout, java.util.concurrent.TimeUnit::MILLISECONDS)
-
end
-
rescue java.util.concurrent.TimeoutException
-
CANCEL
-
end
-
end
-
end
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
ExchangerImplementation = case
-
when Concurrent.on_jruby?
-
JavaExchanger
-
else
-
1
RubyExchanger
-
end
-
1
private_constant :ExchangerImplementation
-
-
# @!macro exchanger
-
1
class Exchanger < ExchangerImplementation
-
-
# @!method initialize
-
# @!macro exchanger_method_initialize
-
-
# @!method exchange(value, timeout = nil)
-
# @!macro exchanger_method_do_exchange
-
# @!macro exchanger_method_exchange
-
-
# @!method exchange!(value, timeout = nil)
-
# @!macro exchanger_method_do_exchange
-
# @!macro exchanger_method_exchange_bang
-
-
# @!method try_exchange(value, timeout = nil)
-
# @!macro exchanger_method_do_exchange
-
# @!macro exchanger_method_try_exchange
-
end
-
end
-
1
require 'concurrent/utility/engine'
-
1
require 'concurrent/executor/thread_pool_executor'
-
-
1
module Concurrent
-
-
# A thread pool that dynamically grows and shrinks to fit the current workload.
-
# New threads are created as needed, existing threads are reused, and threads
-
# that remain idle for too long are killed and removed from the pool. These
-
# pools are particularly suited to applications that perform a high volume of
-
# short-lived tasks.
-
#
-
# On creation a `CachedThreadPool` has zero running threads. New threads are
-
# created on the pool as new operations are `#post`. The size of the pool
-
# will grow until `#max_length` threads are in the pool or until the number
-
# of threads exceeds the number of running and pending operations. When a new
-
# operation is post to the pool the first available idle thread will be tasked
-
# with the new operation.
-
#
-
# Should a thread crash for any reason the thread will immediately be removed
-
# from the pool. Similarly, threads which remain idle for an extended period
-
# of time will be killed and reclaimed. Thus these thread pools are very
-
# efficient at reclaiming unused resources.
-
#
-
# The API and behavior of this class are based on Java's `CachedThreadPool`
-
#
-
# @!macro thread_pool_options
-
1
class CachedThreadPool < ThreadPoolExecutor
-
-
# @!macro [attach] cached_thread_pool_method_initialize
-
#
-
# Create a new thread pool.
-
#
-
# @param [Hash] opts the options defining pool behavior.
-
# @option opts [Symbol] :fallback_policy (`:abort`) the fallback policy
-
#
-
# @raise [ArgumentError] if `fallback_policy` is not a known policy
-
#
-
# @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool--
-
1
def initialize(opts = {})
-
defaults = { idletime: DEFAULT_THREAD_IDLETIMEOUT }
-
overrides = { min_threads: 0,
-
max_threads: DEFAULT_MAX_POOL_SIZE,
-
max_queue: DEFAULT_MAX_QUEUE_SIZE }
-
super(defaults.merge(opts).merge(overrides))
-
end
-
-
1
private
-
-
# @!macro cached_thread_pool_method_initialize
-
# @!visibility private
-
1
def ns_initialize(opts)
-
super(opts)
-
if Concurrent.on_jruby?
-
@max_queue = 0
-
@executor = java.util.concurrent.Executors.newCachedThreadPool
-
@executor.setRejectedExecutionHandler(FALLBACK_POLICY_CLASSES[@fallback_policy].new)
-
@executor.setKeepAliveTime(opts.fetch(:idletime, DEFAULT_THREAD_IDLETIMEOUT), java.util.concurrent.TimeUnit::SECONDS)
-
self.auto_terminate = opts.fetch(:auto_terminate, true)
-
end
-
end
-
end
-
end
-
1
require 'concurrent/atomic/event'
-
1
require 'concurrent/executor/abstract_executor_service'
-
1
require 'concurrent/executor/serial_executor_service'
-
-
1
module Concurrent
-
-
# An executor service which runs all operations on the current thread,
-
# blocking as necessary. Operations are performed in the order they are
-
# received and no two operations can be performed simultaneously.
-
#
-
# This executor service exists mainly for testing an debugging. When used
-
# it immediately runs every `#post` operation on the current thread, blocking
-
# that thread until the operation is complete. This can be very beneficial
-
# during testing because it makes all operations deterministic.
-
#
-
# @note Intended for use primarily in testing and debugging.
-
1
class ImmediateExecutor < AbstractExecutorService
-
1
include SerialExecutorService
-
-
# Creates a new executor
-
1
def initialize
-
1
@stopped = Concurrent::Event.new
-
end
-
-
# @!macro executor_service_method_post
-
1
def post(*args, &task)
-
raise ArgumentError.new('no block given') unless block_given?
-
return false unless running?
-
task.call(*args)
-
true
-
end
-
-
# @!macro executor_service_method_left_shift
-
1
def <<(task)
-
post(&task)
-
self
-
end
-
-
# @!macro executor_service_method_running_question
-
1
def running?
-
! shutdown?
-
end
-
-
# @!macro executor_service_method_shuttingdown_question
-
1
def shuttingdown?
-
false
-
end
-
-
# @!macro executor_service_method_shutdown_question
-
1
def shutdown?
-
@stopped.set?
-
end
-
-
# @!macro executor_service_method_shutdown
-
1
def shutdown
-
@stopped.set
-
true
-
end
-
1
alias_method :kill, :shutdown
-
-
# @!macro executor_service_method_wait_for_termination
-
1
def wait_for_termination(timeout = nil)
-
@stopped.wait(timeout)
-
end
-
end
-
end
-
1
require 'concurrent/executor/immediate_executor'
-
1
require 'concurrent/executor/simple_executor_service'
-
-
1
module Concurrent
-
# An executor service which runs all operations on a new thread, blocking
-
# until it completes. Operations are performed in the order they are received
-
# and no two operations can be performed simultaneously.
-
#
-
# This executor service exists mainly for testing an debugging. When used it
-
# immediately runs every `#post` operation on a new thread, blocking the
-
# current thread until the operation is complete. This is similar to how the
-
# ImmediateExecutor works, but the operation has the full stack of the new
-
# thread at its disposal. This can be helpful when the operations will spawn
-
# more operations on the same executor and so on - such a situation might
-
# overflow the single stack in case of an ImmediateExecutor, which is
-
# inconsistent with how it would behave for a threaded executor.
-
#
-
# @note Intended for use primarily in testing and debugging.
-
1
class IndirectImmediateExecutor < ImmediateExecutor
-
# Creates a new executor
-
1
def initialize
-
super
-
@internal_executor = SimpleExecutorService.new
-
end
-
-
# @!macro executor_service_method_post
-
1
def post(*args, &task)
-
raise ArgumentError.new("no block given") unless block_given?
-
return false unless running?
-
-
event = Concurrent::Event.new
-
@internal_executor.post do
-
begin
-
task.call(*args)
-
ensure
-
event.set
-
end
-
end
-
event.wait
-
-
true
-
end
-
end
-
end
-
1
if Concurrent.on_jruby?
-
-
require 'concurrent/errors'
-
require 'concurrent/utility/engine'
-
require 'concurrent/executor/abstract_executor_service'
-
-
module Concurrent
-
-
# @!macro abstract_executor_service_public_api
-
# @!visibility private
-
class JavaExecutorService < AbstractExecutorService
-
java_import 'java.lang.Runnable'
-
-
FALLBACK_POLICY_CLASSES = {
-
abort: java.util.concurrent.ThreadPoolExecutor::AbortPolicy,
-
discard: java.util.concurrent.ThreadPoolExecutor::DiscardPolicy,
-
caller_runs: java.util.concurrent.ThreadPoolExecutor::CallerRunsPolicy
-
}.freeze
-
private_constant :FALLBACK_POLICY_CLASSES
-
-
def initialize(*args, &block)
-
super
-
ns_make_executor_runnable
-
end
-
-
def post(*args, &task)
-
raise ArgumentError.new('no block given') unless block_given?
-
return handle_fallback(*args, &task) unless running?
-
@executor.submit_runnable Job.new(args, task)
-
true
-
rescue Java::JavaUtilConcurrent::RejectedExecutionException
-
raise RejectedExecutionError
-
end
-
-
def wait_for_termination(timeout = nil)
-
if timeout.nil?
-
ok = @executor.awaitTermination(60, java.util.concurrent.TimeUnit::SECONDS) until ok
-
true
-
else
-
@executor.awaitTermination(1000 * timeout, java.util.concurrent.TimeUnit::MILLISECONDS)
-
end
-
end
-
-
def shutdown
-
synchronize do
-
self.ns_auto_terminate = false
-
@executor.shutdown
-
nil
-
end
-
end
-
-
def kill
-
synchronize do
-
self.ns_auto_terminate = false
-
@executor.shutdownNow
-
nil
-
end
-
end
-
-
private
-
-
def ns_running?
-
!(ns_shuttingdown? || ns_shutdown?)
-
end
-
-
def ns_shuttingdown?
-
if @executor.respond_to? :isTerminating
-
@executor.isTerminating
-
else
-
false
-
end
-
end
-
-
def ns_shutdown?
-
@executor.isShutdown || @executor.isTerminated
-
end
-
-
def ns_make_executor_runnable
-
if !defined?(@executor.submit_runnable)
-
@executor.class.class_eval do
-
java_alias :submit_runnable, :submit, [java.lang.Runnable.java_class]
-
end
-
end
-
end
-
-
class Job
-
include Runnable
-
def initialize(args, block)
-
@args = args
-
@block = block
-
end
-
-
def run
-
@block.call(*@args)
-
end
-
end
-
private_constant :Job
-
end
-
end
-
end
-
1
if Concurrent.on_jruby?
-
-
require 'concurrent/executor/java_executor_service'
-
require 'concurrent/executor/serial_executor_service'
-
-
module Concurrent
-
-
# @!macro single_thread_executor
-
# @!macro abstract_executor_service_public_api
-
# @!visibility private
-
class JavaSingleThreadExecutor < JavaExecutorService
-
include SerialExecutorService
-
-
# @!macro single_thread_executor_method_initialize
-
def initialize(opts = {})
-
super(opts)
-
end
-
-
private
-
-
def ns_initialize(opts)
-
@executor = java.util.concurrent.Executors.newSingleThreadExecutor
-
@fallback_policy = opts.fetch(:fallback_policy, :discard)
-
raise ArgumentError.new("#{@fallback_policy} is not a valid fallback policy") unless FALLBACK_POLICY_CLASSES.keys.include?(@fallback_policy)
-
self.auto_terminate = opts.fetch(:auto_terminate, true)
-
end
-
end
-
end
-
end
-
1
if Concurrent.on_jruby?
-
-
require 'concurrent/executor/java_executor_service'
-
-
module Concurrent
-
-
# @!macro thread_pool_executor
-
# @!macro thread_pool_options
-
# @!visibility private
-
class JavaThreadPoolExecutor < JavaExecutorService
-
-
# @!macro thread_pool_executor_constant_default_max_pool_size
-
DEFAULT_MAX_POOL_SIZE = java.lang.Integer::MAX_VALUE # 2147483647
-
-
# @!macro thread_pool_executor_constant_default_min_pool_size
-
DEFAULT_MIN_POOL_SIZE = 0
-
-
# @!macro thread_pool_executor_constant_default_max_queue_size
-
DEFAULT_MAX_QUEUE_SIZE = 0
-
-
# @!macro thread_pool_executor_constant_default_thread_timeout
-
DEFAULT_THREAD_IDLETIMEOUT = 60
-
-
# @!macro thread_pool_executor_attr_reader_max_length
-
attr_reader :max_length
-
-
# @!macro thread_pool_executor_attr_reader_max_queue
-
attr_reader :max_queue
-
-
# @!macro thread_pool_executor_method_initialize
-
def initialize(opts = {})
-
super(opts)
-
end
-
-
# @!macro executor_service_method_can_overflow_question
-
def can_overflow?
-
@max_queue != 0
-
end
-
-
# @!macro thread_pool_executor_attr_reader_min_length
-
def min_length
-
@executor.getCorePoolSize
-
end
-
-
# @!macro thread_pool_executor_attr_reader_max_length
-
def max_length
-
@executor.getMaximumPoolSize
-
end
-
-
# @!macro thread_pool_executor_attr_reader_length
-
def length
-
@executor.getPoolSize
-
end
-
-
# @!macro thread_pool_executor_attr_reader_largest_length
-
def largest_length
-
@executor.getLargestPoolSize
-
end
-
-
# @!macro thread_pool_executor_attr_reader_scheduled_task_count
-
def scheduled_task_count
-
@executor.getTaskCount
-
end
-
-
# @!macro thread_pool_executor_attr_reader_completed_task_count
-
def completed_task_count
-
@executor.getCompletedTaskCount
-
end
-
-
# @!macro thread_pool_executor_attr_reader_idletime
-
def idletime
-
@executor.getKeepAliveTime(java.util.concurrent.TimeUnit::SECONDS)
-
end
-
-
# @!macro thread_pool_executor_attr_reader_queue_length
-
def queue_length
-
@executor.getQueue.size
-
end
-
-
# @!macro thread_pool_executor_attr_reader_remaining_capacity
-
def remaining_capacity
-
@max_queue == 0 ? -1 : @executor.getQueue.remainingCapacity
-
end
-
-
# @!macro executor_service_method_running_question
-
def running?
-
super && !@executor.isTerminating
-
end
-
-
private
-
-
def ns_initialize(opts)
-
min_length = opts.fetch(:min_threads, DEFAULT_MIN_POOL_SIZE).to_i
-
max_length = opts.fetch(:max_threads, DEFAULT_MAX_POOL_SIZE).to_i
-
idletime = opts.fetch(:idletime, DEFAULT_THREAD_IDLETIMEOUT).to_i
-
@max_queue = opts.fetch(:max_queue, DEFAULT_MAX_QUEUE_SIZE).to_i
-
@fallback_policy = opts.fetch(:fallback_policy, :abort)
-
-
raise ArgumentError.new("`max_threads` cannot be less than #{DEFAULT_MIN_POOL_SIZE}") if max_length < DEFAULT_MIN_POOL_SIZE
-
raise ArgumentError.new("`max_threads` cannot be greater than #{DEFAULT_MAX_POOL_SIZE}") if max_length > DEFAULT_MAX_POOL_SIZE
-
raise ArgumentError.new("`min_threads` cannot be less than #{DEFAULT_MIN_POOL_SIZE}") if min_length < DEFAULT_MIN_POOL_SIZE
-
raise ArgumentError.new("`min_threads` cannot be more than `max_threads`") if min_length > max_length
-
raise ArgumentError.new("#{fallback_policy} is not a valid fallback policy") unless FALLBACK_POLICY_CLASSES.include?(@fallback_policy)
-
-
if @max_queue == 0
-
queue = java.util.concurrent.LinkedBlockingQueue.new
-
else
-
queue = java.util.concurrent.LinkedBlockingQueue.new(@max_queue)
-
end
-
-
@executor = java.util.concurrent.ThreadPoolExecutor.new(
-
min_length, max_length,
-
idletime, java.util.concurrent.TimeUnit::SECONDS,
-
queue, FALLBACK_POLICY_CLASSES[@fallback_policy].new)
-
-
self.auto_terminate = opts.fetch(:auto_terminate, true)
-
end
-
end
-
end
-
end
-
1
require 'concurrent/executor/abstract_executor_service'
-
1
require 'concurrent/atomic/event'
-
-
1
module Concurrent
-
-
# @!macro abstract_executor_service_public_api
-
# @!visibility private
-
1
class RubyExecutorService < AbstractExecutorService
-
1
safe_initialization!
-
-
1
def initialize(*args, &block)
-
super
-
@StopEvent = Event.new
-
@StoppedEvent = Event.new
-
end
-
-
1
def post(*args, &task)
-
raise ArgumentError.new('no block given') unless block_given?
-
synchronize do
-
# If the executor is shut down, reject this task
-
return handle_fallback(*args, &task) unless running?
-
ns_execute(*args, &task)
-
true
-
end
-
end
-
-
1
def shutdown
-
synchronize do
-
break unless running?
-
self.ns_auto_terminate = false
-
stop_event.set
-
ns_shutdown_execution
-
end
-
true
-
end
-
-
1
def kill
-
synchronize do
-
break if shutdown?
-
self.ns_auto_terminate = false
-
stop_event.set
-
ns_kill_execution
-
stopped_event.set
-
end
-
true
-
end
-
-
1
def wait_for_termination(timeout = nil)
-
stopped_event.wait(timeout)
-
end
-
-
1
private
-
-
1
def stop_event
-
@StopEvent
-
end
-
-
1
def stopped_event
-
@StoppedEvent
-
end
-
-
1
def ns_shutdown_execution
-
stopped_event.set
-
end
-
-
1
def ns_running?
-
!stop_event.set?
-
end
-
-
1
def ns_shuttingdown?
-
!(ns_running? || ns_shutdown?)
-
end
-
-
1
def ns_shutdown?
-
stopped_event.set?
-
end
-
end
-
end
-
1
require 'concurrent/executor/ruby_thread_pool_executor'
-
-
1
module Concurrent
-
-
# @!macro single_thread_executor
-
# @!macro abstract_executor_service_public_api
-
# @!visibility private
-
1
class RubySingleThreadExecutor < RubyThreadPoolExecutor
-
-
# @!macro single_thread_executor_method_initialize
-
1
def initialize(opts = {})
-
super(
-
min_threads: 1,
-
max_threads: 1,
-
max_queue: 0,
-
idletime: DEFAULT_THREAD_IDLETIMEOUT,
-
fallback_policy: opts.fetch(:fallback_policy, :discard),
-
auto_terminate: opts.fetch(:auto_terminate, true)
-
)
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'concurrent/atomic/event'
-
1
require 'concurrent/concern/logging'
-
1
require 'concurrent/executor/ruby_executor_service'
-
1
require 'concurrent/utility/monotonic_time'
-
-
1
module Concurrent
-
-
# @!macro thread_pool_executor
-
# @!macro thread_pool_options
-
# @!visibility private
-
1
class RubyThreadPoolExecutor < RubyExecutorService
-
-
# @!macro thread_pool_executor_constant_default_max_pool_size
-
1
DEFAULT_MAX_POOL_SIZE = 2_147_483_647 # java.lang.Integer::MAX_VALUE
-
-
# @!macro thread_pool_executor_constant_default_min_pool_size
-
1
DEFAULT_MIN_POOL_SIZE = 0
-
-
# @!macro thread_pool_executor_constant_default_max_queue_size
-
1
DEFAULT_MAX_QUEUE_SIZE = 0
-
-
# @!macro thread_pool_executor_constant_default_thread_timeout
-
1
DEFAULT_THREAD_IDLETIMEOUT = 60
-
-
# @!macro thread_pool_executor_attr_reader_max_length
-
1
attr_reader :max_length
-
-
# @!macro thread_pool_executor_attr_reader_min_length
-
1
attr_reader :min_length
-
-
# @!macro thread_pool_executor_attr_reader_idletime
-
1
attr_reader :idletime
-
-
# @!macro thread_pool_executor_attr_reader_max_queue
-
1
attr_reader :max_queue
-
-
# @!macro thread_pool_executor_method_initialize
-
1
def initialize(opts = {})
-
super(opts)
-
end
-
-
# @!macro thread_pool_executor_attr_reader_largest_length
-
1
def largest_length
-
synchronize { @largest_length }
-
end
-
-
# @!macro thread_pool_executor_attr_reader_scheduled_task_count
-
1
def scheduled_task_count
-
synchronize { @scheduled_task_count }
-
end
-
-
# @!macro thread_pool_executor_attr_reader_completed_task_count
-
1
def completed_task_count
-
synchronize { @completed_task_count }
-
end
-
-
# @!macro executor_service_method_can_overflow_question
-
1
def can_overflow?
-
synchronize { ns_limited_queue? }
-
end
-
-
# @!macro thread_pool_executor_attr_reader_length
-
1
def length
-
synchronize { @pool.length }
-
end
-
-
# @!macro thread_pool_executor_attr_reader_queue_length
-
1
def queue_length
-
synchronize { @queue.length }
-
end
-
-
# @!macro thread_pool_executor_attr_reader_remaining_capacity
-
1
def remaining_capacity
-
synchronize do
-
if ns_limited_queue?
-
@max_queue - @queue.length
-
else
-
-1
-
end
-
end
-
end
-
-
# @!visibility private
-
1
def remove_busy_worker(worker)
-
synchronize { ns_remove_busy_worker worker }
-
end
-
-
# @!visibility private
-
1
def ready_worker(worker)
-
synchronize { ns_ready_worker worker }
-
end
-
-
# @!visibility private
-
1
def worker_not_old_enough(worker)
-
synchronize { ns_worker_not_old_enough worker }
-
end
-
-
# @!visibility private
-
1
def worker_died(worker)
-
synchronize { ns_worker_died worker }
-
end
-
-
# @!visibility private
-
1
def worker_task_completed
-
synchronize { @completed_task_count += 1 }
-
end
-
-
1
private
-
-
# @!visibility private
-
1
def ns_initialize(opts)
-
@min_length = opts.fetch(:min_threads, DEFAULT_MIN_POOL_SIZE).to_i
-
@max_length = opts.fetch(:max_threads, DEFAULT_MAX_POOL_SIZE).to_i
-
@idletime = opts.fetch(:idletime, DEFAULT_THREAD_IDLETIMEOUT).to_i
-
@max_queue = opts.fetch(:max_queue, DEFAULT_MAX_QUEUE_SIZE).to_i
-
@fallback_policy = opts.fetch(:fallback_policy, :abort)
-
raise ArgumentError.new("#{@fallback_policy} is not a valid fallback policy") unless FALLBACK_POLICIES.include?(@fallback_policy)
-
-
raise ArgumentError.new("`max_threads` cannot be less than #{DEFAULT_MIN_POOL_SIZE}") if @max_length < DEFAULT_MIN_POOL_SIZE
-
raise ArgumentError.new("`max_threads` cannot be greater than #{DEFAULT_MAX_POOL_SIZE}") if @max_length > DEFAULT_MAX_POOL_SIZE
-
raise ArgumentError.new("`min_threads` cannot be less than #{DEFAULT_MIN_POOL_SIZE}") if @min_length < DEFAULT_MIN_POOL_SIZE
-
raise ArgumentError.new("`min_threads` cannot be more than `max_threads`") if min_length > max_length
-
-
self.auto_terminate = opts.fetch(:auto_terminate, true)
-
-
@pool = [] # all workers
-
@ready = [] # used as a stash (most idle worker is at the start)
-
@queue = [] # used as queue
-
# @ready or @queue is empty at all times
-
@scheduled_task_count = 0
-
@completed_task_count = 0
-
@largest_length = 0
-
@ruby_pid = $$ # detects if Ruby has forked
-
-
@gc_interval = opts.fetch(:gc_interval, @idletime / 2.0).to_i # undocumented
-
@next_gc_time = Concurrent.monotonic_time + @gc_interval
-
end
-
-
# @!visibility private
-
1
def ns_limited_queue?
-
@max_queue != 0
-
end
-
-
# @!visibility private
-
1
def ns_execute(*args, &task)
-
ns_reset_if_forked
-
-
if ns_assign_worker(*args, &task) || ns_enqueue(*args, &task)
-
@scheduled_task_count += 1
-
else
-
handle_fallback(*args, &task)
-
end
-
-
ns_prune_pool if @next_gc_time < Concurrent.monotonic_time
-
end
-
-
# @!visibility private
-
1
def ns_shutdown_execution
-
ns_reset_if_forked
-
-
if @pool.empty?
-
# nothing to do
-
stopped_event.set
-
end
-
-
if @queue.empty?
-
# no more tasks will be accepted, just stop all workers
-
@pool.each(&:stop)
-
end
-
end
-
-
# @!visibility private
-
1
def ns_kill_execution
-
# TODO log out unprocessed tasks in queue
-
# TODO try to shutdown first?
-
@pool.each(&:kill)
-
@pool.clear
-
@ready.clear
-
end
-
-
# tries to assign task to a worker, tries to get one from @ready or to create new one
-
# @return [true, false] if task is assigned to a worker
-
#
-
# @!visibility private
-
1
def ns_assign_worker(*args, &task)
-
# keep growing if the pool is not at the minimum yet
-
worker = (@ready.pop if @pool.size >= @min_length) || ns_add_busy_worker
-
if worker
-
worker << [task, args]
-
true
-
else
-
false
-
end
-
rescue ThreadError
-
# Raised when the operating system refuses to create the new thread
-
return false
-
end
-
-
# tries to enqueue task
-
# @return [true, false] if enqueued
-
#
-
# @!visibility private
-
1
def ns_enqueue(*args, &task)
-
if !ns_limited_queue? || @queue.size < @max_queue
-
@queue << [task, args]
-
true
-
else
-
false
-
end
-
end
-
-
# @!visibility private
-
1
def ns_worker_died(worker)
-
ns_remove_busy_worker worker
-
replacement_worker = ns_add_busy_worker
-
ns_ready_worker replacement_worker, false if replacement_worker
-
end
-
-
# creates new worker which has to receive work to do after it's added
-
# @return [nil, Worker] nil of max capacity is reached
-
#
-
# @!visibility private
-
1
def ns_add_busy_worker
-
return if @pool.size >= @max_length
-
-
@pool << (worker = Worker.new(self))
-
@largest_length = @pool.length if @pool.length > @largest_length
-
worker
-
end
-
-
# handle ready worker, giving it new job or assigning back to @ready
-
#
-
# @!visibility private
-
1
def ns_ready_worker(worker, success = true)
-
task_and_args = @queue.shift
-
if task_and_args
-
worker << task_and_args
-
else
-
# stop workers when !running?, do not return them to @ready
-
if running?
-
@ready.push(worker)
-
else
-
worker.stop
-
end
-
end
-
end
-
-
# returns back worker to @ready which was not idle for enough time
-
#
-
# @!visibility private
-
1
def ns_worker_not_old_enough(worker)
-
# let's put workers coming from idle_test back to the start (as the oldest worker)
-
@ready.unshift(worker)
-
true
-
end
-
-
# removes a worker which is not in not tracked in @ready
-
#
-
# @!visibility private
-
1
def ns_remove_busy_worker(worker)
-
@pool.delete(worker)
-
stopped_event.set if @pool.empty? && !running?
-
true
-
end
-
-
# try oldest worker if it is idle for enough time, it's returned back at the start
-
#
-
# @!visibility private
-
1
def ns_prune_pool
-
return if @pool.size <= @min_length
-
-
last_used = @ready.shift
-
last_used << :idle_test if last_used
-
-
@next_gc_time = Concurrent.monotonic_time + @gc_interval
-
end
-
-
1
def ns_reset_if_forked
-
if $$ != @ruby_pid
-
@queue.clear
-
@ready.clear
-
@pool.clear
-
@scheduled_task_count = 0
-
@completed_task_count = 0
-
@largest_length = 0
-
@ruby_pid = $$
-
end
-
end
-
-
# @!visibility private
-
1
class Worker
-
1
include Concern::Logging
-
-
1
def initialize(pool)
-
# instance variables accessed only under pool's lock so no need to sync here again
-
@queue = Queue.new
-
@pool = pool
-
@thread = create_worker @queue, pool, pool.idletime
-
end
-
-
1
def <<(message)
-
@queue << message
-
end
-
-
1
def stop
-
@queue << :stop
-
end
-
-
1
def kill
-
@thread.kill
-
end
-
-
1
private
-
-
1
def create_worker(queue, pool, idletime)
-
Thread.new(queue, pool, idletime) do |my_queue, my_pool, my_idletime|
-
last_message = Concurrent.monotonic_time
-
catch(:stop) do
-
loop do
-
-
case message = my_queue.pop
-
when :idle_test
-
if (Concurrent.monotonic_time - last_message) > my_idletime
-
my_pool.remove_busy_worker(self)
-
throw :stop
-
else
-
my_pool.worker_not_old_enough(self)
-
end
-
-
when :stop
-
my_pool.remove_busy_worker(self)
-
throw :stop
-
-
else
-
task, args = message
-
run_task my_pool, task, args
-
last_message = Concurrent.monotonic_time
-
-
my_pool.ready_worker(self)
-
end
-
end
-
end
-
end
-
end
-
-
1
def run_task(pool, task, args)
-
task.call(*args)
-
pool.worker_task_completed
-
rescue => ex
-
# let it fail
-
log DEBUG, ex
-
rescue Exception => ex
-
log ERROR, ex
-
pool.worker_died(self)
-
throw :stop
-
end
-
end
-
-
1
private_constant :Worker
-
end
-
end
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# A simple utility class that executes a callable and returns and array of three elements:
-
# success - indicating if the callable has been executed without errors
-
# value - filled by the callable result if it has been executed without errors, nil otherwise
-
# reason - the error risen by the callable if it has been executed with errors, nil otherwise
-
1
class SafeTaskExecutor < Synchronization::LockableObject
-
-
1
def initialize(task, opts = {})
-
@task = task
-
@exception_class = opts.fetch(:rescue_exception, false) ? Exception : StandardError
-
super() # ensures visibility
-
end
-
-
# @return [Array]
-
1
def execute(*args)
-
synchronize do
-
success = false
-
value = reason = nil
-
-
begin
-
value = @task.call(*args)
-
success = true
-
rescue @exception_class => ex
-
reason = ex
-
success = false
-
end
-
-
[success, value, reason]
-
end
-
end
-
end
-
end
-
1
require 'concurrent/executor/executor_service'
-
-
1
module Concurrent
-
-
# Indicates that the including `ExecutorService` guarantees
-
# that all operations will occur in the order they are post and that no
-
# two operations may occur simultaneously. This module provides no
-
# functionality and provides no guarantees. That is the responsibility
-
# of the including class. This module exists solely to allow the including
-
# object to be interrogated for its serialization status.
-
#
-
# @example
-
# class Foo
-
# include Concurrent::SerialExecutor
-
# end
-
#
-
# foo = Foo.new
-
#
-
# foo.is_a? Concurrent::ExecutorService #=> true
-
# foo.is_a? Concurrent::SerialExecutor #=> true
-
# foo.serialized? #=> true
-
#
-
# @!visibility private
-
1
module SerialExecutorService
-
1
include ExecutorService
-
-
# @!macro executor_service_method_serialized_question
-
#
-
# @note Always returns `true`
-
1
def serialized?
-
true
-
end
-
end
-
end
-
1
require 'concurrent/errors'
-
1
require 'concurrent/concern/logging'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# Ensures passed jobs in a serialized order never running at the same time.
-
1
class SerializedExecution < Synchronization::LockableObject
-
1
include Concern::Logging
-
-
1
def initialize()
-
super()
-
synchronize { ns_initialize }
-
end
-
-
1
Job = Struct.new(:executor, :args, :block) do
-
1
def call
-
block.call(*args)
-
end
-
end
-
-
# Submit a task to the executor for asynchronous processing.
-
#
-
# @param [Executor] executor to be used for this job
-
#
-
# @param [Array] args zero or more arguments to be passed to the task
-
#
-
# @yield the asynchronous task to perform
-
#
-
# @return [Boolean] `true` if the task is queued, `false` if the executor
-
# is not running
-
#
-
# @raise [ArgumentError] if no task is given
-
1
def post(executor, *args, &task)
-
posts [[executor, args, task]]
-
true
-
end
-
-
# As {#post} but allows to submit multiple tasks at once, it's guaranteed that they will not
-
# be interleaved by other tasks.
-
#
-
# @param [Array<Array(ExecutorService, Array<Object>, Proc)>] posts array of triplets where
-
# first is a {ExecutorService}, second is array of args for task, third is a task (Proc)
-
1
def posts(posts)
-
# if can_overflow?
-
# raise ArgumentError, 'SerializedExecution does not support thread-pools which can overflow'
-
# end
-
-
return nil if posts.empty?
-
-
jobs = posts.map { |executor, args, task| Job.new executor, args, task }
-
-
job_to_post = synchronize do
-
if @being_executed
-
@stash.push(*jobs)
-
nil
-
else
-
@being_executed = true
-
@stash.push(*jobs[1..-1])
-
jobs.first
-
end
-
end
-
-
call_job job_to_post if job_to_post
-
true
-
end
-
-
1
private
-
-
1
def ns_initialize
-
@being_executed = false
-
@stash = []
-
end
-
-
1
def call_job(job)
-
did_it_run = begin
-
job.executor.post { work(job) }
-
true
-
rescue RejectedExecutionError => ex
-
false
-
end
-
-
# TODO not the best idea to run it myself
-
unless did_it_run
-
begin
-
work job
-
rescue => ex
-
# let it fail
-
log DEBUG, ex
-
end
-
end
-
end
-
-
# ensures next job is executed if any is stashed
-
1
def work(job)
-
job.call
-
ensure
-
synchronize do
-
job = @stash.shift || (@being_executed = false)
-
end
-
-
# TODO maybe be able to tell caching pool to just enqueue this job, because the current one end at the end
-
# of this block
-
call_job job if job
-
end
-
end
-
end
-
1
require 'delegate'
-
1
require 'concurrent/executor/serial_executor_service'
-
1
require 'concurrent/executor/serialized_execution'
-
-
1
module Concurrent
-
-
# A wrapper/delegator for any `ExecutorService` that
-
# guarantees serialized execution of tasks.
-
#
-
# @see [SimpleDelegator](http://www.ruby-doc.org/stdlib-2.1.2/libdoc/delegate/rdoc/SimpleDelegator.html)
-
# @see Concurrent::SerializedExecution
-
1
class SerializedExecutionDelegator < SimpleDelegator
-
1
include SerialExecutorService
-
-
1
def initialize(executor)
-
@executor = executor
-
@serializer = SerializedExecution.new
-
super(executor)
-
end
-
-
# @!macro executor_service_method_post
-
1
def post(*args, &task)
-
raise ArgumentError.new('no block given') unless block_given?
-
return false unless running?
-
@serializer.post(@executor, *args, &task)
-
end
-
end
-
end
-
1
require 'concurrent/atomics'
-
1
require 'concurrent/executor/executor_service'
-
-
1
module Concurrent
-
-
# An executor service in which every operation spawns a new,
-
# independently operating thread.
-
#
-
# This is perhaps the most inefficient executor service in this
-
# library. It exists mainly for testing an debugging. Thread creation
-
# and management is expensive in Ruby and this executor performs no
-
# resource pooling. This can be very beneficial during testing and
-
# debugging because it decouples the using code from the underlying
-
# executor implementation. In production this executor will likely
-
# lead to suboptimal performance.
-
#
-
# @note Intended for use primarily in testing and debugging.
-
1
class SimpleExecutorService < RubyExecutorService
-
-
# @!macro executor_service_method_post
-
1
def self.post(*args)
-
raise ArgumentError.new('no block given') unless block_given?
-
Thread.new(*args) do
-
Thread.current.abort_on_exception = false
-
yield(*args)
-
end
-
true
-
end
-
-
# @!macro executor_service_method_left_shift
-
1
def self.<<(task)
-
post(&task)
-
self
-
end
-
-
# @!macro executor_service_method_post
-
1
def post(*args, &task)
-
raise ArgumentError.new('no block given') unless block_given?
-
return false unless running?
-
@count.increment
-
Thread.new(*args) do
-
Thread.current.abort_on_exception = false
-
begin
-
yield(*args)
-
ensure
-
@count.decrement
-
@stopped.set if @running.false? && @count.value == 0
-
end
-
end
-
end
-
-
# @!macro executor_service_method_left_shift
-
1
def <<(task)
-
post(&task)
-
self
-
end
-
-
# @!macro executor_service_method_running_question
-
1
def running?
-
@running.true?
-
end
-
-
# @!macro executor_service_method_shuttingdown_question
-
1
def shuttingdown?
-
@running.false? && ! @stopped.set?
-
end
-
-
# @!macro executor_service_method_shutdown_question
-
1
def shutdown?
-
@stopped.set?
-
end
-
-
# @!macro executor_service_method_shutdown
-
1
def shutdown
-
@running.make_false
-
@stopped.set if @count.value == 0
-
true
-
end
-
-
# @!macro executor_service_method_kill
-
1
def kill
-
@running.make_false
-
@stopped.set
-
true
-
end
-
-
# @!macro executor_service_method_wait_for_termination
-
1
def wait_for_termination(timeout = nil)
-
@stopped.wait(timeout)
-
end
-
-
1
private
-
-
1
def ns_initialize
-
@running = Concurrent::AtomicBoolean.new(true)
-
@stopped = Concurrent::Event.new
-
@count = Concurrent::AtomicFixnum.new(0)
-
end
-
end
-
end
-
1
require 'concurrent/executor/ruby_single_thread_executor'
-
-
1
module Concurrent
-
-
1
if Concurrent.on_jruby?
-
require 'concurrent/executor/java_single_thread_executor'
-
end
-
-
1
SingleThreadExecutorImplementation = case
-
when Concurrent.on_jruby?
-
JavaSingleThreadExecutor
-
else
-
1
RubySingleThreadExecutor
-
end
-
1
private_constant :SingleThreadExecutorImplementation
-
-
# @!macro [attach] single_thread_executor
-
#
-
# A thread pool with a single thread an unlimited queue. Should the thread
-
# die for any reason it will be removed and replaced, thus ensuring that
-
# the executor will always remain viable and available to process jobs.
-
#
-
# A common pattern for background processing is to create a single thread
-
# on which an infinite loop is run. The thread's loop blocks on an input
-
# source (perhaps blocking I/O or a queue) and processes each input as it
-
# is received. This pattern has several issues. The thread itself is highly
-
# susceptible to errors during processing. Also, the thread itself must be
-
# constantly monitored and restarted should it die. `SingleThreadExecutor`
-
# encapsulates all these bahaviors. The task processor is highly resilient
-
# to errors from within tasks. Also, should the thread die it will
-
# automatically be restarted.
-
#
-
# The API and behavior of this class are based on Java's `SingleThreadExecutor`.
-
#
-
# @!macro abstract_executor_service_public_api
-
1
class SingleThreadExecutor < SingleThreadExecutorImplementation
-
-
# @!macro [new] single_thread_executor_method_initialize
-
#
-
# Create a new thread pool.
-
#
-
# @option opts [Symbol] :fallback_policy (:discard) the policy for handling new
-
# tasks that are received when the queue size has reached
-
# `max_queue` or the executor has shut down
-
#
-
# @raise [ArgumentError] if `:fallback_policy` is not one of the values specified
-
# in `FALLBACK_POLICIES`
-
#
-
# @see http://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html
-
# @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html
-
# @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html
-
-
# @!method initialize(opts = {})
-
# @!macro single_thread_executor_method_initialize
-
end
-
end
-
1
require 'concurrent/utility/engine'
-
1
require 'concurrent/executor/ruby_thread_pool_executor'
-
-
1
module Concurrent
-
-
1
if Concurrent.on_jruby?
-
require 'concurrent/executor/java_thread_pool_executor'
-
end
-
-
1
ThreadPoolExecutorImplementation = case
-
when Concurrent.on_jruby?
-
JavaThreadPoolExecutor
-
else
-
1
RubyThreadPoolExecutor
-
end
-
1
private_constant :ThreadPoolExecutorImplementation
-
-
# @!macro [attach] thread_pool_executor
-
#
-
# An abstraction composed of one or more threads and a task queue. Tasks
-
# (blocks or `proc` objects) are submitted to the pool and added to the queue.
-
# The threads in the pool remove the tasks and execute them in the order
-
# they were received.
-
#
-
# A `ThreadPoolExecutor` will automatically adjust the pool size according
-
# to the bounds set by `min-threads` and `max-threads`. When a new task is
-
# submitted and fewer than `min-threads` threads are running, a new thread
-
# is created to handle the request, even if other worker threads are idle.
-
# If there are more than `min-threads` but less than `max-threads` threads
-
# running, a new thread will be created only if the queue is full.
-
#
-
# Threads that are idle for too long will be garbage collected, down to the
-
# configured minimum options. Should a thread crash it, too, will be garbage collected.
-
#
-
# `ThreadPoolExecutor` is based on the Java class of the same name. From
-
# the official Java documentation;
-
#
-
# > Thread pools address two different problems: they usually provide
-
# > improved performance when executing large numbers of asynchronous tasks,
-
# > due to reduced per-task invocation overhead, and they provide a means
-
# > of bounding and managing the resources, including threads, consumed
-
# > when executing a collection of tasks. Each ThreadPoolExecutor also
-
# > maintains some basic statistics, such as the number of completed tasks.
-
# >
-
# > To be useful across a wide range of contexts, this class provides many
-
# > adjustable parameters and extensibility hooks. However, programmers are
-
# > urged to use the more convenient Executors factory methods
-
# > [CachedThreadPool] (unbounded thread pool, with automatic thread reclamation),
-
# > [FixedThreadPool] (fixed size thread pool) and [SingleThreadExecutor] (single
-
# > background thread), that preconfigure settings for the most common usage
-
# > scenarios.
-
#
-
# @!macro thread_pool_options
-
#
-
# @!macro thread_pool_executor_public_api
-
1
class ThreadPoolExecutor < ThreadPoolExecutorImplementation
-
-
# @!macro [new] thread_pool_executor_method_initialize
-
#
-
# Create a new thread pool.
-
#
-
# @param [Hash] opts the options which configure the thread pool.
-
#
-
# @option opts [Integer] :max_threads (DEFAULT_MAX_POOL_SIZE) the maximum
-
# number of threads to be created
-
# @option opts [Integer] :min_threads (DEFAULT_MIN_POOL_SIZE) When a new task is submitted
-
# and fewer than `min_threads` are running, a new thread is created
-
# @option opts [Integer] :idletime (DEFAULT_THREAD_IDLETIMEOUT) the maximum
-
# number of seconds a thread may be idle before being reclaimed
-
# @option opts [Integer] :max_queue (DEFAULT_MAX_QUEUE_SIZE) the maximum
-
# number of tasks allowed in the work queue at any one time; a value of
-
# zero means the queue may grow without bound
-
# @option opts [Symbol] :fallback_policy (:abort) the policy for handling new
-
# tasks that are received when the queue size has reached
-
# `max_queue` or the executor has shut down
-
#
-
# @raise [ArgumentError] if `:max_threads` is less than one
-
# @raise [ArgumentError] if `:min_threads` is less than zero
-
# @raise [ArgumentError] if `:fallback_policy` is not one of the values specified
-
# in `FALLBACK_POLICIES`
-
#
-
# @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html
-
-
# @!method initialize(opts = {})
-
# @!macro thread_pool_executor_method_initialize
-
end
-
end
-
1
require 'concurrent/scheduled_task'
-
1
require 'concurrent/atomic/event'
-
1
require 'concurrent/collection/non_concurrent_priority_queue'
-
1
require 'concurrent/executor/executor_service'
-
1
require 'concurrent/executor/single_thread_executor'
-
-
1
require 'concurrent/options'
-
-
1
module Concurrent
-
-
# Executes a collection of tasks, each after a given delay. A master task
-
# monitors the set and schedules each task for execution at the appropriate
-
# time. Tasks are run on the global thread pool or on the supplied executor.
-
# Each task is represented as a `ScheduledTask`.
-
#
-
# @see Concurrent::ScheduledTask
-
#
-
# @!macro monotonic_clock_warning
-
1
class TimerSet < RubyExecutorService
-
-
# Create a new set of timed tasks.
-
#
-
# @!macro [attach] executor_options
-
#
-
# @param [Hash] opts the options used to specify the executor on which to perform actions
-
# @option opts [Executor] :executor when set use the given `Executor` instance.
-
# Three special values are also supported: `:task` returns the global task pool,
-
# `:operation` returns the global operation pool, and `:immediate` returns a new
-
# `ImmediateExecutor` object.
-
1
def initialize(opts = {})
-
super(opts)
-
end
-
-
# Post a task to be execute run after a given delay (in seconds). If the
-
# delay is less than 1/100th of a second the task will be immediately post
-
# to the executor.
-
#
-
# @param [Float] delay the number of seconds to wait for before executing the task.
-
# @param [Array<Object>] args the arguments passed to the task on execution.
-
#
-
# @yield the task to be performed.
-
#
-
# @return [Concurrent::ScheduledTask, false] IVar representing the task if the post
-
# is successful; false after shutdown.
-
#
-
# @raise [ArgumentError] if the intended execution time is not in the future.
-
# @raise [ArgumentError] if no block is given.
-
1
def post(delay, *args, &task)
-
raise ArgumentError.new('no block given') unless block_given?
-
return false unless running?
-
opts = {
-
executor: @task_executor,
-
args: args,
-
timer_set: self
-
}
-
task = ScheduledTask.execute(delay, opts, &task) # may raise exception
-
task.unscheduled? ? false : task
-
end
-
-
# Begin an immediate shutdown. In-progress tasks will be allowed to
-
# complete but enqueued tasks will be dismissed and no new tasks
-
# will be accepted. Has no additional effect if the thread pool is
-
# not running.
-
1
def kill
-
shutdown
-
end
-
-
1
private :<<
-
-
1
private
-
-
# Initialize the object.
-
#
-
# @param [Hash] opts the options to create the object with.
-
# @!visibility private
-
1
def ns_initialize(opts)
-
@queue = Collection::NonConcurrentPriorityQueue.new(order: :min)
-
@task_executor = Options.executor_from_options(opts) || Concurrent.global_io_executor
-
@timer_executor = SingleThreadExecutor.new
-
@condition = Event.new
-
@ruby_pid = $$ # detects if Ruby has forked
-
self.auto_terminate = opts.fetch(:auto_terminate, true)
-
end
-
-
# Post the task to the internal queue.
-
#
-
# @note This is intended as a callback method from ScheduledTask
-
# only. It is not intended to be used directly. Post a task
-
# by using the `SchedulesTask#execute` method.
-
#
-
# @!visibility private
-
1
def post_task(task)
-
synchronize{ ns_post_task(task) }
-
end
-
-
# @!visibility private
-
1
def ns_post_task(task)
-
return false unless ns_running?
-
ns_reset_if_forked
-
if (task.initial_delay) <= 0.01
-
task.executor.post{ task.process_task }
-
else
-
@queue.push(task)
-
# only post the process method when the queue is empty
-
@timer_executor.post(&method(:process_tasks)) if @queue.length == 1
-
@condition.set
-
end
-
true
-
end
-
-
# Remove the given task from the queue.
-
#
-
# @note This is intended as a callback method from `ScheduledTask`
-
# only. It is not intended to be used directly. Cancel a task
-
# by using the `ScheduledTask#cancel` method.
-
#
-
# @!visibility private
-
1
def remove_task(task)
-
synchronize{ @queue.delete(task) }
-
end
-
-
# `ExecutorService` callback called during shutdown.
-
#
-
# @!visibility private
-
1
def ns_shutdown_execution
-
ns_reset_if_forked
-
@queue.clear
-
@timer_executor.kill
-
stopped_event.set
-
end
-
-
1
def ns_reset_if_forked
-
if $$ != @ruby_pid
-
@queue.clear
-
@condition.reset
-
@ruby_pid = $$
-
end
-
end
-
-
# Run a loop and execute tasks in the scheduled order and at the approximate
-
# scheduled time. If no tasks remain the thread will exit gracefully so that
-
# garbage collection can occur. If there are no ready tasks it will sleep
-
# for up to 60 seconds waiting for the next scheduled task.
-
#
-
# @!visibility private
-
1
def process_tasks
-
loop do
-
task = synchronize { @condition.reset; @queue.peek }
-
break unless task
-
-
now = Concurrent.monotonic_time
-
diff = task.schedule_time - now
-
-
if diff <= 0
-
# We need to remove the task from the queue before passing
-
# it to the executor, to avoid race conditions where we pass
-
# the peek'ed task to the executor and then pop a different
-
# one that's been added in the meantime.
-
#
-
# Note that there's no race condition between the peek and
-
# this pop - this pop could retrieve a different task from
-
# the peek, but that task would be due to fire now anyway
-
# (because @queue is a priority queue, and this thread is
-
# the only reader, so whatever timer is at the head of the
-
# queue now must have the same pop time, or a closer one, as
-
# when we peeked).
-
task = synchronize { @queue.pop }
-
task.executor.post{ task.process_task }
-
else
-
@condition.wait([diff, 60].min)
-
end
-
end
-
end
-
end
-
end
-
1
require 'concurrent/executor/abstract_executor_service'
-
1
require 'concurrent/executor/cached_thread_pool'
-
1
require 'concurrent/executor/executor_service'
-
1
require 'concurrent/executor/fixed_thread_pool'
-
1
require 'concurrent/executor/immediate_executor'
-
1
require 'concurrent/executor/indirect_immediate_executor'
-
1
require 'concurrent/executor/java_executor_service'
-
1
require 'concurrent/executor/java_single_thread_executor'
-
1
require 'concurrent/executor/java_thread_pool_executor'
-
1
require 'concurrent/executor/ruby_executor_service'
-
1
require 'concurrent/executor/ruby_single_thread_executor'
-
1
require 'concurrent/executor/ruby_thread_pool_executor'
-
1
require 'concurrent/executor/cached_thread_pool'
-
1
require 'concurrent/executor/safe_task_executor'
-
1
require 'concurrent/executor/serial_executor_service'
-
1
require 'concurrent/executor/serialized_execution'
-
1
require 'concurrent/executor/serialized_execution_delegator'
-
1
require 'concurrent/executor/single_thread_executor'
-
1
require 'concurrent/executor/thread_pool_executor'
-
1
require 'concurrent/executor/timer_set'
-
1
require 'thread'
-
1
require 'concurrent/constants'
-
1
require 'concurrent/errors'
-
1
require 'concurrent/ivar'
-
1
require 'concurrent/executor/safe_task_executor'
-
-
1
require 'concurrent/options'
-
-
1
module Concurrent
-
-
# {include:file:doc/future.md}
-
#
-
# @!macro copy_options
-
#
-
# @see http://ruby-doc.org/stdlib-2.1.1/libdoc/observer/rdoc/Observable.html Ruby Observable module
-
# @see http://clojuredocs.org/clojure_core/clojure.core/future Clojure's future function
-
# @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html java.util.concurrent.Future
-
1
class Future < IVar
-
-
# Create a new `Future` in the `:unscheduled` state.
-
#
-
# @yield the asynchronous operation to perform
-
#
-
# @!macro executor_and_deref_options
-
#
-
# @option opts [object, Array] :args zero or more arguments to be passed the task
-
# block on execution
-
#
-
# @raise [ArgumentError] if no block is given
-
1
def initialize(opts = {}, &block)
-
raise ArgumentError.new('no block given') unless block_given?
-
super(NULL, opts.merge(__task_from_block__: block), &nil)
-
end
-
-
# Execute an `:unscheduled` `Future`. Immediately sets the state to `:pending` and
-
# passes the block to a new thread/thread pool for eventual execution.
-
# Does nothing if the `Future` is in any state other than `:unscheduled`.
-
#
-
# @return [Future] a reference to `self`
-
#
-
# @example Instance and execute in separate steps
-
# future = Concurrent::Future.new{ sleep(1); 42 }
-
# future.state #=> :unscheduled
-
# future.execute
-
# future.state #=> :pending
-
#
-
# @example Instance and execute in one line
-
# future = Concurrent::Future.new{ sleep(1); 42 }.execute
-
# future.state #=> :pending
-
1
def execute
-
if compare_and_set_state(:pending, :unscheduled)
-
@executor.post{ safe_execute(@task, @args) }
-
self
-
end
-
end
-
-
# Create a new `Future` object with the given block, execute it, and return the
-
# `:pending` object.
-
#
-
# @yield the asynchronous operation to perform
-
#
-
# @!macro executor_and_deref_options
-
#
-
# @option opts [object, Array] :args zero or more arguments to be passed the task
-
# block on execution
-
#
-
# @raise [ArgumentError] if no block is given
-
#
-
# @return [Future] the newly created `Future` in the `:pending` state
-
#
-
# @example
-
# future = Concurrent::Future.execute{ sleep(1); 42 }
-
# future.state #=> :pending
-
1
def self.execute(opts = {}, &block)
-
Future.new(opts, &block).execute
-
end
-
-
# @!macro ivar_set_method
-
1
def set(value = NULL, &block)
-
check_for_block_or_value!(block_given?, value)
-
synchronize do
-
if @state != :unscheduled
-
raise MultipleAssignmentError
-
else
-
@task = block || Proc.new { value }
-
end
-
end
-
execute
-
end
-
-
# Attempt to cancel the operation if it has not already processed.
-
# The operation can only be cancelled while still `pending`. It cannot
-
# be cancelled once it has begun processing or has completed.
-
#
-
# @return [Boolean] was the operation successfully cancelled.
-
1
def cancel
-
if compare_and_set_state(:cancelled, :pending)
-
complete(false, nil, CancelledOperationError.new)
-
true
-
else
-
false
-
end
-
end
-
-
# Has the operation been successfully cancelled?
-
#
-
# @return [Boolean]
-
1
def cancelled?
-
state == :cancelled
-
end
-
-
# Wait the given number of seconds for the operation to complete.
-
# On timeout attempt to cancel the operation.
-
#
-
# @param [Numeric] timeout the maximum time in seconds to wait.
-
# @return [Boolean] true if the operation completed before the timeout
-
# else false
-
1
def wait_or_cancel(timeout)
-
wait(timeout)
-
if complete?
-
true
-
else
-
cancel
-
false
-
end
-
end
-
-
1
protected
-
-
1
def ns_initialize(value, opts)
-
super
-
@state = :unscheduled
-
@task = opts[:__task_from_block__]
-
@executor = Options.executor_from_options(opts) || Concurrent.global_io_executor
-
@args = get_arguments_from(opts)
-
end
-
end
-
end
-
1
require 'concurrent/utility/engine'
-
1
require 'concurrent/thread_safe/util'
-
-
1
module Concurrent
-
1
if Concurrent.on_cruby?
-
-
# @!macro [attach] concurrent_hash
-
#
-
# A thread-safe subclass of Hash. This version locks against the object
-
# itself for every method call, ensuring only one thread can be reading
-
# or writing at a time. This includes iteration methods like `#each`,
-
# which takes the lock repeatedly when reading an item.
-
#
-
# @see http://ruby-doc.org/core-2.2.0/Hash.html Ruby standard library `Hash`
-
1
class Hash < ::Hash;
-
end
-
-
elsif Concurrent.on_jruby?
-
require 'jruby/synchronized'
-
-
# @!macro concurrent_hash
-
class Hash < ::Hash
-
include JRuby::Synchronized
-
end
-
-
elsif Concurrent.on_rbx? || Concurrent.on_truffle?
-
require 'monitor'
-
require 'concurrent/thread_safe/util/array_hash_rbx'
-
-
# @!macro concurrent_hash
-
class Hash < ::Hash
-
end
-
-
ThreadSafe::Util.make_synchronized_on_rbx Hash
-
end
-
end
-
1
require 'concurrent/synchronization/abstract_struct'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# A thread-safe, immutable variation of Ruby's standard `Struct`.
-
#
-
# @see http://ruby-doc.org/core-2.2.0/Struct.html Ruby standard library `Struct`
-
1
module ImmutableStruct
-
1
include Synchronization::AbstractStruct
-
-
1
def self.included(base)
-
base.safe_initialization!
-
end
-
-
# @!macro struct_values
-
1
def values
-
ns_values
-
end
-
-
1
alias_method :to_a, :values
-
-
# @!macro struct_values_at
-
1
def values_at(*indexes)
-
ns_values_at(indexes)
-
end
-
-
# @!macro struct_inspect
-
1
def inspect
-
ns_inspect
-
end
-
-
1
alias_method :to_s, :inspect
-
-
# @!macro struct_merge
-
1
def merge(other, &block)
-
ns_merge(other, &block)
-
end
-
-
# @!macro struct_to_h
-
1
def to_h
-
ns_to_h
-
end
-
-
# @!macro struct_get
-
1
def [](member)
-
ns_get(member)
-
end
-
-
# @!macro struct_equality
-
1
def ==(other)
-
ns_equality(other)
-
end
-
-
# @!macro struct_each
-
1
def each(&block)
-
return enum_for(:each) unless block_given?
-
ns_each(&block)
-
end
-
-
# @!macro struct_each_pair
-
1
def each_pair(&block)
-
return enum_for(:each_pair) unless block_given?
-
ns_each_pair(&block)
-
end
-
-
# @!macro struct_select
-
1
def select(&block)
-
return enum_for(:select) unless block_given?
-
ns_select(&block)
-
end
-
-
# @!macro struct_new
-
1
def self.new(*args, &block)
-
clazz_name = nil
-
if args.length == 0
-
raise ArgumentError.new('wrong number of arguments (0 for 1+)')
-
elsif args.length > 0 && args.first.is_a?(String)
-
clazz_name = args.shift
-
end
-
FACTORY.define_struct(clazz_name, args, &block)
-
end
-
-
1
FACTORY = Class.new(Synchronization::LockableObject) do
-
1
def define_struct(name, members, &block)
-
synchronize do
-
Synchronization::AbstractStruct.define_struct_class(ImmutableStruct, Synchronization::Object, name, members, &block)
-
end
-
end
-
end.new
-
1
private_constant :FACTORY
-
end
-
end
-
1
require 'concurrent/constants'
-
1
require 'concurrent/errors'
-
1
require 'concurrent/collection/copy_on_write_observer_set'
-
1
require 'concurrent/concern/obligation'
-
1
require 'concurrent/concern/observable'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# An `IVar` is like a future that you can assign. As a future is a value that
-
# is being computed that you can wait on, an `IVar` is a value that is waiting
-
# to be assigned, that you can wait on. `IVars` are single assignment and
-
# deterministic.
-
#
-
# Then, express futures as an asynchronous computation that assigns an `IVar`.
-
# The `IVar` becomes the primitive on which [futures](Future) and
-
# [dataflow](Dataflow) are built.
-
#
-
# An `IVar` is a single-element container that is normally created empty, and
-
# can only be set once. The I in `IVar` stands for immutable. Reading an
-
# `IVar` normally blocks until it is set. It is safe to set and read an `IVar`
-
# from different threads.
-
#
-
# If you want to have some parallel task set the value in an `IVar`, you want
-
# a `Future`. If you want to create a graph of parallel tasks all executed
-
# when the values they depend on are ready you want `dataflow`. `IVar` is
-
# generally a low-level primitive.
-
#
-
# ## Examples
-
#
-
# Create, set and get an `IVar`
-
#
-
# ```ruby
-
# ivar = Concurrent::IVar.new
-
# ivar.set 14
-
# ivar.value #=> 14
-
# ivar.set 2 # would now be an error
-
# ```
-
#
-
# ## See Also
-
#
-
# 1. For the theory: Arvind, R. Nikhil, and K. Pingali.
-
# [I-Structures: Data structures for parallel computing](http://dl.acm.org/citation.cfm?id=69562).
-
# In Proceedings of Workshop on Graph Reduction, 1986.
-
# 2. For recent application:
-
# [DataDrivenFuture in Habanero Java from Rice](http://www.cs.rice.edu/~vs3/hjlib/doc/edu/rice/hj/api/HjDataDrivenFuture.html).
-
1
class IVar < Synchronization::LockableObject
-
1
include Concern::Obligation
-
1
include Concern::Observable
-
-
# Create a new `IVar` in the `:pending` state with the (optional) initial value.
-
#
-
# @param [Object] value the initial value
-
# @param [Hash] opts the options to create a message with
-
# @option opts [String] :dup_on_deref (false) call `#dup` before returning
-
# the data
-
# @option opts [String] :freeze_on_deref (false) call `#freeze` before
-
# returning the data
-
# @option opts [String] :copy_on_deref (nil) call the given `Proc` passing
-
# the internal value and returning the value returned from the proc
-
1
def initialize(value = NULL, opts = {}, &block)
-
if value != NULL && block_given?
-
raise ArgumentError.new('provide only a value or a block')
-
end
-
super(&nil)
-
synchronize { ns_initialize(value, opts, &block) }
-
end
-
-
# Add an observer on this object that will receive notification on update.
-
#
-
# Upon completion the `IVar` will notify all observers in a thread-safe way.
-
# The `func` method of the observer will be called with three arguments: the
-
# `Time` at which the `Future` completed the asynchronous operation, the
-
# final `value` (or `nil` on rejection), and the final `reason` (or `nil` on
-
# fulfillment).
-
#
-
# @param [Object] observer the object that will be notified of changes
-
# @param [Symbol] func symbol naming the method to call when this
-
# `Observable` has changes`
-
1
def add_observer(observer = nil, func = :update, &block)
-
raise ArgumentError.new('cannot provide both an observer and a block') if observer && block
-
direct_notification = false
-
-
if block
-
observer = block
-
func = :call
-
end
-
-
synchronize do
-
if event.set?
-
direct_notification = true
-
else
-
observers.add_observer(observer, func)
-
end
-
end
-
-
observer.send(func, Time.now, self.value, reason) if direct_notification
-
observer
-
end
-
-
# @!macro [attach] ivar_set_method
-
# Set the `IVar` to a value and wake or notify all threads waiting on it.
-
#
-
# @!macro [attach] ivar_set_parameters_and_exceptions
-
# @param [Object] value the value to store in the `IVar`
-
# @yield A block operation to use for setting the value
-
# @raise [ArgumentError] if both a value and a block are given
-
# @raise [Concurrent::MultipleAssignmentError] if the `IVar` has already
-
# been set or otherwise completed
-
#
-
# @return [IVar] self
-
1
def set(value = NULL)
-
check_for_block_or_value!(block_given?, value)
-
raise MultipleAssignmentError unless compare_and_set_state(:processing, :pending)
-
-
begin
-
value = yield if block_given?
-
complete_without_notification(true, value, nil)
-
rescue => ex
-
complete_without_notification(false, nil, ex)
-
end
-
-
notify_observers(self.value, reason)
-
self
-
end
-
-
# @!macro [attach] ivar_fail_method
-
# Set the `IVar` to failed due to some error and wake or notify all threads waiting on it.
-
#
-
# @param [Object] reason for the failure
-
# @raise [Concurrent::MultipleAssignmentError] if the `IVar` has already
-
# been set or otherwise completed
-
# @return [IVar] self
-
1
def fail(reason = StandardError.new)
-
complete(false, nil, reason)
-
end
-
-
# Attempt to set the `IVar` with the given value or block. Return a
-
# boolean indicating the success or failure of the set operation.
-
#
-
# @!macro ivar_set_parameters_and_exceptions
-
#
-
# @return [Boolean] true if the value was set else false
-
1
def try_set(value = NULL, &block)
-
set(value, &block)
-
true
-
rescue MultipleAssignmentError
-
false
-
end
-
-
1
protected
-
-
# @!visibility private
-
1
def ns_initialize(value, opts)
-
value = yield if block_given?
-
init_obligation
-
self.observers = Collection::CopyOnWriteObserverSet.new
-
set_deref_options(opts)
-
-
if value == NULL
-
@state = :pending
-
else
-
ns_complete_without_notification(true, value, nil)
-
end
-
end
-
-
# @!visibility private
-
1
def safe_execute(task, args = [])
-
if compare_and_set_state(:processing, :pending)
-
success, val, reason = SafeTaskExecutor.new(task, rescue_exception: true).execute(*@args)
-
complete(success, val, reason)
-
yield(success, val, reason) if block_given?
-
end
-
end
-
-
# @!visibility private
-
1
def complete(success, value, reason)
-
complete_without_notification(success, value, reason)
-
notify_observers(self.value, reason)
-
self
-
end
-
-
# @!visibility private
-
1
def complete_without_notification(success, value, reason)
-
synchronize { ns_complete_without_notification(success, value, reason) }
-
self
-
end
-
-
# @!visibility private
-
1
def notify_observers(value, reason)
-
observers.notify_and_delete_observers{ [Time.now, value, reason] }
-
end
-
-
# @!visibility private
-
1
def ns_complete_without_notification(success, value, reason)
-
raise MultipleAssignmentError if [:fulfilled, :rejected].include? @state
-
set_state(success, value, reason)
-
event.set
-
end
-
-
# @!visibility private
-
1
def check_for_block_or_value!(block_given, value) # :nodoc:
-
if (block_given && value != NULL) || (! block_given && value == NULL)
-
raise ArgumentError.new('must set with either a value or a block')
-
end
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'concurrent/constants'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
# @!visibility private
-
1
module Collection
-
-
# @!visibility private
-
1
MapImplementation = if Concurrent.java_extensions_loaded?
-
# noinspection RubyResolve
-
JRubyMapBackend
-
elsif defined?(RUBY_ENGINE)
-
1
case RUBY_ENGINE
-
when 'ruby'
-
1
require 'concurrent/collection/map/mri_map_backend'
-
1
MriMapBackend
-
when 'rbx'
-
require 'concurrent/collection/map/atomic_reference_map_backend'
-
AtomicReferenceMapBackend
-
when 'jruby+truffle'
-
require 'concurrent/collection/map/atomic_reference_map_backend'
-
AtomicReferenceMapBackend
-
else
-
warn 'Concurrent::Map: unsupported Ruby engine, using a fully synchronized Concurrent::Map implementation' if $VERBOSE
-
require 'concurrent/collection/map/synchronized_map_backend'
-
SynchronizedMapBackend
-
end
-
else
-
MriMapBackend
-
end
-
end
-
-
# `Concurrent::Map` is a hash-like object and should have much better performance
-
# characteristics, especially under high concurrency, than `Concurrent::Hash`.
-
# However, `Concurrent::Map `is not strictly semantically equivalent to a ruby `Hash`
-
# -- for instance, it does not necessarily retain ordering by insertion time as `Hash`
-
# does. For most uses it should do fine though, and we recommend you consider
-
# `Concurrent::Map` instead of `Concurrent::Hash` for your concurrency-safe hash needs.
-
#
-
# > require 'concurrent'
-
# >
-
# > map = Concurrent::Map.new
-
1
class Map < Collection::MapImplementation
-
-
# @!macro [new] map_method_is_atomic
-
# This method is atomic. Atomic methods of `Map` which accept a block
-
# do not allow the `self` instance to be used within the block. Doing
-
# so will cause a deadlock.
-
-
# @!method put_if_absent
-
# @!macro map_method_is_atomic
-
-
# @!method compute_if_absent
-
# @!macro map_method_is_atomic
-
-
# @!method compute_if_present
-
# @!macro map_method_is_atomic
-
-
# @!method compute
-
# @!macro map_method_is_atomic
-
-
# @!method merge_pair
-
# @!macro map_method_is_atomic
-
-
# @!method replace_pair
-
# @!macro map_method_is_atomic
-
-
# @!method replace_if_exists
-
# @!macro map_method_is_atomic
-
-
# @!method get_and_set
-
# @!macro map_method_is_atomic
-
-
# @!method delete
-
# @!macro map_method_is_atomic
-
-
# @!method delete_pair
-
# @!macro map_method_is_atomic
-
-
1
def initialize(options = nil, &block)
-
if options.kind_of?(::Hash)
-
validate_options_hash!(options)
-
else
-
options = nil
-
end
-
-
super(options)
-
@default_proc = block
-
end
-
-
1
def [](key)
-
if value = super # non-falsy value is an existing mapping, return it right away
-
value
-
# re-check is done with get_or_default(key, NULL) instead of a simple !key?(key) in order to avoid a race condition, whereby by the time the current thread gets to the key?(key) call
-
# a key => value mapping might have already been created by a different thread (key?(key) would then return true, this elsif branch wouldn't be taken and an incorrent +nil+ value
-
# would be returned)
-
# note: nil == value check is not technically necessary
-
elsif @default_proc && nil == value && NULL == (value = get_or_default(key, NULL))
-
@default_proc.call(self, key)
-
else
-
value
-
end
-
end
-
-
1
alias_method :get, :[]
-
1
alias_method :put, :[]=
-
-
# @!macro [attach] map_method_not_atomic
-
# The "fetch-then-act" methods of `Map` are not atomic. `Map` is intended
-
# to be use as a concurrency primitive with strong happens-before
-
# guarantees. It is not intended to be used as a high-level abstraction
-
# supporting complex operations. All read and write operations are
-
# thread safe, but no guarantees are made regarding race conditions
-
# between the fetch operation and yielding to the block. Additionally,
-
# this method does not support recursion. This is due to internal
-
# constraints that are very unlikely to change in the near future.
-
1
def fetch(key, default_value = NULL)
-
if NULL != (value = get_or_default(key, NULL))
-
value
-
elsif block_given?
-
yield key
-
elsif NULL != default_value
-
default_value
-
else
-
raise_fetch_no_key
-
end
-
end
-
-
# @!macro map_method_not_atomic
-
1
def fetch_or_store(key, default_value = NULL)
-
fetch(key) do
-
put(key, block_given? ? yield(key) : (NULL == default_value ? raise_fetch_no_key : default_value))
-
end
-
end
-
-
# @!macro map_method_is_atomic
-
def put_if_absent(key, value)
-
computed = false
-
result = compute_if_absent(key) do
-
computed = true
-
value
-
end
-
computed ? nil : result
-
1
end unless method_defined?(:put_if_absent)
-
-
1
def value?(value)
-
each_value do |v|
-
return true if value.equal?(v)
-
end
-
false
-
end
-
-
def keys
-
arr = []
-
each_pair {|k, v| arr << k}
-
arr
-
1
end unless method_defined?(:keys)
-
-
def values
-
arr = []
-
each_pair {|k, v| arr << v}
-
arr
-
1
end unless method_defined?(:values)
-
-
def each_key
-
each_pair {|k, v| yield k}
-
1
end unless method_defined?(:each_key)
-
-
def each_value
-
each_pair {|k, v| yield v}
-
1
end unless method_defined?(:each_value)
-
-
1
alias_method :each, :each_pair unless method_defined?(:each)
-
-
def key(value)
-
each_pair {|k, v| return k if v == value}
-
nil
-
1
end unless method_defined?(:key)
-
1
alias_method :index, :key if RUBY_VERSION < '1.9'
-
-
def empty?
-
each_pair {|k, v| return false}
-
true
-
1
end unless method_defined?(:empty?)
-
-
def size
-
count = 0
-
each_pair {|k, v| count += 1}
-
count
-
1
end unless method_defined?(:size)
-
-
1
def marshal_dump
-
raise TypeError, "can't dump hash with default proc" if @default_proc
-
h = {}
-
each_pair {|k, v| h[k] = v}
-
h
-
end
-
-
1
def marshal_load(hash)
-
initialize
-
populate_from(hash)
-
end
-
-
1
undef :freeze
-
-
# @!visibility private
-
1
DEFAULT_OBJ_ID_STR_WIDTH = 0.size == 4 ? 7 : 14 # we want to look "native", 7 for 32-bit, 14 for 64-bit
-
# override default #inspect() method: firstly, we don't want to be spilling our guts (i-vars), secondly, MRI backend's
-
# #inspect() call on its @backend i-var will bump @backend's iter level while possibly yielding GVL
-
1
def inspect
-
id_str = (object_id << 1).to_s(16).rjust(DEFAULT_OBJ_ID_STR_WIDTH, '0')
-
"#<#{self.class.name}:0x#{id_str} entries=#{size} default_proc=#{@default_proc.inspect}>"
-
end
-
-
1
private
-
1
def raise_fetch_no_key
-
raise KeyError, 'key not found'
-
end
-
-
1
def initialize_copy(other)
-
super
-
populate_from(other)
-
end
-
-
1
def populate_from(hash)
-
hash.each_pair {|k, v| self[k] = v}
-
self
-
end
-
-
1
def validate_options_hash!(options)
-
if (initial_capacity = options[:initial_capacity]) && (!initial_capacity.kind_of?(Integer) || initial_capacity < 0)
-
raise ArgumentError, ":initial_capacity must be a positive Integer"
-
end
-
if (load_factor = options[:load_factor]) && (!load_factor.kind_of?(Numeric) || load_factor <= 0 || load_factor > 1)
-
raise ArgumentError, ":load_factor must be a number between 0 and 1"
-
end
-
end
-
end
-
end
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# A `Maybe` encapsulates an optional value. A `Maybe` either contains a value
-
# of (represented as `Just`), or it is empty (represented as `Nothing`). Using
-
# `Maybe` is a good way to deal with errors or exceptional cases without
-
# resorting to drastic measures such as exceptions.
-
#
-
# `Maybe` is a replacement for the use of `nil` with better type checking.
-
#
-
# For compatibility with {Concurrent::Concern::Obligation} the predicate and
-
# accessor methods are aliased as `fulfilled?`, `rejected?`, `value`, and
-
# `reason`.
-
#
-
# ## Motivation
-
#
-
# A common pattern in languages with pattern matching, such as Erlang and
-
# Haskell, is to return *either* a value *or* an error from a function
-
# Consider this Erlang code:
-
#
-
# ```erlang
-
# case file:consult("data.dat") of
-
# {ok, Terms} -> do_something_useful(Terms);
-
# {error, Reason} -> lager:error(Reason)
-
# end.
-
# ```
-
#
-
# In this example the standard library function `file:consult` returns a
-
# [tuple](http://erlang.org/doc/reference_manual/data_types.html#id69044)
-
# with two elements: an [atom](http://erlang.org/doc/reference_manual/data_types.html#id64134)
-
# (similar to a ruby symbol) and a variable containing ancillary data. On
-
# success it returns the atom `ok` and the data from the file. On failure it
-
# returns `error` and a string with an explanation of the problem. With this
-
# pattern there is no ambiguity regarding success or failure. If the file is
-
# empty the return value cannot be misinterpreted as an error. And when an
-
# error occurs the return value provides useful information.
-
#
-
# In Ruby we tend to return `nil` when an error occurs or else we raise an
-
# exception. Both of these idioms are problematic. Returning `nil` is
-
# ambiguous because `nil` may also be a valid value. It also lacks
-
# information pertaining to the nature of the error. Raising an exception
-
# is both expensive and usurps the normal flow of control. All of these
-
# problems can be solved with the use of a `Maybe`.
-
#
-
# A `Maybe` is unambiguous with regard to whether or not it contains a value.
-
# When `Just` it contains a value, when `Nothing` it does not. When `Just`
-
# the value it contains may be `nil`, which is perfectly valid. When
-
# `Nothing` the reason for the lack of a value is contained as well. The
-
# previous Erlang example can be duplicated in Ruby in a principled way by
-
# having functions return `Maybe` objects:
-
#
-
# ```ruby
-
# result = MyFileUtils.consult("data.dat") # returns a Maybe
-
# if result.just?
-
# do_something_useful(result.value) # or result.just
-
# else
-
# logger.error(result.reason) # or result.nothing
-
# end
-
# ```
-
#
-
# @example Returning a Maybe from a Function
-
# module MyFileUtils
-
# def self.consult(path)
-
# file = File.open(path, 'r')
-
# Concurrent::Maybe.just(file.read)
-
# rescue => ex
-
# return Concurrent::Maybe.nothing(ex)
-
# ensure
-
# file.close if file
-
# end
-
# end
-
#
-
# maybe = MyFileUtils.consult('bogus.file')
-
# maybe.just? #=> false
-
# maybe.nothing? #=> true
-
# maybe.reason #=> #<Errno::ENOENT: No such file or directory @ rb_sysopen - bogus.file>
-
#
-
# maybe = MyFileUtils.consult('README.md')
-
# maybe.just? #=> true
-
# maybe.nothing? #=> false
-
# maybe.value #=> "# Concurrent Ruby\n[![Gem Version..."
-
#
-
# @example Using Maybe with a Block
-
# result = Concurrent::Maybe.from do
-
# Client.find(10) # Client is an ActiveRecord model
-
# end
-
#
-
# # -- if the record was found
-
# result.just? #=> true
-
# result.value #=> #<Client id: 10, first_name: "Ryan">
-
#
-
# # -- if the record was not found
-
# result.just? #=> false
-
# result.reason #=> ActiveRecord::RecordNotFound
-
#
-
# @example Using Maybe with the Null Object Pattern
-
# # In a Rails controller...
-
# result = ClientService.new(10).find # returns a Maybe
-
# render json: result.or(NullClient.new)
-
#
-
# @see https://hackage.haskell.org/package/base-4.2.0.1/docs/Data-Maybe.html Haskell Data.Maybe
-
# @see https://github.com/purescript/purescript-maybe/blob/master/docs/Data.Maybe.md PureScript Data.Maybe
-
1
class Maybe < Synchronization::Object
-
1
include Comparable
-
1
safe_initialization!
-
-
# Indicates that the given attribute has not been set.
-
# When `Just` the {#nothing} getter will return `NONE`.
-
# When `Nothing` the {#just} getter will return `NONE`.
-
1
NONE = Object.new.freeze
-
-
# The value of a `Maybe` when `Just`. Will be `NONE` when `Nothing`.
-
1
attr_reader :just
-
-
# The reason for the `Maybe` when `Nothing`. Will be `NONE` when `Just`.
-
1
attr_reader :nothing
-
-
1
private_class_method :new
-
-
# Create a new `Maybe` using the given block.
-
#
-
# Runs the given block passing all function arguments to the block as block
-
# arguments. If the block runs to completion without raising an exception
-
# a new `Just` is created with the value set to the return value of the
-
# block. If the block raises an exception a new `Nothing` is created with
-
# the reason being set to the raised exception.
-
#
-
# @param [Array<Object>] args Zero or more arguments to pass to the block.
-
# @yield The block from which to create a new `Maybe`.
-
# @yieldparam [Array<Object>] args Zero or more block arguments passed as
-
# arguments to the function.
-
#
-
# @return [Maybe] The newly created object.
-
#
-
# @raise [ArgumentError] when no block given.
-
1
def self.from(*args)
-
raise ArgumentError.new('no block given') unless block_given?
-
begin
-
value = yield(*args)
-
return new(value, NONE)
-
rescue => ex
-
return new(NONE, ex)
-
end
-
end
-
-
# Create a new `Just` with the given value.
-
#
-
# @param [Object] value The value to set for the new `Maybe` object.
-
#
-
# @return [Maybe] The newly created object.
-
1
def self.just(value)
-
return new(value, NONE)
-
end
-
-
# Create a new `Nothing` with the given (optional) reason.
-
#
-
# @param [Exception] error The reason to set for the new `Maybe` object.
-
# When given a string a new `StandardError` will be created with the
-
# argument as the message. When no argument is given a new
-
# `StandardError` with an empty message will be created.
-
#
-
# @return [Maybe] The newly created object.
-
1
def self.nothing(error = '')
-
if error.is_a?(Exception)
-
nothing = error
-
else
-
nothing = StandardError.new(error.to_s)
-
end
-
return new(NONE, nothing)
-
end
-
-
# Is this `Maybe` a `Just` (successfully fulfilled with a value)?
-
#
-
# @return [Boolean] True if `Just` or false if `Nothing`.
-
1
def just?
-
! nothing?
-
end
-
1
alias :fulfilled? :just?
-
-
# Is this `Maybe` a `nothing` (rejected with an exception upon fulfillment)?
-
#
-
# @return [Boolean] True if `Nothing` or false if `Just`.
-
1
def nothing?
-
@nothing != NONE
-
end
-
1
alias :rejected? :nothing?
-
-
1
alias :value :just
-
-
1
alias :reason :nothing
-
-
# Comparison operator.
-
#
-
# @return [Integer] 0 if self and other are both `Nothing`;
-
# -1 if self is `Nothing` and other is `Just`;
-
# 1 if self is `Just` and other is nothing;
-
# `self.just <=> other.just` if both self and other are `Just`.
-
1
def <=>(other)
-
if nothing?
-
other.nothing? ? 0 : -1
-
else
-
other.nothing? ? 1 : just <=> other.just
-
end
-
end
-
-
# Return either the value of self or the given default value.
-
#
-
# @return [Object] The value of self when `Just`; else the given default.
-
1
def or(other)
-
just? ? just : other
-
end
-
-
1
private
-
-
# Create a new `Maybe` with the given attributes.
-
#
-
# @param [Object] just The value when `Just` else `NONE`.
-
# @param [Exception, Object] nothing The exception when `Nothing` else `NONE`.
-
#
-
# @return [Maybe] The new `Maybe`.
-
#
-
# @!visibility private
-
1
def initialize(just, nothing)
-
@just = just
-
@nothing = nothing
-
end
-
end
-
end
-
1
require 'concurrent/synchronization/abstract_struct'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# An thread-safe variation of Ruby's standard `Struct`. Values can be set at
-
# construction or safely changed at any time during the object's lifecycle.
-
#
-
# @see http://ruby-doc.org/core-2.2.0/Struct.html Ruby standard library `Struct`
-
1
module MutableStruct
-
1
include Synchronization::AbstractStruct
-
-
# @!macro [new] struct_new
-
#
-
# Factory for creating new struct classes.
-
#
-
# ```
-
# new([class_name] [, member_name]+>) -> StructClass click to toggle source
-
# new([class_name] [, member_name]+>) {|StructClass| block } -> StructClass
-
# new(value, ...) -> obj
-
# StructClass[value, ...] -> obj
-
# ```
-
#
-
# The first two forms are used to create a new struct subclass `class_name`
-
# that can contain a value for each member_name . This subclass can be
-
# used to create instances of the structure like any other Class .
-
#
-
# If the `class_name` is omitted an anonymous struct class will be created.
-
# Otherwise, the name of this struct will appear as a constant in the struct class,
-
# so it must be unique for all structs under this base class and must start with a
-
# capital letter. Assigning a struct class to a constant also gives the class
-
# the name of the constant.
-
#
-
# If a block is given it will be evaluated in the context of `StructClass`, passing
-
# the created class as a parameter. This is the recommended way to customize a struct.
-
# Subclassing an anonymous struct creates an extra anonymous class that will never be used.
-
#
-
# The last two forms create a new instance of a struct subclass. The number of value
-
# parameters must be less than or equal to the number of attributes defined for the
-
# struct. Unset parameters default to nil. Passing more parameters than number of attributes
-
# will raise an `ArgumentError`.
-
#
-
# @see http://ruby-doc.org/core-2.2.0/Struct.html#method-c-new Ruby standard library `Struct#new`
-
-
# @!macro [attach] struct_values
-
#
-
# Returns the values for this struct as an Array.
-
#
-
# @return [Array] the values for this struct
-
#
-
1
def values
-
synchronize { ns_values }
-
end
-
1
alias_method :to_a, :values
-
-
# @!macro [attach] struct_values_at
-
#
-
# Returns the struct member values for each selector as an Array.
-
#
-
# A selector may be either an Integer offset or a Range of offsets (as in `Array#values_at`).
-
#
-
# @param [Fixnum, Range] indexes the index(es) from which to obatin the values (in order)
-
1
def values_at(*indexes)
-
synchronize { ns_values_at(indexes) }
-
end
-
-
# @!macro [attach] struct_inspect
-
#
-
# Describe the contents of this struct in a string.
-
#
-
# @return [String] the contents of this struct in a string
-
1
def inspect
-
synchronize { ns_inspect }
-
end
-
1
alias_method :to_s, :inspect
-
-
# @!macro [attach] struct_merge
-
#
-
# Returns a new struct containing the contents of `other` and the contents
-
# of `self`. If no block is specified, the value for entries with duplicate
-
# keys will be that of `other`. Otherwise the value for each duplicate key
-
# is determined by calling the block with the key, its value in `self` and
-
# its value in `other`.
-
#
-
# @param [Hash] other the hash from which to set the new values
-
# @yield an options block for resolving duplicate keys
-
# @yieldparam [String, Symbol] member the name of the member which is duplicated
-
# @yieldparam [Object] selfvalue the value of the member in `self`
-
# @yieldparam [Object] othervalue the value of the member in `other`
-
#
-
# @return [Synchronization::AbstractStruct] a new struct with the new values
-
#
-
# @raise [ArgumentError] of given a member that is not defined in the struct
-
1
def merge(other, &block)
-
synchronize { ns_merge(other, &block) }
-
end
-
-
# @!macro [attach] struct_to_h
-
#
-
# Returns a hash containing the names and values for the struct’s members.
-
#
-
# @return [Hash] the names and values for the struct’s members
-
1
def to_h
-
synchronize { ns_to_h }
-
end
-
-
# @!macro [attach] struct_get
-
#
-
# Attribute Reference
-
#
-
# @param [Symbol, String, Integer] member the string or symbol name of the memeber
-
# for which to obtain the value or the member's index
-
#
-
# @return [Object] the value of the given struct member or the member at the given index.
-
#
-
# @raise [NameError] if the member does not exist
-
# @raise [IndexError] if the index is out of range.
-
1
def [](member)
-
synchronize { ns_get(member) }
-
end
-
-
# @!macro [attach] struct_equality
-
#
-
# Equality
-
#
-
# @return [Boolean] true if other has the same struct subclass and has
-
# equal member values (according to `Object#==`)
-
1
def ==(other)
-
synchronize { ns_equality(other) }
-
end
-
-
# @!macro [attach] struct_each
-
#
-
# Yields the value of each struct member in order. If no block is given
-
# an enumerator is returned.
-
#
-
# @yield the operation to be performed on each struct member
-
# @yieldparam [Object] value each struct value (in order)
-
1
def each(&block)
-
return enum_for(:each) unless block_given?
-
synchronize { ns_each(&block) }
-
end
-
-
# @!macro [attach] struct_each_pair
-
#
-
# Yields the name and value of each struct member in order. If no block is
-
# given an enumerator is returned.
-
#
-
# @yield the operation to be performed on each struct member/value pair
-
# @yieldparam [Object] member each struct member (in order)
-
# @yieldparam [Object] value each struct value (in order)
-
1
def each_pair(&block)
-
return enum_for(:each_pair) unless block_given?
-
synchronize { ns_each_pair(&block) }
-
end
-
-
# @!macro [attach] struct_select
-
#
-
# Yields each member value from the struct to the block and returns an Array
-
# containing the member values from the struct for which the given block
-
# returns a true value (equivalent to `Enumerable#select`).
-
#
-
# @yield the operation to be performed on each struct member
-
# @yieldparam [Object] value each struct value (in order)
-
#
-
# @return [Array] an array containing each value for which the block returns true
-
1
def select(&block)
-
return enum_for(:select) unless block_given?
-
synchronize { ns_select(&block) }
-
end
-
-
# @!macro [new] struct_set
-
#
-
# Attribute Assignment
-
#
-
# Sets the value of the given struct member or the member at the given index.
-
#
-
# @param [Symbol, String, Integer] member the string or symbol name of the memeber
-
# for which to obtain the value or the member's index
-
#
-
# @return [Object] the value of the given struct member or the member at the given index.
-
#
-
# @raise [NameError] if the name does not exist
-
# @raise [IndexError] if the index is out of range.
-
1
def []=(member, value)
-
if member.is_a? Integer
-
length = synchronize { @values.length }
-
if member >= length
-
raise IndexError.new("offset #{member} too large for struct(size:#{length})")
-
end
-
synchronize { @values[member] = value }
-
else
-
send("#{member}=", value)
-
end
-
rescue NoMethodError
-
raise NameError.new("no member '#{member}' in struct")
-
end
-
-
# @!macro struct_new
-
1
def self.new(*args, &block)
-
clazz_name = nil
-
if args.length == 0
-
raise ArgumentError.new('wrong number of arguments (0 for 1+)')
-
elsif args.length > 0 && args.first.is_a?(String)
-
clazz_name = args.shift
-
end
-
FACTORY.define_struct(clazz_name, args, &block)
-
end
-
-
1
FACTORY = Class.new(Synchronization::LockableObject) do
-
1
def define_struct(name, members, &block)
-
synchronize do
-
clazz = Synchronization::AbstractStruct.define_struct_class(MutableStruct, Synchronization::LockableObject, name, members, &block)
-
members.each_with_index do |member, index|
-
clazz.send(:define_method, member) do
-
synchronize { @values[index] }
-
end
-
clazz.send(:define_method, "#{member}=") do |value|
-
synchronize { @values[index] = value }
-
end
-
end
-
clazz
-
end
-
end
-
end.new
-
1
private_constant :FACTORY
-
end
-
end
-
1
require 'concurrent/concern/dereferenceable'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# An `MVar` is a synchronized single element container. They are empty or
-
# contain one item. Taking a value from an empty `MVar` blocks, as does
-
# putting a value into a full one. You can either think of them as blocking
-
# queue of length one, or a special kind of mutable variable.
-
#
-
# On top of the fundamental `#put` and `#take` operations, we also provide a
-
# `#mutate` that is atomic with respect to operations on the same instance.
-
# These operations all support timeouts.
-
#
-
# We also support non-blocking operations `#try_put!` and `#try_take!`, a
-
# `#set!` that ignores existing values, a `#value` that returns the value
-
# without removing it or returns `MVar::EMPTY`, and a `#modify!` that yields
-
# `MVar::EMPTY` if the `MVar` is empty and can be used to set `MVar::EMPTY`.
-
# You shouldn't use these operations in the first instance.
-
#
-
# `MVar` is a [Dereferenceable](Dereferenceable).
-
#
-
# `MVar` is related to M-structures in Id, `MVar` in Haskell and `SyncVar` in Scala.
-
#
-
# Note that unlike the original Haskell paper, our `#take` is blocking. This is how
-
# Haskell and Scala do it today.
-
#
-
# @!macro copy_options
-
#
-
# ## See Also
-
#
-
# 1. P. Barth, R. Nikhil, and Arvind. [M-Structures: Extending a parallel, non- strict, functional language with state](http://dl.acm.org/citation.cfm?id=652538). In Proceedings of the 5th
-
# ACM Conference on Functional Programming Languages and Computer Architecture (FPCA), 1991.
-
#
-
# 2. S. Peyton Jones, A. Gordon, and S. Finne. [Concurrent Haskell](http://dl.acm.org/citation.cfm?id=237794).
-
# In Proceedings of the 23rd Symposium on Principles of Programming Languages
-
# (PoPL), 1996.
-
1
class MVar < Synchronization::Object
-
1
include Concern::Dereferenceable
-
1
safe_initialization!
-
-
# Unique value that represents that an `MVar` was empty
-
1
EMPTY = Object.new
-
-
# Unique value that represents that an `MVar` timed out before it was able
-
# to produce a value.
-
1
TIMEOUT = Object.new
-
-
# Create a new `MVar`, either empty or with an initial value.
-
#
-
# @param [Hash] opts the options controlling how the future will be processed
-
#
-
# @!macro deref_options
-
1
def initialize(value = EMPTY, opts = {})
-
@value = value
-
@mutex = Mutex.new
-
@empty_condition = ConditionVariable.new
-
@full_condition = ConditionVariable.new
-
set_deref_options(opts)
-
end
-
-
# Remove the value from an `MVar`, leaving it empty, and blocking if there
-
# isn't a value. A timeout can be set to limit the time spent blocked, in
-
# which case it returns `TIMEOUT` if the time is exceeded.
-
# @return [Object] the value that was taken, or `TIMEOUT`
-
1
def take(timeout = nil)
-
@mutex.synchronize do
-
wait_for_full(timeout)
-
-
# If we timed out we'll still be empty
-
if unlocked_full?
-
value = @value
-
@value = EMPTY
-
@empty_condition.signal
-
apply_deref_options(value)
-
else
-
TIMEOUT
-
end
-
end
-
end
-
-
# acquires lock on the from an `MVAR`, yields the value to provided block,
-
# and release lock. A timeout can be set to limit the time spent blocked,
-
# in which case it returns `TIMEOUT` if the time is exceeded.
-
# @return [Object] the value returned by the block, or `TIMEOUT`
-
1
def borrow(timeout = nil)
-
@mutex.synchronize do
-
wait_for_full(timeout)
-
-
# if we timeoud out we'll still be empty
-
if unlocked_full?
-
yield @value
-
else
-
TIMEOUT
-
end
-
end
-
end
-
-
# Put a value into an `MVar`, blocking if there is already a value until
-
# it is empty. A timeout can be set to limit the time spent blocked, in
-
# which case it returns `TIMEOUT` if the time is exceeded.
-
# @return [Object] the value that was put, or `TIMEOUT`
-
1
def put(value, timeout = nil)
-
@mutex.synchronize do
-
wait_for_empty(timeout)
-
-
# If we timed out we won't be empty
-
if unlocked_empty?
-
@value = value
-
@full_condition.signal
-
apply_deref_options(value)
-
else
-
TIMEOUT
-
end
-
end
-
end
-
-
# Atomically `take`, yield the value to a block for transformation, and then
-
# `put` the transformed value. Returns the transformed value. A timeout can
-
# be set to limit the time spent blocked, in which case it returns `TIMEOUT`
-
# if the time is exceeded.
-
# @return [Object] the transformed value, or `TIMEOUT`
-
1
def modify(timeout = nil)
-
raise ArgumentError.new('no block given') unless block_given?
-
-
@mutex.synchronize do
-
wait_for_full(timeout)
-
-
# If we timed out we'll still be empty
-
if unlocked_full?
-
value = @value
-
@value = yield value
-
@full_condition.signal
-
apply_deref_options(value)
-
else
-
TIMEOUT
-
end
-
end
-
end
-
-
# Non-blocking version of `take`, that returns `EMPTY` instead of blocking.
-
1
def try_take!
-
@mutex.synchronize do
-
if unlocked_full?
-
value = @value
-
@value = EMPTY
-
@empty_condition.signal
-
apply_deref_options(value)
-
else
-
EMPTY
-
end
-
end
-
end
-
-
# Non-blocking version of `put`, that returns whether or not it was successful.
-
1
def try_put!(value)
-
@mutex.synchronize do
-
if unlocked_empty?
-
@value = value
-
@full_condition.signal
-
true
-
else
-
false
-
end
-
end
-
end
-
-
# Non-blocking version of `put` that will overwrite an existing value.
-
1
def set!(value)
-
@mutex.synchronize do
-
old_value = @value
-
@value = value
-
@full_condition.signal
-
apply_deref_options(old_value)
-
end
-
end
-
-
# Non-blocking version of `modify` that will yield with `EMPTY` if there is no value yet.
-
1
def modify!
-
raise ArgumentError.new('no block given') unless block_given?
-
-
@mutex.synchronize do
-
value = @value
-
@value = yield value
-
if unlocked_empty?
-
@empty_condition.signal
-
else
-
@full_condition.signal
-
end
-
apply_deref_options(value)
-
end
-
end
-
-
# Returns if the `MVar` is currently empty.
-
1
def empty?
-
@mutex.synchronize { @value == EMPTY }
-
end
-
-
# Returns if the `MVar` currently contains a value.
-
1
def full?
-
!empty?
-
end
-
-
1
protected
-
-
1
def synchronize(&block)
-
@mutex.synchronize(&block)
-
end
-
-
1
private
-
-
1
def unlocked_empty?
-
@value == EMPTY
-
end
-
-
1
def unlocked_full?
-
! unlocked_empty?
-
end
-
-
1
def wait_for_full(timeout)
-
wait_while(@full_condition, timeout) { unlocked_empty? }
-
end
-
-
1
def wait_for_empty(timeout)
-
wait_while(@empty_condition, timeout) { unlocked_full? }
-
end
-
-
1
def wait_while(condition, timeout)
-
if timeout.nil?
-
while yield
-
condition.wait(@mutex)
-
end
-
else
-
stop = Concurrent.monotonic_time + timeout
-
while yield && timeout > 0.0
-
condition.wait(@mutex, timeout)
-
timeout = stop - Concurrent.monotonic_time
-
end
-
end
-
end
-
end
-
end
-
1
require 'concurrent/configuration'
-
-
1
module Concurrent
-
-
# @!visibility private
-
1
module Options
-
-
# Get the requested `Executor` based on the values set in the options hash.
-
#
-
# @param [Hash] opts the options defining the requested executor
-
# @option opts [Executor] :executor when set use the given `Executor` instance.
-
# Three special values are also supported: `:fast` returns the global fast executor,
-
# `:io` returns the global io executor, and `:immediate` returns a new
-
# `ImmediateExecutor` object.
-
#
-
# @return [Executor, nil] the requested thread pool, or nil when no option specified
-
#
-
# @!visibility private
-
1
def self.executor_from_options(opts = {}) # :nodoc:
-
if identifier = opts.fetch(:executor, nil)
-
executor(identifier)
-
else
-
nil
-
end
-
end
-
-
1
def self.executor(executor_identifier)
-
case executor_identifier
-
when :fast
-
Concurrent.global_fast_executor
-
when :io
-
Concurrent.global_io_executor
-
when :immediate
-
Concurrent.global_immediate_executor
-
when Concurrent::ExecutorService
-
executor_identifier
-
else
-
raise ArgumentError, "executor not recognized by '#{executor_identifier}'"
-
end
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'concurrent/constants'
-
1
require 'concurrent/errors'
-
1
require 'concurrent/ivar'
-
1
require 'concurrent/executor/safe_task_executor'
-
-
1
require 'concurrent/options'
-
-
1
module Concurrent
-
-
1
PromiseExecutionError = Class.new(StandardError)
-
-
# Promises are inspired by the JavaScript [Promises/A](http://wiki.commonjs.org/wiki/Promises/A)
-
# and [Promises/A+](http://promises-aplus.github.io/promises-spec/) specifications.
-
#
-
# > A promise represents the eventual value returned from the single
-
# > completion of an operation.
-
#
-
# Promises are similar to futures and share many of the same behaviours.
-
# Promises are far more robust, however. Promises can be chained in a tree
-
# structure where each promise may have zero or more children. Promises are
-
# chained using the `then` method. The result of a call to `then` is always
-
# another promise. Promises are resolved asynchronously (with respect to the
-
# main thread) but in a strict order: parents are guaranteed to be resolved
-
# before their children, children before their younger siblings. The `then`
-
# method takes two parameters: an optional block to be executed upon parent
-
# resolution and an optional callable to be executed upon parent failure. The
-
# result of each promise is passed to each of its children upon resolution.
-
# When a promise is rejected all its children will be summarily rejected and
-
# will receive the reason.
-
#
-
# Promises have several possible states: *:unscheduled*, *:pending*,
-
# *:processing*, *:rejected*, or *:fulfilled*. These are also aggregated as
-
# `#incomplete?` and `#complete?`. When a Promise is created it is set to
-
# *:unscheduled*. Once the `#execute` method is called the state becomes
-
# *:pending*. Once a job is pulled from the thread pool's queue and is given
-
# to a thread for processing (often immediately upon `#post`) the state
-
# becomes *:processing*. The future will remain in this state until processing
-
# is complete. A future that is in the *:unscheduled*, *:pending*, or
-
# *:processing* is considered `#incomplete?`. A `#complete?` Promise is either
-
# *:rejected*, indicating that an exception was thrown during processing, or
-
# *:fulfilled*, indicating success. If a Promise is *:fulfilled* its `#value`
-
# will be updated to reflect the result of the operation. If *:rejected* the
-
# `reason` will be updated with a reference to the thrown exception. The
-
# predicate methods `#unscheduled?`, `#pending?`, `#rejected?`, and
-
# `#fulfilled?` can be called at any time to obtain the state of the Promise,
-
# as can the `#state` method, which returns a symbol.
-
#
-
# Retrieving the value of a promise is done through the `value` (alias:
-
# `deref`) method. Obtaining the value of a promise is a potentially blocking
-
# operation. When a promise is *rejected* a call to `value` will return `nil`
-
# immediately. When a promise is *fulfilled* a call to `value` will
-
# immediately return the current value. When a promise is *pending* a call to
-
# `value` will block until the promise is either *rejected* or *fulfilled*. A
-
# *timeout* value can be passed to `value` to limit how long the call will
-
# block. If `nil` the call will block indefinitely. If `0` the call will not
-
# block. Any other integer or float value will indicate the maximum number of
-
# seconds to block.
-
#
-
# Promises run on the global thread pool.
-
#
-
# @!macro copy_options
-
#
-
# ### Examples
-
#
-
# Start by requiring promises
-
#
-
# ```ruby
-
# require 'concurrent'
-
# ```
-
#
-
# Then create one
-
#
-
# ```ruby
-
# p = Concurrent::Promise.execute do
-
# # do something
-
# 42
-
# end
-
# ```
-
#
-
# Promises can be chained using the `then` method. The `then` method accepts a
-
# block and an executor, to be executed on fulfillment, and a callable argument to be executed
-
# on rejection. The result of the each promise is passed as the block argument
-
# to chained promises.
-
#
-
# ```ruby
-
# p = Concurrent::Promise.new{10}.then{|x| x * 2}.then{|result| result - 10 }.execute
-
# ```
-
#
-
# And so on, and so on, and so on...
-
#
-
# ```ruby
-
# p = Concurrent::Promise.fulfill(20).
-
# then{|result| result - 10 }.
-
# then{|result| result * 3 }.
-
# then(executor: different_executor){|result| result % 5 }.execute
-
# ```
-
#
-
# The initial state of a newly created Promise depends on the state of its parent:
-
# - if parent is *unscheduled* the child will be *unscheduled*
-
# - if parent is *pending* the child will be *pending*
-
# - if parent is *fulfilled* the child will be *pending*
-
# - if parent is *rejected* the child will be *pending* (but will ultimately be *rejected*)
-
#
-
# Promises are executed asynchronously from the main thread. By the time a
-
# child Promise finishes intialization it may be in a different state than its
-
# parent (by the time a child is created its parent may have completed
-
# execution and changed state). Despite being asynchronous, however, the order
-
# of execution of Promise objects in a chain (or tree) is strictly defined.
-
#
-
# There are multiple ways to create and execute a new `Promise`. Both ways
-
# provide identical behavior:
-
#
-
# ```ruby
-
# # create, operate, then execute
-
# p1 = Concurrent::Promise.new{ "Hello World!" }
-
# p1.state #=> :unscheduled
-
# p1.execute
-
#
-
# # create and immediately execute
-
# p2 = Concurrent::Promise.new{ "Hello World!" }.execute
-
#
-
# # execute during creation
-
# p3 = Concurrent::Promise.execute{ "Hello World!" }
-
# ```
-
#
-
# Once the `execute` method is called a `Promise` becomes `pending`:
-
#
-
# ```ruby
-
# p = Concurrent::Promise.execute{ "Hello, world!" }
-
# p.state #=> :pending
-
# p.pending? #=> true
-
# ```
-
#
-
# Wait a little bit, and the promise will resolve and provide a value:
-
#
-
# ```ruby
-
# p = Concurrent::Promise.execute{ "Hello, world!" }
-
# sleep(0.1)
-
#
-
# p.state #=> :fulfilled
-
# p.fulfilled? #=> true
-
# p.value #=> "Hello, world!"
-
# ```
-
#
-
# If an exception occurs, the promise will be rejected and will provide
-
# a reason for the rejection:
-
#
-
# ```ruby
-
# p = Concurrent::Promise.execute{ raise StandardError.new("Here comes the Boom!") }
-
# sleep(0.1)
-
#
-
# p.state #=> :rejected
-
# p.rejected? #=> true
-
# p.reason #=> "#<StandardError: Here comes the Boom!>"
-
# ```
-
#
-
# #### Rejection
-
#
-
# When a promise is rejected all its children will be rejected and will
-
# receive the rejection `reason` as the rejection callable parameter:
-
#
-
# ```ruby
-
# p = [ Concurrent::Promise.execute{ Thread.pass; raise StandardError } ]
-
#
-
# c1 = p.then(Proc.new{ |reason| 42 })
-
# c2 = p.then(Proc.new{ |reason| raise 'Boom!' })
-
#
-
# sleep(0.1)
-
#
-
# c1.state #=> :rejected
-
# c2.state #=> :rejected
-
# ```
-
#
-
# Once a promise is rejected it will continue to accept children that will
-
# receive immediately rejection (they will be executed asynchronously).
-
#
-
# #### Aliases
-
#
-
# The `then` method is the most generic alias: it accepts a block to be
-
# executed upon parent fulfillment and a callable to be executed upon parent
-
# rejection. At least one of them should be passed. The default block is `{
-
# |result| result }` that fulfills the child with the parent value. The
-
# default callable is `{ |reason| raise reason }` that rejects the child with
-
# the parent reason.
-
#
-
# - `on_success { |result| ... }` is the same as `then {|result| ... }`
-
# - `rescue { |reason| ... }` is the same as `then(Proc.new { |reason| ... } )`
-
# - `rescue` is aliased by `catch` and `on_error`
-
1
class Promise < IVar
-
-
# Initialize a new Promise with the provided options.
-
#
-
# @!macro executor_and_deref_options
-
#
-
# @!macro [attach] promise_init_options
-
#
-
# @option opts [Promise] :parent the parent `Promise` when building a chain/tree
-
# @option opts [Proc] :on_fulfill fulfillment handler
-
# @option opts [Proc] :on_reject rejection handler
-
# @option opts [object, Array] :args zero or more arguments to be passed
-
# the task block on execution
-
#
-
# @yield The block operation to be performed asynchronously.
-
#
-
# @raise [ArgumentError] if no block is given
-
#
-
# @see http://wiki.commonjs.org/wiki/Promises/A
-
# @see http://promises-aplus.github.io/promises-spec/
-
1
def initialize(opts = {}, &block)
-
opts.delete_if { |k, v| v.nil? }
-
super(NULL, opts.merge(__promise_body_from_block__: block), &nil)
-
end
-
-
# Create a new `Promise` and fulfill it immediately.
-
#
-
# @!macro executor_and_deref_options
-
#
-
# @!macro promise_init_options
-
#
-
# @raise [ArgumentError] if no block is given
-
#
-
# @return [Promise] the newly created `Promise`
-
1
def self.fulfill(value, opts = {})
-
Promise.new(opts).tap { |p| p.send(:synchronized_set_state!, true, value, nil) }
-
end
-
-
# Create a new `Promise` and reject it immediately.
-
#
-
# @!macro executor_and_deref_options
-
#
-
# @!macro promise_init_options
-
#
-
# @raise [ArgumentError] if no block is given
-
#
-
# @return [Promise] the newly created `Promise`
-
1
def self.reject(reason, opts = {})
-
Promise.new(opts).tap { |p| p.send(:synchronized_set_state!, false, nil, reason) }
-
end
-
-
# Execute an `:unscheduled` `Promise`. Immediately sets the state to `:pending` and
-
# passes the block to a new thread/thread pool for eventual execution.
-
# Does nothing if the `Promise` is in any state other than `:unscheduled`.
-
#
-
# @return [Promise] a reference to `self`
-
1
def execute
-
if root?
-
if compare_and_set_state(:pending, :unscheduled)
-
set_pending
-
realize(@promise_body)
-
end
-
else
-
@parent.execute
-
end
-
self
-
end
-
-
# @!macro ivar_set_method
-
#
-
# @raise [Concurrent::PromiseExecutionError] if not the root promise
-
1
def set(value = NULL, &block)
-
raise PromiseExecutionError.new('supported only on root promise') unless root?
-
check_for_block_or_value!(block_given?, value)
-
synchronize do
-
if @state != :unscheduled
-
raise MultipleAssignmentError
-
else
-
@promise_body = block || Proc.new { |result| value }
-
end
-
end
-
execute
-
end
-
-
# @!macro ivar_fail_method
-
#
-
# @raise [Concurrent::PromiseExecutionError] if not the root promise
-
1
def fail(reason = StandardError.new)
-
set { raise reason }
-
end
-
-
# Create a new `Promise` object with the given block, execute it, and return the
-
# `:pending` object.
-
#
-
# @!macro executor_and_deref_options
-
#
-
# @!macro promise_init_options
-
#
-
# @return [Promise] the newly created `Promise` in the `:pending` state
-
#
-
# @raise [ArgumentError] if no block is given
-
#
-
# @example
-
# promise = Concurrent::Promise.execute{ sleep(1); 42 }
-
# promise.state #=> :pending
-
1
def self.execute(opts = {}, &block)
-
new(opts, &block).execute
-
end
-
-
# Chain a new promise off the current promise.
-
#
-
# @param [Proc] rescuer An optional rescue block to be executed if the
-
# promise is rejected.
-
#
-
# @param [ThreadPool] executor An optional thread pool executor to be used
-
# in the new Promise
-
#
-
# @yield The block operation to be performed asynchronously.
-
#
-
# @return [Promise] the new promise
-
1
def then(rescuer = nil, executor = @executor, &block)
-
raise ArgumentError.new('rescuers and block are both missing') if rescuer.nil? && !block_given?
-
block = Proc.new { |result| result } unless block_given?
-
child = Promise.new(
-
parent: self,
-
executor: executor,
-
on_fulfill: block,
-
on_reject: rescuer
-
)
-
-
synchronize do
-
child.state = :pending if @state == :pending
-
child.on_fulfill(apply_deref_options(@value)) if @state == :fulfilled
-
child.on_reject(@reason) if @state == :rejected
-
@children << child
-
end
-
-
child
-
end
-
-
# Chain onto this promise an action to be undertaken on success
-
# (fulfillment).
-
#
-
# @yield The block to execute
-
#
-
# @return [Promise] self
-
1
def on_success(&block)
-
raise ArgumentError.new('no block given') unless block_given?
-
self.then(&block)
-
end
-
-
# Chain onto this promise an action to be undertaken on failure
-
# (rejection).
-
#
-
# @yield The block to execute
-
#
-
# @return [Promise] self
-
1
def rescue(&block)
-
self.then(block)
-
end
-
-
1
alias_method :catch, :rescue
-
1
alias_method :on_error, :rescue
-
-
# Yield the successful result to the block that returns a promise. If that
-
# promise is also successful the result is the result of the yielded promise.
-
# If either part fails the whole also fails.
-
#
-
# @example
-
# Promise.execute { 1 }.flat_map { |v| Promise.execute { v + 2 } }.value! #=> 3
-
#
-
# @return [Promise]
-
1
def flat_map(&block)
-
child = Promise.new(
-
parent: self,
-
executor: ImmediateExecutor.new,
-
)
-
-
on_error { |e| child.on_reject(e) }
-
on_success do |result1|
-
begin
-
inner = block.call(result1)
-
inner.execute
-
inner.on_success { |result2| child.on_fulfill(result2) }
-
inner.on_error { |e| child.on_reject(e) }
-
rescue => e
-
child.on_reject(e)
-
end
-
end
-
-
child
-
end
-
-
# Builds a promise that produces the result of promises in an Array
-
# and fails if any of them fails.
-
#
-
# @param [Array<Promise>] promises
-
#
-
# @return [Promise<Array>]
-
1
def self.zip(*promises)
-
zero = fulfill([], executor: ImmediateExecutor.new)
-
-
promises.reduce(zero) do |p1, p2|
-
p1.flat_map do |results|
-
p2.then do |next_result|
-
results << next_result
-
end
-
end
-
end
-
end
-
-
# Builds a promise that produces the result of self and others in an Array
-
# and fails if any of them fails.
-
#
-
# @param [Array<Promise>] others
-
#
-
# @return [Promise<Array>]
-
1
def zip(*others)
-
self.class.zip(self, *others)
-
end
-
-
# Aggregates a collection of promises and executes the `then` condition
-
# if all aggregated promises succeed. Executes the `rescue` handler with
-
# a `Concurrent::PromiseExecutionError` if any of the aggregated promises
-
# fail. Upon execution will execute any of the aggregate promises that
-
# were not already executed.
-
#
-
# @!macro [attach] promise_self_aggregate
-
#
-
# The returned promise will not yet have been executed. Additional `#then`
-
# and `#rescue` handlers may still be provided. Once the returned promise
-
# is execute the aggregate promises will be also be executed (if they have
-
# not been executed already). The results of the aggregate promises will
-
# be checked upon completion. The necessary `#then` and `#rescue` blocks
-
# on the aggregating promise will then be executed as appropriate. If the
-
# `#rescue` handlers are executed the raises exception will be
-
# `Concurrent::PromiseExecutionError`.
-
#
-
# @param [Array] promises Zero or more promises to aggregate
-
# @return [Promise] an unscheduled (not executed) promise that aggregates
-
# the promises given as arguments
-
1
def self.all?(*promises)
-
aggregate(:all?, *promises)
-
end
-
-
# Aggregates a collection of promises and executes the `then` condition
-
# if any aggregated promises succeed. Executes the `rescue` handler with
-
# a `Concurrent::PromiseExecutionError` if any of the aggregated promises
-
# fail. Upon execution will execute any of the aggregate promises that
-
# were not already executed.
-
#
-
# @!macro promise_self_aggregate
-
1
def self.any?(*promises)
-
aggregate(:any?, *promises)
-
end
-
-
1
protected
-
-
1
def ns_initialize(value, opts)
-
super
-
-
@executor = Options.executor_from_options(opts) || Concurrent.global_io_executor
-
@args = get_arguments_from(opts)
-
-
@parent = opts.fetch(:parent) { nil }
-
@on_fulfill = opts.fetch(:on_fulfill) { Proc.new { |result| result } }
-
@on_reject = opts.fetch(:on_reject) { Proc.new { |reason| raise reason } }
-
-
@promise_body = opts[:__promise_body_from_block__] || Proc.new { |result| result }
-
@state = :unscheduled
-
@children = []
-
end
-
-
# Aggregate a collection of zero or more promises under a composite promise,
-
# execute the aggregated promises and collect them into a standard Ruby array,
-
# call the given Ruby `Ennnumerable` predicate (such as `any?`, `all?`, `none?`,
-
# or `one?`) on the collection checking for the success or failure of each,
-
# then executing the composite's `#then` handlers if the predicate returns
-
# `true` or executing the composite's `#rescue` handlers if the predicate
-
# returns false.
-
#
-
# @!macro promise_self_aggregate
-
1
def self.aggregate(method, *promises)
-
composite = Promise.new do
-
completed = promises.collect do |promise|
-
promise.execute if promise.unscheduled?
-
promise.wait
-
promise
-
end
-
unless completed.empty? || completed.send(method){|promise| promise.fulfilled? }
-
raise PromiseExecutionError
-
end
-
end
-
composite
-
end
-
-
# @!visibility private
-
1
def set_pending
-
synchronize do
-
@state = :pending
-
@children.each { |c| c.set_pending }
-
end
-
end
-
-
# @!visibility private
-
1
def root? # :nodoc:
-
@parent.nil?
-
end
-
-
# @!visibility private
-
1
def on_fulfill(result)
-
realize Proc.new { @on_fulfill.call(result) }
-
nil
-
end
-
-
# @!visibility private
-
1
def on_reject(reason)
-
realize Proc.new { @on_reject.call(reason) }
-
nil
-
end
-
-
# @!visibility private
-
1
def notify_child(child)
-
if_state(:fulfilled) { child.on_fulfill(apply_deref_options(@value)) }
-
if_state(:rejected) { child.on_reject(@reason) }
-
end
-
-
# @!visibility private
-
1
def complete(success, value, reason)
-
children_to_notify = synchronize do
-
set_state!(success, value, reason)
-
@children.dup
-
end
-
-
children_to_notify.each { |child| notify_child(child) }
-
observers.notify_and_delete_observers{ [Time.now, self.value, reason] }
-
end
-
-
# @!visibility private
-
1
def realize(task)
-
@executor.post do
-
success, value, reason = SafeTaskExecutor.new(task, rescue_exception: true).execute(*@args)
-
complete(success, value, reason)
-
end
-
end
-
-
# @!visibility private
-
1
def set_state!(success, value, reason)
-
set_state(success, value, reason)
-
event.set
-
end
-
-
# @!visibility private
-
1
def synchronized_set_state!(success, value, reason)
-
synchronize { set_state!(success, value, reason) }
-
end
-
end
-
end
-
1
require 'concurrent/constants'
-
1
require 'concurrent/errors'
-
1
require 'concurrent/configuration'
-
1
require 'concurrent/ivar'
-
1
require 'concurrent/collection/copy_on_notify_observer_set'
-
1
require 'concurrent/utility/monotonic_time'
-
-
1
require 'concurrent/options'
-
-
1
module Concurrent
-
-
# `ScheduledTask` is a close relative of `Concurrent::Future` but with one
-
# important difference: A `Future` is set to execute as soon as possible
-
# whereas a `ScheduledTask` is set to execute after a specified delay. This
-
# implementation is loosely based on Java's
-
# [ScheduledExecutorService](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html).
-
# It is a more feature-rich variant of {Concurrent.timer}.
-
#
-
# The *intended* schedule time of task execution is set on object construction
-
# with the `delay` argument. The delay is a numeric (floating point or integer)
-
# representing a number of seconds in the future. Any other value or a numeric
-
# equal to or less than zero will result in an exception. The *actual* schedule
-
# time of task execution is set when the `execute` method is called.
-
#
-
# The constructor can also be given zero or more processing options. Currently
-
# the only supported options are those recognized by the
-
# [Dereferenceable](Dereferenceable) module.
-
#
-
# The final constructor argument is a block representing the task to be performed.
-
# If no block is given an `ArgumentError` will be raised.
-
#
-
# **States**
-
#
-
# `ScheduledTask` mixes in the [Obligation](Obligation) module thus giving it
-
# "future" behavior. This includes the expected lifecycle states. `ScheduledTask`
-
# has one additional state, however. While the task (block) is being executed the
-
# state of the object will be `:processing`. This additional state is necessary
-
# because it has implications for task cancellation.
-
#
-
# **Cancellation**
-
#
-
# A `:pending` task can be cancelled using the `#cancel` method. A task in any
-
# other state, including `:processing`, cannot be cancelled. The `#cancel`
-
# method returns a boolean indicating the success of the cancellation attempt.
-
# A cancelled `ScheduledTask` cannot be restarted. It is immutable.
-
#
-
# **Obligation and Observation**
-
#
-
# The result of a `ScheduledTask` can be obtained either synchronously or
-
# asynchronously. `ScheduledTask` mixes in both the [Obligation](Obligation)
-
# module and the
-
# [Observable](http://ruby-doc.org/stdlib-2.0/libdoc/observer/rdoc/Observable.html)
-
# module from the Ruby standard library. With one exception `ScheduledTask`
-
# behaves identically to [Future](Observable) with regard to these modules.
-
#
-
# @!macro copy_options
-
#
-
# @example Basic usage
-
#
-
# require 'concurrent'
-
# require 'thread' # for Queue
-
# require 'open-uri' # for open(uri)
-
#
-
# class Ticker
-
# def get_year_end_closing(symbol, year)
-
# uri = "http://ichart.finance.yahoo.com/table.csv?s=#{symbol}&a=11&b=01&c=#{year}&d=11&e=31&f=#{year}&g=m"
-
# data = open(uri) {|f| f.collect{|line| line.strip } }
-
# data[1].split(',')[4].to_f
-
# end
-
# end
-
#
-
# # Future
-
# price = Concurrent::Future.execute{ Ticker.new.get_year_end_closing('TWTR', 2013) }
-
# price.state #=> :pending
-
# sleep(1) # do other stuff
-
# price.value #=> 63.65
-
# price.state #=> :fulfilled
-
#
-
# # ScheduledTask
-
# task = Concurrent::ScheduledTask.execute(2){ Ticker.new.get_year_end_closing('INTC', 2013) }
-
# task.state #=> :pending
-
# sleep(3) # do other stuff
-
# task.value #=> 25.96
-
#
-
# @example Successful task execution
-
#
-
# task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }
-
# task.state #=> :unscheduled
-
# task.execute
-
# task.state #=> pending
-
#
-
# # wait for it...
-
# sleep(3)
-
#
-
# task.unscheduled? #=> false
-
# task.pending? #=> false
-
# task.fulfilled? #=> true
-
# task.rejected? #=> false
-
# task.value #=> 'What does the fox say?'
-
#
-
# @example One line creation and execution
-
#
-
# task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }.execute
-
# task.state #=> pending
-
#
-
# task = Concurrent::ScheduledTask.execute(2){ 'What do you get when you multiply 6 by 9?' }
-
# task.state #=> pending
-
#
-
# @example Failed task execution
-
#
-
# task = Concurrent::ScheduledTask.execute(2){ raise StandardError.new('Call me maybe?') }
-
# task.pending? #=> true
-
#
-
# # wait for it...
-
# sleep(3)
-
#
-
# task.unscheduled? #=> false
-
# task.pending? #=> false
-
# task.fulfilled? #=> false
-
# task.rejected? #=> true
-
# task.value #=> nil
-
# task.reason #=> #<StandardError: Call me maybe?>
-
#
-
# @example Task execution with observation
-
#
-
# observer = Class.new{
-
# def update(time, value, reason)
-
# puts "The task completed at #{time} with value '#{value}'"
-
# end
-
# }.new
-
#
-
# task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }
-
# task.add_observer(observer)
-
# task.execute
-
# task.pending? #=> true
-
#
-
# # wait for it...
-
# sleep(3)
-
#
-
# #>> The task completed at 2013-11-07 12:26:09 -0500 with value 'What does the fox say?'
-
#
-
# @!macro monotonic_clock_warning
-
#
-
# @see Concurrent.timer
-
1
class ScheduledTask < IVar
-
1
include Comparable
-
-
# The executor on which to execute the task.
-
# @!visibility private
-
1
attr_reader :executor
-
-
# Schedule a task for execution at a specified future time.
-
#
-
# @param [Float] delay the number of seconds to wait for before executing the task
-
#
-
# @yield the task to be performed
-
#
-
# @!macro executor_and_deref_options
-
#
-
# @option opts [object, Array] :args zero or more arguments to be passed the task
-
# block on execution
-
#
-
# @raise [ArgumentError] When no block is given
-
# @raise [ArgumentError] When given a time that is in the past
-
1
def initialize(delay, opts = {}, &task)
-
raise ArgumentError.new('no block given') unless block_given?
-
raise ArgumentError.new('seconds must be greater than zero') if delay.to_f < 0.0
-
-
super(NULL, opts, &nil)
-
-
synchronize do
-
ns_set_state(:unscheduled)
-
@parent = opts.fetch(:timer_set, Concurrent.global_timer_set)
-
@args = get_arguments_from(opts)
-
@delay = delay.to_f
-
@task = task
-
@time = nil
-
@executor = Options.executor_from_options(opts) || Concurrent.global_io_executor
-
self.observers = Collection::CopyOnNotifyObserverSet.new
-
end
-
end
-
-
# The `delay` value given at instanciation.
-
#
-
# @return [Float] the initial delay.
-
1
def initial_delay
-
synchronize { @delay }
-
end
-
-
# The monotonic time at which the the task is scheduled to be executed.
-
#
-
# @return [Float] the schedule time or nil if `unscheduled`
-
1
def schedule_time
-
synchronize { @time }
-
end
-
-
# Comparator which orders by schedule time.
-
#
-
# @!visibility private
-
1
def <=>(other)
-
schedule_time <=> other.schedule_time
-
end
-
-
# Has the task been cancelled?
-
#
-
# @return [Boolean] true if the task is in the given state else false
-
1
def cancelled?
-
synchronize { ns_check_state?(:cancelled) }
-
end
-
-
# In the task execution in progress?
-
#
-
# @return [Boolean] true if the task is in the given state else false
-
1
def processing?
-
synchronize { ns_check_state?(:processing) }
-
end
-
-
# Cancel this task and prevent it from executing. A task can only be
-
# cancelled if it is pending or unscheduled.
-
#
-
# @return [Boolean] true if successfully cancelled else false
-
1
def cancel
-
if compare_and_set_state(:cancelled, :pending, :unscheduled)
-
complete(false, nil, CancelledOperationError.new)
-
# To avoid deadlocks this call must occur outside of #synchronize
-
# Changing the state above should prevent redundant calls
-
@parent.send(:remove_task, self)
-
else
-
false
-
end
-
end
-
-
# Reschedule the task using the original delay and the current time.
-
# A task can only be reset while it is `:pending`.
-
#
-
# @return [Boolean] true if successfully rescheduled else false
-
1
def reset
-
synchronize{ ns_reschedule(@delay) }
-
end
-
-
# Reschedule the task using the given delay and the current time.
-
# A task can only be reset while it is `:pending`.
-
#
-
# @param [Float] delay the number of seconds to wait for before executing the task
-
#
-
# @return [Boolean] true if successfully rescheduled else false
-
#
-
# @raise [ArgumentError] When given a time that is in the past
-
1
def reschedule(delay)
-
delay = delay.to_f
-
raise ArgumentError.new('seconds must be greater than zero') if delay < 0.0
-
synchronize{ ns_reschedule(delay) }
-
end
-
-
# Execute an `:unscheduled` `ScheduledTask`. Immediately sets the state to `:pending`
-
# and starts counting down toward execution. Does nothing if the `ScheduledTask` is
-
# in any state other than `:unscheduled`.
-
#
-
# @return [ScheduledTask] a reference to `self`
-
1
def execute
-
if compare_and_set_state(:pending, :unscheduled)
-
synchronize{ ns_schedule(@delay) }
-
end
-
self
-
end
-
-
# Create a new `ScheduledTask` object with the given block, execute it, and return the
-
# `:pending` object.
-
#
-
# @param [Float] delay the number of seconds to wait for before executing the task
-
#
-
# @!macro executor_and_deref_options
-
#
-
# @return [ScheduledTask] the newly created `ScheduledTask` in the `:pending` state
-
#
-
# @raise [ArgumentError] if no block is given
-
1
def self.execute(delay, opts = {}, &task)
-
new(delay, opts, &task).execute
-
end
-
-
# Execute the task.
-
#
-
# @!visibility private
-
1
def process_task
-
safe_execute(@task, @args)
-
end
-
-
1
protected :set, :try_set, :fail, :complete
-
-
1
protected
-
-
# Schedule the task using the given delay and the current time.
-
#
-
# @param [Float] delay the number of seconds to wait for before executing the task
-
#
-
# @return [Boolean] true if successfully rescheduled else false
-
#
-
# @!visibility private
-
1
def ns_schedule(delay)
-
@delay = delay
-
@time = Concurrent.monotonic_time + @delay
-
@parent.send(:post_task, self)
-
end
-
-
# Reschedule the task using the given delay and the current time.
-
# A task can only be reset while it is `:pending`.
-
#
-
# @param [Float] delay the number of seconds to wait for before executing the task
-
#
-
# @return [Boolean] true if successfully rescheduled else false
-
#
-
# @!visibility private
-
1
def ns_reschedule(delay)
-
return false unless ns_check_state?(:pending)
-
@parent.send(:remove_task, self) && ns_schedule(delay)
-
end
-
end
-
end
-
1
require 'concurrent/synchronization/abstract_struct'
-
1
require 'concurrent/errors'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# An thread-safe, write-once variation of Ruby's standard `Struct`.
-
# Each member can have its value set at most once, either at construction
-
# or any time thereafter. Attempting to assign a value to a member
-
# that has already been set will result in a `Concurrent::ImmutabilityError`.
-
#
-
# @see http://ruby-doc.org/core-2.2.0/Struct.html Ruby standard library `Struct`
-
# @see http://en.wikipedia.org/wiki/Final_(Java) Java `final` keyword
-
1
module SettableStruct
-
1
include Synchronization::AbstractStruct
-
-
# @!macro struct_values
-
1
def values
-
synchronize { ns_values }
-
end
-
1
alias_method :to_a, :values
-
-
# @!macro struct_values_at
-
1
def values_at(*indexes)
-
synchronize { ns_values_at(indexes) }
-
end
-
-
# @!macro struct_inspect
-
1
def inspect
-
synchronize { ns_inspect }
-
end
-
1
alias_method :to_s, :inspect
-
-
# @!macro struct_merge
-
1
def merge(other, &block)
-
synchronize { ns_merge(other, &block) }
-
end
-
-
# @!macro struct_to_h
-
1
def to_h
-
synchronize { ns_to_h }
-
end
-
-
# @!macro struct_get
-
1
def [](member)
-
synchronize { ns_get(member) }
-
end
-
-
# @!macro struct_equality
-
1
def ==(other)
-
synchronize { ns_equality(other) }
-
end
-
-
# @!macro struct_each
-
1
def each(&block)
-
return enum_for(:each) unless block_given?
-
synchronize { ns_each(&block) }
-
end
-
-
# @!macro struct_each_pair
-
1
def each_pair(&block)
-
return enum_for(:each_pair) unless block_given?
-
synchronize { ns_each_pair(&block) }
-
end
-
-
# @!macro struct_select
-
1
def select(&block)
-
return enum_for(:select) unless block_given?
-
synchronize { ns_select(&block) }
-
end
-
-
# @!macro struct_set
-
#
-
# @raise [Concurrent::ImmutabilityError] if the given member has already been set
-
1
def []=(member, value)
-
if member.is_a? Integer
-
length = synchronize { @values.length }
-
if member >= length
-
raise IndexError.new("offset #{member} too large for struct(size:#{length})")
-
end
-
synchronize do
-
unless @values[member].nil?
-
raise Concurrent::ImmutabilityError.new('struct member has already been set')
-
end
-
@values[member] = value
-
end
-
else
-
send("#{member}=", value)
-
end
-
rescue NoMethodError
-
raise NameError.new("no member '#{member}' in struct")
-
end
-
-
# @!macro struct_new
-
1
def self.new(*args, &block)
-
clazz_name = nil
-
if args.length == 0
-
raise ArgumentError.new('wrong number of arguments (0 for 1+)')
-
elsif args.length > 0 && args.first.is_a?(String)
-
clazz_name = args.shift
-
end
-
FACTORY.define_struct(clazz_name, args, &block)
-
end
-
-
1
FACTORY = Class.new(Synchronization::LockableObject) do
-
1
def define_struct(name, members, &block)
-
synchronize do
-
clazz = Synchronization::AbstractStruct.define_struct_class(SettableStruct, Synchronization::LockableObject, name, members, &block)
-
members.each_with_index do |member, index|
-
clazz.send(:define_method, member) do
-
synchronize { @values[index] }
-
end
-
clazz.send(:define_method, "#{member}=") do |value|
-
synchronize do
-
unless @values[index].nil?
-
raise Concurrent::ImmutabilityError.new('struct member has already been set')
-
end
-
@values[index] = value
-
end
-
end
-
end
-
clazz
-
end
-
end
-
end.new
-
1
private_constant :FACTORY
-
end
-
end
-
1
require 'concurrent/utility/engine'
-
-
1
require 'concurrent/synchronization/abstract_object'
-
1
require 'concurrent/utility/native_extension_loader' # load native parts first
-
1
Concurrent.load_native_extensions
-
-
1
require 'concurrent/synchronization/mri_object'
-
1
require 'concurrent/synchronization/jruby_object'
-
1
require 'concurrent/synchronization/rbx_object'
-
1
require 'concurrent/synchronization/truffle_object'
-
1
require 'concurrent/synchronization/object'
-
1
require 'concurrent/synchronization/volatile'
-
-
1
require 'concurrent/synchronization/abstract_lockable_object'
-
1
require 'concurrent/synchronization/mri_lockable_object'
-
1
require 'concurrent/synchronization/jruby_lockable_object'
-
1
require 'concurrent/synchronization/rbx_lockable_object'
-
1
require 'concurrent/synchronization/truffle_lockable_object'
-
-
1
require 'concurrent/synchronization/lockable_object'
-
-
1
require 'concurrent/synchronization/condition'
-
1
require 'concurrent/synchronization/lock'
-
-
1
module Concurrent
-
# {include:file:doc/synchronization.md}
-
# {include:file:doc/synchronization-notes.md}
-
1
module Synchronization
-
end
-
end
-
-
1
module Concurrent
-
1
module Synchronization
-
-
# @!visibility private
-
1
class AbstractLockableObject < Synchronization::Object
-
-
1
protected
-
-
# @!macro [attach] synchronization_object_method_synchronize
-
#
-
# @yield runs the block synchronized against this object,
-
# equivalent of java's `synchronize(this) {}`
-
# @note can by made public in descendants if required by `public :synchronize`
-
1
def synchronize
-
raise NotImplementedError
-
end
-
-
# @!macro [attach] synchronization_object_method_ns_wait_until
-
#
-
# Wait until condition is met or timeout passes,
-
# protects against spurious wake-ups.
-
# @param [Numeric, nil] timeout in seconds, `nil` means no timeout
-
# @yield condition to be met
-
# @yieldreturn [true, false]
-
# @return [true, false] if condition met
-
# @note only to be used inside synchronized block
-
# @note to provide direct access to this method in a descendant add method
-
# ```
-
# def wait_until(timeout = nil, &condition)
-
# synchronize { ns_wait_until(timeout, &condition) }
-
# end
-
# ```
-
1
def ns_wait_until(timeout = nil, &condition)
-
if timeout
-
wait_until = Concurrent.monotonic_time + timeout
-
loop do
-
now = Concurrent.monotonic_time
-
condition_result = condition.call
-
return condition_result if now >= wait_until || condition_result
-
ns_wait wait_until - now
-
end
-
else
-
ns_wait timeout until condition.call
-
true
-
end
-
end
-
-
# @!macro [attach] synchronization_object_method_ns_wait
-
#
-
# Wait until another thread calls #signal or #broadcast,
-
# spurious wake-ups can happen.
-
#
-
# @param [Numeric, nil] timeout in seconds, `nil` means no timeout
-
# @return [self]
-
# @note only to be used inside synchronized block
-
# @note to provide direct access to this method in a descendant add method
-
# ```
-
# def wait(timeout = nil)
-
# synchronize { ns_wait(timeout) }
-
# end
-
# ```
-
1
def ns_wait(timeout = nil)
-
raise NotImplementedError
-
end
-
-
# @!macro [attach] synchronization_object_method_ns_signal
-
#
-
# Signal one waiting thread.
-
# @return [self]
-
# @note only to be used inside synchronized block
-
# @note to provide direct access to this method in a descendant add method
-
# ```
-
# def signal
-
# synchronize { ns_signal }
-
# end
-
# ```
-
1
def ns_signal
-
raise NotImplementedError
-
end
-
-
# @!macro [attach] synchronization_object_method_ns_broadcast
-
#
-
# Broadcast to all waiting threads.
-
# @return [self]
-
# @note only to be used inside synchronized block
-
# @note to provide direct access to this method in a descendant add method
-
# ```
-
# def broadcast
-
# synchronize { ns_broadcast }
-
# end
-
# ```
-
1
def ns_broadcast
-
raise NotImplementedError
-
end
-
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class AbstractObject
-
-
# @abstract has to be implemented based on Ruby runtime
-
1
def initialize
-
raise NotImplementedError
-
end
-
-
# @!visibility private
-
# @abstract
-
1
def full_memory_barrier
-
raise NotImplementedError
-
end
-
-
1
def self.attr_volatile(*names)
-
raise NotImplementedError
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
module AbstractStruct
-
-
# @!visibility private
-
1
def initialize(*values)
-
super()
-
ns_initialize(*values)
-
end
-
-
# @!macro [attach] struct_length
-
#
-
# Returns the number of struct members.
-
#
-
# @return [Fixnum] the number of struct members
-
1
def length
-
self.class::MEMBERS.length
-
end
-
1
alias_method :size, :length
-
-
# @!macro [attach] struct_members
-
#
-
# Returns the struct members as an array of symbols.
-
#
-
# @return [Array] the struct members as an array of symbols
-
1
def members
-
self.class::MEMBERS.dup
-
end
-
-
1
protected
-
-
# @!macro struct_values
-
#
-
# @!visibility private
-
1
def ns_values
-
@values.dup
-
end
-
-
# @!macro struct_values_at
-
#
-
# @!visibility private
-
1
def ns_values_at(indexes)
-
@values.values_at(*indexes)
-
end
-
-
# @!macro struct_to_h
-
#
-
# @!visibility private
-
1
def ns_to_h
-
length.times.reduce({}){|memo, i| memo[self.class::MEMBERS[i]] = @values[i]; memo}
-
end
-
-
# @!macro struct_get
-
#
-
# @!visibility private
-
1
def ns_get(member)
-
if member.is_a? Integer
-
if member >= @values.length
-
raise IndexError.new("offset #{member} too large for struct(size:#{@values.length})")
-
end
-
@values[member]
-
else
-
send(member)
-
end
-
rescue NoMethodError
-
raise NameError.new("no member '#{member}' in struct")
-
end
-
-
# @!macro struct_equality
-
#
-
# @!visibility private
-
1
def ns_equality(other)
-
self.class == other.class && self.values == other.values
-
end
-
-
# @!macro struct_each
-
#
-
# @!visibility private
-
1
def ns_each
-
values.each{|value| yield value }
-
end
-
-
# @!macro struct_each_pair
-
#
-
# @!visibility private
-
1
def ns_each_pair
-
@values.length.times do |index|
-
yield self.class::MEMBERS[index], @values[index]
-
end
-
end
-
-
# @!macro struct_select
-
#
-
# @!visibility private
-
1
def ns_select
-
values.select{|value| yield value }
-
end
-
-
# @!macro struct_inspect
-
#
-
# @!visibility private
-
1
def ns_inspect
-
struct = pr_underscore(self.class.ancestors[1])
-
clazz = ((self.class.to_s =~ /^#<Class:/) == 0) ? '' : " #{self.class}"
-
"#<#{struct}#{clazz} #{ns_to_h}>"
-
end
-
-
# @!macro struct_merge
-
#
-
# @!visibility private
-
1
def ns_merge(other, &block)
-
self.class.new(*self.to_h.merge(other, &block).values)
-
end
-
-
# @!visibility private
-
1
def pr_underscore(clazz)
-
word = clazz.to_s
-
word.gsub!(/::/, '/')
-
word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
-
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
-
word.tr!("-", "_")
-
word.downcase!
-
word
-
end
-
-
# @!visibility private
-
1
def self.define_struct_class(parent, base, name, members, &block)
-
clazz = Class.new(base || Object) do
-
include parent
-
self.const_set(:MEMBERS, members.collect{|member| member.to_s.to_sym}.freeze)
-
def ns_initialize(*values)
-
raise ArgumentError.new('struct size differs') if values.length > length
-
@values = values.fill(nil, values.length..length-1)
-
end
-
end
-
unless name.nil?
-
begin
-
parent.const_set(name, clazz)
-
parent.const_get(name)
-
rescue NameError
-
raise NameError.new("identifier #{name} needs to be constant")
-
end
-
end
-
members.each_with_index do |member, index|
-
clazz.send(:define_method, member) do
-
@values[index]
-
end
-
end
-
clazz.class_exec(&block) unless block.nil?
-
clazz
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
# TODO (pitr-ch 04-Dec-2016): should be in edge
-
1
class Condition < LockableObject
-
1
safe_initialization!
-
-
# TODO (pitr 12-Sep-2015): locks two objects, improve
-
# TODO (pitr 26-Sep-2015): study
-
# http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/concurrent/locks/AbstractQueuedSynchronizer.java#AbstractQueuedSynchronizer.Node
-
-
1
singleton_class.send :alias_method, :private_new, :new
-
1
private_class_method :new
-
-
1
def initialize(lock)
-
super()
-
@Lock = lock
-
end
-
-
1
def wait(timeout = nil)
-
@Lock.synchronize { ns_wait(timeout) }
-
end
-
-
1
def ns_wait(timeout = nil)
-
synchronize { super(timeout) }
-
end
-
-
1
def wait_until(timeout = nil, &condition)
-
@Lock.synchronize { ns_wait_until(timeout, &condition) }
-
end
-
-
1
def ns_wait_until(timeout = nil, &condition)
-
synchronize { super(timeout, &condition) }
-
end
-
-
1
def signal
-
@Lock.synchronize { ns_signal }
-
end
-
-
1
def ns_signal
-
synchronize { super }
-
end
-
-
1
def broadcast
-
@Lock.synchronize { ns_broadcast }
-
end
-
-
1
def ns_broadcast
-
synchronize { super }
-
end
-
end
-
-
1
class LockableObject < LockableObjectImplementation
-
1
def new_condition
-
Condition.private_new(self)
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
1
if Concurrent.on_jruby? && Concurrent.java_extensions_loaded?
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
class JRubyLockableObject < AbstractLockableObject
-
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
1
if Concurrent.on_jruby? && Concurrent.java_extensions_loaded?
-
-
module JRubyAttrVolatile
-
def self.included(base)
-
base.extend(ClassMethods)
-
end
-
-
module ClassMethods
-
def attr_volatile(*names)
-
names.each do |name|
-
-
ivar = :"@volatile_#{name}"
-
-
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{name}
-
instance_variable_get_volatile(:#{ivar})
-
end
-
-
def #{name}=(value)
-
instance_variable_set_volatile(:#{ivar}, value)
-
end
-
RUBY
-
-
end
-
names.map { |n| [n, :"#{n}="] }.flatten
-
end
-
end
-
end
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
class JRubyObject < AbstractObject
-
include JRubyAttrVolatile
-
-
def initialize
-
# nothing to do
-
end
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
# TODO (pitr-ch 04-Dec-2016): should be in edge
-
1
class Lock < LockableObject
-
# TODO use JavaReentrantLock on JRuby
-
-
1
public :synchronize
-
-
1
def wait(timeout = nil)
-
synchronize { ns_wait(timeout) }
-
end
-
-
1
public :ns_wait
-
-
1
def wait_until(timeout = nil, &condition)
-
synchronize { ns_wait_until(timeout, &condition) }
-
end
-
-
1
public :ns_wait_until
-
-
1
def signal
-
synchronize { ns_signal }
-
end
-
-
1
public :ns_signal
-
-
1
def broadcast
-
synchronize { ns_broadcast }
-
end
-
-
1
public :ns_broadcast
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
LockableObjectImplementation = case
-
when Concurrent.on_cruby? && Concurrent.ruby_version(:<=, 1, 9, 3)
-
MriMonitorLockableObject
-
when Concurrent.on_cruby? && Concurrent.ruby_version(:>, 1, 9, 3)
-
1
MriMutexLockableObject
-
when Concurrent.on_jruby?
-
JRubyLockableObject
-
when Concurrent.on_rbx?
-
RbxLockableObject
-
when Concurrent.on_truffle?
-
MriMutexLockableObject
-
else
-
warn 'Possibly unsupported Ruby implementation'
-
MriMonitorLockableObject
-
end
-
1
private_constant :LockableObjectImplementation
-
-
# Safe synchronization under any Ruby implementation.
-
# It provides methods like {#synchronize}, {#wait}, {#signal} and {#broadcast}.
-
# Provides a single layer which can improve its implementation over time without changes needed to
-
# the classes using it. Use {Synchronization::Object} not this abstract class.
-
#
-
# @note this object does not support usage together with
-
# [`Thread#wakeup`](http://ruby-doc.org/core-2.2.0/Thread.html#method-i-wakeup)
-
# and [`Thread#raise`](http://ruby-doc.org/core-2.2.0/Thread.html#method-i-raise).
-
# `Thread#sleep` and `Thread#wakeup` will work as expected but mixing `Synchronization::Object#wait` and
-
# `Thread#wakeup` will not work on all platforms.
-
#
-
# @see {Event} implementation as an example of this class use
-
#
-
# @example simple
-
# class AnClass < Synchronization::Object
-
# def initialize
-
# super
-
# synchronize { @value = 'asd' }
-
# end
-
#
-
# def value
-
# synchronize { @value }
-
# end
-
# end
-
#
-
# @!visibility private
-
1
class LockableObject < LockableObjectImplementation
-
-
# TODO (pitr 12-Sep-2015): make private for c-r, prohibit subclassing
-
# TODO (pitr 12-Sep-2015): we inherit too much ourselves :/
-
-
# @!method initialize(*args, &block)
-
# @!macro synchronization_object_method_initialize
-
-
# @!method synchronize
-
# @!macro synchronization_object_method_synchronize
-
-
# @!method wait_until(timeout = nil, &condition)
-
# @!macro synchronization_object_method_ns_wait_until
-
-
# @!method wait(timeout = nil)
-
# @!macro synchronization_object_method_ns_wait
-
-
# @!method signal
-
# @!macro synchronization_object_method_ns_signal
-
-
# @!method broadcast
-
# @!macro synchronization_object_method_ns_broadcast
-
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class MriLockableObject < AbstractLockableObject
-
1
protected
-
-
1
def ns_signal
-
@__condition__.signal
-
self
-
end
-
-
1
def ns_broadcast
-
@__condition__.broadcast
-
self
-
end
-
end
-
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class MriMutexLockableObject < MriLockableObject
-
1
safe_initialization!
-
-
1
def initialize(*defaults)
-
17
super(*defaults)
-
17
@__lock__ = ::Mutex.new
-
17
@__condition__ = ::ConditionVariable.new
-
end
-
-
1
protected
-
-
1
def synchronize
-
21
if @__lock__.owned?
-
5
yield
-
else
-
32
@__lock__.synchronize { yield }
-
end
-
end
-
-
1
def ns_wait(timeout = nil)
-
@__condition__.wait @__lock__, timeout
-
self
-
end
-
end
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class MriMonitorLockableObject < MriLockableObject
-
1
safe_initialization!
-
-
1
def initialize(*defaults)
-
super(*defaults)
-
@__lock__ = ::Monitor.new
-
@__condition__ = @__lock__.new_cond
-
end
-
-
1
protected
-
-
1
def synchronize # TODO may be a problem with lock.synchronize { lock.wait }
-
@__lock__.synchronize { yield }
-
end
-
-
1
def ns_wait(timeout = nil)
-
@__condition__.wait timeout
-
self
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
1
module MriAttrVolatile
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
end
-
-
1
module ClassMethods
-
1
def attr_volatile(*names)
-
names.each do |name|
-
ivar = :"@volatile_#{name}"
-
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{name}
-
#{ivar}
-
end
-
-
def #{name}=(value)
-
#{ivar} = value
-
end
-
RUBY
-
end
-
names.map { |n| [n, :"#{n}="] }.flatten
-
end
-
end
-
-
1
def full_memory_barrier
-
# relying on undocumented behavior of CRuby, GVL acquire has lock which ensures visibility of ivars
-
# https://github.com/ruby/ruby/blob/ruby_2_2/thread_pthread.c#L204-L211
-
end
-
end
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class MriObject < AbstractObject
-
1
include MriAttrVolatile
-
-
1
def initialize
-
# nothing to do
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
ObjectImplementation = case
-
when Concurrent.on_cruby?
-
1
MriObject
-
when Concurrent.on_jruby?
-
JRubyObject
-
when Concurrent.on_rbx?
-
RbxObject
-
when Concurrent.on_truffle?
-
TruffleObject
-
else
-
MriObject
-
end
-
1
private_constant :ObjectImplementation
-
-
# Abstract object providing final, volatile, ans CAS extensions to build other concurrent abstractions.
-
# - final instance variables see {Object.safe_initialization!}
-
# - volatile instance variables see {Object.attr_volatile}
-
# - volatile instance variables see {Object.attr_atomic}
-
1
class Object < ObjectImplementation
-
# TODO make it a module if possible
-
-
# @!method self.attr_volatile(*names)
-
# Creates methods for reading and writing (as `attr_accessor` does) to a instance variable with
-
# volatile (Java) semantic. The instance variable should be accessed oly through generated methods.
-
#
-
# @param [Array<Symbol>] names of the instance variables to be volatile
-
# @return [Array<Symbol>] names of defined method names
-
-
# Has to be called by children.
-
1
def initialize
-
17
super
-
17
initialize_volatile_with_cas
-
end
-
-
# By calling this method on a class, it and all its children are marked to be constructed safely. Meaning that
-
# all writes (ivar initializations) are made visible to all readers of newly constructed object. It ensures
-
# same behaviour as Java's final fields.
-
# @example
-
# class AClass < Concurrent::Synchronization::Object
-
# safe_initialization!
-
#
-
# def initialize
-
# @AFinalValue = 'value' # published safely, does not have to be synchronized
-
# end
-
# end
-
1
def self.safe_initialization!
-
# define only once, and not again in children
-
17
return if safe_initialization?
-
-
11
def self.new(*args, &block)
-
18
object = super(*args, &block)
-
ensure
-
18
object.full_memory_barrier if object
-
end
-
-
11
@safe_initialization = true
-
end
-
-
# @return [true, false] if this class is safely initialized.
-
1
def self.safe_initialization?
-
41
@safe_initialization = false unless defined? @safe_initialization
-
41
@safe_initialization || (superclass.respond_to?(:safe_initialization?) && superclass.safe_initialization?)
-
end
-
-
# For testing purposes, quite slow. Injects assert code to new method which will raise if class instance contains
-
# any instance variables with CamelCase names and isn't {.safe_initialization?}.
-
1
def self.ensure_safe_initialization_when_final_fields_are_present
-
Object.class_eval do
-
def self.new(*args, &block)
-
object = super(*args, &block)
-
ensure
-
has_final_field = object.instance_variables.any? { |v| v.to_s =~ /^@[A-Z]/ }
-
if has_final_field && !safe_initialization?
-
raise "there was an instance of #{object.class} with final field but not marked with safe_initialization!"
-
end
-
end
-
end
-
end
-
-
# Creates methods for reading and writing to a instance variable with
-
# volatile (Java) semantic as {.attr_volatile} does.
-
# The instance variable should be accessed oly through generated methods.
-
# This method generates following methods: `value`, `value=(new_value) #=> new_value`,
-
# `swap_value(new_value) #=> old_value`,
-
# `compare_and_set_value(expected, value) #=> true || false`, `update_value(&block)`.
-
# @param [Array<Symbol>] names of the instance variables to be volatile with CAS.
-
# @return [Array<Symbol>] names of defined method names.
-
1
def self.attr_atomic(*names)
-
3
@volatile_cas_fields ||= []
-
3
@volatile_cas_fields += names
-
3
safe_initialization!
-
3
define_initialize_volatile_with_cas
-
-
3
names.each do |name|
-
6
ivar = :"@Atomic#{name.to_s.gsub(/(?:^|_)(.)/) { $1.upcase }}"
-
3
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{name}
-
#{ivar}.get
-
end
-
-
def #{name}=(value)
-
#{ivar}.set value
-
end
-
-
def swap_#{name}(value)
-
#{ivar}.swap value
-
end
-
-
def compare_and_set_#{name}(expected, value)
-
#{ivar}.compare_and_set expected, value
-
end
-
-
def update_#{name}(&block)
-
#{ivar}.update(&block)
-
end
-
RUBY
-
end
-
6
names.flat_map { |n| [n, :"#{n}=", :"swap_#{n}", :"compare_and_set_#{n}", :"update_#{n}"] }
-
end
-
-
# @param [true,false] inherited should inherited volatile with CAS fields be returned?
-
# @return [Array<Symbol>] Returns defined volatile with CAS fields on this class.
-
1
def self.volatile_cas_fields(inherited = true)
-
@volatile_cas_fields ||= []
-
((superclass.volatile_cas_fields if superclass.respond_to?(:volatile_cas_fields) && inherited) || []) +
-
@volatile_cas_fields
-
end
-
-
1
private
-
-
1
def self.define_initialize_volatile_with_cas
-
9
assignments = @volatile_cas_fields.map { |name| "@Atomic#{name.to_s.gsub(/(?:^|_)(.)/) { $1.upcase }} = AtomicReference.new(nil)" }.join("\n")
-
3
class_eval <<-RUBY
-
def initialize_volatile_with_cas
-
super
-
#{assignments}
-
end
-
RUBY
-
end
-
-
1
private_class_method :define_initialize_volatile_with_cas
-
-
1
def initialize_volatile_with_cas
-
end
-
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class RbxLockableObject < AbstractLockableObject
-
1
safe_initialization!
-
-
1
def initialize(*defaults)
-
super(*defaults)
-
@__Waiters__ = []
-
@__owner__ = nil
-
end
-
-
1
protected
-
-
1
def synchronize(&block)
-
if @__owner__ == Thread.current
-
yield
-
else
-
result = nil
-
Rubinius.synchronize(self) do
-
begin
-
@__owner__ = Thread.current
-
result = yield
-
ensure
-
@__owner__ = nil
-
end
-
end
-
result
-
end
-
end
-
-
1
def ns_wait(timeout = nil)
-
wchan = Rubinius::Channel.new
-
-
begin
-
@__Waiters__.push wchan
-
Rubinius.unlock(self)
-
signaled = wchan.receive_timeout timeout
-
ensure
-
Rubinius.lock(self)
-
-
if !signaled && !@__Waiters__.delete(wchan)
-
# we timed out, but got signaled afterwards,
-
# so pass that signal on to the next waiter
-
@__Waiters__.shift << true unless @__Waiters__.empty?
-
end
-
end
-
-
self
-
end
-
-
1
def ns_signal
-
@__Waiters__.shift << true unless @__Waiters__.empty?
-
self
-
end
-
-
1
def ns_broadcast
-
@__Waiters__.shift << true until @__Waiters__.empty?
-
self
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
1
module RbxAttrVolatile
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
end
-
-
1
module ClassMethods
-
-
1
def attr_volatile(*names)
-
names.each do |name|
-
ivar = :"@volatile_#{name}"
-
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{name}
-
Rubinius.memory_barrier
-
#{ivar}
-
end
-
-
def #{name}=(value)
-
#{ivar} = value
-
Rubinius.memory_barrier
-
end
-
RUBY
-
end
-
names.map { |n| [n, :"#{n}="] }.flatten
-
end
-
-
end
-
-
1
def full_memory_barrier
-
# Rubinius instance variables are not volatile so we need to insert barrier
-
# TODO (pitr 26-Nov-2015): check comments like ^
-
Rubinius.memory_barrier
-
end
-
end
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class RbxObject < AbstractObject
-
1
include RbxAttrVolatile
-
-
1
def initialize
-
# nothing to do
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
1
class TruffleLockableObject < AbstractLockableObject
-
1
def new(*)
-
raise NotImplementedError
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
1
module TruffleAttrVolatile
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
end
-
-
1
module ClassMethods
-
1
def attr_volatile(*names)
-
# TODO may not always be available
-
attr_atomic(*names)
-
end
-
end
-
-
1
def full_memory_barrier
-
Truffle::System.full_memory_barrier
-
end
-
end
-
-
# @!visibility private
-
# @!macro internal_implementation_note
-
1
class TruffleObject < AbstractObject
-
1
include TruffleAttrVolatile
-
-
1
def initialize
-
# nothing to do
-
end
-
end
-
end
-
end
-
1
module Concurrent
-
1
module Synchronization
-
-
# Volatile adds the attr_volatile class method when included.
-
#
-
# @example
-
# class Foo
-
# include Concurrent::Synchronization::Volatile
-
#
-
# attr_volatile :bar
-
#
-
# def initialize
-
# self.bar = 1
-
# end
-
# end
-
#
-
# foo = Foo.new
-
# foo.bar
-
# => 1
-
# foo.bar = 2
-
# => 2
-
-
1
Volatile = case
-
when Concurrent.on_cruby?
-
1
MriAttrVolatile
-
when Concurrent.on_jruby?
-
JRubyAttrVolatile
-
when Concurrent.on_rbx? || Concurrent.on_truffle?
-
RbxAttrVolatile
-
else
-
MriAttrVolatile
-
end
-
end
-
end
-
1
require 'delegate'
-
1
require 'monitor'
-
-
1
module Concurrent
-
1
unless defined?(SynchronizedDelegator)
-
-
# This class provides a trivial way to synchronize all calls to a given object
-
# by wrapping it with a `Delegator` that performs `Monitor#enter/exit` calls
-
# around the delegated `#send`. Example:
-
#
-
# array = [] # not thread-safe on many impls
-
# array = SynchronizedDelegator.new([]) # thread-safe
-
#
-
# A simple `Monitor` provides a very coarse-grained way to synchronize a given
-
# object, in that it will cause synchronization for methods that have no need
-
# for it, but this is a trivial way to get thread-safety where none may exist
-
# currently on some implementations.
-
#
-
# This class is currently being considered for inclusion into stdlib, via
-
# https://bugs.ruby-lang.org/issues/8556
-
#
-
# @!visibility private
-
class SynchronizedDelegator < SimpleDelegator
-
def setup
-
@old_abort = Thread.abort_on_exception
-
Thread.abort_on_exception = true
-
end
-
-
def teardown
-
Thread.abort_on_exception = @old_abort
-
end
-
-
def initialize(obj)
-
__setobj__(obj)
-
@monitor = Monitor.new
-
end
-
-
def method_missing(method, *args, &block)
-
monitor = @monitor
-
begin
-
monitor.enter
-
super
-
ensure
-
monitor.exit
-
end
-
end
-
-
end
-
end
-
end
-
1
module Concurrent
-
-
# @!visibility private
-
1
module ThreadSafe
-
-
# @!visibility private
-
1
module Util
-
-
# TODO (pitr-ch 15-Oct-2016): migrate to Utility::NativeInteger
-
1
FIXNUM_BIT_SIZE = (0.size * 8) - 2
-
1
MAX_INT = (2 ** FIXNUM_BIT_SIZE) - 1
-
# TODO (pitr-ch 15-Oct-2016): migrate to Utility::ProcessorCounter
-
1
CPU_COUNT = 16 # is there a way to determine this?
-
end
-
end
-
end
-
1
require 'concurrent/collection/copy_on_notify_observer_set'
-
1
require 'concurrent/concern/dereferenceable'
-
1
require 'concurrent/concern/observable'
-
1
require 'concurrent/atomic/atomic_boolean'
-
1
require 'concurrent/executor/executor_service'
-
1
require 'concurrent/executor/ruby_executor_service'
-
1
require 'concurrent/executor/safe_task_executor'
-
1
require 'concurrent/scheduled_task'
-
-
1
module Concurrent
-
-
# A very common concurrency pattern is to run a thread that performs a task at
-
# regular intervals. The thread that performs the task sleeps for the given
-
# interval then wakes up and performs the task. Lather, rinse, repeat... This
-
# pattern causes two problems. First, it is difficult to test the business
-
# logic of the task because the task itself is tightly coupled with the
-
# concurrency logic. Second, an exception raised while performing the task can
-
# cause the entire thread to abend. In a long-running application where the
-
# task thread is intended to run for days/weeks/years a crashed task thread
-
# can pose a significant problem. `TimerTask` alleviates both problems.
-
#
-
# When a `TimerTask` is launched it starts a thread for monitoring the
-
# execution interval. The `TimerTask` thread does not perform the task,
-
# however. Instead, the TimerTask launches the task on a separate thread.
-
# Should the task experience an unrecoverable crash only the task thread will
-
# crash. This makes the `TimerTask` very fault tolerant. Additionally, the
-
# `TimerTask` thread can respond to the success or failure of the task,
-
# performing logging or ancillary operations. `TimerTask` can also be
-
# configured with a timeout value allowing it to kill a task that runs too
-
# long.
-
#
-
# One other advantage of `TimerTask` is that it forces the business logic to
-
# be completely decoupled from the concurrency logic. The business logic can
-
# be tested separately then passed to the `TimerTask` for scheduling and
-
# running.
-
#
-
# In some cases it may be necessary for a `TimerTask` to affect its own
-
# execution cycle. To facilitate this, a reference to the TimerTask instance
-
# is passed as an argument to the provided block every time the task is
-
# executed.
-
#
-
# The `TimerTask` class includes the `Dereferenceable` mixin module so the
-
# result of the last execution is always available via the `#value` method.
-
# Dereferencing options can be passed to the `TimerTask` during construction or
-
# at any later time using the `#set_deref_options` method.
-
#
-
# `TimerTask` supports notification through the Ruby standard library
-
# {http://ruby-doc.org/stdlib-2.0/libdoc/observer/rdoc/Observable.html
-
# Observable} module. On execution the `TimerTask` will notify the observers
-
# with three arguments: time of execution, the result of the block (or nil on
-
# failure), and any raised exceptions (or nil on success). If the timeout
-
# interval is exceeded the observer will receive a `Concurrent::TimeoutError`
-
# object as the third argument.
-
#
-
# @!macro copy_options
-
#
-
# @example Basic usage
-
# task = Concurrent::TimerTask.new{ puts 'Boom!' }
-
# task.execute
-
#
-
# task.execution_interval #=> 60 (default)
-
# task.timeout_interval #=> 30 (default)
-
#
-
# # wait 60 seconds...
-
# #=> 'Boom!'
-
#
-
# task.shutdown #=> true
-
#
-
# @example Configuring `:execution_interval` and `:timeout_interval`
-
# task = Concurrent::TimerTask.new(execution_interval: 5, timeout_interval: 5) do
-
# puts 'Boom!'
-
# end
-
#
-
# task.execution_interval #=> 5
-
# task.timeout_interval #=> 5
-
#
-
# @example Immediate execution with `:run_now`
-
# task = Concurrent::TimerTask.new(run_now: true){ puts 'Boom!' }
-
# task.execute
-
#
-
# #=> 'Boom!'
-
#
-
# @example Last `#value` and `Dereferenceable` mixin
-
# task = Concurrent::TimerTask.new(
-
# dup_on_deref: true,
-
# execution_interval: 5
-
# ){ Time.now }
-
#
-
# task.execute
-
# Time.now #=> 2013-11-07 18:06:50 -0500
-
# sleep(10)
-
# task.value #=> 2013-11-07 18:06:55 -0500
-
#
-
# @example Controlling execution from within the block
-
# timer_task = Concurrent::TimerTask.new(execution_interval: 1) do |task|
-
# task.execution_interval.times{ print 'Boom! ' }
-
# print "\n"
-
# task.execution_interval += 1
-
# if task.execution_interval > 5
-
# puts 'Stopping...'
-
# task.shutdown
-
# end
-
# end
-
#
-
# timer_task.execute # blocking call - this task will stop itself
-
# #=> Boom!
-
# #=> Boom! Boom!
-
# #=> Boom! Boom! Boom!
-
# #=> Boom! Boom! Boom! Boom!
-
# #=> Boom! Boom! Boom! Boom! Boom!
-
# #=> Stopping...
-
#
-
# @example Observation
-
# class TaskObserver
-
# def update(time, result, ex)
-
# if result
-
# print "(#{time}) Execution successfully returned #{result}\n"
-
# elsif ex.is_a?(Concurrent::TimeoutError)
-
# print "(#{time}) Execution timed out\n"
-
# else
-
# print "(#{time}) Execution failed with error #{ex}\n"
-
# end
-
# end
-
# end
-
#
-
# task = Concurrent::TimerTask.new(execution_interval: 1, timeout_interval: 1){ 42 }
-
# task.add_observer(TaskObserver.new)
-
# task.execute
-
#
-
# #=> (2013-10-13 19:08:58 -0400) Execution successfully returned 42
-
# #=> (2013-10-13 19:08:59 -0400) Execution successfully returned 42
-
# #=> (2013-10-13 19:09:00 -0400) Execution successfully returned 42
-
# task.shutdown
-
#
-
# task = Concurrent::TimerTask.new(execution_interval: 1, timeout_interval: 1){ sleep }
-
# task.add_observer(TaskObserver.new)
-
# task.execute
-
#
-
# #=> (2013-10-13 19:07:25 -0400) Execution timed out
-
# #=> (2013-10-13 19:07:27 -0400) Execution timed out
-
# #=> (2013-10-13 19:07:29 -0400) Execution timed out
-
# task.shutdown
-
#
-
# task = Concurrent::TimerTask.new(execution_interval: 1){ raise StandardError }
-
# task.add_observer(TaskObserver.new)
-
# task.execute
-
#
-
# #=> (2013-10-13 19:09:37 -0400) Execution failed with error StandardError
-
# #=> (2013-10-13 19:09:38 -0400) Execution failed with error StandardError
-
# #=> (2013-10-13 19:09:39 -0400) Execution failed with error StandardError
-
# task.shutdown
-
#
-
# @see http://ruby-doc.org/stdlib-2.0/libdoc/observer/rdoc/Observable.html
-
# @see http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html
-
1
class TimerTask < RubyExecutorService
-
1
include Concern::Dereferenceable
-
1
include Concern::Observable
-
-
# Default `:execution_interval` in seconds.
-
1
EXECUTION_INTERVAL = 60
-
-
# Default `:timeout_interval` in seconds.
-
1
TIMEOUT_INTERVAL = 30
-
-
# Create a new TimerTask with the given task and configuration.
-
#
-
# @!macro [attach] timer_task_initialize
-
# @param [Hash] opts the options defining task execution.
-
# @option opts [Integer] :execution_interval number of seconds between
-
# task executions (default: EXECUTION_INTERVAL)
-
# @option opts [Integer] :timeout_interval number of seconds a task can
-
# run before it is considered to have failed (default: TIMEOUT_INTERVAL)
-
# @option opts [Boolean] :run_now Whether to run the task immediately
-
# upon instantiation or to wait until the first # execution_interval
-
# has passed (default: false)
-
#
-
# @!macro deref_options
-
#
-
# @raise ArgumentError when no block is given.
-
#
-
# @yield to the block after :execution_interval seconds have passed since
-
# the last yield
-
# @yieldparam task a reference to the `TimerTask` instance so that the
-
# block can control its own lifecycle. Necessary since `self` will
-
# refer to the execution context of the block rather than the running
-
# `TimerTask`.
-
#
-
# @return [TimerTask] the new `TimerTask`
-
1
def initialize(opts = {}, &task)
-
raise ArgumentError.new('no block given') unless block_given?
-
super
-
end
-
-
# Is the executor running?
-
#
-
# @return [Boolean] `true` when running, `false` when shutting down or shutdown
-
1
def running?
-
@running.true?
-
end
-
-
# Execute a previously created `TimerTask`.
-
#
-
# @return [TimerTask] a reference to `self`
-
#
-
# @example Instance and execute in separate steps
-
# task = Concurrent::TimerTask.new(execution_interval: 10){ print "Hello World\n" }
-
# task.running? #=> false
-
# task.execute
-
# task.running? #=> true
-
#
-
# @example Instance and execute in one line
-
# task = Concurrent::TimerTask.new(execution_interval: 10){ print "Hello World\n" }.execute
-
# task.running? #=> true
-
1
def execute
-
synchronize do
-
if @running.false?
-
@running.make_true
-
schedule_next_task(@run_now ? 0 : @execution_interval)
-
end
-
end
-
self
-
end
-
-
# Create and execute a new `TimerTask`.
-
#
-
# @!macro timer_task_initialize
-
#
-
# @example
-
# task = Concurrent::TimerTask.execute(execution_interval: 10){ print "Hello World\n" }
-
# task.running? #=> true
-
1
def self.execute(opts = {}, &task)
-
TimerTask.new(opts, &task).execute
-
end
-
-
# @!attribute [rw] execution_interval
-
# @return [Fixnum] Number of seconds after the task completes before the
-
# task is performed again.
-
1
def execution_interval
-
synchronize { @execution_interval }
-
end
-
-
# @!attribute [rw] execution_interval
-
# @return [Fixnum] Number of seconds after the task completes before the
-
# task is performed again.
-
1
def execution_interval=(value)
-
if (value = value.to_f) <= 0.0
-
raise ArgumentError.new('must be greater than zero')
-
else
-
synchronize { @execution_interval = value }
-
end
-
end
-
-
# @!attribute [rw] timeout_interval
-
# @return [Fixnum] Number of seconds the task can run before it is
-
# considered to have failed.
-
1
def timeout_interval
-
synchronize { @timeout_interval }
-
end
-
-
# @!attribute [rw] timeout_interval
-
# @return [Fixnum] Number of seconds the task can run before it is
-
# considered to have failed.
-
1
def timeout_interval=(value)
-
if (value = value.to_f) <= 0.0
-
raise ArgumentError.new('must be greater than zero')
-
else
-
synchronize { @timeout_interval = value }
-
end
-
end
-
-
1
private :post, :<<
-
-
1
private
-
-
1
def ns_initialize(opts, &task)
-
set_deref_options(opts)
-
-
self.execution_interval = opts[:execution] || opts[:execution_interval] || EXECUTION_INTERVAL
-
self.timeout_interval = opts[:timeout] || opts[:timeout_interval] || TIMEOUT_INTERVAL
-
@run_now = opts[:now] || opts[:run_now]
-
@executor = Concurrent::SafeTaskExecutor.new(task)
-
@running = Concurrent::AtomicBoolean.new(false)
-
-
self.observers = Collection::CopyOnNotifyObserverSet.new
-
end
-
-
# @!visibility private
-
1
def ns_shutdown_execution
-
@running.make_false
-
super
-
end
-
-
# @!visibility private
-
1
def ns_kill_execution
-
@running.make_false
-
super
-
end
-
-
# @!visibility private
-
1
def schedule_next_task(interval = execution_interval)
-
ScheduledTask.execute(interval, args: [Concurrent::Event.new], &method(:execute_task))
-
nil
-
end
-
-
# @!visibility private
-
1
def execute_task(completion)
-
return nil unless @running.true?
-
ScheduledTask.execute(execution_interval, args: [completion], &method(:timeout_task))
-
_success, value, reason = @executor.execute(self)
-
if completion.try?
-
self.value = value
-
schedule_next_task
-
time = Time.now
-
observers.notify_observers do
-
[time, self.value, reason]
-
end
-
end
-
nil
-
end
-
-
# @!visibility private
-
1
def timeout_task(completion)
-
return unless @running.true?
-
if completion.try?
-
self.value = value
-
schedule_next_task
-
observers.notify_observers(Time.now, nil, Concurrent::TimeoutError.new)
-
end
-
end
-
end
-
end
-
1
require 'concurrent/atomic/atomic_reference'
-
-
1
module Concurrent
-
-
# A fixed size array with volatile (synchronized, thread safe) getters/setters.
-
# Mixes in Ruby's `Enumerable` module for enhanced search, sort, and traversal.
-
#
-
# @example
-
# tuple = Concurrent::Tuple.new(16)
-
#
-
# tuple.set(0, :foo) #=> :foo | volatile write
-
# tuple.get(0) #=> :foo | volatile read
-
# tuple.compare_and_set(0, :foo, :bar) #=> true | strong CAS
-
# tuple.cas(0, :foo, :baz) #=> false | strong CAS
-
# tuple.get(0) #=> :bar | volatile read
-
#
-
# @see https://en.wikipedia.org/wiki/Tuple Tuple entry at Wikipedia
-
# @see http://www.erlang.org/doc/reference_manual/data_types.html#id70396 Erlang Tuple
-
# @see http://ruby-doc.org/core-2.2.2/Enumerable.html Enumerable
-
1
class Tuple
-
1
include Enumerable
-
-
# The (fixed) size of the tuple.
-
1
attr_reader :size
-
-
# @!visibility private
-
1
Tuple = defined?(Rubinius::Tuple) ? Rubinius::Tuple : Array
-
1
private_constant :Tuple
-
-
# Create a new tuple of the given size.
-
#
-
# @param [Integer] size the number of elements in the tuple
-
1
def initialize(size)
-
@size = size
-
@tuple = tuple = Tuple.new(size)
-
i = 0
-
while i < size
-
tuple[i] = Concurrent::AtomicReference.new
-
i += 1
-
end
-
end
-
-
# Get the value of the element at the given index.
-
#
-
# @param [Integer] i the index from which to retrieve the value
-
# @return [Object] the value at the given index or nil if the index is out of bounds
-
1
def get(i)
-
return nil if i >= @size || i < 0
-
@tuple[i].get
-
end
-
1
alias_method :volatile_get, :get
-
-
# Set the element at the given index to the given value
-
#
-
# @param [Integer] i the index for the element to set
-
# @param [Object] value the value to set at the given index
-
#
-
# @return [Object] the new value of the element at the given index or nil if the index is out of bounds
-
1
def set(i, value)
-
return nil if i >= @size || i < 0
-
@tuple[i].set(value)
-
end
-
1
alias_method :volatile_set, :set
-
-
# Set the value at the given index to the new value if and only if the current
-
# value matches the given old value.
-
#
-
# @param [Integer] i the index for the element to set
-
# @param [Object] old_value the value to compare against the current value
-
# @param [Object] new_value the value to set at the given index
-
#
-
# @return [Boolean] true if the value at the given element was set else false
-
1
def compare_and_set(i, old_value, new_value)
-
return false if i >= @size || i < 0
-
@tuple[i].compare_and_set(old_value, new_value)
-
end
-
1
alias_method :cas, :compare_and_set
-
-
# Calls the given block once for each element in self, passing that element as a parameter.
-
#
-
# @yieldparam [Object] ref the `Concurrent::AtomicReference` object at the current index
-
1
def each
-
@tuple.each {|ref| yield ref.get}
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# A `TVar` is a transactional variable - a single-element container that
-
# is used as part of a transaction - see `Concurrent::atomically`.
-
#
-
# @!macro thread_safe_variable_comparison
-
#
-
# {include:file:doc/tvar.md}
-
1
class TVar < Synchronization::Object
-
1
safe_initialization!
-
-
# Create a new `TVar` with an initial value.
-
1
def initialize(value)
-
@value = value
-
@version = 0
-
@lock = Mutex.new
-
end
-
-
# Get the value of a `TVar`.
-
1
def value
-
Concurrent::atomically do
-
Transaction::current.read(self)
-
end
-
end
-
-
# Set the value of a `TVar`.
-
1
def value=(value)
-
Concurrent::atomically do
-
Transaction::current.write(self, value)
-
end
-
end
-
-
# @!visibility private
-
1
def unsafe_value # :nodoc:
-
@value
-
end
-
-
# @!visibility private
-
1
def unsafe_value=(value) # :nodoc:
-
@value = value
-
end
-
-
# @!visibility private
-
1
def unsafe_version # :nodoc:
-
@version
-
end
-
-
# @!visibility private
-
1
def unsafe_increment_version # :nodoc:
-
@version += 1
-
end
-
-
# @!visibility private
-
1
def unsafe_lock # :nodoc:
-
@lock
-
end
-
-
end
-
-
# Run a block that reads and writes `TVar`s as a single atomic transaction.
-
# With respect to the value of `TVar` objects, the transaction is atomic, in
-
# that it either happens or it does not, consistent, in that the `TVar`
-
# objects involved will never enter an illegal state, and isolated, in that
-
# transactions never interfere with each other. You may recognise these
-
# properties from database transactions.
-
#
-
# There are some very important and unusual semantics that you must be aware of:
-
#
-
# * Most importantly, the block that you pass to atomically may be executed
-
# more than once. In most cases your code should be free of
-
# side-effects, except for via TVar.
-
#
-
# * If an exception escapes an atomically block it will abort the transaction.
-
#
-
# * It is undefined behaviour to use callcc or Fiber with atomically.
-
#
-
# * If you create a new thread within an atomically, it will not be part of
-
# the transaction. Creating a thread counts as a side-effect.
-
#
-
# Transactions within transactions are flattened to a single transaction.
-
#
-
# @example
-
# a = new TVar(100_000)
-
# b = new TVar(100)
-
#
-
# Concurrent::atomically do
-
# a.value -= 10
-
# b.value += 10
-
# end
-
1
def atomically
-
raise ArgumentError.new('no block given') unless block_given?
-
-
# Get the current transaction
-
-
transaction = Transaction::current
-
-
# Are we not already in a transaction (not nested)?
-
-
if transaction.nil?
-
# New transaction
-
-
begin
-
# Retry loop
-
-
loop do
-
-
# Create a new transaction
-
-
transaction = Transaction.new
-
Transaction::current = transaction
-
-
# Run the block, aborting on exceptions
-
-
begin
-
result = yield
-
rescue Transaction::AbortError => e
-
transaction.abort
-
result = Transaction::ABORTED
-
rescue Transaction::LeaveError => e
-
transaction.abort
-
break result
-
rescue => e
-
transaction.abort
-
raise e
-
end
-
# If we can commit, break out of the loop
-
-
if result != Transaction::ABORTED
-
if transaction.commit
-
break result
-
end
-
end
-
end
-
ensure
-
# Clear the current transaction
-
-
Transaction::current = nil
-
end
-
else
-
# Nested transaction - flatten it and just run the block
-
-
yield
-
end
-
end
-
-
# Abort a currently running transaction - see `Concurrent::atomically`.
-
1
def abort_transaction
-
raise Transaction::AbortError.new
-
end
-
-
# Leave a transaction without committing or aborting - see `Concurrent::atomically`.
-
1
def leave_transaction
-
raise Transaction::LeaveError.new
-
end
-
-
1
module_function :atomically, :abort_transaction, :leave_transaction
-
-
1
private
-
-
1
class Transaction
-
-
1
ABORTED = Object.new
-
-
1
ReadLogEntry = Struct.new(:tvar, :version)
-
-
1
AbortError = Class.new(StandardError)
-
1
LeaveError = Class.new(StandardError)
-
-
1
def initialize
-
@read_log = []
-
@write_log = {}
-
end
-
-
1
def read(tvar)
-
Concurrent::abort_transaction unless valid?
-
-
if @write_log.has_key? tvar
-
@write_log[tvar]
-
else
-
@read_log.push(ReadLogEntry.new(tvar, tvar.unsafe_version))
-
tvar.unsafe_value
-
end
-
end
-
-
1
def write(tvar, value)
-
# Have we already written to this TVar?
-
-
unless @write_log.has_key? tvar
-
# Try to lock the TVar
-
-
unless tvar.unsafe_lock.try_lock
-
# Someone else is writing to this TVar - abort
-
Concurrent::abort_transaction
-
end
-
-
# If we previously wrote to it, check the version hasn't changed
-
-
@read_log.each do |log_entry|
-
if log_entry.tvar == tvar and tvar.unsafe_version > log_entry.version
-
Concurrent::abort_transaction
-
end
-
end
-
end
-
-
# Record the value written
-
-
@write_log[tvar] = value
-
end
-
-
1
def abort
-
unlock
-
end
-
-
1
def commit
-
return false unless valid?
-
-
@write_log.each_pair do |tvar, value|
-
tvar.unsafe_value = value
-
tvar.unsafe_increment_version
-
end
-
-
unlock
-
-
true
-
end
-
-
1
def valid?
-
@read_log.each do |log_entry|
-
unless @write_log.has_key? log_entry.tvar
-
if log_entry.tvar.unsafe_version > log_entry.version
-
return false
-
end
-
end
-
end
-
-
true
-
end
-
-
1
def unlock
-
@write_log.each_key do |tvar|
-
tvar.unsafe_lock.unlock
-
end
-
end
-
-
1
def self.current
-
Thread.current[:current_tvar_transaction]
-
end
-
-
1
def self.current=(transaction)
-
Thread.current[:current_tvar_transaction] = transaction
-
end
-
-
end
-
-
end
-
1
require 'logger'
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
# Provides ability to add and remove handlers to be run at `Kernel#at_exit`, order is undefined.
-
# Each handler is executed at most once.
-
#
-
# @!visibility private
-
1
class AtExitImplementation < Synchronization::LockableObject
-
1
include Logger::Severity
-
-
1
def initialize(*args)
-
1
super()
-
2
synchronize { ns_initialize(*args) }
-
end
-
-
# Add a handler to be run at `Kernel#at_exit`
-
# @param [Object] handler_id optionally provide an id, if allready present, handler is replaced
-
# @yield the handler
-
# @return id of the handler
-
1
def add(handler_id = nil, &handler)
-
id = handler_id || handler.object_id
-
synchronize { @handlers[id] = handler }
-
id
-
end
-
-
# Delete a handler by handler_id
-
# @return [true, false]
-
1
def delete(handler_id)
-
!!synchronize { @handlers.delete handler_id }
-
end
-
-
# Is handler with handler_id rpesent?
-
# @return [true, false]
-
1
def handler?(handler_id)
-
synchronize { @handlers.key? handler_id }
-
end
-
-
# @return copy of the handlers
-
1
def handlers
-
synchronize { @handlers }.clone
-
end
-
-
# install `Kernel#at_exit` callback to execute added handlers
-
1
def install
-
1
synchronize do
-
@installed ||= begin
-
2
at_exit { runner }
-
1
true
-
1
end
-
1
self
-
end
-
end
-
-
# Will it run during `Kernel#at_exit`
-
1
def enabled?
-
synchronize { @enabled }
-
end
-
-
# Configure if it runs during `Kernel#at_exit`
-
1
def enabled=(value)
-
synchronize { @enabled = value }
-
end
-
-
# run the handlers manually
-
# @return ids of the handlers
-
1
def run
-
2
handlers, _ = synchronize { handlers, @handlers = @handlers, {} }
-
1
handlers.each do |_, handler|
-
begin
-
handler.call
-
rescue => error
-
Concurrent.global_logger.call(ERROR, error)
-
end
-
end
-
1
handlers.keys
-
end
-
-
1
private
-
-
1
def ns_initialize(enabled = true)
-
1
@handlers = {}
-
1
@enabled = enabled
-
end
-
-
1
def runner
-
2
run if synchronize { @enabled }
-
end
-
end
-
-
1
private_constant :AtExitImplementation
-
-
# @see AtExitImplementation
-
# @!visibility private
-
1
AtExit = AtExitImplementation.new.install
-
end
-
1
module Concurrent
-
1
module Utility
-
-
# @!visibility private
-
1
module EngineDetector
-
1
def on_jruby?
-
18
ruby_engine == 'jruby'
-
end
-
-
1
def on_jruby_9000?
-
on_jruby? && ruby_version(:>=, 9, 0, 0, JRUBY_VERSION)
-
end
-
-
1
def on_cruby?
-
7
ruby_engine == 'ruby'
-
end
-
-
1
def on_rbx?
-
ruby_engine == 'rbx'
-
end
-
-
1
def on_truffle?
-
ruby_engine == 'jruby+truffle'
-
end
-
-
1
def on_windows?
-
!(RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/).nil?
-
end
-
-
1
def on_osx?
-
!(RbConfig::CONFIG['host_os'] =~ /darwin|mac os/).nil?
-
end
-
-
1
def on_linux?
-
!(RbConfig::CONFIG['host_os'] =~ /linux/).nil?
-
end
-
-
1
def ruby_engine
-
26
defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'
-
end
-
-
1
def ruby_version(comparison, major, minor, patch, version = RUBY_VERSION)
-
2
result = (version.split('.').map(&:to_i) <=> [major, minor, patch])
-
2
comparisons = { :== => [0],
-
:>= => [1, 0],
-
:<= => [-1, 0],
-
:> => [1],
-
:< => [-1] }
-
2
comparisons.fetch(comparison).include? result
-
end
-
end
-
end
-
-
# @!visibility private
-
1
extend Utility::EngineDetector
-
end
-
1
require 'concurrent/synchronization'
-
-
1
module Concurrent
-
-
1
class_definition = Class.new(Synchronization::LockableObject) do
-
1
def initialize
-
1
@last_time = Time.now.to_f
-
1
super()
-
end
-
-
1
if defined?(Process::CLOCK_MONOTONIC)
-
# @!visibility private
-
1
def get_time
-
Process.clock_gettime(Process::CLOCK_MONOTONIC)
-
end
-
elsif Concurrent.on_jruby?
-
# @!visibility private
-
def get_time
-
java.lang.System.nanoTime() / 1_000_000_000.0
-
end
-
else
-
-
# @!visibility private
-
def get_time
-
synchronize do
-
now = Time.now.to_f
-
if @last_time < now
-
@last_time = now
-
else # clock has moved back in time
-
@last_time += 0.000_001
-
end
-
end
-
end
-
-
end
-
end
-
-
# Clock that cannot be set and represents monotonic time since
-
# some unspecified starting point.
-
#
-
# @!visibility private
-
1
GLOBAL_MONOTONIC_CLOCK = class_definition.new
-
1
private_constant :GLOBAL_MONOTONIC_CLOCK
-
-
# @!macro [attach] monotonic_get_time
-
#
-
# Returns the current time a tracked by the application monotonic clock.
-
#
-
# @return [Float] The current monotonic time when `since` not given else
-
# the elapsed monotonic time between `since` and the current time
-
#
-
# @!macro monotonic_clock_warning
-
1
def monotonic_time
-
GLOBAL_MONOTONIC_CLOCK.get_time
-
end
-
-
1
module_function :monotonic_time
-
end
-
1
require 'concurrent/utility/engine'
-
-
1
module Concurrent
-
-
1
module Utility
-
-
# @!visibility private
-
1
module NativeExtensionLoader
-
-
1
def allow_c_extensions?
-
Concurrent.on_cruby?
-
end
-
-
1
def c_extensions_loaded?
-
1
@c_extensions_loaded ||= false
-
end
-
-
1
def java_extensions_loaded?
-
1
@java_extensions_loaded ||= false
-
end
-
-
1
def set_c_extensions_loaded
-
@c_extensions_loaded = true
-
end
-
-
1
def set_java_extensions_loaded
-
@java_extensions_loaded = true
-
end
-
-
1
def load_native_extensions
-
1
unless defined? Synchronization::AbstractObject
-
raise 'native_extension_loader loaded before Synchronization::AbstractObject'
-
end
-
-
1
if Concurrent.on_cruby? && !c_extensions_loaded?
-
1
tries = [
-
lambda do
-
1
require 'concurrent/extension'
-
set_c_extensions_loaded
-
end,
-
lambda do
-
# may be a Windows cross-compiled native gem
-
1
require "concurrent/#{RUBY_VERSION[0..2]}/extension"
-
set_c_extensions_loaded
-
end]
-
-
1
tries.each do |try|
-
2
begin
-
2
try.call
-
break
-
rescue LoadError
-
2
next
-
end
-
end
-
end
-
-
1
if Concurrent.on_jruby? && !java_extensions_loaded?
-
begin
-
require 'concurrent_ruby_ext'
-
set_java_extensions_loaded
-
rescue LoadError
-
# move on with pure-Ruby implementations
-
raise 'On JRuby but Java extensions failed to load.'
-
end
-
end
-
end
-
end
-
end
-
-
# @!visibility private
-
1
extend Utility::NativeExtensionLoader
-
end
-
-
1
module Concurrent
-
1
module Utility
-
# @private
-
1
module NativeInteger
-
# http://stackoverflow.com/questions/535721/ruby-max-integer
-
1
MIN_VALUE = -(2**(0.size * 8 - 2))
-
1
MAX_VALUE = (2**(0.size * 8 - 2) - 1)
-
-
1
def ensure_upper_bound(value)
-
if value > MAX_VALUE
-
raise RangeError.new("#{value} is greater than the maximum value of #{MAX_VALUE}")
-
end
-
value
-
end
-
-
1
def ensure_lower_bound(value)
-
if value < MIN_VALUE
-
raise RangeError.new("#{value} is less than the maximum value of #{MIN_VALUE}")
-
end
-
value
-
end
-
-
1
def ensure_integer(value)
-
unless value.is_a?(Integer)
-
raise ArgumentError.new("#{value} is not an Integer")
-
end
-
value
-
end
-
-
1
def ensure_integer_and_bounds(value)
-
ensure_integer value
-
ensure_upper_bound value
-
ensure_lower_bound value
-
end
-
-
1
def ensure_positive(value)
-
if value < 0
-
raise ArgumentError.new("#{value} cannot be negative")
-
end
-
value
-
end
-
-
1
def ensure_positive_and_no_zero(value)
-
if value < 1
-
raise ArgumentError.new("#{value} cannot be negative or zero")
-
end
-
value
-
end
-
-
1
extend self
-
end
-
end
-
end
-
1
require 'rbconfig'
-
1
require 'concurrent/delay'
-
-
1
module Concurrent
-
1
module Utility
-
-
# @!visibility private
-
1
class ProcessorCounter
-
1
def initialize
-
1
@processor_count = Delay.new { compute_processor_count }
-
1
@physical_processor_count = Delay.new { compute_physical_processor_count }
-
end
-
-
# Number of processors seen by the OS and used for process scheduling. For
-
# performance reasons the calculated value will be memoized on the first
-
# call.
-
#
-
# When running under JRuby the Java runtime call
-
# `java.lang.Runtime.getRuntime.availableProcessors` will be used. According
-
# to the Java documentation this "value may change during a particular
-
# invocation of the virtual machine... [applications] should therefore
-
# occasionally poll this property." Subsequently the result will NOT be
-
# memoized under JRuby.
-
#
-
# On Windows the Win32 API will be queried for the
-
# `NumberOfLogicalProcessors from Win32_Processor`. This will return the
-
# total number "logical processors for the current instance of the
-
# processor", which taked into account hyperthreading.
-
#
-
# * AIX: /usr/sbin/pmcycles (AIX 5+), /usr/sbin/lsdev
-
# * Alpha: /usr/bin/nproc (/proc/cpuinfo exists but cannot be used)
-
# * BSD: /sbin/sysctl
-
# * Cygwin: /proc/cpuinfo
-
# * Darwin: /usr/bin/hwprefs, /usr/sbin/sysctl
-
# * HP-UX: /usr/sbin/ioscan
-
# * IRIX: /usr/sbin/sysconf
-
# * Linux: /proc/cpuinfo
-
# * Minix 3+: /proc/cpuinfo
-
# * Solaris: /usr/sbin/psrinfo
-
# * Tru64 UNIX: /usr/sbin/psrinfo
-
# * UnixWare: /usr/sbin/psrinfo
-
#
-
# @return [Integer] number of processors seen by the OS or Java runtime
-
#
-
# @see https://github.com/grosser/parallel/blob/4fc8b89d08c7091fe0419ca8fba1ec3ce5a8d185/lib/parallel.rb
-
#
-
# @see http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#availableProcessors()
-
# @see http://msdn.microsoft.com/en-us/library/aa394373(v=vs.85).aspx
-
1
def processor_count
-
@processor_count.value
-
end
-
-
# Number of physical processor cores on the current system. For performance
-
# reasons the calculated value will be memoized on the first call.
-
#
-
# On Windows the Win32 API will be queried for the `NumberOfCores from
-
# Win32_Processor`. This will return the total number "of cores for the
-
# current instance of the processor." On Unix-like operating systems either
-
# the `hwprefs` or `sysctl` utility will be called in a subshell and the
-
# returned value will be used. In the rare case where none of these methods
-
# work or an exception is raised the function will simply return 1.
-
#
-
# @return [Integer] number physical processor cores on the current system
-
#
-
# @see https://github.com/grosser/parallel/blob/4fc8b89d08c7091fe0419ca8fba1ec3ce5a8d185/lib/parallel.rb
-
#
-
# @see http://msdn.microsoft.com/en-us/library/aa394373(v=vs.85).aspx
-
# @see http://www.unix.com/man-page/osx/1/HWPREFS/
-
# @see http://linux.die.net/man/8/sysctl
-
1
def physical_processor_count
-
@physical_processor_count.value
-
end
-
-
1
private
-
-
1
def compute_processor_count
-
if Concurrent.on_jruby?
-
java.lang.Runtime.getRuntime.availableProcessors
-
elsif Concurrent.on_truffle?
-
Truffle::Primitive.logical_processors
-
else
-
os_name = RbConfig::CONFIG["target_os"]
-
if os_name =~ /mingw|mswin/
-
require 'win32ole'
-
result = WIN32OLE.connect("winmgmts://").ExecQuery(
-
"select NumberOfLogicalProcessors from Win32_Processor")
-
result.to_enum.collect(&:NumberOfLogicalProcessors).reduce(:+)
-
elsif File.readable?("/proc/cpuinfo") && (cpuinfo_count = IO.read("/proc/cpuinfo").scan(/^processor/).size) > 0
-
cpuinfo_count
-
elsif File.executable?("/usr/bin/nproc")
-
IO.popen("/usr/bin/nproc --all", &:read).to_i
-
elsif File.executable?("/usr/bin/hwprefs")
-
IO.popen("/usr/bin/hwprefs thread_count", &:read).to_i
-
elsif File.executable?("/usr/sbin/psrinfo")
-
IO.popen("/usr/sbin/psrinfo", &:read).scan(/^.*on-*line/).size
-
elsif File.executable?("/usr/sbin/ioscan")
-
IO.popen("/usr/sbin/ioscan -kC processor", &:read).scan(/^.*processor/).size
-
elsif File.executable?("/usr/sbin/pmcycles")
-
IO.popen("/usr/sbin/pmcycles -m", &:read).count("\n")
-
elsif File.executable?("/usr/sbin/lsdev")
-
IO.popen("/usr/sbin/lsdev -Cc processor -S 1", &:read).count("\n")
-
elsif File.executable?("/usr/sbin/sysconf") and os_name =~ /irix/i
-
IO.popen("/usr/sbin/sysconf NPROC_ONLN", &:read).to_i
-
elsif File.executable?("/usr/sbin/sysctl")
-
IO.popen("/usr/sbin/sysctl -n hw.ncpu", &:read).to_i
-
elsif File.executable?("/sbin/sysctl")
-
IO.popen("/sbin/sysctl -n hw.ncpu", &:read).to_i
-
else
-
# TODO (pitr-ch 05-Nov-2016): warn about failures
-
1
-
end
-
end
-
rescue
-
return 1
-
end
-
-
1
def compute_physical_processor_count
-
ppc = case RbConfig::CONFIG["target_os"]
-
when /darwin1/
-
IO.popen("/usr/sbin/sysctl -n hw.physicalcpu", &:read).to_i
-
when /linux/
-
cores = {} # unique physical ID / core ID combinations
-
phy = 0
-
IO.read("/proc/cpuinfo").scan(/^physical id.*|^core id.*/) do |ln|
-
if ln.start_with?("physical")
-
phy = ln[/\d+/]
-
elsif ln.start_with?("core")
-
cid = phy + ":" + ln[/\d+/]
-
cores[cid] = true if not cores[cid]
-
end
-
end
-
cores.count
-
when /mswin|mingw/
-
require 'win32ole'
-
result_set = WIN32OLE.connect("winmgmts://").ExecQuery(
-
"select NumberOfCores from Win32_Processor")
-
result_set.to_enum.collect(&:NumberOfCores).reduce(:+)
-
else
-
processor_count
-
end
-
# fall back to logical count if physical info is invalid
-
ppc > 0 ? ppc : processor_count
-
rescue
-
return 1
-
end
-
end
-
end
-
-
# create the default ProcessorCounter on load
-
1
@processor_counter = Utility::ProcessorCounter.new
-
1
singleton_class.send :attr_reader, :processor_counter
-
-
1
def self.processor_count
-
processor_counter.processor_count
-
end
-
-
1
def self.physical_processor_count
-
processor_counter.physical_processor_count
-
end
-
end
-
1
module Concurrent
-
1
VERSION = '1.0.5'
-
1
EDGE_VERSION = '0.3.1'
-
end
-
1
require 'fileutils'
-
1
require 'cucumber/formatter/console'
-
1
require 'cucumber/formatter/io'
-
1
require 'cucumber/gherkin/formatter/escaping'
-
-
1
module Cucumber
-
1
module Formatter
-
# The formatter used for <tt>--format pretty</tt> (the default formatter).
-
#
-
# This formatter prints features to plain text - exactly how they were parsed,
-
# just prettier. That means with proper indentation and alignment of table columns.
-
#
-
# If the output is STDOUT (and not a file), there are bright colours to watch too.
-
#
-
1
class Pretty
-
1
include FileUtils
-
1
include Console
-
1
include Io
-
1
include Cucumber::Gherkin::Formatter::Escaping
-
1
attr_writer :indent
-
1
attr_reader :runtime
-
-
1
def initialize(runtime, path_or_io, options)
-
1
@runtime, @io, @options = runtime, ensure_io(path_or_io), options
-
1
@exceptions = []
-
1
@indent = 0
-
1
@prefixes = options[:prefixes] || {}
-
1
@delayed_messages = []
-
1
@previous_step_keyword = nil
-
1
@snippets_input = []
-
end
-
-
1
def before_features(features)
-
1
print_profile_information
-
end
-
-
1
def after_features(features)
-
1
print_summary(features)
-
end
-
-
1
def before_feature(feature)
-
4
@exceptions = []
-
4
@indent = 0
-
end
-
-
1
def comment_line(comment_line)
-
@io.puts(comment_line.indent(@indent))
-
@io.flush
-
end
-
-
1
def after_tags(tags)
-
22
if @indent == 1
-
@io.puts
-
@io.flush
-
end
-
end
-
-
1
def tag_name(tag_name)
-
tag = format_string(tag_name, :tag).indent(@indent)
-
@io.print(tag)
-
@io.flush
-
@indent = 1
-
end
-
-
1
def feature_name(keyword, name)
-
4
@io.puts("#{keyword}: #{name}")
-
4
@io.puts
-
4
@io.flush
-
end
-
-
1
def before_feature_element(feature_element)
-
18
@indent = 2
-
18
@scenario_indent = 2
-
end
-
-
1
def after_feature_element(feature_element)
-
18
print_messages
-
18
@io.puts
-
18
@io.flush
-
end
-
-
1
def before_background(background)
-
4
@indent = 2
-
4
@scenario_indent = 2
-
4
@in_background = true
-
end
-
-
1
def after_background(background)
-
4
print_messages
-
4
@in_background = nil
-
4
@io.puts
-
4
@io.flush
-
end
-
-
1
def background_name(keyword, name, file_colon_line, source_indent)
-
4
print_feature_element_name(keyword, name, file_colon_line, source_indent)
-
end
-
-
1
def before_examples_array(examples_array)
-
@indent = 4
-
@io.puts
-
@visiting_first_example_name = true
-
end
-
-
1
def examples_name(keyword, name)
-
@io.puts unless @visiting_first_example_name
-
@visiting_first_example_name = false
-
@io.puts(" #{keyword}: #{name}")
-
@io.flush
-
@indent = 6
-
@scenario_indent = 6
-
end
-
-
1
def before_outline_table(outline_table)
-
@table = outline_table
-
end
-
-
1
def after_outline_table(outline_table)
-
@table = nil
-
@indent = 4
-
end
-
-
1
def scenario_name(keyword, name, file_colon_line, source_indent)
-
18
print_feature_element_name(keyword, name, file_colon_line, source_indent)
-
end
-
-
1
def before_step(step)
-
98
@current_step = step
-
98
@indent = 6
-
98
print_messages
-
end
-
-
1
def before_step_result(keyword, step_match, multiline_arg, status, exception, source_indent, background, file_colon_line)
-
98
@hide_this_step = false
-
98
if exception
-
if @exceptions.include?(exception)
-
@hide_this_step = true
-
return
-
end
-
@exceptions << exception
-
end
-
98
if status != :failed && @in_background ^ background
-
@hide_this_step = true
-
return
-
end
-
98
@status = status
-
end
-
-
1
def step_name(keyword, step_match, status, source_indent, background, file_colon_line)
-
98
return if @hide_this_step
-
98
source_indent = nil unless @options[:source]
-
98
name_to_report = format_step(keyword, step_match, status, source_indent)
-
98
@io.puts(name_to_report.indent(@scenario_indent + 2))
-
98
print_messages
-
end
-
-
1
def doc_string(string)
-
return if @options[:no_multiline] || @hide_this_step
-
s = %{"""\n#{string}\n"""}.indent(@indent)
-
s = s.split("\n").map{|l| l =~ /^\s+$/ ? '' : l}.join("\n")
-
@io.puts(format_string(s, @current_step.status))
-
@io.flush
-
end
-
-
1
def exception(exception, status)
-
return if @hide_this_step
-
print_messages
-
print_exception(exception, status, @indent)
-
@io.flush
-
end
-
-
1
def before_multiline_arg(multiline_arg)
-
4
return if @options[:no_multiline] || @hide_this_step
-
4
@table = multiline_arg
-
end
-
-
1
def after_multiline_arg(multiline_arg)
-
4
@table = nil
-
end
-
-
1
def before_table_row(table_row)
-
9
return if !@table || @hide_this_step
-
9
@col_index = 0
-
9
@io.print ' |'.indent(@indent-2)
-
end
-
-
1
def after_table_row(table_row)
-
9
return if !@table || @hide_this_step
-
9
print_table_row_messages
-
9
@io.puts
-
9
if table_row.exception && !@exceptions.include?(table_row.exception)
-
print_exception(table_row.exception, table_row.status, @indent)
-
end
-
end
-
-
1
def after_table_cell(cell)
-
28
return unless @table
-
28
@col_index += 1
-
end
-
-
1
def table_cell_value(value, status)
-
28
return if !@table || @hide_this_step
-
28
status ||= @status || :passed
-
28
width = @table.col_width(@col_index)
-
28
cell_text = escape_cell(value.to_s || '')
-
28
padded = cell_text + (' ' * (width - cell_text.unpack('U*').length))
-
28
prefix = cell_prefix(status)
-
28
@io.print(' ' + format_string("#{prefix}#{padded}", status) + ::Cucumber::Term::ANSIColor.reset(" |"))
-
28
@io.flush
-
end
-
-
1
def before_test_case(test_case)
-
18
@previous_step_keyword = nil
-
end
-
-
1
def after_test_step(test_step, result)
-
292
collect_snippet_data(test_step, result)
-
end
-
-
1
private
-
-
1
def print_feature_element_name(keyword, name, file_colon_line, source_indent)
-
22
@io.puts if @scenario_indent == 6
-
22
names = name.empty? ? [name] : name.split("\n")
-
22
line = "#{keyword}: #{names[0]}".indent(@scenario_indent)
-
22
@io.print(line)
-
22
if @options[:source]
-
22
line_comment = "# #{file_colon_line}".indent(source_indent)
-
22
@io.print(format_string(line_comment, :comment))
-
end
-
22
@io.puts
-
22
names[1..-1].each {|s| @io.puts "#{s}"}
-
22
@io.flush
-
end
-
-
1
def cell_prefix(status)
-
28
@prefixes[status]
-
end
-
-
1
def print_summary(features)
-
1
print_stats(features, @options)
-
1
print_snippets(@options)
-
1
print_passing_wip(@options)
-
end
-
end
-
end
-
end
-
3
env_caller = File.dirname(caller.detect{ |f| f =~ /\/env\.rb:/ }) if caller.detect{ |f| f =~ /\/env\.rb:/ }
-
1
if env_caller
-
1
require 'rails'
-
1
require 'cucumber/rails/application'
-
1
ENV['RAILS_ENV'] ||= 'test'
-
1
ENV['RAILS_ROOT'] ||= File.expand_path(env_caller + '/../..')
-
1
require File.expand_path(ENV['RAILS_ROOT'] + '/config/environment')
-
1
require 'cucumber/rails/action_controller'
-
-
1
if defined?(ActiveRecord::Base)
-
1
require 'rails/test_help'
-
else
-
require 'action_dispatch/testing/test_process'
-
require 'action_dispatch/testing/integration'
-
end
-
-
1
unless Rails.application.config.cache_classes
-
warn "WARNING: You have set Rails' config.cache_classes to false (most likely in config/environments/cucumber.rb). This setting is known to cause problems with database transactions. Set config.cache_classes to true if you want to use transactions."
-
end
-
-
1
require 'cucumber/rails/world'
-
1
require 'cucumber/rails/hooks'
-
1
require 'cucumber/rails/capybara'
-
1
require 'cucumber/rails/database'
-
-
1
MultiTest.disable_autorun
-
else
-
warn "WARNING: Cucumber-rails required outside of env.rb. The rest of loading is being deferred until env.rb is called.
-
To avoid this warning, move 'gem \'cucumber-rails\', :require => false' under only group :test in your Gemfile.
-
If already in the :test group, be sure you are specifying ':require => false'."
-
end
-
1
ActionController::Base.class_eval do
-
1
cattr_accessor :allow_rescue
-
end
-
-
1
class ActionDispatch::ShowExceptions
-
1
alias __cucumber_orig_call__ call
-
-
1
def call(env)
-
66
env['action_dispatch.show_exceptions'] = !!ActionController::Base.allow_rescue
-
66
__cucumber_orig_call__(env)
-
end
-
end
-
1
require 'rails/application'
-
-
# Make sure the ActionDispatch::ShowExceptions middleware is always enabled,
-
# regardless of what is in config/environments/test.rb
-
# Instead we are overriding ActionDispatch::ShowExceptions to be able to
-
# toggle whether or not exceptions are raised.
-
1
class Rails::Application
-
1
alias __cucumber_orig_initialize__ initialize!
-
-
1
def initialize!
-
1
ad = config.action_dispatch
-
1
def ad.show_exceptions
-
1
true
-
end
-
1
__cucumber_orig_initialize__
-
end
-
end
-
1
require 'capybara'
-
1
require 'capybara/rails'
-
1
require 'capybara/cucumber'
-
1
require 'capybara/session'
-
1
require 'cucumber/rails/capybara/javascript_emulation'
-
1
require 'cucumber/rails/capybara/select_dates_and_times'
-
1
module Cucumber
-
1
module Rails
-
1
module Capybara
-
1
module JavascriptEmulation
-
1
def self.included(base)
-
1
base.class_eval do
-
1
alias_method :click_without_javascript_emulation, :click
-
1
alias_method :click, :click_with_javascript_emulation
-
end
-
end
-
-
1
def click_with_javascript_emulation
-
37
if link_with_non_get_http_method?
-
3
::Capybara::RackTest::Form.new(driver, js_form(element_node.document, self[:href], emulated_method)).submit(self)
-
else
-
34
click_without_javascript_emulation
-
end
-
end
-
-
1
private
-
-
1
def csrf?
-
3
csrf_param_node && csrf_token_node
-
end
-
-
1
def csrf_param_node
-
3
element_node.document.at_xpath("//meta[@name='csrf-param']")
-
end
-
-
1
def csrf_param
-
csrf_param_node['content']
-
end
-
-
1
def csrf_token_node
-
element_node.document.at_xpath("//meta[@name='csrf-token']")
-
end
-
-
1
def csrf_token
-
csrf_token_node['content']
-
end
-
-
1
def js_form(document, action, emulated_method, method = 'POST')
-
3
js_form = document.create_element('form')
-
3
js_form['action'] = action
-
3
js_form['method'] = method
-
-
3
if emulated_method and emulated_method.downcase != method.downcase
-
3
input = document.create_element('input')
-
3
input['type'] = 'hidden'
-
3
input['name'] = '_method'
-
3
input['value'] = emulated_method
-
3
js_form.add_child(input)
-
end
-
-
# rails will wipe the session if the CSRF token is not sent
-
# with non-GET requests
-
3
if csrf? && emulated_method.downcase != 'get'
-
input = document.create_element('input')
-
input['type'] = 'hidden'
-
input['name'] = csrf_param
-
input['value'] = csrf_token
-
js_form.add_child(input)
-
end
-
-
3
js_form
-
end
-
-
1
def link_with_non_get_http_method?
-
37
if ::Rails.version.to_f >= 3.0
-
37
tag_name == 'a' && element_node['data-method'] && element_node['data-method'] =~ /(?:delete|put|post)/
-
else
-
tag_name == 'a' && element_node['onclick'] && element_node['onclick'] =~ /var f = document\.createElement\('form'\); f\.style\.display = 'none';/
-
end
-
end
-
-
1
def emulated_method
-
3
if ::Rails.version.to_f >= 3.0
-
3
element_node['data-method']
-
else
-
element_node['onclick'][/m\.setAttribute\('value', '([^']*)'\)/, 1]
-
end
-
end
-
-
1
def element_node
-
41
if self.respond_to? :native
-
41
self.native
-
else
-
warn 'DEPRECATED: cucumber-rails loves you, just not your version of Capybara. Please update Capybara to >= 0.4.0'
-
self.node
-
end
-
end
-
end
-
end
-
end
-
end
-
-
1
class Capybara::RackTest::Node
-
1
include ::Cucumber::Rails::Capybara::JavascriptEmulation
-
end
-
-
1
Before('~@no-js-emulation') do
-
# Enable javascript emulation
-
18
::Capybara::RackTest::Node.class_eval do
-
18
alias_method :click, :click_with_javascript_emulation
-
end
-
end
-
-
1
Before('@no-js-emulation') do
-
# Disable javascript emulation
-
::Capybara::RackTest::Node.class_eval do
-
alias_method :click, :click_without_javascript_emulation
-
end
-
end
-
1
module Cucumber
-
1
module Rails
-
1
module Capybara
-
# This module defines methods for selecting dates and times
-
1
module SelectDatesAndTimes
-
# Select a Rails date. Options hash must include :from => +label+
-
1
def select_date(date, options)
-
date = Date.parse(date)
-
base_dom_id = get_base_dom_id_from_label_tag(options[:from])
-
-
find(:xpath, ".//select[@id='#{base_dom_id}_1i']").select(date.year.to_s)
-
find(:xpath, ".//select[@id='#{base_dom_id}_2i']").select(I18n.l date, format: '%B')
-
find(:xpath, ".//select[@id='#{base_dom_id}_3i']").select(date.day.to_s)
-
end
-
-
# Select a Rails time. Options hash must include :from => +label+
-
1
def select_time(time, options)
-
time = Time.zone.parse(time)
-
base_dom_id = get_base_dom_id_from_label_tag(options[:from])
-
-
find(:xpath, ".//select[@id='#{base_dom_id}_4i']").select(time.hour.to_s.rjust(2, '0'))
-
find(:xpath, ".//select[@id='#{base_dom_id}_5i']").select(time.min.to_s.rjust(2, '0'))
-
end
-
-
# Select a Rails datetime. Options hash must include :from => +label+
-
1
def select_datetime(datetime, options)
-
select_date(datetime, options)
-
select_time(datetime, options)
-
end
-
-
1
private
-
-
# @example "event_starts_at_"
-
1
def get_base_dom_id_from_label_tag(field)
-
find(:xpath, ".//label[contains(., '#{field}')]")['for'].gsub(/(_[1-5]i)$/, '')
-
end
-
end
-
end
-
end
-
end
-
-
1
World(::Cucumber::Rails::Capybara::SelectDatesAndTimes)
-
1
require 'cucumber/rails/hooks/active_record'
-
1
require 'cucumber/rails/hooks/database_cleaner'
-
1
require 'cucumber/rails/hooks/allow_rescue'
-
1
require 'cucumber/rails/hooks/mail'
-
1
if defined?(ActiveRecord::Base)
-
1
class ActiveRecord::Base
-
1
class_attribute :shared_connection
-
-
1
def self.connection
-
701
self.shared_connection || retrieve_connection
-
end
-
end
-
-
1
Before('@javascript') do
-
Cucumber::Rails::Database.before_js if Cucumber::Rails::Database.autorun_database_cleaner
-
end
-
-
1
Before('~@javascript') do
-
18
Cucumber::Rails::Database.before_non_js if Cucumber::Rails::Database.autorun_database_cleaner
-
end
-
-
1
After do
-
18
Cucumber::Rails::Database.after if Cucumber::Rails::Database.autorun_database_cleaner
-
end
-
end
-
1
Before('@allow-rescue') do
-
@__orig_allow_rescue = ActionController::Base.allow_rescue
-
ActionController::Base.allow_rescue = true
-
end
-
-
1
After('@allow-rescue') do
-
ActionController::Base.allow_rescue = @__orig_allow_rescue
-
end
-
1
begin
-
1
require 'database_cleaner'
-
-
1
Before('~@no-database-cleaner') do
-
18
DatabaseCleaner.start if Cucumber::Rails::Database.autorun_database_cleaner
-
end
-
-
1
After('~@no-database-cleaner') do
-
18
DatabaseCleaner.clean if Cucumber::Rails::Database.autorun_database_cleaner
-
end
-
-
rescue LoadError => ignore_if_database_cleaner_not_present
-
end
-
1
if defined?(ActionMailer::Base)
-
1
Before do
-
18
ActionMailer::Base.deliveries = []
-
end
-
end
-
1
begin
-
# Try to load it so we can assign @_result below if needed.
-
1
require 'test/unit/testresult'
-
rescue LoadError => ignore
-
end
-
-
1
module Cucumber #:nodoc:
-
1
module Rails #:nodoc:
-
1
class World < ActionDispatch::IntegrationTest #:nodoc:
-
1
include Rack::Test::Methods
-
1
include ActiveSupport::Testing::SetupAndTeardown if ActiveSupport::Testing.const_defined?('SetupAndTeardown')
-
-
1
def initialize #:nodoc:
-
18
@_result = Test::Unit::TestResult.new if defined?(Test::Unit::TestResult)
-
end
-
-
1
unless defined?(ActiveRecord::Base)
-
def self.fixture_table_names; []; end # Workaround for projects that don't use ActiveRecord
-
end
-
end
-
end
-
end
-
-
1
World do
-
18
Cucumber::Rails::World.new
-
end
-
1
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__))) unless $LOAD_PATH.include?(File.expand_path(File.dirname(__FILE__)))
-
1
require 'database_cleaner/configuration'
-
-
1
module DatabaseCleaner
-
1
def self.can_detect_orm?
-
DatabaseCleaner::Base.autodetect_orm
-
end
-
end
-
1
require 'database_cleaner/generic/base'
-
1
require 'active_record'
-
1
require 'erb'
-
-
1
module DatabaseCleaner
-
1
module ActiveRecord
-
-
1
def self.available_strategies
-
%w[truncation transaction deletion]
-
end
-
-
1
def self.config_file_location=(path)
-
@config_file_location = path
-
end
-
-
1
def self.config_file_location
-
@config_file_location ||= "#{DatabaseCleaner.app_root}/config/database.yml"
-
end
-
-
1
module Base
-
1
include ::DatabaseCleaner::Generic::Base
-
-
1
attr_accessor :connection_hash
-
-
1
def db=(desired_db)
-
3
@db = desired_db
-
3
load_config
-
end
-
-
1
def db
-
5
@db ||= super
-
end
-
-
1
def load_config
-
3
if self.db != :default && self.db.is_a?(Symbol) && File.file?(ActiveRecord.config_file_location)
-
connection_details = YAML::load(ERB.new(IO.read(ActiveRecord.config_file_location)).result)
-
@connection_hash = valid_config(connection_details)[self.db.to_s]
-
end
-
end
-
-
1
def valid_config(connection_file)
-
if !::ActiveRecord::Base.configurations.nil? && !::ActiveRecord::Base.configurations.empty?
-
if connection_file != ::ActiveRecord::Base.configurations
-
return ::ActiveRecord::Base.configurations
-
end
-
end
-
connection_file
-
end
-
-
1
def connection_class
-
@connection_class ||= if db && !db.is_a?(Symbol)
-
db
-
elsif connection_hash
-
lookup_from_connection_pool || establish_connection
-
else
-
1
::ActiveRecord::Base
-
126
end
-
end
-
-
1
private
-
-
1
def lookup_from_connection_pool
-
if ::ActiveRecord::Base.respond_to?(:descendants)
-
database_name = connection_hash["database"] || connection_hash[:database]
-
models = ::ActiveRecord::Base.descendants
-
models.detect { |m| m.connection_pool.spec.config[:database] == database_name }
-
end
-
end
-
-
1
def establish_connection
-
::ActiveRecord::Base.establish_connection(connection_hash)
-
end
-
-
end
-
end
-
end
-
1
require 'database_cleaner/active_record/base'
-
1
require 'database_cleaner/generic/transaction'
-
-
1
module DatabaseCleaner::ActiveRecord
-
1
class Transaction
-
1
include ::DatabaseCleaner::ActiveRecord::Base
-
1
include ::DatabaseCleaner::Generic::Transaction
-
-
1
def start
-
# Hack to make sure that the connection is properly setup for
-
# the clean code.
-
18
connection_class.connection.transaction{ }
-
-
18
if connection_maintains_transaction_count?
-
if connection_class.connection.respond_to?(:increment_open_transactions)
-
connection_class.connection.increment_open_transactions
-
else
-
connection_class.__send__(:increment_open_transactions)
-
end
-
end
-
18
if connection_class.connection.respond_to?(:begin_transaction)
-
18
connection_class.connection.begin_transaction :joinable => false
-
else
-
connection_class.connection.begin_db_transaction
-
end
-
end
-
-
-
1
def clean
-
18
return unless connection_class.connection.open_transactions > 0
-
-
18
if connection_class.connection.respond_to?(:rollback_transaction)
-
18
connection_class.connection.rollback_transaction
-
else
-
connection_class.connection.rollback_db_transaction
-
end
-
-
# The below is for handling after_commit hooks.. see https://github.com/bmabey/database_cleaner/issues/99
-
18
if connection_class.connection.respond_to?(:rollback_transaction_records, true)
-
connection_class.connection.send(:rollback_transaction_records, true)
-
end
-
-
18
if connection_maintains_transaction_count?
-
if connection_class.connection.respond_to?(:decrement_open_transactions)
-
connection_class.connection.decrement_open_transactions
-
else
-
connection_class.__send__(:decrement_open_transactions)
-
end
-
end
-
end
-
-
1
def connection_maintains_transaction_count?
-
36
ActiveRecord::VERSION::MAJOR < 4
-
end
-
-
end
-
end
-
1
require 'database_cleaner/null_strategy'
-
1
module DatabaseCleaner
-
1
class Base
-
1
def initialize(desired_orm = nil,opts = {})
-
2
if [:autodetect, nil, "autodetect"].include?(desired_orm)
-
1
autodetect
-
else
-
1
self.orm = desired_orm
-
end
-
2
self.db = opts[:connection] || opts[:model] if opts.has_key?(:connection) || opts.has_key?(:model)
-
2
set_default_orm_strategy
-
end
-
-
1
def db=(desired_db)
-
self.strategy_db = desired_db
-
@db = desired_db
-
end
-
-
1
def strategy_db=(desired_db)
-
if strategy.respond_to? :db=
-
strategy.db = desired_db
-
elsif desired_db!= :default
-
raise ArgumentError, "You must provide a strategy object that supports non default databases when you specify a database"
-
end
-
end
-
-
1
def db
-
3
@db ||= :default
-
end
-
-
1
def create_strategy(*args)
-
3
strategy, *strategy_args = args
-
3
orm_strategy(strategy).new(*strategy_args)
-
end
-
-
1
def clean_with(*args)
-
strategy = create_strategy(*args)
-
set_strategy_db strategy, self.db
-
-
strategy.clean
-
strategy
-
end
-
-
1
alias clean_with! clean_with
-
-
1
def set_strategy_db(strategy, desired_db)
-
3
if strategy.respond_to? :db=
-
3
strategy.db = desired_db
-
elsif desired_db != :default
-
raise ArgumentError, "You must provide a strategy object that supports non default databases when you specify a database"
-
end
-
end
-
-
1
def strategy=(args)
-
3
strategy, *strategy_args = args
-
3
if strategy.is_a?(Symbol)
-
3
@strategy = create_strategy(*args)
-
elsif strategy_args.empty?
-
@strategy = strategy
-
else
-
raise ArgumentError, "You must provide a strategy object, or a symbol for a known strategy along with initialization params."
-
end
-
-
3
set_strategy_db @strategy, self.db
-
-
3
@strategy
-
end
-
-
1
def strategy
-
36
@strategy ||= NullStrategy
-
end
-
-
1
def orm=(desired_orm)
-
1
@orm = desired_orm.to_sym
-
end
-
-
1
def orm
-
9
@orm || autodetect
-
end
-
-
1
def start
-
18
strategy.start
-
end
-
-
1
def clean
-
18
strategy.clean
-
end
-
-
1
alias clean! clean
-
-
1
def cleaning(&block)
-
strategy.cleaning(&block)
-
end
-
-
1
def auto_detected?
-
!!@autodetected
-
end
-
-
#TODO make strategies directly comparable
-
1
def ==(other)
-
self.orm == other.orm && self.db == other.db
-
end
-
-
1
def autodetect_orm
-
1
if defined? ::ActiveRecord
-
1
:active_record
-
elsif defined? ::DataMapper
-
:data_mapper
-
elsif defined? ::MongoMapper
-
:mongo_mapper
-
elsif defined? ::Mongoid
-
:mongoid
-
elsif defined? ::CouchPotato
-
:couch_potato
-
elsif defined? ::Sequel
-
:sequel
-
elsif defined? ::Moped
-
:moped
-
elsif defined? ::Ohm
-
:ohm
-
elsif defined? ::Redis
-
:redis
-
elsif defined? ::Neo4j
-
:neo4j
-
end
-
end
-
-
1
private
-
-
1
def orm_module
-
3
::DatabaseCleaner.orm_module(orm)
-
end
-
-
1
def orm_strategy(strategy)
-
3
require "database_cleaner/#{orm.to_s}/#{strategy.to_s}"
-
3
orm_module.const_get(strategy.to_s.capitalize)
-
rescue LoadError
-
if orm_module.respond_to? :available_strategies
-
raise UnknownStrategySpecified, "The '#{strategy}' strategy does not exist for the #{orm} ORM! Available strategies: #{orm_module.available_strategies.join(', ')}"
-
else
-
raise UnknownStrategySpecified, "The '#{strategy}' strategy does not exist for the #{orm} ORM!"
-
end
-
end
-
-
1
def autodetect
-
1
@autodetected = true
-
-
@orm ||= autodetect_orm ||
-
1
raise(NoORMDetected, "No known ORM was detected! Is ActiveRecord, DataMapper, Sequel, MongoMapper, Mongoid, Moped, or CouchPotato, Redis or Ohm loaded?")
-
end
-
-
1
def set_default_orm_strategy
-
2
case orm
-
when :active_record, :data_mapper, :sequel
-
2
self.strategy = :transaction
-
when :mongo_mapper, :mongoid, :couch_potato, :moped, :ohm, :redis
-
self.strategy = :truncation
-
when :neo4j
-
self.strategy = :transaction
-
end
-
end
-
end
-
end
-
1
module ::DatabaseCleaner
-
1
module Generic
-
1
module Base
-
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
end
-
-
1
def db
-
:default
-
end
-
-
1
def cleaning(&block)
-
start
-
yield
-
clean
-
end
-
-
1
module ClassMethods
-
1
def available_strategies
-
%W[]
-
end
-
end
-
end
-
end
-
end
-
1
module DatabaseCleaner
-
1
module Generic
-
1
module Transaction
-
1
def initialize(opts = {})
-
3
if !opts.empty?
-
raise ArgumentError, "Options are not available for transaction strategies."
-
end
-
end
-
end
-
end
-
end
-
1
module DatabaseCleaner
-
1
class NullStrategy
-
1
def self.start
-
# no-op
-
end
-
-
1
def self.db=(connection)
-
# no-op
-
end
-
-
1
def self.clean
-
# no-op
-
end
-
end
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
##
-
## an implementation of eRuby
-
##
-
## ex.
-
## input = <<'END'
-
## <ul>
-
## <% for item in @list %>
-
## <li><%= item %>
-
## <%== item %></li>
-
## <% end %>
-
## </ul>
-
## END
-
## list = ['<aaa>', 'b&b', '"ccc"']
-
## eruby = Erubis::Eruby.new(input)
-
## puts "--- code ---"
-
## puts eruby.src
-
## puts "--- result ---"
-
## context = Erubis::Context.new() # or new(:list=>list)
-
## context[:list] = list
-
## puts eruby.evaluate(context)
-
##
-
## result:
-
## --- source ---
-
## _buf = ''; _buf << '<ul>
-
## '; for item in @list
-
## _buf << ' <li>'; _buf << ( item ).to_s; _buf << '
-
## '; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</li>
-
## '; end
-
## _buf << '</ul>
-
## ';
-
## _buf.to_s
-
## --- result ---
-
## <ul>
-
## <li><aaa>
-
## <aaa></li>
-
## <li>b&b
-
## b&b</li>
-
## <li>"ccc"
-
## "ccc"</li>
-
## </ul>
-
##
-
-
-
1
module Erubis
-
1
VERSION = ('$Release: 2.7.0 $' =~ /([.\d]+)/) && $1
-
end
-
-
1
require 'erubis/engine'
-
#require 'erubis/generator'
-
#require 'erubis/converter'
-
#require 'erubis/evaluator'
-
#require 'erubis/error'
-
#require 'erubis/context'
-
#requier 'erubis/util'
-
1
require 'erubis/helper'
-
1
require 'erubis/enhancer'
-
#require 'erubis/tiny'
-
1
require 'erubis/engine/eruby'
-
#require 'erubis/engine/enhanced' # enhanced eruby engines
-
#require 'erubis/engine/optimized' # generates optimized ruby code
-
#require 'erubis/engine/ephp'
-
#require 'erubis/engine/ec'
-
#require 'erubis/engine/ejava'
-
#require 'erubis/engine/escheme'
-
#require 'erubis/engine/eperl'
-
#require 'erubis/engine/ejavascript'
-
-
1
require 'erubis/local-setting'
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
1
module Erubis
-
-
-
##
-
## context object for Engine#evaluate
-
##
-
## ex.
-
## template = <<'END'
-
## Hello <%= @user %>!
-
## <% for item in @list %>
-
## - <%= item %>
-
## <% end %>
-
## END
-
##
-
## context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
-
## # or
-
## # context = Erubis::Context.new
-
## # context[:user] = 'World'
-
## # context[:list] = ['a', 'b', 'c']
-
##
-
## eruby = Erubis::Eruby.new(template)
-
## print eruby.evaluate(context)
-
##
-
1
class Context
-
1
include Enumerable
-
-
1
def initialize(hash=nil)
-
hash.each do |name, value|
-
self[name] = value
-
end if hash
-
end
-
-
1
def [](key)
-
return instance_variable_get("@#{key}")
-
end
-
-
1
def []=(key, value)
-
return instance_variable_set("@#{key}", value)
-
end
-
-
1
def keys
-
return instance_variables.collect { |name| name[1..-1] }
-
end
-
-
1
def each
-
instance_variables.each do |name|
-
key = name[1..-1]
-
value = instance_variable_get(name)
-
yield(key, value)
-
end
-
end
-
-
1
def to_hash
-
hash = {}
-
self.keys.each { |key| hash[key] = self[key] }
-
return hash
-
end
-
-
1
def update(context_or_hash)
-
arg = context_or_hash
-
if arg.is_a?(Hash)
-
arg.each do |key, val|
-
self[key] = val
-
end
-
else
-
arg.instance_variables.each do |varname|
-
key = varname[1..-1]
-
val = arg.instance_variable_get(varname)
-
self[key] = val
-
end
-
end
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
require 'erubis/util'
-
-
1
module Erubis
-
-
-
##
-
## convert
-
##
-
1
module Converter
-
-
1
attr_accessor :preamble, :postamble, :escape
-
-
1
def self.supported_properties # :nodoc:
-
return [
-
[:preamble, nil, "preamble (no preamble when false)"],
-
[:postamble, nil, "postamble (no postamble when false)"],
-
[:escape, nil, "escape expression or not in default"],
-
]
-
end
-
-
1
def init_converter(properties={})
-
@preamble = properties[:preamble]
-
@postamble = properties[:postamble]
-
@escape = properties[:escape]
-
end
-
-
## convert input string into target language
-
1
def convert(input)
-
codebuf = "" # or []
-
@preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble))
-
convert_input(codebuf, input)
-
@postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble))
-
@_proc = nil # clear cached proc object
-
return codebuf # or codebuf.join()
-
end
-
-
1
protected
-
-
##
-
## detect spaces at beginning of line
-
##
-
1
def detect_spaces_at_bol(text, is_bol)
-
lspace = nil
-
if text.empty?
-
lspace = "" if is_bol
-
elsif text[-1] == ?\n
-
lspace = ""
-
else
-
rindex = text.rindex(?\n)
-
if rindex
-
s = text[rindex+1..-1]
-
if s =~ /\A[ \t]*\z/
-
lspace = s
-
#text = text[0..rindex]
-
text[rindex+1..-1] = ''
-
end
-
else
-
if is_bol && text =~ /\A[ \t]*\z/
-
#lspace = text
-
#text = nil
-
lspace = text.dup
-
text[0..-1] = ''
-
end
-
end
-
end
-
return lspace
-
end
-
-
##
-
## (abstract) convert input to code
-
##
-
1
def convert_input(codebuf, input)
-
not_implemented
-
end
-
-
end
-
-
-
1
module Basic
-
end
-
-
-
##
-
## basic converter which supports '<% ... %>' notation.
-
##
-
1
module Basic::Converter
-
1
include Erubis::Converter
-
-
1
def self.supported_properties # :nodoc:
-
return [
-
[:pattern, '<% %>', "embed pattern"],
-
[:trim, true, "trim spaces around <% ... %>"],
-
]
-
end
-
-
1
attr_accessor :pattern, :trim
-
-
1
def init_converter(properties={})
-
super(properties)
-
@pattern = properties[:pattern]
-
@trim = properties[:trim] != false
-
end
-
-
1
protected
-
-
## return regexp of pattern to parse eRuby script
-
1
def pattern_regexp(pattern)
-
1
@prefix, @postfix = pattern.split() # '<% %>' => '<%', '%>'
-
#return /(.*?)(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
-
#return /(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
-
1
return /#{@prefix}(=+|-|\#|%)?(.*?)([-=])?#{@postfix}([ \t]*\r?\n)?/m
-
end
-
1
module_function :pattern_regexp
-
-
#DEFAULT_REGEXP = /(.*?)(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
#DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
#DEFAULT_REGEXP = /<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
1
DEFAULT_REGEXP = pattern_regexp('<% %>')
-
-
1
public
-
-
1
def convert_input(src, input)
-
pat = @pattern
-
regexp = pat.nil? || pat == '<% %>' ? DEFAULT_REGEXP : pattern_regexp(pat)
-
pos = 0
-
is_bol = true # is beginning of line
-
input.scan(regexp) do |indicator, code, tailch, rspace|
-
match = Regexp.last_match()
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
ch = indicator ? indicator[0] : nil
-
lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
-
is_bol = rspace ? true : false
-
add_text(src, text) if text && !text.empty?
-
## * when '<%= %>', do nothing
-
## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
-
if ch == ?= # <%= %>
-
rspace = nil if tailch && !tailch.empty?
-
add_text(src, lspace) if lspace
-
add_expr(src, code, indicator)
-
add_text(src, rspace) if rspace
-
elsif ch == ?\# # <%# %>
-
n = code.count("\n") + (rspace ? 1 : 0)
-
if @trim && lspace && rspace
-
add_stmt(src, "\n" * n)
-
else
-
add_text(src, lspace) if lspace
-
add_stmt(src, "\n" * n)
-
add_text(src, rspace) if rspace
-
end
-
elsif ch == ?% # <%% %>
-
s = "#{lspace}#{@prefix||='<%'}#{code}#{tailch}#{@postfix||='%>'}#{rspace}"
-
add_text(src, s)
-
else # <% %>
-
if @trim && lspace && rspace
-
add_stmt(src, "#{lspace}#{code}#{rspace}")
-
else
-
add_text(src, lspace) if lspace
-
add_stmt(src, code)
-
add_text(src, rspace) if rspace
-
end
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
add_text(src, rest)
-
end
-
-
## add expression code to src
-
1
def add_expr(src, code, indicator)
-
case indicator
-
when '='
-
@escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
-
when '=='
-
@escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
-
when '==='
-
add_expr_debug(src, code)
-
end
-
end
-
-
end
-
-
-
1
module PI
-
end
-
-
##
-
## Processing Instructions (PI) converter for XML.
-
## this class converts '<?rb ... ?>' and '${...}' notation.
-
##
-
1
module PI::Converter
-
1
include Erubis::Converter
-
-
1
def self.desc # :nodoc:
-
"use processing instructions (PI) instead of '<% %>'"
-
end
-
-
1
def self.supported_properties # :nodoc:
-
return [
-
[:trim, true, "trim spaces around <% ... %>"],
-
[:pi, 'rb', "PI (Processing Instrunctions) name"],
-
[:embchar, '@', "char for embedded expression pattern('@{...}@')"],
-
[:pattern, '<% %>', "embed pattern"],
-
]
-
end
-
-
1
attr_accessor :pi, :prefix
-
-
1
def init_converter(properties={})
-
super(properties)
-
@trim = properties.fetch(:trim, true)
-
@pi = properties[:pi] if properties[:pi]
-
@embchar = properties[:embchar] || '@'
-
@pattern = properties[:pattern]
-
@pattern = '<% %>' if @pattern.nil? #|| @pattern == true
-
end
-
-
1
def convert(input)
-
code = super(input)
-
return @header || @footer ? "#{@header}#{code}#{@footer}" : code
-
end
-
-
1
protected
-
-
1
def convert_input(codebuf, input)
-
unless @regexp
-
@pi ||= 'e'
-
ch = Regexp.escape(@embchar)
-
if @pattern
-
left, right = @pattern.split(' ')
-
@regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/m
-
else
-
@regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}/m
-
end
-
end
-
#
-
is_bol = true
-
pos = 0
-
input.scan(@regexp) do |pi_arg, stmt, rspace,
-
indicator1, expr1, indicator2, expr2|
-
match = Regexp.last_match
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
lspace = stmt ? detect_spaces_at_bol(text, is_bol) : nil
-
is_bol = stmt && rspace ? true : false
-
add_text(codebuf, text) # unless text.empty?
-
#
-
if stmt
-
if @trim && lspace && rspace
-
add_pi_stmt(codebuf, "#{lspace}#{stmt}#{rspace}", pi_arg)
-
else
-
add_text(codebuf, lspace) if lspace
-
add_pi_stmt(codebuf, stmt, pi_arg)
-
add_text(codebuf, rspace) if rspace
-
end
-
else
-
add_pi_expr(codebuf, expr1 || expr2, indicator1 || indicator2)
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
add_text(codebuf, rest)
-
end
-
-
#--
-
#def convert_input(codebuf, input)
-
# parse_stmts(codebuf, input)
-
# #parse_stmts2(codebuf, input)
-
#end
-
#
-
#def parse_stmts(codebuf, input)
-
# #regexp = pattern_regexp(@pattern)
-
# @pi ||= 'e'
-
# @stmt_pattern ||= /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?/m
-
# is_bol = true
-
# pos = 0
-
# input.scan(@stmt_pattern) do |pi_arg, code, rspace|
-
# match = Regexp.last_match
-
# len = match.begin(0) - pos
-
# text = input[pos, len]
-
# pos = match.end(0)
-
# lspace = detect_spaces_at_bol(text, is_bol)
-
# is_bol = rspace ? true : false
-
# parse_exprs(codebuf, text) # unless text.empty?
-
# if @trim && lspace && rspace
-
# add_pi_stmt(codebuf, "#{lspace}#{code}#{rspace}", pi_arg)
-
# else
-
# add_text(codebuf, lspace)
-
# add_pi_stmt(codebuf, code, pi_arg)
-
# add_text(codebuf, rspace)
-
# end
-
# end
-
# rest = $' || input
-
# parse_exprs(codebuf, rest)
-
#end
-
#
-
#def parse_exprs(codebuf, input)
-
# unless @expr_pattern
-
# ch = Regexp.escape(@embchar)
-
# if @pattern
-
# left, right = @pattern.split(' ')
-
# @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/
-
# else
-
# @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}/
-
# end
-
# end
-
# pos = 0
-
# input.scan(@expr_pattern) do |indicator1, code1, indicator2, code2|
-
# indicator = indicator1 || indicator2
-
# code = code1 || code2
-
# match = Regexp.last_match
-
# len = match.begin(0) - pos
-
# text = input[pos, len]
-
# pos = match.end(0)
-
# add_text(codebuf, text) # unless text.empty?
-
# add_pi_expr(codebuf, code, indicator)
-
# end
-
# rest = $' || input
-
# add_text(codebuf, rest)
-
#end
-
#++
-
-
1
def add_pi_stmt(codebuf, code, pi_arg) # :nodoc:
-
case pi_arg
-
when nil ; add_stmt(codebuf, code)
-
when 'header' ; @header = code
-
when 'footer' ; @footer = code
-
when 'comment'; add_stmt(codebuf, "\n" * code.count("\n"))
-
when 'value' ; add_expr_literal(codebuf, code)
-
else ; add_stmt(codebuf, code)
-
end
-
end
-
-
1
def add_pi_expr(codebuf, code, indicator) # :nodoc:
-
case indicator
-
when nil, '', '==' # @{...}@ or <%== ... %>
-
@escape == false ? add_expr_literal(codebuf, code) : add_expr_escaped(codebuf, code)
-
when '!', '=' # @!{...}@ or <%= ... %>
-
@escape == false ? add_expr_escaped(codebuf, code) : add_expr_literal(codebuf, code)
-
when '!!', '===' # @!!{...}@ or <%=== ... %>
-
add_expr_debug(codebuf, code)
-
else
-
# ignore
-
end
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
1
require 'erubis/generator'
-
1
require 'erubis/converter'
-
1
require 'erubis/evaluator'
-
1
require 'erubis/context'
-
-
-
1
module Erubis
-
-
-
##
-
## (abstract) abstract engine class.
-
## subclass must include evaluator and converter module.
-
##
-
1
class Engine
-
#include Evaluator
-
#include Converter
-
#include Generator
-
-
1
def initialize(input=nil, properties={})
-
#@input = input
-
init_generator(properties)
-
init_converter(properties)
-
init_evaluator(properties)
-
@src = convert(input) if input
-
end
-
-
-
##
-
## convert input string and set it to @src
-
##
-
1
def convert!(input)
-
@src = convert(input)
-
end
-
-
-
##
-
## load file, write cache file, and return engine object.
-
## this method create code cache file automatically.
-
## cachefile name can be specified with properties[:cachename],
-
## or filname + 'cache' is used as default.
-
##
-
1
def self.load_file(filename, properties={})
-
cachename = properties[:cachename] || (filename + '.cache')
-
properties[:filename] = filename
-
timestamp = File.mtime(filename)
-
if test(?f, cachename) && timestamp == File.mtime(cachename)
-
engine = self.new(nil, properties)
-
engine.src = File.read(cachename)
-
else
-
input = File.open(filename, 'rb') {|f| f.read }
-
engine = self.new(input, properties)
-
tmpname = cachename + rand().to_s[1,8]
-
File.open(tmpname, 'wb') {|f| f.write(engine.src) }
-
File.rename(tmpname, cachename)
-
File.utime(timestamp, timestamp, cachename)
-
end
-
engine.src.untaint # ok?
-
return engine
-
end
-
-
-
##
-
## helper method to convert and evaluate input text with context object.
-
## context may be Binding, Hash, or Object.
-
##
-
1
def process(input, context=nil, filename=nil)
-
code = convert(input)
-
filename ||= '(erubis)'
-
if context.is_a?(Binding)
-
return eval(code, context, filename)
-
else
-
context = Context.new(context) if context.is_a?(Hash)
-
return context.instance_eval(code, filename)
-
end
-
end
-
-
-
##
-
## helper method evaluate Proc object with contect object.
-
## context may be Binding, Hash, or Object.
-
##
-
1
def process_proc(proc_obj, context=nil, filename=nil)
-
if context.is_a?(Binding)
-
filename ||= '(erubis)'
-
return eval(proc_obj, context, filename)
-
else
-
context = Context.new(context) if context.is_a?(Hash)
-
return context.instance_eval(&proc_obj)
-
end
-
end
-
-
-
end # end of class Engine
-
-
-
##
-
## (abstract) base engine class for Eruby, Eperl, Ejava, and so on.
-
## subclass must include generator.
-
##
-
1
class Basic::Engine < Engine
-
1
include Evaluator
-
1
include Basic::Converter
-
1
include Generator
-
end
-
-
-
1
class PI::Engine < Engine
-
1
include Evaluator
-
1
include PI::Converter
-
1
include Generator
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
1
module Erubis
-
-
-
##
-
## switch '<%= ... %>' to escaped and '<%== ... %>' to unescaped
-
##
-
## ex.
-
## class XmlEruby < Eruby
-
## include EscapeEnhancer
-
## end
-
##
-
## this is language-indenedent.
-
##
-
1
module EscapeEnhancer
-
-
1
def self.desc # :nodoc:
-
"switch '<%= %>' to escaped and '<%== %>' to unescaped"
-
end
-
-
#--
-
#def self.included(klass)
-
# klass.class_eval <<-END
-
# alias _add_expr_literal add_expr_literal
-
# alias _add_expr_escaped add_expr_escaped
-
# alias add_expr_literal _add_expr_escaped
-
# alias add_expr_escaped _add_expr_literal
-
# END
-
#end
-
#++
-
-
1
def add_expr(src, code, indicator)
-
case indicator
-
when '='
-
@escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
-
when '=='
-
@escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
-
when '==='
-
add_expr_debug(src, code)
-
end
-
end
-
-
end
-
-
-
#--
-
## (obsolete)
-
#module FastEnhancer
-
#end
-
#++
-
-
-
##
-
## use $stdout instead of string
-
##
-
## this is only for Eruby.
-
##
-
1
module StdoutEnhancer
-
-
1
def self.desc # :nodoc:
-
"use $stdout instead of array buffer or string buffer"
-
end
-
-
1
def add_preamble(src)
-
src << "#{@bufvar} = $stdout;"
-
end
-
-
1
def add_postamble(src)
-
src << "\n''\n"
-
end
-
-
end
-
-
-
##
-
## use print statement instead of '_buf << ...'
-
##
-
## this is only for Eruby.
-
##
-
1
module PrintOutEnhancer
-
-
1
def self.desc # :nodoc:
-
"use print statement instead of '_buf << ...'"
-
end
-
-
1
def add_preamble(src)
-
end
-
-
1
def add_text(src, text)
-
src << " print '#{escape_text(text)}';" unless text.empty?
-
end
-
-
1
def add_expr_literal(src, code)
-
src << " print((#{code}).to_s);"
-
end
-
-
1
def add_expr_escaped(src, code)
-
src << " print #{escaped_expr(code)};"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
end
-
-
end
-
-
-
##
-
## enable print function
-
##
-
## Notice: use Eruby#evaluate() and don't use Eruby#result()
-
## to be enable print function.
-
##
-
## this is only for Eruby.
-
##
-
1
module PrintEnabledEnhancer
-
-
1
def self.desc # :nodoc:
-
"enable to use print function in '<% %>'"
-
end
-
-
1
def add_preamble(src)
-
src << "@_buf = "
-
super
-
end
-
-
1
def print(*args)
-
args.each do |arg|
-
@_buf << arg.to_s
-
end
-
end
-
-
1
def evaluate(context=nil)
-
_src = @src
-
if context.is_a?(Hash)
-
context.each do |key, val| instance_variable_set("@#{key}", val) end
-
elsif context
-
context.instance_variables.each do |name|
-
instance_variable_set(name, context.instance_variable_get(name))
-
end
-
end
-
return instance_eval(_src, (@filename || '(erubis)'))
-
end
-
-
end
-
-
-
##
-
## return array instead of string
-
##
-
## this is only for Eruby.
-
##
-
1
module ArrayEnhancer
-
-
1
def self.desc # :nodoc:
-
"return array instead of string"
-
end
-
-
1
def add_preamble(src)
-
src << "#{@bufvar} = [];"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}\n"
-
end
-
-
end
-
-
-
##
-
## use an Array object as buffer (included in Eruby by default)
-
##
-
## this is only for Eruby.
-
##
-
1
module ArrayBufferEnhancer
-
-
1
def self.desc # :nodoc:
-
"use an Array object for buffering (included in Eruby class)"
-
end
-
-
1
def add_preamble(src)
-
src << "_buf = [];"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "_buf.join\n"
-
end
-
-
end
-
-
-
##
-
## use String class for buffering
-
##
-
## this is only for Eruby.
-
##
-
1
module StringBufferEnhancer
-
-
1
def self.desc # :nodoc:
-
"use a String object for buffering"
-
end
-
-
1
def add_preamble(src)
-
src << "#{@bufvar} = '';"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.to_s\n"
-
end
-
-
end
-
-
-
##
-
## use StringIO class for buffering
-
##
-
## this is only for Eruby.
-
##
-
1
module StringIOEnhancer # :nodoc:
-
-
1
def self.desc # :nodoc:
-
"use a StringIO object for buffering"
-
end
-
-
1
def add_preamble(src)
-
src << "#{@bufvar} = StringIO.new;"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.string\n"
-
end
-
-
end
-
-
-
##
-
## set buffer variable name to '_erbout' as well as '_buf'
-
##
-
## this is only for Eruby.
-
##
-
1
module ErboutEnhancer
-
-
1
def self.desc # :nodoc:
-
"set '_erbout = _buf = \"\";' to be compatible with ERB."
-
end
-
-
1
def add_preamble(src)
-
src << "_erbout = #{@bufvar} = '';"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.to_s\n"
-
end
-
-
end
-
-
-
##
-
## remove text and leave code, especially useful when debugging.
-
##
-
## ex.
-
## $ erubis -s -E NoText file.eruby | more
-
##
-
## this is language independent.
-
##
-
1
module NoTextEnhancer
-
-
1
def self.desc # :nodoc:
-
"remove text and leave code (useful when debugging)"
-
end
-
-
1
def add_text(src, text)
-
src << ("\n" * text.count("\n"))
-
if text[-1] != ?\n
-
text =~ /^(.*?)\z/
-
src << (' ' * $1.length)
-
end
-
end
-
-
end
-
-
-
##
-
## remove code and leave text, especially useful when validating HTML tags.
-
##
-
## ex.
-
## $ erubis -s -E NoCode file.eruby | tidy -errors
-
##
-
## this is language independent.
-
##
-
1
module NoCodeEnhancer
-
-
1
def self.desc # :nodoc:
-
"remove code and leave text (useful when validating HTML)"
-
end
-
-
1
def add_preamble(src)
-
end
-
-
1
def add_postamble(src)
-
end
-
-
1
def add_text(src, text)
-
src << text
-
end
-
-
1
def add_expr(src, code, indicator)
-
src << "\n" * code.count("\n")
-
end
-
-
1
def add_stmt(src, code)
-
src << "\n" * code.count("\n")
-
end
-
-
end
-
-
-
##
-
## get convert faster, but spaces around '<%...%>' are not trimmed.
-
##
-
## this is language-independent.
-
##
-
1
module SimplifyEnhancer
-
-
1
def self.desc # :nodoc:
-
"get convert faster but leave spaces around '<% %>'"
-
end
-
-
#DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
1
SIMPLE_REGEXP = /<%(=+|\#)?(.*?)-?%>/m
-
-
1
def convert(input)
-
src = ""
-
add_preamble(src)
-
#regexp = pattern_regexp(@pattern)
-
pos = 0
-
input.scan(SIMPLE_REGEXP) do |indicator, code|
-
match = Regexp.last_match
-
index = match.begin(0)
-
text = input[pos, index - pos]
-
pos = match.end(0)
-
add_text(src, text)
-
if !indicator # <% %>
-
add_stmt(src, code)
-
elsif indicator[0] == ?\# # <%# %>
-
n = code.count("\n")
-
add_stmt(src, "\n" * n)
-
else # <%= %>
-
add_expr(src, code, indicator)
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
add_text(src, rest)
-
add_postamble(src)
-
return src
-
end
-
-
end
-
-
-
##
-
## enable to use other embedded expression pattern (default is '\[= =\]').
-
##
-
## notice! this is an experimental. spec may change in the future.
-
##
-
## ex.
-
## input = <<END
-
## <% for item in list %>
-
## <%= item %> : <%== item %>
-
## [= item =] : [== item =]
-
## <% end %>
-
## END
-
##
-
## class BiPatternEruby
-
## include BiPatternEnhancer
-
## end
-
## eruby = BiPatternEruby.new(input, :bipattern=>'\[= =\]')
-
## list = ['<a>', 'b&b', '"c"']
-
## print eruby.result(binding())
-
##
-
## ## output
-
## <a> : <a>
-
## <a> : <a>
-
## b&b : b&b
-
## b&b : b&b
-
## "c" : "c"
-
## "c" : "c"
-
##
-
## this is language independent.
-
##
-
1
module BiPatternEnhancer
-
-
1
def self.desc # :nodoc:
-
"another embedded expression pattern (default '\[= =\]')."
-
end
-
-
1
def initialize(input, properties={})
-
self.bipattern = properties[:bipattern] # or '\$\{ \}'
-
super
-
end
-
-
## when pat is nil then '\[= =\]' is used
-
1
def bipattern=(pat) # :nodoc:
-
@bipattern = pat || '\[= =\]'
-
pre, post = @bipattern.split()
-
@bipattern_regexp = /(.*?)#{pre}(=*)(.*?)#{post}/m
-
end
-
-
1
def add_text(src, text)
-
return unless text
-
m = nil
-
text.scan(@bipattern_regexp) do |txt, indicator, code|
-
m = Regexp.last_match
-
super(src, txt)
-
add_expr(src, code, '=' + indicator)
-
end
-
#rest = $' || text # ruby1.8
-
rest = m ? text[m.end(0)..-1] : text # ruby1.9
-
super(src, rest)
-
end
-
-
end
-
-
-
##
-
## regards lines starting with '^[ \t]*%' as program code
-
##
-
## in addition you can specify prefix character (default '%')
-
##
-
## this is language-independent.
-
##
-
1
module PrefixedLineEnhancer
-
-
1
def self.desc # :nodoc:
-
"regard lines matched to '^[ \t]*%' as program code"
-
end
-
-
1
def init_generator(properties={})
-
super
-
@prefixchar = properties[:prefixchar]
-
end
-
-
1
def add_text(src, text)
-
unless @prefixrexp
-
@prefixchar ||= '%'
-
@prefixrexp = Regexp.compile("^([ \\t]*)\\#{@prefixchar}(.*?\\r?\\n)")
-
end
-
pos = 0
-
text2 = ''
-
text.scan(@prefixrexp) do
-
space = $1
-
line = $2
-
space, line = '', $1 unless $2
-
match = Regexp.last_match
-
len = match.begin(0) - pos
-
str = text[pos, len]
-
pos = match.end(0)
-
if text2.empty?
-
text2 = str
-
else
-
text2 << str
-
end
-
if line[0, 1] == @prefixchar
-
text2 << space << line
-
else
-
super(src, text2)
-
text2 = ''
-
add_stmt(src, space + line)
-
end
-
end
-
#rest = pos == 0 ? text : $' # ruby1.8
-
rest = pos == 0 ? text : text[pos..-1] # ruby1.9
-
unless text2.empty?
-
text2 << rest if rest
-
rest = text2
-
end
-
super(src, rest)
-
end
-
-
end
-
-
-
##
-
## regards lines starting with '%' as program code
-
##
-
## this is for compatibility to eruby and ERB.
-
##
-
## this is language-independent.
-
##
-
1
module PercentLineEnhancer
-
1
include PrefixedLineEnhancer
-
-
1
def self.desc # :nodoc:
-
"regard lines starting with '%' as program code"
-
end
-
-
#--
-
#def init_generator(properties={})
-
# super
-
# @prefixchar = '%'
-
# @prefixrexp = /^\%(.*?\r?\n)/
-
#end
-
#++
-
-
1
def add_text(src, text)
-
unless @prefixrexp
-
@prefixchar = '%'
-
@prefixrexp = /^\%(.*?\r?\n)/
-
end
-
super(src, text)
-
end
-
-
end
-
-
-
##
-
## [experimental] allow header and footer in eRuby script
-
##
-
## ex.
-
## ====================
-
## ## without header and footer
-
## $ cat ex1.eruby
-
## <% def list_items(list) %>
-
## <% for item in list %>
-
## <li><%= item %></li>
-
## <% end %>
-
## <% end %>
-
##
-
## $ erubis -s ex1.eruby
-
## _buf = []; def list_items(list)
-
## ; for item in list
-
## ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
-
## '; end
-
## ; end
-
## ;
-
## _buf.join
-
##
-
## ## with header and footer
-
## $ cat ex2.eruby
-
## <!--#header:
-
## def list_items(list)
-
## #-->
-
## <% for item in list %>
-
## <li><%= item %></li>
-
## <% end %>
-
## <!--#footer:
-
## end
-
## #-->
-
##
-
## $ erubis -s -c HeaderFooterEruby ex4.eruby
-
##
-
## def list_items(list)
-
## _buf = []; _buf << '
-
## '; for item in list
-
## ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
-
## '; end
-
## ; _buf << '
-
## ';
-
## _buf.join
-
## end
-
##
-
## ====================
-
##
-
## this is language-independent.
-
##
-
1
module HeaderFooterEnhancer
-
-
1
def self.desc # :nodoc:
-
"allow header/footer in document (ex. '<!--#header: #-->')"
-
end
-
-
1
HEADER_FOOTER_PATTERN = /(.*?)(^[ \t]*)?<!--\#(\w+):(.*?)\#-->([ \t]*\r?\n)?/m
-
-
1
def add_text(src, text)
-
m = nil
-
text.scan(HEADER_FOOTER_PATTERN) do |txt, lspace, word, content, rspace|
-
m = Regexp.last_match
-
flag_trim = @trim && lspace && rspace
-
super(src, txt)
-
content = "#{lspace}#{content}#{rspace}" if flag_trim
-
super(src, lspace) if !flag_trim && lspace
-
instance_variable_set("@#{word}", content)
-
super(src, rspace) if !flag_trim && rspace
-
end
-
#rest = $' || text # ruby1.8
-
rest = m ? text[m.end(0)..-1] : text # ruby1.9
-
super(src, rest)
-
end
-
-
1
attr_accessor :header, :footer
-
-
1
def convert(input)
-
source = super
-
return @src = "#{@header}#{source}#{@footer}"
-
end
-
-
end
-
-
-
##
-
## delete indentation of HTML.
-
##
-
## this is language-independent.
-
##
-
1
module DeleteIndentEnhancer
-
-
1
def self.desc # :nodoc:
-
"delete indentation of HTML."
-
end
-
-
1
def convert_input(src, input)
-
input = input.gsub(/^[ \t]+</, '<')
-
super(src, input)
-
end
-
-
end
-
-
-
##
-
## convert "<h1><%=title%></h1>" into "_buf << %Q`<h1>#{title}</h1>`"
-
##
-
## this is only for Eruby.
-
##
-
1
module InterpolationEnhancer
-
-
1
def self.desc # :nodoc:
-
"convert '<p><%=text%></p>' into '_buf << %Q`<p>\#{text}</p>`'"
-
end
-
-
1
def convert_input(src, input)
-
pat = @pattern
-
regexp = pat.nil? || pat == '<% %>' ? Basic::Converter::DEFAULT_REGEXP : pattern_regexp(pat)
-
pos = 0
-
is_bol = true # is beginning of line
-
str = ''
-
input.scan(regexp) do |indicator, code, tailch, rspace|
-
match = Regexp.last_match()
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
ch = indicator ? indicator[0] : nil
-
lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
-
is_bol = rspace ? true : false
-
_add_text_to_str(str, text)
-
## * when '<%= %>', do nothing
-
## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
-
if ch == ?= # <%= %>
-
rspace = nil if tailch && !tailch.empty?
-
str << lspace if lspace
-
add_expr(str, code, indicator)
-
str << rspace if rspace
-
elsif ch == ?\# # <%# %>
-
n = code.count("\n") + (rspace ? 1 : 0)
-
if @trim && lspace && rspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "\n" * n)
-
else
-
str << lspace if lspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "\n" * n)
-
str << rspace if rspace
-
end
-
else # <% %>
-
if @trim && lspace && rspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "#{lspace}#{code}#{rspace}")
-
else
-
str << lspace if lspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, code)
-
str << rspace if rspace
-
end
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
_add_text_to_str(str, rest)
-
add_text(src, str)
-
end
-
-
1
def add_text(src, text)
-
return if !text || text.empty?
-
#src << " _buf << %Q`" << text << "`;"
-
if text[-1] == ?\n
-
text[-1] = "\\n"
-
src << " #{@bufvar} << %Q`#{text}`\n"
-
else
-
src << " #{@bufvar} << %Q`#{text}`;"
-
end
-
end
-
-
1
def _add_text_to_str(str, text)
-
return if !text || text.empty?
-
str << text.gsub(/[`\#\\]/, '\\\\\&')
-
end
-
-
1
def add_expr_escaped(str, code)
-
str << "\#{#{escaped_expr(code)}}"
-
end
-
-
1
def add_expr_literal(str, code)
-
str << "\#{#{code}}"
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
module Erubis
-
-
-
##
-
## base error class
-
##
-
1
class ErubisError < StandardError
-
end
-
-
-
##
-
## raised when method or function is not supported
-
##
-
1
class NotSupportedError < ErubisError
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
require 'erubis/error'
-
1
require 'erubis/context'
-
-
-
1
module Erubis
-
-
1
EMPTY_BINDING = binding()
-
-
-
##
-
## evaluate code
-
##
-
1
module Evaluator
-
-
1
def self.supported_properties # :nodoc:
-
return []
-
end
-
-
1
attr_accessor :src, :filename
-
-
1
def init_evaluator(properties)
-
@filename = properties[:filename]
-
end
-
-
1
def result(*args)
-
raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
-
end
-
-
1
def evaluate(*args)
-
raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
-
end
-
-
end
-
-
-
##
-
## evaluator for Ruby
-
##
-
1
module RubyEvaluator
-
1
include Evaluator
-
-
1
def self.supported_properties # :nodoc:
-
list = Evaluator.supported_properties
-
return list
-
end
-
-
## eval(@src) with binding object
-
1
def result(_binding_or_hash=TOPLEVEL_BINDING)
-
_arg = _binding_or_hash
-
if _arg.is_a?(Hash)
-
_b = binding()
-
eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _b
-
elsif _arg.is_a?(Binding)
-
_b = _arg
-
elsif _arg.nil?
-
_b = binding()
-
else
-
raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.")
-
end
-
return eval(@src, _b, (@filename || '(erubis'))
-
end
-
-
## invoke context.instance_eval(@src)
-
1
def evaluate(_context=Context.new)
-
_context = Context.new(_context) if _context.is_a?(Hash)
-
#return _context.instance_eval(@src, @filename || '(erubis)')
-
#@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)')
-
@_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)')
-
return _context.instance_eval(&@_proc)
-
end
-
-
## if object is an Class or Module then define instance method to it,
-
## else define singleton method to it.
-
1
def def_method(object, method_name, filename=nil)
-
m = object.is_a?(Module) ? :module_eval : :instance_eval
-
object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)')
-
end
-
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
require 'erubis/util'
-
-
1
module Erubis
-
-
-
##
-
## code generator, called by Converter module
-
##
-
1
module Generator
-
-
1
def self.supported_properties() # :nodoc:
-
return [
-
[:escapefunc, nil, "escape function name"],
-
]
-
end
-
-
1
attr_accessor :escapefunc
-
-
1
def init_generator(properties={})
-
@escapefunc = properties[:escapefunc]
-
end
-
-
-
## (abstract) escape text string
-
##
-
## ex.
-
## def escape_text(text)
-
## return text.dump
-
## # or return "'" + text.gsub(/['\\]/, '\\\\\&') + "'"
-
## end
-
1
def escape_text(text)
-
not_implemented
-
end
-
-
## return escaped expression code (ex. 'h(...)' or 'htmlspecialchars(...)')
-
1
def escaped_expr(code)
-
code.strip!
-
return "#{@escapefunc}(#{code})"
-
end
-
-
## (abstract) add @preamble to src
-
1
def add_preamble(src)
-
not_implemented
-
end
-
-
## (abstract) add text string to src
-
1
def add_text(src, text)
-
not_implemented
-
end
-
-
## (abstract) add statement code to src
-
1
def add_stmt(src, code)
-
not_implemented
-
end
-
-
## (abstract) add expression literal code to src. this is called by add_expr().
-
1
def add_expr_literal(src, code)
-
not_implemented
-
end
-
-
## (abstract) add escaped expression code to src. this is called by add_expr().
-
1
def add_expr_escaped(src, code)
-
not_implemented
-
end
-
-
## (abstract) add expression code to src for debug. this is called by add_expr().
-
1
def add_expr_debug(src, code)
-
not_implemented
-
end
-
-
## (abstract) add @postamble to src
-
1
def add_postamble(src)
-
not_implemented
-
end
-
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
1
module Erubis
-
-
##
-
## helper for xml
-
##
-
1
module XmlHelper
-
-
1
module_function
-
-
1
ESCAPE_TABLE = {
-
'&' => '&',
-
'<' => '<',
-
'>' => '>',
-
'"' => '"',
-
"'" => ''',
-
}
-
-
1
def escape_xml(value)
-
value.to_s.gsub(/[&<>"]/) { |s| ESCAPE_TABLE[s] } # or /[&<>"']/
-
#value.to_s.gsub(/[&<>"]/) { ESCAPE_TABLE[$&] }
-
end
-
-
1
def escape_xml2(value)
-
return value.to_s.gsub(/\&/,'&').gsub(/</,'<').gsub(/>/,'>').gsub(/"/,'"')
-
end
-
-
1
alias h escape_xml
-
1
alias html_escape escape_xml
-
-
1
def url_encode(str)
-
return str.gsub(/[^-_.a-zA-Z0-9]+/) { |s|
-
s.unpack('C*').collect { |i| "%%%02X" % i }.join
-
}
-
end
-
-
1
alias u url_encode
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
##
-
## you can add site-local settings here.
-
## this files is required by erubis.rb
-
##
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
module Erubis
-
-
##
-
## tiny and the simplest implementation of eRuby
-
##
-
## ex.
-
## eruby = TinyEruby.new(File.read('example.rhtml'))
-
## print eruby.src # print ruby code
-
## print eruby.result(binding()) # eval ruby code with Binding object
-
## print eruby.evalute(context) # eval ruby code with context object
-
##
-
1
class TinyEruby
-
-
1
def initialize(input=nil)
-
@src = convert(input) if input
-
end
-
1
attr_reader :src
-
-
1
EMBEDDED_PATTERN = /<%(=+|\#)?(.*?)-?%>/m
-
-
1
def convert(input)
-
src = "_buf = '';" # preamble
-
pos = 0
-
input.scan(EMBEDDED_PATTERN) do |indicator, code|
-
m = Regexp.last_match
-
text = input[pos...m.begin(0)]
-
pos = m.end(0)
-
#src << " _buf << '" << escape_text(text) << "';"
-
text.gsub!(/['\\]/, '\\\\\&')
-
src << " _buf << '" << text << "';" unless text.empty?
-
if !indicator # <% %>
-
src << code << ";"
-
elsif indicator == '#' # <%# %>
-
src << ("\n" * code.count("\n"))
-
else # <%= %>
-
src << " _buf << (" << code << ").to_s;"
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
#src << " _buf << '" << escape_text(rest) << "';"
-
rest.gsub!(/['\\]/, '\\\\\&')
-
src << " _buf << '" << rest << "';" unless rest.empty?
-
src << "\n_buf.to_s\n" # postamble
-
return src
-
end
-
-
#def escape_text(text)
-
# return text.gsub!(/['\\]/, '\\\\\&') || text
-
#end
-
-
1
def result(_binding=TOPLEVEL_BINDING)
-
eval @src, _binding
-
end
-
-
1
def evaluate(_context=Object.new)
-
if _context.is_a?(Hash)
-
_obj = Object.new
-
_context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end
-
_context = _obj
-
end
-
_context.instance_eval @src
-
end
-
-
end
-
-
-
-
1
module PI
-
end
-
-
1
class PI::TinyEruby
-
-
1
def initialize(input=nil, options={})
-
@escape = options[:escape] || 'Erubis::XmlHelper.escape_xml'
-
@src = convert(input) if input
-
end
-
-
1
attr_reader :src
-
-
1
EMBEDDED_PATTERN = /(^[ \t]*)?<\?rb(\s.*?)\?>([ \t]*\r?\n)?|@(!+)?\{(.*?)\}@/m
-
-
1
def convert(input)
-
src = "_buf = '';" # preamble
-
pos = 0
-
input.scan(EMBEDDED_PATTERN) do |lspace, stmt, rspace, indicator, expr|
-
match = Regexp.last_match
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
#src << " _buf << '" << escape_text(text) << "';"
-
text.gsub!(/['\\]/, '\\\\\&')
-
src << " _buf << '" << text << "';" unless text.empty?
-
if stmt # <?rb ... ?>
-
if lspace && rspace
-
src << "#{lspace}#{stmt}#{rspace}"
-
else
-
src << " _buf << '" << lspace << "';" if lspace
-
src << stmt << ";"
-
src << " _buf << '" << rspace << "';" if rspace
-
end
-
else # ${...}, $!{...}
-
if !indicator
-
src << " _buf << " << @escape << "(" << expr << ");"
-
elsif indicator == '!'
-
src << " _buf << (" << expr << ").to_s;"
-
end
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
#src << " _buf << '" << escape_text(rest) << "';"
-
rest.gsub!(/['\\]/, '\\\\\&')
-
src << " _buf << '" << rest << "';" unless rest.empty?
-
src << "\n_buf.to_s\n" # postamble
-
return src
-
end
-
-
#def escape_text(text)
-
# return text.gsub!(/['\\]/, '\\\\\&') || text
-
#end
-
-
1
def result(_binding=TOPLEVEL_BINDING)
-
eval @src, _binding
-
end
-
-
1
def evaluate(_context=Object.new)
-
if _context.is_a?(Hash)
-
_obj = Object.new
-
_context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end
-
_context = _obj
-
end
-
_context.instance_eval @src
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
module Kernel
-
-
##
-
## raise NotImplementedError
-
##
-
1
def not_implemented #:doc:
-
backtrace = caller()
-
method_name = (backtrace.shift =~ /`(\w+)'$/) && $1
-
mesg = "class #{self.class.name} must implement abstract method '#{method_name}()'."
-
#mesg = "#{self.class.name}##{method_name}() is not implemented."
-
err = NotImplementedError.new mesg
-
err.set_backtrace backtrace
-
raise err
-
end
-
1
private :not_implemented
-
-
end
-
1
require "execjs/module"
-
1
require "execjs/runtimes"
-
-
1
module ExecJS
-
1
self.runtime ||= Runtimes.autodetect
-
end
-
1
require "execjs/runtime"
-
-
1
module ExecJS
-
1
class DisabledRuntime < Runtime
-
1
def name
-
"Disabled"
-
end
-
-
1
def exec(source, options = {})
-
raise Error, "ExecJS disabled"
-
end
-
-
1
def eval(source, options = {})
-
raise Error, "ExecJS disabled"
-
end
-
-
1
def compile(source, options = {})
-
raise Error, "ExecJS disabled"
-
end
-
-
1
def deprecated?
-
true
-
end
-
-
1
def available?
-
true
-
end
-
end
-
end
-
1
require "execjs/runtime"
-
1
require "json"
-
-
1
module ExecJS
-
1
class DuktapeRuntime < Runtime
-
1
class Context < Runtime::Context
-
1
def initialize(runtime, source = "", options = {})
-
@ctx = Duktape::Context.new(complex_object: nil)
-
@ctx.exec_string(encode(source), '(execjs)')
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
1
def exec(source, options = {})
-
return unless /\S/ =~ source
-
@ctx.eval_string("(function(){#{encode(source)}})()", '(execjs)')
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
1
def eval(source, options = {})
-
return unless /\S/ =~ source
-
@ctx.eval_string("(#{encode(source)})", '(execjs)')
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
1
def call(identifier, *args)
-
@ctx.call_prop(identifier.split("."), *args)
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
1
private
-
1
def wrap_error(e)
-
klass = case e
-
when Duktape::SyntaxError
-
RuntimeError
-
when Duktape::Error
-
ProgramError
-
when Duktape::InternalError
-
RuntimeError
-
end
-
-
if klass
-
re = / \(line (\d+)\)$/
-
lineno = e.message[re, 1] || 1
-
error = klass.new(e.message.sub(re, ""))
-
error.set_backtrace(["(execjs):#{lineno}"] + e.backtrace)
-
error
-
else
-
e
-
end
-
end
-
end
-
-
1
def name
-
"Duktape"
-
end
-
-
1
def available?
-
1
require "duktape"
-
true
-
rescue LoadError
-
1
false
-
end
-
end
-
end
-
1
module ExecJS
-
# Encodes strings as UTF-8
-
1
module Encoding
-
1
if RUBY_ENGINE == 'jruby' || RUBY_ENGINE == 'rbx'
-
# workaround for jruby bug http://jira.codehaus.org/browse/JRUBY-6588
-
# workaround for rbx bug https://github.com/rubinius/rubinius/issues/1729
-
def encode(string)
-
if string.encoding.name == 'ASCII-8BIT'
-
data = string.dup
-
data.force_encoding('UTF-8')
-
-
unless data.valid_encoding?
-
raise ::Encoding::UndefinedConversionError, "Could not encode ASCII-8BIT data #{string.dump} as UTF-8"
-
end
-
else
-
data = string.encode('UTF-8')
-
end
-
data
-
end
-
else
-
1
def encode(string)
-
string.encode('UTF-8')
-
end
-
end
-
end
-
end
-
1
require "tmpdir"
-
1
require "execjs/runtime"
-
-
1
module ExecJS
-
1
class ExternalRuntime < Runtime
-
1
class Context < Runtime::Context
-
1
def initialize(runtime, source = "", options = {})
-
source = encode(source)
-
-
@runtime = runtime
-
@source = source
-
-
# Test compile context source
-
exec("")
-
end
-
-
1
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
exec("return eval(#{::JSON.generate("(#{source})", quirks_mode: true)})")
-
end
-
end
-
-
1
def exec(source, options = {})
-
source = encode(source)
-
source = "#{@source}\n#{source}" if @source != ""
-
source = @runtime.compile_source(source)
-
-
tmpfile = write_to_tempfile(source)
-
-
if ExecJS.cygwin?
-
filepath = `cygpath -m #{tmpfile.path}`.rstrip
-
else
-
filepath = tmpfile.path
-
end
-
-
begin
-
extract_result(@runtime.exec_runtime(filepath), filepath)
-
ensure
-
File.unlink(tmpfile)
-
end
-
end
-
-
1
def call(identifier, *args)
-
eval "#{identifier}.apply(this, #{::JSON.generate(args)})"
-
end
-
-
1
protected
-
# See Tempfile.create on Ruby 2.1
-
1
def create_tempfile(basename)
-
tmpfile = nil
-
Dir::Tmpname.create(basename) do |tmpname|
-
mode = File::WRONLY | File::CREAT | File::EXCL
-
tmpfile = File.open(tmpname, mode, 0600)
-
end
-
tmpfile
-
end
-
-
1
def write_to_tempfile(contents)
-
tmpfile = create_tempfile(['execjs', 'js'])
-
tmpfile.write(contents)
-
tmpfile.close
-
tmpfile
-
end
-
-
1
def extract_result(output, filename)
-
status, value, stack = output.empty? ? [] : ::JSON.parse(output, create_additions: false)
-
if status == "ok"
-
value
-
else
-
stack ||= ""
-
real_filename = File.realpath(filename)
-
stack = stack.split("\n").map do |line|
-
line.sub(" at ", "")
-
.sub(real_filename, "(execjs)")
-
.sub(filename, "(execjs)")
-
.strip
-
end
-
stack.reject! { |line| ["eval code", "eval@[native code]"].include?(line) }
-
stack.shift unless stack[0].to_s.include?("(execjs)")
-
error_class = value =~ /SyntaxError:/ ? RuntimeError : ProgramError
-
error = error_class.new(value)
-
error.set_backtrace(stack + caller)
-
raise error
-
end
-
end
-
end
-
-
1
attr_reader :name
-
-
1
def initialize(options)
-
5
@name = options[:name]
-
5
@command = options[:command]
-
5
@runner_path = options[:runner_path]
-
5
@encoding = options[:encoding]
-
5
@deprecated = !!options[:deprecated]
-
5
@binary = nil
-
-
5
@popen_options = {}
-
5
@popen_options[:external_encoding] = @encoding if @encoding
-
5
@popen_options[:internal_encoding] = ::Encoding.default_internal || 'UTF-8'
-
-
5
if @runner_path
-
5
instance_eval generate_compile_method(@runner_path)
-
end
-
end
-
-
1
def available?
-
2
require 'json'
-
2
binary ? true : false
-
end
-
-
1
def deprecated?
-
5
@deprecated
-
end
-
-
1
private
-
1
def binary
-
2
@binary ||= which(@command)
-
end
-
-
1
def locate_executable(command)
-
2
commands = Array(command)
-
2
if ExecJS.windows? && File.extname(command) == ""
-
ENV['PATHEXT'].split(File::PATH_SEPARATOR).each { |p|
-
commands << (command + p)
-
}
-
end
-
-
2
commands.find { |cmd|
-
2
if File.executable? cmd
-
cmd
-
else
-
2
path = ENV['PATH'].split(File::PATH_SEPARATOR).find { |p|
-
25
full_path = File.join(p, cmd)
-
25
File.executable?(full_path) && File.file?(full_path)
-
}
-
2
path && File.expand_path(cmd, path)
-
end
-
}
-
end
-
-
1
protected
-
1
def generate_compile_method(path)
-
<<-RUBY
-
def compile_source(source)
-
<<-RUNNER
-
5
#{IO.read(path)}
-
RUNNER
-
end
-
RUBY
-
end
-
-
1
def json2_source
-
@json2_source ||= IO.read(ExecJS.root + "/support/json2.js")
-
end
-
-
1
def encode_source(source)
-
encoded_source = encode_unicode_codepoints(source)
-
::JSON.generate("(function(){ #{encoded_source} })()", quirks_mode: true)
-
end
-
-
1
def encode_unicode_codepoints(str)
-
str.gsub(/[\u0080-\uffff]/) do |ch|
-
"\\u%04x" % ch.codepoints.to_a
-
end
-
end
-
-
1
if ExecJS.windows?
-
def exec_runtime(filename)
-
path = Dir::Tmpname.create(['execjs', 'json']) {}
-
begin
-
command = binary.split(" ") << filename
-
`#{shell_escape(*command)} 2>&1 > #{path}`
-
output = File.open(path, 'rb', @popen_options) { |f| f.read }
-
ensure
-
File.unlink(path) if path
-
end
-
-
if $?.success?
-
output
-
else
-
raise exec_runtime_error(output)
-
end
-
end
-
-
def shell_escape(*args)
-
# see http://technet.microsoft.com/en-us/library/cc723564.aspx#XSLTsection123121120120
-
args.map { |arg|
-
arg = %Q("#{arg.gsub('"','""')}") if arg.match(/[&|()<>^ "]/)
-
arg
-
}.join(" ")
-
end
-
elsif RUBY_ENGINE == 'jruby'
-
require 'shellwords'
-
-
def exec_runtime(filename)
-
command = "#{Shellwords.join(binary.split(' ') << filename)} 2>&1"
-
io = IO.popen(command, @popen_options)
-
output = io.read
-
io.close
-
-
if $?.success?
-
output
-
else
-
raise exec_runtime_error(output)
-
end
-
end
-
else
-
1
def exec_runtime(filename)
-
io = IO.popen(binary.split(' ') << filename, @popen_options.merge({err: [:child, :out]}))
-
output = io.read
-
io.close
-
-
if $?.success?
-
output
-
else
-
raise exec_runtime_error(output)
-
end
-
end
-
end
-
# Internally exposed for Context.
-
1
public :exec_runtime
-
-
1
def exec_runtime_error(output)
-
error = RuntimeError.new(output)
-
lines = output.split("\n")
-
lineno = lines[0][/:(\d+)$/, 1] if lines[0]
-
lineno ||= 1
-
error.set_backtrace(["(execjs):#{lineno}"] + caller)
-
error
-
end
-
-
1
def which(command)
-
1
Array(command).find do |name|
-
2
name, args = name.split(/\s+/, 2)
-
2
path = locate_executable(name)
-
-
2
next unless path
-
-
1
args ? "#{path} #{args}" : path
-
end
-
end
-
end
-
end
-
1
require "execjs/version"
-
1
require "rbconfig"
-
-
1
module ExecJS
-
1
class Error < ::StandardError; end
-
1
class RuntimeError < Error; end
-
1
class ProgramError < Error; end
-
1
class RuntimeUnavailable < RuntimeError; end
-
-
1
class << self
-
1
attr_reader :runtime
-
-
1
def runtime=(runtime)
-
1
raise RuntimeUnavailable, "#{runtime.name} is unavailable on this system" unless runtime.available?
-
1
@runtime = runtime
-
end
-
-
1
def exec(source, options = {})
-
runtime.exec(source, options)
-
end
-
-
1
def eval(source, options = {})
-
runtime.eval(source, options)
-
end
-
-
1
def compile(source, options = {})
-
runtime.compile(source, options)
-
end
-
-
1
def root
-
5
@root ||= File.expand_path("..", __FILE__)
-
end
-
-
1
def windows?
-
3
@windows ||= RbConfig::CONFIG["host_os"] =~ /mswin|mingw/
-
end
-
-
1
def cygwin?
-
@cygwin ||= RbConfig::CONFIG["host_os"] =~ /cygwin/
-
end
-
end
-
end
-
1
require "execjs/runtime"
-
-
1
module ExecJS
-
1
class RubyRacerRuntime < Runtime
-
1
class Context < Runtime::Context
-
1
def initialize(runtime, source = "", options = {})
-
source = encode(source)
-
-
lock do
-
@v8_context = ::V8::Context.new
-
-
begin
-
@v8_context.eval(source)
-
rescue ::V8::JSError => e
-
raise wrap_error(e)
-
end
-
end
-
end
-
-
1
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
1
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
lock do
-
begin
-
unbox @v8_context.eval("(#{source})")
-
rescue ::V8::JSError => e
-
raise wrap_error(e)
-
end
-
end
-
end
-
end
-
-
1
def call(properties, *args)
-
lock do
-
begin
-
unbox @v8_context.eval(properties).call(*args)
-
rescue ::V8::JSError => e
-
raise wrap_error(e)
-
end
-
end
-
end
-
-
1
def unbox(value)
-
case value
-
when ::V8::Function
-
nil
-
when ::V8::Array
-
value.map { |v| unbox(v) }
-
when ::V8::Object
-
value.inject({}) do |vs, (k, v)|
-
vs[k] = unbox(v) unless v.is_a?(::V8::Function)
-
vs
-
end
-
when String
-
value.force_encoding('UTF-8')
-
else
-
value
-
end
-
end
-
-
1
private
-
1
def lock
-
result, exception = nil, nil
-
V8::C::Locker() do
-
begin
-
result = yield
-
rescue Exception => e
-
exception = e
-
end
-
end
-
-
if exception
-
raise exception
-
else
-
result
-
end
-
end
-
-
1
def wrap_error(e)
-
error_class = e.value["name"] == "SyntaxError" ? RuntimeError : ProgramError
-
-
stack = e.value["stack"] || ""
-
stack = stack.split("\n")
-
stack.shift
-
stack = [e.message[/<eval>:\d+:\d+/, 0]].compact if stack.empty?
-
stack = stack.map { |line| line.sub(" at ", "").sub("<eval>", "(execjs)").strip }
-
-
error = error_class.new(e.value.to_s)
-
error.set_backtrace(stack + caller)
-
error
-
end
-
end
-
-
1
def name
-
"therubyracer (V8)"
-
end
-
-
1
def available?
-
1
require "v8"
-
true
-
rescue LoadError
-
1
false
-
end
-
end
-
end
-
1
require "execjs/runtime"
-
-
1
module ExecJS
-
1
class RubyRhinoRuntime < Runtime
-
1
class Context < Runtime::Context
-
1
def initialize(runtime, source = "", options = {})
-
source = encode(source)
-
-
@rhino_context = ::Rhino::Context.new
-
fix_memory_limit! @rhino_context
-
@rhino_context.eval(source)
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
1
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
1
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
unbox @rhino_context.eval("(#{source})")
-
end
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
1
def call(properties, *args)
-
unbox @rhino_context.eval(properties).call(*args)
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
1
def unbox(value)
-
case value = ::Rhino::to_ruby(value)
-
when Java::OrgMozillaJavascript::NativeFunction
-
nil
-
when Java::OrgMozillaJavascript::NativeObject
-
value.inject({}) do |vs, (k, v)|
-
case v
-
when Java::OrgMozillaJavascript::NativeFunction, ::Rhino::JS::Function
-
nil
-
else
-
vs[k] = unbox(v)
-
end
-
vs
-
end
-
when Array
-
value.map { |v| unbox(v) }
-
else
-
value
-
end
-
end
-
-
1
def wrap_error(e)
-
return e unless e.is_a?(::Rhino::JSError)
-
-
error_class = e.message == "syntax error" ? RuntimeError : ProgramError
-
-
stack = e.backtrace
-
stack = stack.map { |line| line.sub(" at ", "").sub("<eval>", "(execjs)").strip }
-
stack.unshift("(execjs):1") if e.javascript_backtrace.empty?
-
-
error = error_class.new(e.value.to_s)
-
error.set_backtrace(stack)
-
error
-
end
-
-
1
private
-
# Disables bytecode compiling which limits you to 64K scripts
-
1
def fix_memory_limit!(context)
-
if context.respond_to?(:optimization_level=)
-
context.optimization_level = -1
-
else
-
context.instance_eval { @native.setOptimizationLevel(-1) }
-
end
-
end
-
end
-
-
1
def name
-
"therubyrhino (Rhino)"
-
end
-
-
1
def available?
-
1
require "rhino"
-
true
-
rescue LoadError
-
1
false
-
end
-
end
-
end
-
1
require "execjs/encoding"
-
-
1
module ExecJS
-
# Abstract base class for runtimes
-
1
class Runtime
-
1
class Context
-
1
include Encoding
-
-
1
def initialize(runtime, source = "", options = {})
-
end
-
-
1
def exec(source, options = {})
-
raise NotImplementedError
-
end
-
-
1
def eval(source, options = {})
-
raise NotImplementedError
-
end
-
-
1
def call(properties, *args)
-
raise NotImplementedError
-
end
-
end
-
-
1
def name
-
raise NotImplementedError
-
end
-
-
1
def context_class
-
self.class::Context
-
end
-
-
1
def exec(source, options = {})
-
context = compile("", options)
-
-
if context.method(:exec).arity == 1
-
context.exec(source)
-
else
-
context.exec(source, options)
-
end
-
end
-
-
1
def eval(source, options = {})
-
context = compile("", options)
-
-
if context.method(:eval).arity == 1
-
context.eval(source)
-
else
-
context.eval(source, options)
-
end
-
end
-
-
1
def compile(source, options = {})
-
if context_class.instance_method(:initialize).arity == 2
-
context_class.new(self, source)
-
else
-
context_class.new(self, source, options)
-
end
-
end
-
-
1
def deprecated?
-
4
false
-
end
-
-
1
def available?
-
raise NotImplementedError
-
end
-
end
-
end
-
1
require "execjs/module"
-
1
require "execjs/disabled_runtime"
-
1
require "execjs/duktape_runtime"
-
1
require "execjs/external_runtime"
-
1
require "execjs/ruby_racer_runtime"
-
1
require "execjs/ruby_rhino_runtime"
-
1
require "execjs/mini_racer_runtime"
-
-
1
module ExecJS
-
1
module Runtimes
-
1
Disabled = DisabledRuntime.new
-
-
1
Duktape = DuktapeRuntime.new
-
-
1
RubyRacer = RubyRacerRuntime.new
-
-
1
RubyRhino = RubyRhinoRuntime.new
-
-
1
MiniRacer = MiniRacerRuntime.new
-
-
1
Node = ExternalRuntime.new(
-
name: "Node.js (V8)",
-
command: ["nodejs", "node"],
-
runner_path: ExecJS.root + "/support/node_runner.js",
-
encoding: 'UTF-8'
-
)
-
-
1
JavaScriptCore = ExternalRuntime.new(
-
name: "JavaScriptCore",
-
command: "/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc",
-
runner_path: ExecJS.root + "/support/jsc_runner.js"
-
)
-
-
1
SpiderMonkey = Spidermonkey = ExternalRuntime.new(
-
name: "SpiderMonkey",
-
command: "js",
-
runner_path: ExecJS.root + "/support/spidermonkey_runner.js",
-
deprecated: true
-
)
-
-
1
JScript = ExternalRuntime.new(
-
name: "JScript",
-
command: "cscript //E:jscript //Nologo //U",
-
runner_path: ExecJS.root + "/support/jscript_runner.js",
-
encoding: 'UTF-16LE' # CScript with //U returns UTF-16LE
-
)
-
-
1
V8 = ExternalRuntime.new(
-
name: "V8",
-
command: "d8",
-
runner_path: ExecJS.root + "/support/v8_runner.js",
-
encoding: 'UTF-8'
-
)
-
-
-
1
def self.autodetect
-
1
from_environment || best_available ||
-
raise(RuntimeUnavailable, "Could not find a JavaScript runtime. " +
-
"See https://github.com/rails/execjs for a list of available runtimes.")
-
end
-
-
1
def self.best_available
-
1
runtimes.reject(&:deprecated?).find(&:available?)
-
end
-
-
1
def self.from_environment
-
1
if name = ENV["EXECJS_RUNTIME"]
-
raise RuntimeUnavailable, "#{name} runtime is not defined" unless const_defined?(name)
-
runtime = const_get(name)
-
-
raise RuntimeUnavailable, "#{runtime.name} runtime is not available on this system" unless runtime.available?
-
runtime
-
end
-
end
-
-
1
def self.names
-
@names ||= constants.inject({}) { |h, name| h.merge(const_get(name) => name) }.values
-
end
-
-
1
def self.runtimes
-
@runtimes ||= [
-
RubyRacer,
-
RubyRhino,
-
Duktape,
-
MiniRacer,
-
Node,
-
JavaScriptCore,
-
SpiderMonkey,
-
JScript,
-
V8
-
1
]
-
end
-
end
-
-
1
def self.runtimes
-
Runtimes.runtimes
-
end
-
end
-
1
module ExecJS
-
1
VERSION = "2.7.0"
-
end
-
1
require 'set'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/deprecation'
-
1
require 'active_support/notifications'
-
-
1
require 'factory_girl/definition_hierarchy'
-
1
require 'factory_girl/configuration'
-
1
require 'factory_girl/errors'
-
1
require 'factory_girl/factory_runner'
-
1
require 'factory_girl/strategy_syntax_method_registrar'
-
1
require 'factory_girl/strategy_calculator'
-
1
require 'factory_girl/strategy/build'
-
1
require 'factory_girl/strategy/create'
-
1
require 'factory_girl/strategy/attributes_for'
-
1
require 'factory_girl/strategy/stub'
-
1
require 'factory_girl/strategy/null'
-
1
require 'factory_girl/registry'
-
1
require 'factory_girl/null_factory'
-
1
require 'factory_girl/null_object'
-
1
require 'factory_girl/evaluation'
-
1
require 'factory_girl/factory'
-
1
require 'factory_girl/attribute_assigner'
-
1
require 'factory_girl/evaluator'
-
1
require 'factory_girl/evaluator_class_definer'
-
1
require 'factory_girl/attribute'
-
1
require 'factory_girl/callback'
-
1
require 'factory_girl/callbacks_observer'
-
1
require 'factory_girl/declaration_list'
-
1
require 'factory_girl/declaration'
-
1
require 'factory_girl/sequence'
-
1
require 'factory_girl/attribute_list'
-
1
require 'factory_girl/trait'
-
1
require 'factory_girl/aliases'
-
1
require 'factory_girl/definition'
-
1
require 'factory_girl/definition_proxy'
-
1
require 'factory_girl/syntax'
-
1
require 'factory_girl/syntax_runner'
-
1
require 'factory_girl/find_definitions'
-
1
require 'factory_girl/reload'
-
1
require 'factory_girl/decorator'
-
1
require 'factory_girl/decorator/attribute_hash'
-
1
require 'factory_girl/decorator/class_key_hash'
-
1
require 'factory_girl/decorator/disallows_duplicates_registry'
-
1
require 'factory_girl/decorator/invocation_tracker'
-
1
require 'factory_girl/decorator/new_constructor'
-
1
require 'factory_girl/linter'
-
1
require 'factory_girl/version'
-
-
1
module FactoryGirl
-
1
def self.configuration
-
11
@configuration ||= Configuration.new
-
end
-
-
1
def self.reset_configuration
-
@configuration = nil
-
end
-
-
# Look for errors in factories and (optionally) their traits.
-
# Parameters:
-
# factories - which factories to lint; omit for all factories
-
# options:
-
# traits : true - to lint traits as well as factories
-
1
def self.lint(*args)
-
options = args.extract_options!
-
factories_to_lint = args[0] || FactoryGirl.factories
-
strategy = options[:traits] ? :factory_and_traits : :factory
-
Linter.new(factories_to_lint, strategy).lint!
-
end
-
-
1
class << self
-
1
delegate :factories,
-
:sequences,
-
:traits,
-
:callbacks,
-
:strategies,
-
:callback_names,
-
:to_create,
-
:skip_create,
-
:initialize_with,
-
:constructor,
-
:duplicate_attribute_assignment_from_initialize_with,
-
:duplicate_attribute_assignment_from_initialize_with=,
-
:allow_class_lookup,
-
:allow_class_lookup=,
-
:use_parent_strategy,
-
:use_parent_strategy=,
-
to: :configuration
-
end
-
-
1
def self.register_factory(factory)
-
2
factory.names.each do |name|
-
2
factories.register(name, factory)
-
end
-
2
factory
-
end
-
-
1
def self.factory_by_name(name)
-
factories.find(name)
-
end
-
-
1
def self.register_sequence(sequence)
-
sequence.names.each do |name|
-
sequences.register(name, sequence)
-
end
-
sequence
-
end
-
-
1
def self.sequence_by_name(name)
-
sequences.find(name)
-
end
-
-
1
def self.register_trait(trait)
-
trait.names.each do |name|
-
traits.register(name, trait)
-
end
-
trait
-
end
-
-
1
def self.trait_by_name(name)
-
traits.find(name)
-
end
-
-
1
def self.register_strategy(strategy_name, strategy_class)
-
5
strategies.register(strategy_name, strategy_class)
-
5
StrategySyntaxMethodRegistrar.new(strategy_name).define_strategy_methods
-
end
-
-
1
def self.strategy_by_name(name)
-
strategies.find(name)
-
end
-
-
1
def self.register_default_strategies
-
1
register_strategy(:build, FactoryGirl::Strategy::Build)
-
1
register_strategy(:create, FactoryGirl::Strategy::Create)
-
1
register_strategy(:attributes_for, FactoryGirl::Strategy::AttributesFor)
-
1
register_strategy(:build_stubbed, FactoryGirl::Strategy::Stub)
-
1
register_strategy(:null, FactoryGirl::Strategy::Null)
-
end
-
-
1
def self.register_default_callbacks
-
1
register_callback(:after_build)
-
1
register_callback(:after_create)
-
1
register_callback(:after_stub)
-
1
register_callback(:before_create)
-
end
-
-
1
def self.register_callback(name)
-
4
name = name.to_sym
-
4
callback_names << name
-
end
-
end
-
-
1
FactoryGirl.register_default_strategies
-
1
FactoryGirl.register_default_callbacks
-
1
module FactoryGirl
-
1
class << self
-
1
attr_accessor :aliases
-
end
-
-
1
self.aliases = [
-
[/(.+)_id/, '\1'],
-
[/(.*)/, '\1_id']
-
]
-
-
1
def self.aliases_for(attribute)
-
aliases.map do |(pattern, replace)|
-
if pattern.match(attribute.to_s)
-
attribute.to_s.sub(pattern, replace).to_sym
-
end
-
end.compact << attribute
-
end
-
end
-
1
require 'factory_girl/attribute/static'
-
1
require 'factory_girl/attribute/dynamic'
-
1
require 'factory_girl/attribute/association'
-
1
require 'factory_girl/attribute/sequence'
-
-
1
module FactoryGirl
-
# @api private
-
1
class Attribute
-
1
attr_reader :name, :ignored
-
-
1
def initialize(name, ignored)
-
@name = name.to_sym
-
@ignored = ignored
-
ensure_non_attribute_writer!
-
end
-
-
1
def to_proc
-
-> { }
-
end
-
-
1
def association?
-
false
-
end
-
-
1
def alias_for?(attr)
-
FactoryGirl.aliases_for(attr).include?(name)
-
end
-
-
1
private
-
-
1
def ensure_non_attribute_writer!
-
NonAttributeWriterValidator.new(@name).validate!
-
end
-
-
1
class NonAttributeWriterValidator
-
1
def initialize(method_name)
-
@method_name = method_name.to_s
-
@method_name_setter_match = @method_name.match(/(.*)=$/)
-
end
-
-
1
def validate!
-
if method_is_writer?
-
raise AttributeDefinitionError, error_message
-
end
-
end
-
-
1
private
-
-
1
def method_is_writer?
-
!!@method_name_setter_match
-
end
-
-
1
def attribute_name
-
@method_name_setter_match[1]
-
end
-
-
1
def error_message
-
"factory_girl uses '#{attribute_name} value' syntax rather than '#{attribute_name} = value'"
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Attribute
-
# @api private
-
1
class Association < Attribute
-
1
attr_reader :factory
-
-
1
def initialize(name, factory, overrides)
-
super(name, false)
-
@factory = factory
-
@overrides = overrides
-
end
-
-
1
def to_proc
-
factory = @factory
-
overrides = @overrides
-
traits_and_overrides = [factory, overrides].flatten
-
factory_name = traits_and_overrides.shift
-
-
-> { association(factory_name, *traits_and_overrides) }
-
end
-
-
1
def association?
-
true
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Attribute
-
# @api private
-
1
class Dynamic < Attribute
-
1
def initialize(name, ignored, block)
-
super(name, ignored)
-
@block = block
-
end
-
-
1
def to_proc
-
block = @block
-
-
-> {
-
value = case block.arity
-
when 1, -1 then instance_exec(self, &block)
-
else instance_exec(&block)
-
end
-
raise SequenceAbuseError if FactoryGirl::Sequence === value
-
value
-
}
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Attribute
-
# @api private
-
1
class Sequence < Attribute
-
1
def initialize(name, sequence, ignored)
-
super(name, ignored)
-
@sequence = sequence
-
end
-
-
1
def to_proc
-
sequence = @sequence
-
-> { FactoryGirl.generate(sequence) }
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Attribute
-
# @api private
-
1
class Static < Attribute
-
1
def initialize(name, value, ignored)
-
super(name, ignored)
-
@value = value
-
end
-
-
1
def to_proc
-
value = @value
-
-> { value }
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class AttributeAssigner
-
1
def initialize(evaluator, build_class, &instance_builder)
-
@build_class = build_class
-
@instance_builder = instance_builder
-
@evaluator = evaluator
-
@attribute_list = evaluator.class.attribute_list
-
@attribute_names_assigned = []
-
end
-
-
1
def object
-
@evaluator.instance = build_class_instance
-
build_class_instance.tap do |instance|
-
attributes_to_set_on_instance.each do |attribute|
-
instance.public_send("#{attribute}=", get(attribute))
-
@attribute_names_assigned << attribute
-
end
-
end
-
end
-
-
1
def hash
-
@evaluator.instance = build_hash
-
-
attributes_to_set_on_hash.inject({}) do |result, attribute|
-
result[attribute] = get(attribute)
-
result
-
end
-
end
-
-
1
private
-
-
1
def method_tracking_evaluator
-
@method_tracking_evaluator ||= Decorator::AttributeHash.new(decorated_evaluator, attribute_names_to_assign)
-
end
-
-
1
def decorated_evaluator
-
Decorator::InvocationTracker.new(
-
Decorator::NewConstructor.new(@evaluator, @build_class)
-
)
-
end
-
-
1
def methods_invoked_on_evaluator
-
method_tracking_evaluator.__invoked_methods__
-
end
-
-
1
def build_class_instance
-
@build_class_instance ||= method_tracking_evaluator.instance_exec(&@instance_builder)
-
end
-
-
1
def build_hash
-
@build_hash ||= NullObject.new(hash_instance_methods_to_respond_to)
-
end
-
-
1
def get(attribute_name)
-
@evaluator.send(attribute_name)
-
end
-
-
1
def attributes_to_set_on_instance
-
(attribute_names_to_assign - @attribute_names_assigned - methods_invoked_on_evaluator).uniq
-
end
-
-
1
def attributes_to_set_on_hash
-
attribute_names_to_assign - association_names
-
end
-
-
1
def attribute_names_to_assign
-
@attribute_names_to_assign ||= non_ignored_attribute_names + override_names - ignored_attribute_names - alias_names_to_ignore
-
end
-
-
1
def non_ignored_attribute_names
-
@attribute_list.non_ignored.names
-
end
-
-
1
def ignored_attribute_names
-
@attribute_list.ignored.names
-
end
-
-
1
def association_names
-
@attribute_list.associations.names
-
end
-
-
1
def override_names
-
@evaluator.__override_names__
-
end
-
-
1
def hash_instance_methods_to_respond_to
-
@attribute_list.names + override_names + @build_class.instance_methods
-
end
-
-
1
def alias_names_to_ignore
-
@attribute_list.non_ignored.flat_map do |attribute|
-
override_names.map { |override| attribute.name if attribute.alias_for?(override) && attribute.name != override && !ignored_attribute_names.include?(override) }
-
end.compact
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class AttributeList
-
1
include Enumerable
-
-
1
def initialize(name = nil, attributes = [])
-
@name = name
-
@attributes = attributes
-
end
-
-
1
def define_attribute(attribute)
-
ensure_attribute_not_self_referencing! attribute
-
ensure_attribute_not_defined! attribute
-
-
add_attribute attribute
-
end
-
-
1
def each(&block)
-
@attributes.each(&block)
-
end
-
-
1
def names
-
map(&:name)
-
end
-
-
1
def associations
-
AttributeList.new(@name, select(&:association?))
-
end
-
-
1
def ignored
-
AttributeList.new(@name, select(&:ignored))
-
end
-
-
1
def non_ignored
-
AttributeList.new(@name, reject(&:ignored))
-
end
-
-
1
def apply_attributes(attributes_to_apply)
-
attributes_to_apply.each { |attribute| add_attribute(attribute) }
-
end
-
-
1
private
-
-
1
def add_attribute(attribute)
-
@attributes << attribute
-
attribute
-
end
-
-
1
def ensure_attribute_not_defined!(attribute)
-
if attribute_defined?(attribute.name)
-
raise AttributeDefinitionError, "Attribute already defined: #{attribute.name}"
-
end
-
end
-
-
1
def ensure_attribute_not_self_referencing!(attribute)
-
if attribute.respond_to?(:factory) && attribute.factory == @name
-
raise AssociationDefinitionError, "Self-referencing association '#{attribute.name}' in '#{attribute.factory}'"
-
end
-
end
-
-
1
def attribute_defined?(attribute_name)
-
@attributes.any? do |attribute|
-
attribute.name == attribute_name
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Callback
-
1
attr_reader :name
-
-
1
def initialize(name, block)
-
@name = name.to_sym
-
@block = block
-
ensure_valid_callback_name!
-
end
-
-
1
def run(instance, evaluator)
-
case block.arity
-
when 1, -1 then syntax_runner.instance_exec(instance, &block)
-
when 2 then syntax_runner.instance_exec(instance, evaluator, &block)
-
else syntax_runner.instance_exec(&block)
-
end
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
block == other.block
-
end
-
-
1
protected
-
1
attr_reader :block
-
-
1
private
-
-
1
def ensure_valid_callback_name!
-
unless FactoryGirl.callback_names.include?(name)
-
raise InvalidCallbackNameError, "#{name} is not a valid callback name. " +
-
"Valid callback names are #{FactoryGirl.callback_names.inspect}"
-
end
-
end
-
-
1
def syntax_runner
-
@syntax_runner ||= SyntaxRunner.new
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class CallbacksObserver
-
1
def initialize(callbacks, evaluator)
-
@callbacks = callbacks
-
@evaluator = evaluator
-
end
-
-
1
def update(name, result_instance)
-
callbacks_by_name(name).each do |callback|
-
callback.run(result_instance, @evaluator)
-
end
-
end
-
-
1
private
-
-
1
def callbacks_by_name(name)
-
@callbacks.select { |callback| callback.name == name }
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class Configuration
-
1
attr_reader :factories, :sequences, :traits, :strategies, :callback_names
-
-
1
attr_accessor :allow_class_lookup, :use_parent_strategy
-
-
1
def initialize
-
1
@factories = Decorator::DisallowsDuplicatesRegistry.new(Registry.new('Factory'))
-
1
@sequences = Decorator::DisallowsDuplicatesRegistry.new(Registry.new('Sequence'))
-
1
@traits = Decorator::DisallowsDuplicatesRegistry.new(Registry.new('Trait'))
-
1
@strategies = Registry.new('Strategy')
-
1
@callback_names = Set.new
-
1
@definition = Definition.new
-
-
1
@allow_class_lookup = true
-
-
1
to_create { |instance| instance.save! }
-
1
initialize_with { new }
-
end
-
-
1
delegate :to_create, :skip_create, :constructor, :before, :after,
-
:callback, :callbacks, to: :@definition
-
-
1
def initialize_with(&block)
-
1
@definition.define_constructor(&block)
-
end
-
-
1
def duplicate_attribute_assignment_from_initialize_with
-
false
-
end
-
-
1
def duplicate_attribute_assignment_from_initialize_with=(value)
-
ActiveSupport::Deprecation.warn 'Assignment of duplicate_attribute_assignment_from_initialize_with is unnecessary as this is now default behavior in FactoryGirl 4.0; this line can be removed', caller
-
end
-
end
-
end
-
1
require 'factory_girl/declaration/static'
-
1
require 'factory_girl/declaration/dynamic'
-
1
require 'factory_girl/declaration/association'
-
1
require 'factory_girl/declaration/implicit'
-
-
1
module FactoryGirl
-
# @api private
-
1
class Declaration
-
1
attr_reader :name
-
-
1
def initialize(name, ignored = false)
-
12
@name = name
-
12
@ignored = ignored
-
end
-
-
1
def to_attributes
-
build
-
end
-
-
1
protected
-
1
attr_reader :ignored
-
end
-
end
-
1
module FactoryGirl
-
1
class Declaration
-
# @api private
-
1
class Association < Declaration
-
1
def initialize(name, *options)
-
super(name, false)
-
@options = options.dup
-
@overrides = options.extract_options!
-
@traits = options
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
options == other.options
-
end
-
-
1
protected
-
1
attr_reader :options
-
-
1
private
-
-
1
def build
-
factory_name = @overrides[:factory] || name
-
[Attribute::Association.new(name, factory_name, [@traits, @overrides.except(:factory)].flatten)]
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Declaration
-
# @api private
-
1
class Dynamic < Declaration
-
1
def initialize(name, ignored = false, block = nil)
-
super(name, ignored)
-
@block = block
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
ignored == other.ignored &&
-
block == other.block
-
end
-
-
1
protected
-
1
attr_reader :block
-
-
1
private
-
-
1
def build
-
[Attribute::Dynamic.new(name, @ignored, @block)]
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Declaration
-
# @api private
-
1
class Implicit < Declaration
-
1
def initialize(name, factory = nil, ignored = false)
-
super(name, ignored)
-
@factory = factory
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
factory == other.factory &&
-
ignored == other.ignored
-
end
-
-
1
protected
-
1
attr_reader :factory
-
-
1
private
-
-
1
def build
-
if FactoryGirl.factories.registered?(name)
-
[Attribute::Association.new(name, name, {})]
-
elsif FactoryGirl.sequences.registered?(name)
-
[Attribute::Sequence.new(name, name, @ignored)]
-
else
-
@factory.inherit_traits([name])
-
[]
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Declaration
-
# @api private
-
1
class Static < Declaration
-
1
def initialize(name, value, ignored = false)
-
12
super(name, ignored)
-
12
@value = value
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
value == other.value &&
-
ignored == other.ignored
-
end
-
-
1
protected
-
1
attr_reader :value
-
-
1
private
-
-
1
def build
-
[Attribute::Static.new(name, @value, @ignored)]
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class DeclarationList
-
1
include Enumerable
-
-
1
def initialize(name = nil)
-
3
@declarations = []
-
3
@name = name
-
3
@overridable = false
-
end
-
-
1
def declare_attribute(declaration)
-
12
delete_declaration(declaration) if overridable?
-
-
12
@declarations << declaration
-
12
declaration
-
end
-
-
1
def overridable
-
@overridable = true
-
end
-
-
1
def attributes
-
@attributes ||= AttributeList.new(@name).tap do |list|
-
to_attributes.each do |attribute|
-
list.define_attribute(attribute)
-
end
-
end
-
end
-
-
1
def each(&block)
-
@declarations.each(&block)
-
end
-
-
1
private
-
-
1
def delete_declaration(declaration)
-
@declarations.delete_if { |decl| decl.name == declaration.name }
-
end
-
-
1
def to_attributes
-
@declarations.inject([]) { |result, declaration| result += declaration.to_attributes }
-
end
-
-
1
def overridable?
-
12
@overridable
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator < BasicObject
-
1
undef_method :==
-
-
1
def initialize(component)
-
7
@component = component
-
end
-
-
1
def method_missing(name, *args, &block)
-
2
@component.send(name, *args, &block)
-
end
-
-
1
def send(symbol, *args, &block)
-
__send__(symbol, *args, &block)
-
end
-
-
1
def self.const_missing(name)
-
::Object.const_get(name)
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator
-
1
class AttributeHash < Decorator
-
1
def initialize(component, attributes = [])
-
super(component)
-
@attributes = attributes
-
end
-
-
1
def attributes
-
@attributes.each_with_object({}) do |attribute_name, result|
-
result[attribute_name] = send(attribute_name)
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator
-
1
class ClassKeyHash < Decorator
-
1
def [](key)
-
@component[symbolized_key key]
-
end
-
-
1
def []=(key, value)
-
7
@component[symbolized_key key] = value
-
end
-
-
1
def key?(key)
-
2
@component.key? symbolized_key(key)
-
end
-
-
1
private
-
-
1
def symbolized_key(key)
-
9
if key.respond_to?(:to_sym)
-
9
key.to_sym
-
elsif FactoryGirl.allow_class_lookup
-
ActiveSupport::Deprecation.warn "Looking up factories by class is deprecated and will be removed in 5.0. Use symbols instead and set FactoryGirl.allow_class_lookup = false", caller
-
key.to_s.underscore.to_sym
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator
-
1
class DisallowsDuplicatesRegistry < Decorator
-
1
def register(name, item)
-
2
if registered?(name)
-
raise DuplicateDefinitionError, "#{@component.name} already registered: #{name}"
-
else
-
2
@component.register(name, item)
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator
-
1
class InvocationTracker < Decorator
-
1
def initialize(component)
-
super
-
@invoked_methods = []
-
end
-
-
1
def method_missing(name, *args, &block)
-
@invoked_methods << name
-
super
-
end
-
-
1
def __invoked_methods__
-
@invoked_methods.uniq
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator
-
1
class NewConstructor < Decorator
-
1
def initialize(component, build_class)
-
super(component)
-
@build_class = build_class
-
end
-
-
1
delegate :new, to: :@build_class
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class Definition
-
1
attr_reader :defined_traits, :declarations
-
-
1
def initialize(name = nil, base_traits = [])
-
3
@declarations = DeclarationList.new(name)
-
3
@callbacks = []
-
3
@defined_traits = Set.new
-
3
@to_create = nil
-
3
@base_traits = base_traits
-
3
@additional_traits = []
-
3
@constructor = nil
-
3
@attributes = nil
-
3
@compiled = false
-
end
-
-
1
delegate :declare_attribute, to: :declarations
-
-
1
def attributes
-
@attributes ||= AttributeList.new.tap do |attribute_list|
-
attribute_lists = aggregate_from_traits_and_self(:attributes) { declarations.attributes }
-
attribute_lists.each do |attributes|
-
attribute_list.apply_attributes attributes
-
end
-
end
-
end
-
-
1
def to_create(&block)
-
1
if block_given?
-
1
@to_create = block
-
else
-
aggregate_from_traits_and_self(:to_create) { @to_create }.last
-
end
-
end
-
-
1
def constructor
-
aggregate_from_traits_and_self(:constructor) { @constructor }.last
-
end
-
-
1
def callbacks
-
aggregate_from_traits_and_self(:callbacks) { @callbacks }
-
end
-
-
1
def compile
-
unless @compiled
-
declarations.attributes
-
-
defined_traits.each do |defined_trait|
-
base_traits.each { |bt| bt.define_trait defined_trait }
-
additional_traits.each { |bt| bt.define_trait defined_trait }
-
end
-
-
@compiled = true
-
end
-
end
-
-
1
def overridable
-
declarations.overridable
-
self
-
end
-
-
1
def inherit_traits(new_traits)
-
@base_traits += new_traits
-
end
-
-
1
def append_traits(new_traits)
-
@additional_traits += new_traits
-
end
-
-
1
def add_callback(callback)
-
@callbacks << callback
-
end
-
-
1
def skip_create
-
@to_create = ->(instance) { }
-
end
-
-
1
def define_trait(trait)
-
@defined_traits.add(trait)
-
end
-
-
1
def define_constructor(&block)
-
1
@constructor = block
-
end
-
-
1
def before(*names, &block)
-
callback(*names.map { |name| "before_#{name}" }, &block)
-
end
-
-
1
def after(*names, &block)
-
callback(*names.map { |name| "after_#{name}" }, &block)
-
end
-
-
1
def callback(*names, &block)
-
names.each do |name|
-
FactoryGirl.register_callback(name)
-
add_callback(Callback.new(name, block))
-
end
-
end
-
-
1
private
-
-
1
def base_traits
-
@base_traits.map { |name| trait_by_name(name) }
-
end
-
-
1
def additional_traits
-
@additional_traits.map { |name| trait_by_name(name) }
-
end
-
-
1
def trait_by_name(name)
-
trait_for(name) || FactoryGirl.trait_by_name(name)
-
end
-
-
1
def trait_for(name)
-
defined_traits.detect { |trait| trait.name == name }
-
end
-
-
1
def initialize_copy(source)
-
super
-
@attributes = nil
-
@compiled = false
-
end
-
-
1
def aggregate_from_traits_and_self(method_name, &block)
-
compile
-
-
[
-
base_traits.map(&method_name),
-
instance_exec(&block),
-
additional_traits.map(&method_name),
-
].flatten.compact
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class DefinitionHierarchy
-
1
def callbacks
-
FactoryGirl.callbacks
-
end
-
-
1
def constructor
-
FactoryGirl.constructor
-
end
-
-
1
def to_create
-
FactoryGirl.to_create
-
end
-
-
1
def self.build_from_definition(definition)
-
build_to_create(&definition.to_create)
-
build_constructor(&definition.constructor)
-
add_callbacks definition.callbacks
-
end
-
-
1
def self.add_callbacks(callbacks)
-
if callbacks.any?
-
define_method :callbacks do
-
super() + callbacks
-
end
-
end
-
end
-
1
private_class_method :add_callbacks
-
-
1
def self.build_constructor(&block)
-
if block
-
define_method(:constructor) do
-
block
-
end
-
end
-
end
-
1
private_class_method :build_constructor
-
-
1
def self.build_to_create(&block)
-
if block
-
define_method(:to_create) do
-
block
-
end
-
end
-
end
-
1
private_class_method :build_to_create
-
end
-
end
-
1
module FactoryGirl
-
1
class DefinitionProxy
-
1
UNPROXIED_METHODS = %w(__send__ __id__ nil? send object_id extend instance_eval initialize block_given? raise caller method)
-
-
1
(instance_methods + private_instance_methods).each do |method|
-
178
undef_method(method) unless UNPROXIED_METHODS.include?(method.to_s)
-
end
-
-
1
delegate :before, :after, :callback, to: :@definition
-
-
1
attr_reader :child_factories
-
-
1
def initialize(definition, ignore = false)
-
2
@definition = definition
-
2
@ignore = ignore
-
2
@child_factories = []
-
end
-
-
1
def singleton_method_added(name)
-
message = "Defining methods in blocks (trait or factory) is not supported (#{name})"
-
raise FactoryGirl::MethodDefinitionError, message
-
end
-
-
# Adds an attribute that should be assigned on generated instances for this
-
# factory.
-
#
-
# This method should be called with either a value or block, but not both. If
-
# called with a block, the attribute will be generated "lazily," whenever an
-
# instance is generated. Lazy attribute blocks will not be called if that
-
# attribute is overridden for a specific instance.
-
#
-
# When defining lazy attributes, an instance of FactoryGirl::Strategy will
-
# be yielded, allowing associations to be built using the correct build
-
# strategy.
-
#
-
# Arguments:
-
# * name: +Symbol+ or +String+
-
# The name of this attribute. This will be assigned using "name=" for
-
# generated instances.
-
# * value: +Object+
-
# If no block is given, this value will be used for this attribute.
-
1
def add_attribute(name, value = nil, &block)
-
12
raise AttributeDefinitionError, 'Both value and block given' if value && block_given?
-
-
12
declaration = if block_given?
-
Declaration::Dynamic.new(name, @ignore, block)
-
else
-
12
Declaration::Static.new(name, value, @ignore)
-
end
-
-
12
@definition.declare_attribute(declaration)
-
end
-
-
1
def ignore(&block)
-
ActiveSupport::Deprecation.warn "`#ignore` is deprecated and will be "\
-
"removed in 5.0. Please use `#transient` instead."
-
transient(&block)
-
end
-
-
1
def transient(&block)
-
proxy = DefinitionProxy.new(@definition, true)
-
proxy.instance_eval(&block)
-
end
-
-
# Calls add_attribute using the missing method name as the name of the
-
# attribute, so that:
-
#
-
# factory :user do
-
# name 'Billy Idol'
-
# end
-
#
-
# and:
-
#
-
# factory :user do
-
# add_attribute :name, 'Billy Idol'
-
# end
-
#
-
# are equivalent.
-
#
-
# If no argument or block is given, factory_girl will look for a sequence
-
# or association with the same name. This means that:
-
#
-
# factory :user do
-
# email { create(:email) }
-
# association :account
-
# end
-
#
-
# and:
-
#
-
# factory :user do
-
# email
-
# account
-
# end
-
#
-
# are equivalent.
-
1
def method_missing(name, *args, &block)
-
12
if args.empty? && block.nil?
-
@definition.declare_attribute(Declaration::Implicit.new(name, @definition, @ignore))
-
12
elsif args.first.respond_to?(:has_key?) && args.first.has_key?(:factory)
-
association(name, *args)
-
else
-
12
add_attribute(name, *args, &block)
-
end
-
end
-
-
# Adds an attribute that will have unique values generated by a sequence with
-
# a specified format.
-
#
-
# The result of:
-
# factory :user do
-
# sequence(:email) { |n| "person#{n}@example.com" }
-
# end
-
#
-
# Is equal to:
-
# sequence(:email) { |n| "person#{n}@example.com" }
-
#
-
# factory :user do
-
# email { FactoryGirl.generate(:email) }
-
# end
-
#
-
# Except that no globally available sequence will be defined.
-
1
def sequence(name, *args, &block)
-
sequence = Sequence.new(name, *args, &block)
-
add_attribute(name) { increment_sequence(sequence) }
-
end
-
-
# Adds an attribute that builds an association. The associated instance will
-
# be built using the same build strategy as the parent instance.
-
#
-
# Example:
-
# factory :user do
-
# name 'Joey'
-
# end
-
#
-
# factory :post do
-
# association :author, factory: :user
-
# end
-
#
-
# Arguments:
-
# * name: +Symbol+
-
# The name of this attribute.
-
# * options: +Hash+
-
#
-
# Options:
-
# * factory: +Symbol+ or +String+
-
# The name of the factory to use when building the associated instance.
-
# If no name is given, the name of the attribute is assumed to be the
-
# name of the factory. For example, a "user" association will by
-
# default use the "user" factory.
-
1
def association(name, *options)
-
@definition.declare_attribute(Declaration::Association.new(name, *options))
-
end
-
-
1
def to_create(&block)
-
@definition.to_create(&block)
-
end
-
-
1
def skip_create
-
@definition.skip_create
-
end
-
-
1
def factory(name, options = {}, &block)
-
@child_factories << [name, options, block]
-
end
-
-
1
def trait(name, &block)
-
@definition.define_trait(Trait.new(name, &block))
-
end
-
-
1
def initialize_with(&block)
-
@definition.define_constructor(&block)
-
end
-
end
-
end
-
1
module FactoryGirl
-
# Raised when a factory is defined that attempts to instantiate itself.
-
1
class AssociationDefinitionError < RuntimeError; end
-
-
# Raised when a callback is defined that has an invalid name
-
1
class InvalidCallbackNameError < RuntimeError; end
-
-
# Raised when a factory is defined with the same name as a previously-defined factory.
-
1
class DuplicateDefinitionError < RuntimeError; end
-
-
# Raised when attempting to register a sequence from a dynamic attribute block
-
1
class SequenceAbuseError < RuntimeError; end
-
-
# Raised when defining an invalid attribute:
-
# * Defining an attribute which has a name ending in "="
-
# * Defining an attribute with both a static and lazy value
-
# * Defining an attribute twice in the same factory
-
1
class AttributeDefinitionError < RuntimeError; end
-
-
# Raised when a method is defined in a factory or trait with arguments
-
1
class MethodDefinitionError < RuntimeError; end
-
-
# Raised when any factory is considered invalid
-
1
class InvalidFactoryError < RuntimeError; end
-
end
-
1
require 'observer'
-
-
1
module FactoryGirl
-
1
class Evaluation
-
1
include Observable
-
-
1
def initialize(attribute_assigner, to_create)
-
@attribute_assigner = attribute_assigner
-
@to_create = to_create
-
end
-
-
1
delegate :object, :hash, to: :@attribute_assigner
-
-
1
def create(result_instance)
-
@to_create[result_instance]
-
end
-
-
1
def notify(name, result_instance)
-
changed
-
notify_observers(name, result_instance)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/class/attribute'
-
-
1
module FactoryGirl
-
# @api private
-
1
class Evaluator
-
1
class_attribute :attribute_lists
-
-
1
private_instance_methods.each do |method|
-
84
undef_method(method) unless method =~ /^__|initialize/
-
end
-
-
1
def initialize(build_strategy, overrides = {})
-
@build_strategy = build_strategy
-
@overrides = overrides
-
@cached_attributes = overrides
-
@instance = nil
-
-
@overrides.each do |name, value|
-
singleton_class.define_attribute(name) { value }
-
end
-
end
-
-
1
def association(factory_name, *traits_and_overrides)
-
overrides = traits_and_overrides.extract_options!
-
strategy_override = overrides.fetch(:strategy) do
-
FactoryGirl.use_parent_strategy ? @build_strategy.class : :create
-
end
-
-
traits_and_overrides += [overrides.except(:strategy)]
-
-
runner = FactoryRunner.new(factory_name, strategy_override, traits_and_overrides)
-
@build_strategy.association(runner)
-
end
-
-
1
def instance=(object_instance)
-
@instance = object_instance
-
end
-
-
1
def method_missing(method_name, *args, &block)
-
if @instance.respond_to?(method_name)
-
@instance.send(method_name, *args, &block)
-
else
-
SyntaxRunner.new.send(method_name, *args, &block)
-
end
-
end
-
-
1
def respond_to_missing?(method_name, include_private = false)
-
@instance.respond_to?(method_name) || SyntaxRunner.new.respond_to?(method_name)
-
end
-
-
1
def __override_names__
-
@overrides.keys
-
end
-
-
1
def increment_sequence(sequence)
-
sequence.next(self)
-
end
-
-
1
def self.attribute_list
-
AttributeList.new.tap do |list|
-
attribute_lists.each do |attribute_list|
-
list.apply_attributes attribute_list.to_a
-
end
-
end
-
end
-
-
1
def self.define_attribute(name, &block)
-
if method_defined?(name) || private_method_defined?(name)
-
undef_method(name)
-
end
-
-
define_method(name) do
-
if @cached_attributes.key?(name)
-
@cached_attributes[name]
-
else
-
@cached_attributes[name] = instance_exec(&block)
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class EvaluatorClassDefiner
-
1
def initialize(attributes, parent_class)
-
@parent_class = parent_class
-
@attributes = attributes
-
-
attributes.each do |attribute|
-
evaluator_class.define_attribute(attribute.name, &attribute.to_proc)
-
end
-
end
-
-
1
def evaluator_class
-
@evaluator_class ||= Class.new(@parent_class).tap do |klass|
-
klass.attribute_lists ||= []
-
klass.attribute_lists += [@attributes]
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/inflector'
-
-
1
module FactoryGirl
-
# @api private
-
1
class Factory
-
1
attr_reader :name, :definition
-
-
1
def initialize(name, options = {})
-
2
assert_valid_options(options)
-
2
@name = name.respond_to?(:to_sym) ? name.to_sym : name.to_s.underscore.to_sym
-
2
@parent = options[:parent]
-
2
@aliases = options[:aliases] || []
-
2
@class_name = options[:class]
-
2
@definition = Definition.new(@name, options[:traits] || [])
-
2
@compiled = false
-
end
-
-
1
delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor,
-
:defined_traits, :inherit_traits, :append_traits, to: :@definition
-
-
1
def build_class
-
@build_class ||= if class_name.is_a? Class
-
class_name
-
else
-
class_name.to_s.camelize.constantize
-
end
-
end
-
-
1
def run(build_strategy, overrides, &block)
-
block ||= ->(result) { result }
-
compile
-
-
strategy = StrategyCalculator.new(build_strategy).strategy.new
-
-
evaluator = evaluator_class.new(strategy, overrides.symbolize_keys)
-
attribute_assigner = AttributeAssigner.new(evaluator, build_class, &compiled_constructor)
-
-
evaluation = Evaluation.new(attribute_assigner, compiled_to_create)
-
evaluation.add_observer(CallbacksObserver.new(callbacks, evaluator))
-
-
strategy.result(evaluation).tap(&block)
-
end
-
-
1
def human_names
-
names.map { |name| name.to_s.humanize.downcase }
-
end
-
-
1
def associations
-
evaluator_class.attribute_list.associations
-
end
-
-
# Names for this factory, including aliases.
-
#
-
# Example:
-
#
-
# factory :user, aliases: [:author] do
-
# # ...
-
# end
-
#
-
# FactoryGirl.create(:author).class
-
# # => User
-
#
-
# Because an attribute defined without a value or block will build an
-
# association with the same name, this allows associations to be defined
-
# without factories, such as:
-
#
-
# factory :user, aliases: [:author] do
-
# # ...
-
# end
-
#
-
# factory :post do
-
# author
-
# end
-
#
-
# FactoryGirl.create(:post).author.class
-
# # => User
-
1
def names
-
2
[name] + @aliases
-
end
-
-
1
def compile
-
unless @compiled
-
parent.compile
-
parent.defined_traits.each { |trait| define_trait(trait) }
-
@definition.compile
-
build_hierarchy
-
@compiled = true
-
end
-
end
-
-
1
def with_traits(traits)
-
self.clone.tap do |factory_with_traits|
-
factory_with_traits.append_traits traits
-
end
-
end
-
-
1
protected
-
-
1
def class_name
-
@class_name || parent.class_name || name
-
end
-
-
1
def evaluator_class
-
@evaluator_class ||= EvaluatorClassDefiner.new(attributes, parent.evaluator_class).evaluator_class
-
end
-
-
1
def attributes
-
compile
-
AttributeList.new(@name).tap do |list|
-
list.apply_attributes definition.attributes
-
end
-
end
-
-
1
def hierarchy_class
-
@hierarchy_class ||= Class.new(parent.hierarchy_class)
-
end
-
-
1
def hierarchy_instance
-
@hierarchy_instance ||= hierarchy_class.new
-
end
-
-
1
def build_hierarchy
-
hierarchy_class.build_from_definition definition
-
end
-
-
1
def callbacks
-
hierarchy_instance.callbacks
-
end
-
-
1
def compiled_to_create
-
hierarchy_instance.to_create
-
end
-
-
1
def compiled_constructor
-
hierarchy_instance.constructor
-
end
-
-
1
private
-
-
1
def assert_valid_options(options)
-
2
options.assert_valid_keys(:class, :parent, :aliases, :traits)
-
end
-
-
1
def parent
-
if @parent
-
FactoryGirl.factory_by_name(@parent)
-
else
-
NullFactory.new
-
end
-
end
-
-
1
def initialize_copy(source)
-
super
-
@definition = @definition.clone
-
@evaluator_class = nil
-
@hierarchy_class = nil
-
@hierarchy_instance = nil
-
@compiled = false
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class FactoryRunner
-
1
def initialize(name, strategy, traits_and_overrides)
-
@name = name
-
@strategy = strategy
-
-
@overrides = traits_and_overrides.extract_options!
-
@traits = traits_and_overrides
-
end
-
-
1
def run(runner_strategy = @strategy, &block)
-
factory = FactoryGirl.factory_by_name(@name)
-
-
factory.compile
-
-
if @traits.any?
-
factory = factory.with_traits(@traits)
-
end
-
-
instrumentation_payload = {
-
name: @name,
-
strategy: runner_strategy,
-
traits: @traits,
-
overrides: @overrides,
-
factory: factory
-
}
-
-
ActiveSupport::Notifications.instrument('factory_girl.run_factory', instrumentation_payload) do
-
factory.run(runner_strategy, @overrides, &block)
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class << self
-
# An Array of strings specifying locations that should be searched for
-
# factory definitions. By default, factory_girl will attempt to require
-
# "factories", "test/factories" and "spec/factories". Only the first
-
# existing file will be loaded.
-
1
attr_accessor :definition_file_paths
-
end
-
-
1
self.definition_file_paths = %w(factories test/factories spec/factories)
-
-
1
def self.find_definitions
-
4
absolute_definition_file_paths = definition_file_paths.map { |path| File.expand_path(path) }
-
-
1
absolute_definition_file_paths.uniq.each do |path|
-
3
load("#{path}.rb") if File.exist?("#{path}.rb")
-
-
3
if File.directory? path
-
1
Dir[File.join(path, '**', '*.rb')].sort.each do |file|
-
2
load file
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Linter
-
-
1
def initialize(factories_to_lint, linting_strategy)
-
@factories_to_lint = factories_to_lint
-
@linting_method = "lint_#{linting_strategy}"
-
@invalid_factories = calculate_invalid_factories
-
end
-
-
1
def lint!
-
if invalid_factories.any?
-
raise InvalidFactoryError, error_message
-
end
-
end
-
-
1
attr_reader :factories_to_lint, :invalid_factories
-
1
private :factories_to_lint, :invalid_factories
-
-
1
private
-
-
1
def calculate_invalid_factories
-
factories_to_lint.reduce(Hash.new([])) do |result, factory|
-
errors = send(@linting_method, factory)
-
result[factory] |= errors unless errors.empty?
-
result
-
end
-
end
-
-
1
class FactoryError
-
1
def initialize(wrapped_error, factory)
-
@wrapped_error = wrapped_error
-
@factory = factory
-
end
-
-
1
def message
-
message = @wrapped_error.message
-
"* #{location} - #{message} (#{@wrapped_error.class.name})"
-
end
-
-
1
def location
-
@factory.name
-
end
-
end
-
-
1
class FactoryTraitError < FactoryError
-
1
def initialize(wrapped_error, factory, trait_name)
-
super(wrapped_error, factory)
-
@trait_name = trait_name
-
end
-
-
1
def location
-
"#{@factory.name}+#{@trait_name}"
-
end
-
end
-
-
1
def lint_factory(factory)
-
result = []
-
begin
-
FactoryGirl.create(factory.name)
-
rescue => error
-
result |= [FactoryError.new(error, factory)]
-
end
-
result
-
end
-
-
1
def lint_traits(factory)
-
result = []
-
factory.definition.defined_traits.map(&:name).each do |trait_name|
-
begin
-
FactoryGirl.create(factory.name, trait_name)
-
rescue => error
-
result |=
-
[FactoryTraitError.new(error, factory, trait_name)]
-
end
-
end
-
result
-
end
-
-
1
def lint_factory_and_traits(factory)
-
errors = lint_factory(factory)
-
errors |= lint_traits(factory)
-
errors
-
end
-
-
1
def error_message
-
lines = invalid_factories.map do |_factory, exceptions|
-
exceptions.map(&:message)
-
end.flatten
-
-
<<-ERROR_MESSAGE.strip
-
The following factories are invalid:
-
-
#{lines.join("\n")}
-
ERROR_MESSAGE
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class NullFactory
-
1
attr_reader :definition
-
-
1
def initialize
-
@definition = Definition.new(:null_factory)
-
end
-
-
1
delegate :defined_traits, :callbacks, :attributes, :constructor,
-
:to_create, to: :definition
-
-
1
def compile; end
-
1
def class_name; end
-
1
def evaluator_class; FactoryGirl::Evaluator; end
-
1
def hierarchy_class; FactoryGirl::DefinitionHierarchy; end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class NullObject < ::BasicObject
-
1
def initialize(methods_to_respond_to)
-
@methods_to_respond_to = methods_to_respond_to.map(&:to_s)
-
end
-
-
1
def method_missing(name, *args, &block)
-
if respond_to?(name)
-
nil
-
else
-
super
-
end
-
end
-
-
1
def respond_to?(method, include_private=false)
-
@methods_to_respond_to.include? method.to_s
-
end
-
-
1
def respond_to_missing?(*args)
-
false
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Registry
-
1
include Enumerable
-
-
1
attr_reader :name
-
-
1
def initialize(name)
-
4
@name = name
-
4
@items = Decorator::ClassKeyHash.new({})
-
end
-
-
1
def clear
-
@items.clear
-
end
-
-
1
def each(&block)
-
@items.values.uniq.each(&block)
-
end
-
-
1
def find(name)
-
if registered?(name)
-
@items[name]
-
else
-
raise ArgumentError, "#{@name} not registered: #{name}"
-
end
-
end
-
-
1
alias :[] :find
-
-
1
def register(name, item)
-
7
@items[name] = item
-
end
-
-
1
def registered?(name)
-
2
@items.key?(name)
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
def self.reload
-
reset_configuration
-
register_default_strategies
-
register_default_callbacks
-
find_definitions
-
end
-
end
-
1
module FactoryGirl
-
-
# Sequences are defined using sequence within a FactoryGirl.define block.
-
# Sequence values are generated using next.
-
# @api private
-
1
class Sequence
-
1
attr_reader :name
-
-
1
def initialize(name, *args, &proc)
-
@name = name
-
@proc = proc
-
-
options = args.extract_options!
-
@value = args.first || 1
-
@aliases = options.fetch(:aliases) { [] }
-
-
if !@value.respond_to?(:peek)
-
@value = EnumeratorAdapter.new(@value)
-
end
-
end
-
-
1
def next(scope = nil)
-
if @proc && scope
-
scope.instance_exec(value, &@proc)
-
elsif @proc
-
@proc.call(value)
-
else
-
value
-
end
-
ensure
-
increment_value
-
end
-
-
1
def names
-
[@name] + @aliases
-
end
-
-
1
private
-
-
1
def value
-
@value.peek
-
end
-
-
1
def increment_value
-
@value.next
-
end
-
-
1
class EnumeratorAdapter
-
1
def initialize(value)
-
@value = value
-
end
-
-
1
def peek
-
@value
-
end
-
-
1
def next
-
@value = @value.next
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
module Strategy
-
1
class AttributesFor
-
1
def association(runner)
-
runner.run(:null)
-
end
-
-
1
def result(evaluation)
-
evaluation.hash
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
module Strategy
-
1
class Build
-
1
def association(runner)
-
runner.run
-
end
-
-
1
def result(evaluation)
-
evaluation.object.tap do |instance|
-
evaluation.notify(:after_build, instance)
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
module Strategy
-
1
class Create
-
1
def association(runner)
-
runner.run
-
end
-
-
1
def result(evaluation)
-
evaluation.object.tap do |instance|
-
evaluation.notify(:after_build, instance)
-
evaluation.notify(:before_create, instance)
-
evaluation.create(instance)
-
evaluation.notify(:after_create, instance)
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
module Strategy
-
1
class Null
-
1
def association(runner)
-
end
-
-
1
def result(evaluation)
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
module Strategy
-
1
class Stub
-
1
@@next_id = 1000
-
-
1
DISABLED_PERSISTENCE_METHODS = [
-
:connection,
-
:decrement!,
-
:decrement,
-
:delete,
-
:destroy!,
-
:destroy,
-
:destroyed?,
-
:increment!,
-
:increment,
-
:reload,
-
:save!,
-
:save,
-
:toggle!,
-
:toggle,
-
:touch,
-
:update!,
-
:update,
-
:update_attribute,
-
:update_attributes!,
-
:update_attributes,
-
:update_column,
-
:update_columns,
-
].freeze
-
-
1
def association(runner)
-
runner.run(:build_stubbed)
-
end
-
-
1
def result(evaluation)
-
evaluation.object.tap do |instance|
-
stub_database_interaction_on_result(instance)
-
clear_changed_attributes_on_result(instance)
-
evaluation.notify(:after_stub, instance)
-
end
-
end
-
-
1
private
-
-
1
def next_id
-
@@next_id += 1
-
end
-
-
1
def stub_database_interaction_on_result(result_instance)
-
result_instance.id ||= next_id
-
-
result_instance.instance_eval do
-
def persisted?
-
!new_record?
-
end
-
-
def new_record?
-
id.nil?
-
end
-
-
DISABLED_PERSISTENCE_METHODS.each do |write_method|
-
define_singleton_method(write_method) do |*args|
-
raise "stubbed models are not allowed to access the database - #{self.class}##{write_method}(#{args.join(",")})"
-
end
-
end
-
end
-
-
created_at_missing_default = result_instance.respond_to?(:created_at) && !result_instance.created_at
-
result_instance_missing_created_at = !result_instance.respond_to?(:created_at)
-
-
if created_at_missing_default || result_instance_missing_created_at
-
result_instance.instance_eval do
-
def created_at
-
@created_at ||= Time.now.in_time_zone
-
end
-
end
-
end
-
-
has_updated_at = result_instance.respond_to?(:updated_at)
-
updated_at_no_default = has_updated_at && !result_instance.updated_at
-
result_instance_missing_updated_at = !has_updated_at
-
-
if updated_at_no_default || result_instance_missing_updated_at
-
result_instance.instance_eval do
-
def updated_at
-
@updated_at ||= Time.current
-
end
-
end
-
end
-
end
-
-
1
def clear_changed_attributes_on_result(result_instance)
-
unless result_instance.respond_to?(:clear_changes_information)
-
result_instance.extend ActiveModelDirtyBackport
-
end
-
-
result_instance.clear_changes_information
-
end
-
end
-
-
1
module ActiveModelDirtyBackport
-
1
def clear_changes_information
-
@previously_changed = ActiveSupport::HashWithIndifferentAccess.new
-
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class StrategyCalculator
-
1
def initialize(name_or_object)
-
@name_or_object = name_or_object
-
end
-
-
1
def strategy
-
if strategy_is_object?
-
@name_or_object
-
else
-
strategy_name_to_object
-
end
-
end
-
-
1
private
-
-
1
def strategy_is_object?
-
@name_or_object.is_a?(Class)
-
end
-
-
1
def strategy_name_to_object
-
FactoryGirl.strategy_by_name(@name_or_object)
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class StrategySyntaxMethodRegistrar
-
1
def initialize(strategy_name)
-
5
@strategy_name = strategy_name
-
end
-
-
1
def define_strategy_methods
-
5
define_singular_strategy_method
-
5
define_list_strategy_method
-
5
define_pair_strategy_method
-
end
-
-
1
private
-
-
1
def define_singular_strategy_method
-
5
strategy_name = @strategy_name
-
-
5
define_syntax_method(strategy_name) do |name, *traits_and_overrides, &block|
-
FactoryRunner.new(name, strategy_name, traits_and_overrides).run(&block)
-
end
-
end
-
-
1
def define_list_strategy_method
-
5
strategy_name = @strategy_name
-
-
5
define_syntax_method("#{strategy_name}_list") do |name, amount, *traits_and_overrides, &block|
-
unless amount.respond_to?(:times)
-
raise ArgumentError, "count missing for #{strategy_name}_list"
-
end
-
-
amount.times.map { send(strategy_name, name, *traits_and_overrides, &block) }
-
end
-
end
-
-
1
def define_pair_strategy_method
-
5
strategy_name = @strategy_name
-
-
5
define_syntax_method("#{strategy_name}_pair") do |name, *traits_and_overrides, &block|
-
2.times.map { send(strategy_name, name, *traits_and_overrides, &block) }
-
end
-
end
-
-
1
def define_syntax_method(name, &block)
-
15
FactoryGirl::Syntax::Methods.module_exec do
-
15
if method_defined?(name) || private_method_defined?(name)
-
undef_method(name)
-
end
-
-
15
define_method(name, &block)
-
end
-
end
-
end
-
end
-
1
require 'factory_girl/syntax/methods'
-
1
require 'factory_girl/syntax/default'
-
-
1
module FactoryGirl
-
1
module Syntax
-
end
-
end
-
1
module FactoryGirl
-
1
module Syntax
-
1
module Default
-
1
include Methods
-
-
1
def define(&block)
-
2
DSL.run(block)
-
end
-
-
1
def modify(&block)
-
ModifyDSL.run(block)
-
end
-
-
1
class DSL
-
1
def factory(name, options = {}, &block)
-
2
factory = Factory.new(name, options)
-
2
proxy = FactoryGirl::DefinitionProxy.new(factory.definition)
-
2
proxy.instance_eval(&block) if block_given?
-
-
2
FactoryGirl.register_factory(factory)
-
-
2
proxy.child_factories.each do |(child_name, child_options, child_block)|
-
parent_factory = child_options.delete(:parent) || name
-
factory(child_name, child_options.merge(parent: parent_factory), &child_block)
-
end
-
end
-
-
1
def sequence(name, *args, &block)
-
FactoryGirl.register_sequence(Sequence.new(name, *args, &block))
-
end
-
-
1
def trait(name, &block)
-
FactoryGirl.register_trait(Trait.new(name, &block))
-
end
-
-
1
def to_create(&block)
-
FactoryGirl.to_create(&block)
-
end
-
-
1
def skip_create
-
FactoryGirl.skip_create
-
end
-
-
1
def initialize_with(&block)
-
FactoryGirl.initialize_with(&block)
-
end
-
-
1
def self.run(block)
-
2
new.instance_eval(&block)
-
end
-
-
1
delegate :before, :after, :callback, to: :configuration
-
-
1
private
-
-
1
def configuration
-
FactoryGirl.configuration
-
end
-
end
-
-
1
class ModifyDSL
-
1
def factory(name, options = {}, &block)
-
factory = FactoryGirl.factory_by_name(name)
-
proxy = FactoryGirl::DefinitionProxy.new(factory.definition.overridable)
-
proxy.instance_eval(&block)
-
end
-
-
1
def self.run(block)
-
new.instance_eval(&block)
-
end
-
end
-
end
-
end
-
-
1
extend Syntax::Default
-
end
-
1
module FactoryGirl
-
1
module Syntax
-
## This module is a container for all strategy methods provided by
-
## FactoryGirl. This includes all the default strategies provided ({Methods#build},
-
## {Methods#create}, {Methods#build_stubbed}, and {Methods#attributes_for}), as well as
-
## the complementary *_list methods.
-
## @example singular factory execution
-
## # basic use case
-
## build(:completed_order)
-
##
-
## # factory yielding its result to a block
-
## create(:post) do |post|
-
## create(:comment, post: post)
-
## end
-
##
-
## # factory with attribute override
-
## attributes_for(:post, title: "I love Ruby!")
-
##
-
## # factory with traits and attribute override
-
## build_stubbed(:user, :admin, :male, name: "John Doe")
-
##
-
## @example multiple factory execution
-
## # basic use case
-
## build_list(:completed_order, 2)
-
## create_list(:completed_order, 2)
-
##
-
## # factory with attribute override
-
## attributes_for_list(:post, 4, title: "I love Ruby!")
-
##
-
## # factory with traits and attribute override
-
## build_stubbed_list(:user, 15, :admin, :male, name: "John Doe")
-
1
module Methods
-
# @!parse FactoryGirl.register_default_strategies
-
# @!method build(name, *traits_and_overrides, &block)
-
# (see #strategy_method)
-
# Builds a registered factory by name.
-
# @return [Object] instantiated object defined by the factory
-
-
# @!method create(name, *traits_and_overrides, &block)
-
# (see #strategy_method)
-
# Creates a registered factory by name.
-
# @return [Object] instantiated object defined by the factory
-
-
# @!method build_stubbed(name, *traits_and_overrides, &block)
-
# (see #strategy_method)
-
# Builds a stubbed registered factory by name.
-
# @return [Object] instantiated object defined by the factory
-
-
# @!method attributes_for(name, *traits_and_overrides, &block)
-
# (see #strategy_method)
-
# Generates a hash of attributes for a registered factory by name.
-
# @return [Hash] hash of attributes for the factory
-
-
# @!method build_list(name, amount, *traits_and_overrides)
-
# (see #strategy_method_list)
-
# @return [Array] array of built objects defined by the factory
-
-
# @!method create_list(name, amount, *traits_and_overrides)
-
# (see #strategy_method_list)
-
# @return [Array] array of created objects defined by the factory
-
-
# @!method build_stubbed_list(name, amount, *traits_and_overrides)
-
# (see #strategy_method_list)
-
# @return [Array] array of stubbed objects defined by the factory
-
-
# @!method attributes_for_list(name, amount, *traits_and_overrides)
-
# (see #strategy_method_list)
-
# @return [Array<Hash>] array of attribute hashes for the factory
-
-
# @!method strategy_method
-
# @!visibility private
-
# @param [Symbol] name the name of the factory to build
-
# @param [Array<Symbol, Symbol, Hash>] traits_and_overrides splat args traits and a hash of overrides
-
# @param [Proc] block block to be executed
-
-
# @!method strategy_method_list
-
# @!visibility private
-
# @param [Symbol] name the name of the factory to execute
-
# @param [Integer] amount the number of instances to execute
-
# @param [Array<Symbol, Symbol, Hash>] traits_and_overrides splat args traits and a hash of overrides
-
-
# Generates and returns the next value in a sequence.
-
#
-
# Arguments:
-
# name: (Symbol)
-
# The name of the sequence that a value should be generated for.
-
#
-
# Returns:
-
# The next value in the sequence. (Object)
-
1
def generate(name)
-
FactoryGirl.sequence_by_name(name).next
-
end
-
-
# Generates and returns the list of values in a sequence.
-
#
-
# Arguments:
-
# name: (Symbol)
-
# The name of the sequence that a value should be generated for.
-
# count: (Fixnum)
-
# Count of values
-
#
-
# Returns:
-
# The next value in the sequence. (Object)
-
1
def generate_list(name, count)
-
(1..count).map do
-
FactoryGirl.sequence_by_name(name).next
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class SyntaxRunner
-
1
include Syntax::Methods
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class Trait
-
1
attr_reader :name, :definition
-
-
1
def initialize(name, &block)
-
@name = name
-
@block = block
-
@definition = Definition.new(@name)
-
-
proxy = FactoryGirl::DefinitionProxy.new(@definition)
-
proxy.instance_eval(&@block) if block_given?
-
end
-
-
1
delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor,
-
:callbacks, :attributes, to: :@definition
-
-
1
def names
-
[@name]
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
block == other.block
-
end
-
-
1
protected
-
1
attr_reader :block
-
end
-
end
-
1
module FactoryGirl
-
1
VERSION = '4.8.0'.freeze
-
end
-
1
require 'factory_girl_rails/railtie'
-
-
1
module FactoryGirlRails
-
end
-
1
require 'factory_girl_rails/generators/rspec_generator'
-
1
require 'factory_girl_rails/generators/non_rspec_generator'
-
1
require 'factory_girl_rails/generators/null_generator'
-
-
1
module FactoryGirlRails
-
1
class Generator
-
1
def initialize(config)
-
1
@generators = if config.respond_to?(:app_generators)
-
1
config.app_generators
-
else
-
config.generators
-
end
-
end
-
-
1
def run
-
1
generator.new(@generators).run
-
end
-
-
1
def generator
-
1
if factory_girl_disabled?
-
Generators::NullGenerator
-
else
-
1
if test_framework == :rspec
-
1
Generators::RSpecGenerator
-
else
-
Generators::NonRSpecGenerator
-
end
-
end
-
end
-
-
1
def test_framework
-
1
rails_options[:test_framework]
-
end
-
-
1
def factory_girl_disabled?
-
1
rails_options[:factory_girl] == false
-
end
-
-
1
def rails_options
-
2
@generators.options[:rails]
-
end
-
end
-
end
-
1
module FactoryGirlRails
-
1
module Generators
-
1
class NonRSpecGenerator
-
1
def initialize(generators)
-
@generators = generators
-
end
-
-
1
def run
-
@generators.test_framework test_framework, fixture: false, fixture_replacement: :factory_girl
-
end
-
-
1
private
-
-
1
def test_framework
-
@generators.options[:rails][:test_framework]
-
end
-
end
-
end
-
end
-
1
module FactoryGirlRails
-
1
module Generators
-
1
class NullGenerator
-
1
def initialize(generators)
-
end
-
-
1
def run
-
end
-
end
-
end
-
end
-
1
module FactoryGirlRails
-
1
module Generators
-
1
class RSpecGenerator
-
1
def initialize(generators)
-
1
@generators = generators
-
end
-
-
1
def run
-
1
@generators.fixture_replacement fixture_replacement_setting, dir: factory_girl_directory
-
end
-
-
1
private
-
-
1
def fixture_replacement_setting
-
1
@generators.options[:rails][:fixture_replacement] || :factory_girl
-
end
-
-
1
def factory_girl_directory
-
1
@generators.options.fetch(:factory_girl, {}).fetch(:dir, 'spec/factories')
-
end
-
end
-
end
-
end
-
1
require 'factory_girl'
-
1
require 'factory_girl_rails/generator'
-
1
require 'rails'
-
-
1
module FactoryGirl
-
1
class Railtie < Rails::Railtie
-
-
1
initializer "factory_girl.set_fixture_replacement" do
-
1
FactoryGirlRails::Generator.new(config).run
-
end
-
-
1
initializer "factory_girl.set_factory_paths" do
-
1
FactoryGirl.definition_file_paths = [
-
Rails.root.join('factories'),
-
Rails.root.join('test', 'factories'),
-
Rails.root.join('spec', 'factories')
-
]
-
end
-
-
1
config.after_initialize do
-
1
FactoryGirl.find_definitions
-
-
1
if defined?(Spring)
-
Spring.after_fork { FactoryGirl.reload }
-
end
-
end
-
end
-
end
-
1
class Array
-
1
unless self.method_defined? :sample
-
def sample(n = nil)
-
#based on code from https://github.com/marcandre/backports
-
size = self.length
-
return self[Kernel.rand(size)] if n.nil?
-
-
n = n.to_int
-
raise ArgumentError, "negative array size" if n < 0
-
-
n = size if n > size
-
-
result = Array.new(self)
-
n.times do |i|
-
r = i + Kernel.rand(size - i)
-
result[i], result[r] = result[r], result[i]
-
end
-
result[n..size] = []
-
result
-
end
-
end
-
end
-
# For Ruby 1.8
-
1
unless :symbol.respond_to?(:downcase)
-
Symbol.class_eval do
-
def downcase
-
to_s.downcase.intern
-
end
-
end
-
end
-
-
# -*- coding: utf-8 -*-
-
1
mydir = File.expand_path(File.dirname(__FILE__))
-
-
1
begin
-
1
require 'psych'
-
rescue LoadError
-
end
-
-
1
require 'i18n'
-
1
require 'set' # Fixes a bug in i18n 0.6.11
-
-
1
if I18n.respond_to?(:enforce_available_locales=)
-
1
I18n.enforce_available_locales = true
-
end
-
1
I18n.load_path += Dir[File.join(mydir, 'locales', '**/*.yml')]
-
1
I18n.reload! if I18n.backend.initialized?
-
-
-
1
module Faker
-
1
class Config
-
1
@locale = nil
-
1
@random = nil
-
-
1
class << self
-
1
attr_writer :locale
-
1
attr_writer :random
-
-
1
def locale
-
@locale || I18n.locale
-
end
-
-
1
def own_locale
-
@locale
-
end
-
-
1
def random
-
@random || Random::DEFAULT
-
end
-
end
-
end
-
-
1
class Base
-
1
Numbers = Array(0..9)
-
1
ULetters = Array('A'..'Z')
-
1
Letters = ULetters + Array('a'..'z')
-
-
1
class << self
-
## make sure numerify results doesn’t start with a zero
-
1
def numerify(number_string)
-
number_string.sub(/#/) { (rand(9)+1).to_s }.gsub(/#/) { rand(10).to_s }
-
end
-
-
1
def letterify(letter_string)
-
letter_string.gsub(/\?/) { sample(ULetters) }
-
end
-
-
1
def bothify(string)
-
letterify(numerify(string))
-
end
-
-
# Given a regular expression, attempt to generate a string
-
# that would match it. This is a rather simple implementation,
-
# so don't be shocked if it blows up on you in a spectacular fashion.
-
#
-
# It does not handle ., *, unbounded ranges such as {1,},
-
# extensions such as (?=), character classes, some abbreviations
-
# for character classes, and nested parentheses.
-
#
-
# I told you it was simple. :) It's also probably dog-slow,
-
# so you shouldn't use it.
-
#
-
# It will take a regex like this:
-
#
-
# /^[A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}$/
-
#
-
# and generate a string like this:
-
#
-
# "U3V 3TP"
-
#
-
1
def regexify(re)
-
re = re.source if re.respond_to?(:source) # Handle either a Regexp or a String that looks like a Regexp
-
re.
-
gsub(/^\/?\^?/, '').gsub(/\$?\/?$/, ''). # Ditch the anchors
-
gsub(/\{(\d+)\}/, '{\1,\1}').gsub(/\?/, '{0,1}'). # All {2} become {2,2} and ? become {0,1}
-
gsub(/(\[[^\]]+\])\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }. # [12]{1,2} becomes [12] or [12][12]
-
gsub(/(\([^\)]+\))\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }. # (12|34){1,2} becomes (12|34) or (12|34)(12|34)
-
gsub(/(\\?.)\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }. # A{1,2} becomes A or AA or \d{3} becomes \d\d\d
-
gsub(/\((.*?)\)/) {|match| sample(match.gsub(/[\(\)]/, '').split('|')) }. # (this|that) becomes 'this' or 'that'
-
gsub(/\[([^\]]+)\]/) {|match| match.gsub(/(\w\-\w)/) {|range| sample(Array(Range.new(*range.split('-')))) } }. # All A-Z inside of [] become C (or X, or whatever)
-
gsub(/\[([^\]]+)\]/) {|match| sample($1.split('')) }. # All [ABC] become B (or A or C)
-
gsub('\d') {|match| sample(Numbers) }.
-
gsub('\w') {|match| sample(Letters) }
-
end
-
-
# Helper for the common approach of grabbing a translation
-
# with an array of values and selecting one of them.
-
1
def fetch(key)
-
fetched = sample(translate("faker.#{key}"))
-
if fetched && fetched.match(/^\//) and fetched.match(/\/$/) # A regex
-
regexify(fetched)
-
else
-
fetched
-
end
-
end
-
-
# Helper for the common approach of grabbing a translation
-
# with an array of values and returning all of them.
-
1
def fetch_all(key)
-
fetched = translate("faker.#{key}")
-
fetched = fetched.last if fetched.size <= 1
-
if !fetched.respond_to?(:sample) && fetched.match(/^\//) and fetched.match(/\/$/) # A regex
-
regexify(fetched)
-
else
-
fetched
-
end
-
end
-
-
# Load formatted strings from the locale, "parsing" them
-
# into method calls that can be used to generate a
-
# formatted translation: e.g., "#{first_name} #{last_name}".
-
1
def parse(key)
-
fetched = fetch(key)
-
parts = fetched.scan(/(\(?)#\{([A-Za-z]+\.)?([^\}]+)\}([^#]+)?/).map {|prefix, kls, meth, etc|
-
# If the token had a class Prefix (e.g., Name.first_name)
-
# grab the constant, otherwise use self
-
cls = kls ? Faker.const_get(kls.chop) : self
-
-
# If an optional leading parentheses is not present, prefix.should == "", otherwise prefix.should == "("
-
# In either case the information will be retained for reconstruction of the string.
-
text = prefix
-
-
# If the class has the method, call it, otherwise
-
# fetch the transation (i.e., faker.name.first_name)
-
text += cls.respond_to?(meth) ? cls.send(meth) : fetch("#{(kls || self).to_s.split('::').last.downcase}.#{meth.downcase}")
-
-
# And tack on spaces, commas, etc. left over in the string
-
text += etc.to_s
-
}
-
# If the fetched key couldn't be parsed, then fallback to numerify
-
parts.any? ? parts.join : numerify(fetched)
-
end
-
-
# Call I18n.translate with our configured locale if no
-
# locale is specified
-
1
def translate(*args)
-
opts = args.last.is_a?(Hash) ? args.pop : {}
-
opts[:locale] ||= Faker::Config.locale
-
opts[:raise] = true
-
I18n.translate(*(args.push(opts)))
-
rescue I18n::MissingTranslationData
-
opts = args.last.is_a?(Hash) ? args.pop : {}
-
opts[:locale] = :en
-
-
# Super-simple fallback -- fallback to en if the
-
# translation was missing. If the translation isn't
-
# in en either, then it will raise again.
-
I18n.translate(*(args.push(opts)))
-
end
-
-
# Executes block with given locale set.
-
1
def with_locale(tmp_locale = nil)
-
current_locale = Faker::Config.own_locale
-
Faker::Config.locale = tmp_locale
-
I18n.with_locale(tmp_locale) { yield }
-
ensure
-
Faker::Config.locale = current_locale
-
end
-
-
1
def flexible(key)
-
20
@flexible_key = key
-
end
-
-
# You can add whatever you want to the locale file, and it will get caught here.
-
# E.g., in your locale file, create a
-
# name:
-
# girls_name: ["Alice", "Cheryl", "Tatiana"]
-
# Then you can call Faker::Name.girls_name and it will act like #first_name
-
1
def method_missing(m, *args, &block)
-
super unless @flexible_key
-
-
# Use the alternate form of translate to get a nil rather than a "missing translation" string
-
if translation = translate(:faker)[@flexible_key][m]
-
sample(translation)
-
else
-
super
-
end
-
end
-
-
# Generates a random value between the interval
-
1
def rand_in_range(from, to)
-
from, to = to, from if to < from
-
rand(from..to)
-
end
-
-
1
def unique(max_retries = 10_000)
-
@unique_generator ||= UniqueGenerator.new(self, max_retries)
-
end
-
-
1
def sample(list)
-
list.respond_to?(:sample) ? list.sample(random: Faker::Config.random) : list
-
end
-
-
1
def shuffle(list)
-
list.shuffle(random: Faker::Config.random)
-
end
-
-
1
def rand(max = nil)
-
if max.nil?
-
Faker::Config.random.rand
-
elsif max.is_a?(Range) || max.to_i > 0
-
Faker::Config.random.rand(max)
-
else
-
0
-
end
-
end
-
end
-
end
-
end
-
-
92
Dir.glob(File.join(File.dirname(__FILE__), 'faker','*.rb')).sort.each {|f| require f }
-
-
1
require 'extensions/array'
-
1
require 'extensions/symbol'
-
-
1
require 'helpers/char'
-
1
require 'helpers/unique_generator'
-
1
module Faker
-
1
class Address < Base
-
1
flexible :address
-
-
1
class << self
-
1
def city(options = {})
-
parse(options[:with_state] ? 'address.city_with_state' : 'address.city')
-
end
-
-
1
def street_name
-
parse('address.street_name')
-
end
-
-
1
def street_address(include_secondary = false)
-
numerify(parse('address.street_address') + (include_secondary ? ' ' + secondary_address : ''))
-
end
-
-
1
def secondary_address
-
bothify(fetch('address.secondary_address'))
-
end
-
-
1
def building_number
-
bothify(fetch('address.building_number'))
-
end
-
-
1
def community
-
parse('address.community')
-
end
-
-
1
def zip_code(state_abbreviation = '')
-
return bothify(fetch('address.postcode')) if state_abbreviation === ''
-
-
# provide a zip code that is valid for the state provided
-
# see http://www.fincen.gov/forms/files/us_state_territory_zip_codes.pdf
-
bothify(fetch('address.postcode_by_state.' + state_abbreviation))
-
end
-
-
1
def time_zone
-
fetch('address.time_zone')
-
end
-
-
1
alias_method :zip, :zip_code
-
1
alias_method :postcode, :zip_code
-
-
1
def street_suffix; fetch('address.street_suffix'); end
-
1
def city_suffix; fetch('address.city_suffix'); end
-
1
def city_prefix; fetch('address.city_prefix'); end
-
1
def state_abbr; fetch('address.state_abbr'); end
-
1
def state; fetch('address.state'); end
-
1
def country; fetch('address.country'); end
-
1
def country_code; fetch('address.country_code'); end
-
1
def country_code_long; fetch('address.country_code_long'); end
-
-
1
def latitude
-
((rand * 180) - 90).to_s
-
end
-
-
1
def longitude
-
((rand * 360) - 180).to_s
-
end
-
-
1
def full_address
-
parse('address.full_address')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Ancient < Base
-
1
class << self
-
1
def god
-
fetch('ancient.god')
-
end
-
-
1
def primordial
-
fetch('ancient.primordial')
-
end
-
-
1
def titan
-
fetch('ancient.titan')
-
end
-
-
1
def hero
-
fetch('ancient.hero')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class App < Base
-
1
class << self
-
-
1
def name
-
fetch('app.name')
-
end
-
-
1
def version
-
parse('app.version')
-
end
-
-
1
def author
-
parse('app.author')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Artist < Base
-
1
class << self
-
1
def name
-
fetch('artist.names')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Avatar < Base
-
1
class << self
-
1
SUPPORTED_FORMATS = %w(png jpg bmp)
-
-
1
def image(slug = nil, size = '300x300', format = 'png', set = 'set1', bgset = nil)
-
raise ArgumentError, "Size should be specified in format 300x300" unless size.match(/^[0-9]+x[0-9]+$/)
-
raise ArgumentError, "Supported formats are #{SUPPORTED_FORMATS.join(', ')}" unless SUPPORTED_FORMATS.include?(format)
-
slug ||= Faker::Lorem.words.join
-
bgset_query = "&bgset=#{bgset}" if bgset
-
"https://robohash.org/#{slug}.#{format}?size=#{size}&set=#{set}#{bgset_query}"
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Bank < Base
-
1
flexible :bank
-
-
1
class << self
-
1
def name
-
fetch('bank.name')
-
end
-
-
1
def swift_bic
-
fetch('bank.swift_bic')
-
end
-
-
1
def iban(bank_country_code="GB")
-
details = iban_details.find { |country| country["bank_country_code"] == bank_country_code.upcase }
-
raise ArgumentError, "Could not find iban details for #{bank_country_code}" unless details
-
bcc = details["bank_country_code"] + 2.times.map{ rand(10) }.join
-
ilc = (0...details["iban_letter_code"].to_i).map{ (65 + rand(26)).chr }.join
-
ib = details["iban_digits"].to_i.times.map{ rand(10) }.join
-
bcc + ilc + ib
-
end
-
-
1
private
-
-
1
def iban_details
-
fetch_all('bank.iban_details')
-
end
-
end
-
end
-
end
-
-
# encoding: utf-8
-
1
module Faker
-
1
class Beer < Base
-
1
flexible :beer
-
-
1
class << self
-
1
def name
-
fetch('beer.name')
-
end
-
-
1
def style
-
fetch('beer.style')
-
end
-
-
1
def hop
-
fetch('beer.hop')
-
end
-
-
1
def yeast
-
fetch('beer.yeast')
-
end
-
-
1
def malts
-
fetch('beer.malt')
-
end
-
-
1
def ibu
-
rand(10..100).to_s + ' IBU'
-
end
-
-
1
def alcohol
-
rand(2.0..10.0).round(1).to_s + '%'
-
end
-
-
1
def blg
-
rand(5.0..20.0).round(1).to_s + '°Blg'
-
end
-
end
-
end
-
end
-
1
require 'digest'
-
1
require 'securerandom'
-
-
1
module Faker
-
1
class Bitcoin < Base
-
1
class << self
-
-
1
PROTOCOL_VERSIONS = {
-
main: 0,
-
testnet: 111
-
}
-
-
1
def address
-
address_for(:main)
-
end
-
-
1
def testnet_address
-
address_for(:testnet)
-
end
-
-
1
protected
-
-
1
def base58(str)
-
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
-
base = alphabet.size
-
-
lv = 0
-
str.split('').reverse.each_with_index { |v,i| lv += v.unpack('C')[0] * 256**i }
-
-
ret = ''
-
while lv > 0 do
-
lv, mod = lv.divmod(base)
-
ret << alphabet[mod]
-
end
-
-
npad = str.match(/^#{0.chr}*/)[0].to_s.size
-
'1'*npad + ret.reverse
-
end
-
-
1
def address_for(network)
-
version = PROTOCOL_VERSIONS.fetch(network)
-
packed = version.chr + Faker::Config.random.bytes(20)
-
checksum = Digest::SHA2.digest(Digest::SHA2.digest(packed))[0..3]
-
base58(packed + checksum)
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Book < Base
-
1
flexible :book
-
-
1
class << self
-
1
def title
-
fetch('book.title')
-
end
-
-
1
def author
-
parse('book.author')
-
end
-
-
1
def publisher
-
fetch('book.publisher')
-
end
-
-
1
def genre
-
fetch('book.genre')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Boolean < Base
-
1
class << self
-
1
def boolean(true_ratio = 0.5)
-
(rand < true_ratio)
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class BossaNova < Base
-
1
class << self
-
1
def artist
-
fetch('bossa_nova.artists')
-
end
-
-
1
def song
-
fetch('bossa_nova.songs')
-
end
-
end
-
end
-
end
-
1
require 'date'
-
-
1
module Faker
-
1
class Business < Base
-
1
flexible :business
-
-
1
class << self
-
1
def credit_card_number
-
fetch('business.credit_card_numbers')
-
end
-
-
1
def credit_card_expiry_date
-
::Date.today + (365 * (rand(4) + 1))
-
end
-
-
1
def credit_card_type
-
fetch('business.credit_card_types')
-
end
-
end
-
-
end
-
end
-
1
module Faker
-
1
class Cat < Base
-
1
flexible :cat
-
-
1
class << self
-
1
def name
-
fetch('cat.name')
-
end
-
-
1
def breed
-
fetch('cat.breed')
-
end
-
-
1
def registry
-
fetch('cat.registry')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class ChuckNorris < Base
-
1
flexible :name
-
-
1
class << self
-
# from: https://github.com/jenkinsci/chucknorris-plugin/blob/master/src/main/java/hudson/plugins/chucknorris/FactGenerator.java
-
1
def fact; fetch('chuck_norris.fact'); end
-
-
end
-
end
-
end
-
1
module Faker
-
1
class Code < Base
-
1
flexible :code
-
1
class << self
-
-
# Generates a 10 digit NPI (National Provider Identifier
-
# issued to health care providers in the United States)
-
1
def npi
-
rand(10 ** 10).to_s.rjust(10, '0')
-
end
-
-
# By default generates 10 sign isbn code in format 123456789-X
-
# You can pass 13 to generate new 13 sign code
-
1
def isbn(base = 10)
-
base == 13 ? generate_base13_isbn : generate_base10_isbn
-
end
-
-
# By default generates 13 sign ean code in format 1234567890123
-
# You can pass 8 to generate ean8 code
-
1
def ean(base = 13)
-
base == 8 ? generate_base8_ean : generate_base13_ean
-
end
-
-
1
def rut
-
value = Number.number(8)
-
vd = rut_verificator_digit(value)
-
value << "-#{vd}"
-
end
-
-
# By default generates a Singaporean NRIC ID for someone
-
# who is born between the age of 18 and 65.
-
1
def nric(min_age = 18, max_age = 65)
-
birthyear = Date.birthday(min_age, max_age).year
-
prefix = birthyear < 2000 ? 'S' : 'T'
-
values = birthyear.to_s[-2..-1]
-
values << regexify(/\d{5}/)
-
check_alpha = generate_nric_check_alphabet(values, prefix)
-
"#{prefix}#{values}#{check_alpha}"
-
end
-
-
# Generate GSM modem, device or mobile phone 15 digit IMEI number.
-
1
def imei
-
generate_imei
-
end
-
-
# Retrieves a real Amazon ASIN code list taken from
-
# https://archive.org/details/asin_listing
-
1
def asin
-
fetch('code.asin')
-
end
-
-
1
private
-
-
# Reporting body identifier
-
1
RBI = %w(01 10 30 33 35 44 45 49 50 51 52 53 54 86 91 98 99).freeze
-
-
1
def generate_imei
-
pos = 0
-
str = Array.new(15, 0)
-
sum = 0
-
t = 0
-
len_offset = 0
-
len = 15
-
-
# Fill in the first two values of the string based with the specified prefix.
-
# Reporting Body Identifier list: http://en.wikipedia.org/wiki/Reporting_Body_Identifier
-
arr = sample(RBI)
-
str[0] = arr[0].to_i
-
str[1] = arr[1].to_i
-
pos = 2
-
-
# Fill all the remaining numbers except for the last one with random values.
-
while pos < (len - 1)
-
str[pos] = rand(0..9)
-
pos += 1
-
end
-
-
# Calculate the Luhn checksum of the values thus far
-
len_offset = (len + 1) % 2
-
(0..(len - 1)).each do |position|
-
if (position + len_offset) % 2 != 0
-
t = str[position] * 2
-
-
if t > 9
-
t -= 9
-
end
-
-
sum += t
-
else
-
sum += str[position]
-
end
-
end
-
-
# Choose the last digit so that it causes the entire string to pass the checksum.
-
str[len - 1] = (10 - (sum % 10)) % 10
-
-
# Output the IMEI value.
-
str.join('')
-
end
-
-
1
def generate_base10_isbn
-
values = regexify(/\d{9}/)
-
remainder = sum(values) { |value, index| (index + 1) * value.to_i } % 11
-
values << "-#{remainder == 10 ? 'X' : remainder}"
-
end
-
-
1
def generate_base13_isbn
-
values = regexify(/\d{12}/)
-
remainder = sum(values) { |value, index| index.even? ? value.to_i : value.to_i * 3 } % 10
-
values << "-#{((10 - remainder) % 10)}"
-
end
-
-
1
def sum(values, &block)
-
values.split(//).each_with_index.inject(0) do |sum, (value, index)|
-
sum + block.call(value, index)
-
end
-
end
-
-
1
def generate_base8_ean
-
values = regexify(/\d{7}/)
-
check_digit = 10 - values.split(//).each_with_index.inject(0){ |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT8[i] } % 10
-
values << (check_digit == 10 ? 0 : check_digit).to_s
-
end
-
-
1
def generate_base13_ean
-
values = regexify(/\d{12}/)
-
check_digit = 10 - values.split(//).each_with_index.inject(0){ |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT13[i] } % 10
-
values << (check_digit == 10 ? 0 : check_digit).to_s
-
end
-
-
1
EAN_CHECK_DIGIT8 = [3, 1, 3, 1, 3, 1, 3]
-
1
EAN_CHECK_DIGIT13 = [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3]
-
-
1
def rut_verificator_digit(rut)
-
total = rut.to_s.rjust(8, '0').split(//).zip(%w(3 2 7 6 5 4 3 2)).collect{|a, b| a.to_i * b.to_i}.inject(:+)
-
(11 - total % 11).to_s.gsub(/10/, 'k').gsub(/11/, '0')
-
end
-
-
1
def generate_nric_check_alphabet(values, prefix)
-
weight = %w(2 7 6 5 4 3 2)
-
total = values.split(//).zip(weight).collect { |a, b| a.to_i * b.to_i }.inject(:+)
-
total = total + 4 if prefix == 'T'
-
%w(A B C D E F G H I Z J)[10 - total % 11]
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Coffee < Base
-
1
class << self
-
1
def blend_name
-
parse('coffee.blend_name')
-
end
-
-
1
def origin
-
country = fetch('coffee.country')
-
region = fetch("coffee.regions.#{search_format(country)}")
-
"#{region}, #{country}"
-
end
-
-
1
def variety
-
fetch('coffee.variety')
-
end
-
-
1
def notes
-
parse('coffee.notes')
-
end
-
-
1
private
-
-
1
def search_format(key)
-
key.split.length > 1 ? key.split.join('_').downcase : key.downcase
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Color < Base
-
1
class << self
-
1
def hex_color
-
'#%06x' % (rand * 0xffffff)
-
end
-
-
1
def color_name
-
fetch('color.name')
-
end
-
-
1
def single_rgb_color
-
sample((0..255).to_a)
-
end
-
-
1
def rgb_color
-
3.times.collect { single_rgb_color }
-
end
-
-
# returns [hue, saturation, lightness]
-
1
def hsl_color
-
[sample((0..360).to_a), rand.round(2), rand.round(2)]
-
end
-
-
1
def hsla_color
-
hsl_color << rand.round(1)
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Commerce < Base
-
-
1
class << self
-
1
def color
-
fetch('color.name')
-
end
-
-
1
def promotion_code(digits = 6)
-
[
-
fetch('commerce.promotion_code.adjective'),
-
fetch('commerce.promotion_code.noun'),
-
Faker::Number.number(digits)
-
].join
-
end
-
-
1
def department(max = 3, fixed_amount = false)
-
num = max if fixed_amount
-
num ||= 1 + rand(max)
-
-
categories = categories(num)
-
-
return merge_categories(categories) if num > 1
-
categories[0]
-
end
-
-
1
def product_name
-
"#{fetch('commerce.product_name.adjective')} #{fetch('commerce.product_name.material')} #{fetch('commerce.product_name.product')}"
-
end
-
-
1
def material
-
fetch('commerce.product_name.material')
-
end
-
-
1
def price(range=0..100.0, as_string=false)
-
price = (rand(range) * 100).floor/100.0
-
if as_string
-
price_parts = price.to_s.split('.')
-
price = price_parts[0] + price_parts[-1].ljust(2, "0")
-
end
-
price
-
end
-
-
1
private
-
-
1
def categories(num)
-
categories = []
-
while categories.length < num
-
category = fetch('commerce.department')
-
categories << category unless categories.include?(category)
-
end
-
-
categories
-
end
-
-
1
def merge_categories(categories)
-
separator = fetch('separator')
-
comma_separated = categories.slice!(0...-1).join(', ')
-
-
[comma_separated, categories[0]].join(separator)
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Company < Base
-
1
flexible :company
-
-
1
class << self
-
1
def name
-
parse('company.name')
-
end
-
-
1
def suffix
-
fetch('company.suffix')
-
end
-
-
1
def industry
-
fetch('company.industry')
-
end
-
-
# Generate a buzzword-laden catch phrase.
-
1
def catch_phrase
-
translate('faker.company.buzzwords').collect {|list| sample(list) }.join(' ')
-
end
-
-
1
def buzzword
-
sample(translate('faker.company.buzzwords').flatten)
-
end
-
-
# When a straight answer won't do, BS to the rescue!
-
1
def bs
-
translate('faker.company.bs').collect {|list| sample(list) }.join(' ')
-
end
-
-
1
def ein
-
('%09d' % rand(10 ** 9)).gsub(/(\d{2})(\d{7})/, '\\1-\\2')
-
end
-
-
1
def duns_number
-
('%09d' % rand(10 ** 9)).gsub(/(\d{2})(\d{3})(\d{4})/, '\\1-\\2-\\3')
-
end
-
-
# Get a random company logo url in PNG format.
-
1
def logo
-
rand_num = rand(13) + 1
-
"https://pigment.github.io/fake-logos/logos/medium/color/#{rand_num}.png"
-
end
-
-
# Get a random Swedish organization number. See more here https://sv.wikipedia.org/wiki/Organisationsnummer
-
1
def swedish_organisation_number
-
# Valid leading digit: 1, 2, 3, 5, 6, 7, 8, 9
-
# Valid third digit: >= 2
-
# Last digit is a control digit
-
base = [sample([1, 2, 3, 5, 6, 7, 8, 9]), sample((0..9).to_a), sample((2..9).to_a), ('%06d' % rand(10 ** 6))].join
-
base + luhn_algorithm(base).to_s
-
end
-
-
# Get a random Norwegian organization number. Info: https://www.brreg.no/om-oss/samfunnsoppdraget-vart/registera-vare/einingsregisteret/organisasjonsnummeret/
-
1
def norwegian_organisation_number
-
# Valid leading digit: 8, 9
-
mod11_check = nil
-
while mod11_check.nil?
-
base = [sample([8, 9]), ('%07d' % rand(10 ** 7))].join
-
mod11_check = mod11(base)
-
end
-
base + mod11_check.to_s
-
end
-
-
1
def australian_business_number
-
base = ('%09d' % rand(10 ** 9))
-
abn = "00#{base}"
-
-
(99 - (abn_checksum(abn) % 89)).to_s + base
-
end
-
-
1
def profession
-
fetch('company.profession')
-
end
-
-
1
private
-
-
# Mod11 functionality from https://github.com/badmanski/mod11/blob/master/lib/mod11.rb
-
1
def mod11(number)
-
weight = [2, 3, 4, 5, 6, 7,
-
2, 3, 4, 5, 6, 7,
-
2, 3, 4, 5, 6, 7]
-
-
sum = 0
-
-
number.to_s.reverse.chars.each_with_index do |char, i|
-
sum += char.to_i * weight[i]
-
end
-
-
remainder = sum % 11
-
-
case remainder
-
when 0 then remainder
-
when 1 then nil
-
else 11 - remainder
-
end
-
end
-
-
1
def luhn_algorithm(number)
-
multiplications = []
-
-
number.split(//).each_with_index do |digit, i|
-
if i.even?
-
multiplications << digit.to_i * 2
-
else
-
multiplications << digit.to_i
-
end
-
end
-
-
sum = 0
-
-
multiplications.each do |num|
-
num.to_s.each_byte do |character|
-
sum += character.chr.to_i
-
end
-
end
-
-
if sum % 10 == 0
-
control_digit = 0
-
else
-
control_digit = (sum / 10 + 1) * 10 - sum
-
end
-
-
control_digit
-
end
-
-
1
def abn_checksum(abn)
-
abn_weights = [10,1,3,5,7,9,11,13,15,17,19]
-
sum = 0
-
-
abn_weights.each_with_index do |weight, i|
-
sum += weight * abn[i].to_i
-
end
-
-
sum
-
end
-
-
end
-
end
-
end
-
1
module Faker
-
1
class Compass < Base
-
1
class << self
-
1
def cardinal
-
fetch('compass.cardinal.word')
-
end
-
-
1
def ordinal
-
fetch('compass.ordinal.word')
-
end
-
-
1
def half_wind
-
fetch('compass.half-wind.word')
-
end
-
-
1
def quarter_wind
-
fetch('compass.quarter-wind.word')
-
end
-
-
1
def direction
-
parse('compass.direction')
-
end
-
-
1
def abbreviation
-
parse('compass.abbreviation')
-
end
-
-
1
def azimuth
-
parse('compass.azimuth')
-
end
-
-
1
def cardinal_abbreviation
-
fetch('compass.cardinal.abbreviation')
-
end
-
-
1
def ordinal_abbreviation
-
fetch('compass.ordinal.abbreviation')
-
end
-
-
1
def half_wind_abbreviation
-
fetch('compass.half-wind.abbreviation')
-
end
-
-
1
def quarter_wind_abbreviation
-
fetch('compass.quarter-wind.abbreviation')
-
end
-
-
1
def cardinal_azimuth
-
fetch('compass.cardinal.azimuth')
-
end
-
-
1
def ordinal_azimuth
-
fetch('compass.ordinal.azimuth')
-
end
-
-
1
def half_wind_azimuth
-
fetch('compass.half-wind.azimuth')
-
end
-
-
1
def quarter_wind_azimuth
-
fetch('compass.quarter-wind.azimuth')
-
end
-
end
-
end
-
end
-
1
require 'digest'
-
-
1
module Faker
-
1
class Crypto < Base
-
1
class << self
-
1
def md5
-
Digest::MD5.hexdigest(Lorem.characters)
-
end
-
-
1
def sha1
-
Digest::SHA1.hexdigest(Lorem.characters)
-
end
-
-
1
def sha256
-
Digest::SHA256.hexdigest(Lorem.characters)
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Date < Base
-
1
class << self
-
1
def between(from, to)
-
from = get_date_object(from)
-
to = get_date_object(to)
-
-
Faker::Base.rand_in_range(from, to)
-
end
-
-
1
def between_except(from, to, excepted)
-
begin
-
date = between(from, to)
-
end while date == excepted
-
-
date
-
end
-
-
1
def forward(days = 365)
-
from = ::Date.today + 1
-
to = ::Date.today + days
-
-
between(from, to).to_date
-
end
-
-
1
def backward(days = 365)
-
from = ::Date.today - days
-
to = ::Date.today - 1
-
-
between(from, to).to_date
-
end
-
-
1
def birthday(min_age = 18, max_age = 65)
-
t = ::Date.today
-
top_bound, bottom_bound = prepare_bounds(t, min_age, max_age)
-
years = handled_leap_years(top_bound, bottom_bound)
-
-
from = ::Date.new(years[0], t.month, t.day)
-
to = ::Date.new(years[1], t.month, t.day)
-
-
between(from, to).to_date
-
end
-
-
1
private
-
-
1
def prepare_bounds(t, min_age, max_age)
-
[t.year - min_age, t.year - max_age]
-
end
-
-
1
def handled_leap_years(top_bound, bottom_bound)
-
if (top_bound % 4) != 0 || (bottom_bound % 4) != 0
-
[
-
customized_bound(top_bound),
-
customized_bound(bottom_bound, true)
-
]
-
else
-
[top_bound, bottom_bound]
-
end
-
end
-
-
1
def customized_bound(bound, increase = false)
-
if (bound % 4) != 0
-
bound += 1 if increase
-
bound -= 1 unless increase
-
customized_bound(bound, increase)
-
else
-
bound
-
end
-
end
-
-
1
def get_date_object(date)
-
date = ::Date.parse(date) if date.is_a?(String)
-
date = date.to_date if date.respond_to?(:to_date)
-
date
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Demographic < Base
-
1
class << self
-
1
def race
-
fetch('demographic.race')
-
end
-
-
1
def educational_attainment
-
fetch('demographic.educational_attainment')
-
end
-
-
1
def demonym
-
fetch('demographic.demonym')
-
end
-
-
1
def marital_status
-
fetch('demographic.marital_status')
-
end
-
-
1
def sex
-
fetch('demographic.sex')
-
end
-
-
1
def height(unit = :metric)
-
case unit
-
when :imperial
-
inches = rand_in_range(57, 86)
-
return "#{inches / 12} ft, #{inches % 12} in"
-
when :metric
-
return rand_in_range(1.45, 2.13).round(2).to_s
-
end
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Dessert < Base
-
1
flexible :dessert
-
-
1
class << self
-
1
def variety
-
fetch('dessert.variety')
-
end
-
-
1
def topping
-
fetch('dessert.topping')
-
end
-
-
1
def flavor
-
fetch('dessert.flavor')
-
end
-
end
-
end
-
end
-
#encoding: utf-8
-
#frozen_string_literal: true
-
-
1
module Faker
-
-
1
class DrWho < Base
-
-
1
def self.character
-
fetch('dr_who.character')
-
end
-
-
1
def self.the_doctor
-
fetch('dr_who.the_doctors')
-
end
-
-
1
def self.catch_phrase
-
fetch('dr_who.catch_phrases')
-
end
-
-
1
def self.quote
-
fetch('dr_who.quotes')
-
end
-
-
1
def self.villian
-
fetch('dr_who.villians')
-
end
-
-
1
def self.specie
-
fetch('dr_who.species')
-
end
-
-
end #class DrWho
-
-
end #module Faker
-
1
module Faker
-
1
class DragonBall < Base
-
1
class << self
-
1
def character
-
fetch('dragon_ball.characters')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Educator < Base
-
1
flexible :educator
-
-
1
class << self
-
1
def university
-
"#{parse('educator.name')} #{fetch('educator.tertiary.type')}"
-
end
-
-
1
def course
-
"#{fetch('educator.tertiary.course.type')} #{fetch('educator.tertiary.course.subject')}"
-
end
-
-
1
def secondary_school
-
"#{parse('educator.name')} #{fetch('educator.secondary')}"
-
end
-
-
1
def campus
-
"#{parse('educator.name')} Campus"
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class ElderScrolls < Base
-
1
class << self
-
1
def race
-
fetch('elder_scrolls.race')
-
end
-
-
1
def creature
-
fetch('elder_scrolls.creature')
-
end
-
-
1
def region
-
fetch('elder_scrolls.region')
-
end
-
-
1
def dragon
-
fetch('elder_scrolls.dragon')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Esport < Base
-
1
class << self
-
1
def player
-
fetch('esports.players')
-
end
-
-
1
def team
-
fetch('esports.teams')
-
end
-
-
1
def league
-
fetch('esports.leagues')
-
end
-
-
1
def event
-
fetch('esports.events')
-
end
-
-
1
def game
-
fetch('esports.games')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class FamilyGuy < Base
-
1
class << self
-
1
def character
-
fetch('family_guy.character')
-
end
-
-
1
def location
-
fetch('family_guy.location')
-
end
-
-
1
def quote
-
fetch('family_guy.quote')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class File < Base
-
1
class << self
-
-
1
def extension
-
fetch('file.extension')
-
end
-
-
1
def mime_type
-
fetch('file.mime_type')
-
end
-
-
1
def file_name(dir = nil, name = nil, ext = nil, directory_separator = '/')
-
-
dir = Faker::Internet::slug unless dir
-
name = Faker::Lorem::word.downcase unless name
-
ext ||= extension
-
-
[dir, name].join(directory_separator) + ".#{ext}"
-
end
-
-
end
-
end
-
end
-
1
module Faker
-
1
class Fillmurray < Base
-
1
class << self
-
-
1
def image(grayscale = false, width = 200, height = 200)
-
raise ArgumentError, "Width should be a number" unless width.to_s.match(/^\d+$/)
-
raise ArgumentError, "Height should be a number" unless height.to_s.match(/^\d+$/)
-
raise ArgumentError, "Grayscale should be a boolean" unless [true, false].include?(grayscale)
-
-
grayscale == true ? "https://fillmurray.com/g/#{width}/#{height}" : "https://fillmurray.com/#{width}/#{height}"
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Finance < Base
-
-
1
CREDIT_CARD_TYPES = [:visa, :mastercard, :discover, :american_express,
-
:diners_club, :jcb, :switch, :solo, :dankort,
-
:maestro, :forbrugsforeningen, :laser].freeze
-
-
1
class << self
-
1
def credit_card(*types)
-
types = CREDIT_CARD_TYPES if types.empty?
-
type = sample(types)
-
template = numerify(fetch("credit_card.#{type}"))
-
-
# calculate the luhn checksum digit
-
multiplier = 1
-
luhn_sum = template.gsub(/[^0-9]/, '').split('').reverse.map(&:to_i).inject(0) do |sum, digit|
-
multiplier = (multiplier == 2 ? 1 : 2)
-
sum + (digit * multiplier).to_s.split('').map(&:to_i).inject(0) { |digit_sum, cur| digit_sum + cur }
-
end
-
# the sum plus whatever the last digit is must be a multiple of 10. So, the
-
# last digit must be 10 - the last digit of the sum.
-
luhn_digit = (10 - (luhn_sum % 10)) % 10
-
-
template.gsub('L', luhn_digit.to_s)
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Food < Base
-
1
class << self
-
1
def dish
-
fetch('food.dish')
-
end
-
-
1
def ingredient
-
fetch('food.ingredients')
-
end
-
-
1
def spice
-
fetch('food.spices')
-
end
-
-
1
def measurement
-
fetch('food.measurement_sizes') + ' ' + fetch('food.measurements')
-
end
-
-
1
def metric_measurement
-
fetch('food.metric_measurements')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Friends < Base
-
1
class << self
-
1
def character
-
fetch('friends.characters')
-
end
-
-
1
def location
-
fetch('friends.locations')
-
end
-
-
1
def quote
-
fetch('friends.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class FunnyName < Base
-
1
flexible :funny_name
-
-
1
class << self
-
1
def name
-
fetch('funny_name.name')
-
end
-
-
1
def two_word_name
-
two_word_names = fetch_all('funny_name.name').select do |name|
-
name.count(' ') == 1
-
end
-
-
sample(two_word_names)
-
end
-
-
1
def three_word_name
-
three_word_names = fetch_all('funny_name.name').select do |name|
-
name.count(' ') == 2
-
end
-
-
sample(three_word_names)
-
end
-
-
1
def four_word_name
-
four_word_names = fetch_all('funny_name.name').select do |name|
-
name.count(' ') == 3
-
end
-
-
sample(four_word_names)
-
end
-
-
1
def name_with_initial
-
names_with_initials = fetch_all('funny_name.name').select do |name|
-
name.count('.') > 0
-
end
-
-
sample(names_with_initials)
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class GameOfThrones < Base
-
1
class << self
-
1
def character
-
fetch('game_of_thrones.characters')
-
end
-
-
1
def house
-
fetch('game_of_thrones.houses')
-
end
-
-
1
def city
-
fetch('game_of_thrones.cities')
-
end
-
-
1
def quote
-
fetch('game_of_thrones.quotes')
-
end
-
-
1
def dragon
-
fetch('game_of_thrones.dragons')
-
end
-
end
-
end
-
end
-
#Port of http://shinytoylabs.com/jargon/
-
1
module Faker
-
1
class Hacker < Base
-
1
flexible :hacker
-
-
1
class << self
-
1
def say_something_smart
-
sample(phrases)
-
end
-
-
1
def abbreviation
-
fetch('hacker.abbreviation')
-
end
-
-
1
def adjective
-
fetch('hacker.adjective')
-
end
-
-
1
def noun
-
fetch('hacker.noun')
-
end
-
-
1
def verb
-
fetch('hacker.verb')
-
end
-
-
1
def ingverb
-
fetch('hacker.ingverb')
-
end
-
-
1
def phrases
-
[ "If we #{verb} the #{noun}, we can get to the #{abbreviation} #{noun} through the #{adjective} #{abbreviation} #{noun}!",
-
"We need to #{verb} the #{adjective} #{abbreviation} #{noun}!",
-
"Try to #{verb} the #{abbreviation} #{noun}, maybe it will #{verb} the #{adjective} #{noun}!",
-
"You can't #{verb} the #{noun} without #{ingverb} the #{adjective} #{abbreviation} #{noun}!",
-
"Use the #{adjective} #{abbreviation} #{noun}, then you can #{verb} the #{adjective} #{noun}!",
-
"The #{abbreviation} #{noun} is down, #{verb} the #{adjective} #{noun} so we can #{verb} the #{abbreviation} #{noun}!",
-
"#{ingverb} the #{noun} won't do anything, we need to #{verb} the #{adjective} #{abbreviation} #{noun}!".capitalize,
-
"I'll #{verb} the #{adjective} #{abbreviation} #{noun}, that should #{noun} the #{abbreviation} #{noun}!"
-
]
-
end
-
end
-
-
end
-
end
-
1
module Faker
-
1
class HarryPotter < Base
-
1
class << self
-
1
def character
-
fetch('harry_potter.characters')
-
end
-
-
1
def location
-
fetch('harry_potter.locations')
-
end
-
-
1
def quote
-
fetch('harry_potter.quotes')
-
end
-
-
1
def book
-
fetch('harry_potter.books')
-
end
-
-
1
def house
-
fetch('harry_potter.houses')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class HeyArnold < Base
-
1
class << self
-
1
def character
-
fetch('hey_arnold.characters')
-
end
-
-
1
def location
-
fetch('hey_arnold.locations')
-
end
-
-
1
def quote
-
fetch('hey_arnold.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Hipster < Base
-
1
class << self
-
1
def word
-
random_word = sample(translate('faker.hipster.words'))
-
random_word.match(/\s/) ? word : random_word
-
end
-
-
1
def words(num = 3, supplemental = false, spaces_allowed = false)
-
resolved_num = resolve(num)
-
word_list = (
-
translate('faker.hipster.words') +
-
(supplemental ? translate('faker.lorem.words') : [])
-
)
-
word_list = word_list * ((resolved_num / word_list.length) + 1)
-
-
return shuffle(word_list)[0, resolved_num] if spaces_allowed
-
words = shuffle(word_list)[0, resolved_num]
-
words.each_with_index { |w, i| words[i] = word if w.match(/\s/) }
-
end
-
-
1
def sentence(word_count = 4, supplemental = false, random_words_to_add = 6)
-
words(word_count + rand(random_words_to_add.to_i).to_i, supplemental, true).join(' ').capitalize + '.'
-
end
-
-
1
def sentences(sentence_count = 3, supplemental = false)
-
[].tap do |sentences|
-
1.upto(resolve(sentence_count)) do
-
sentences << sentence(3, supplemental)
-
end
-
end
-
end
-
-
1
def paragraph(sentence_count = 3, supplemental = false, random_sentences_to_add = 3)
-
sentences(resolve(sentence_count) + rand(random_sentences_to_add.to_i).to_i, supplemental).join(' ')
-
end
-
-
1
def paragraphs(paragraph_count = 3, supplemental = false)
-
[].tap do |paragraphs|
-
1.upto(resolve(paragraph_count)) do
-
paragraphs << paragraph(3, supplemental)
-
end
-
end
-
end
-
-
1
private
-
-
# If an array or range is passed, a random value will be selected.
-
# All other values are simply returned.
-
1
def resolve(value)
-
case value
-
when Array then value[rand(value.size)]
-
when Range then value.to_a[rand(value.size)]
-
else value
-
end
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class HitchhikersGuideToTheGalaxy < Base
-
1
class << self
-
1
def character
-
fetch('hitchhikers_guide_to_the_galaxy.characters')
-
end
-
-
1
def location
-
fetch('hitchhikers_guide_to_the_galaxy.locations')
-
end
-
-
1
def marvin_quote
-
fetch('hitchhikers_guide_to_the_galaxy.marvin_quote')
-
end
-
-
1
def planet
-
fetch('hitchhikers_guide_to_the_galaxy.planets')
-
end
-
-
1
def quote
-
fetch('hitchhikers_guide_to_the_galaxy.quotes')
-
end
-
-
1
def specie
-
fetch('hitchhikers_guide_to_the_galaxy.species')
-
end
-
-
1
def starship
-
fetch('hitchhikers_guide_to_the_galaxy.starships')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Hobbit < Base
-
1
class << self
-
1
def character
-
fetch('hobbit.character')
-
end
-
-
1
def thorins_company
-
fetch('hobbit.thorins_company')
-
end
-
-
1
def quote
-
fetch('hobbit.quote')
-
end
-
-
1
def location
-
fetch('hobbit.location')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class HowIMetYourMother < Base
-
1
class << self
-
1
def character
-
fetch('how_i_met_your_mother.character')
-
end
-
-
1
def catch_phrase
-
fetch('how_i_met_your_mother.catch_phrase')
-
end
-
-
1
def high_five
-
fetch('how_i_met_your_mother.high_five')
-
end
-
-
1
def quote
-
fetch('how_i_met_your_mother.quote')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class IDNumber < Base
-
-
1
INVALID_SSN = [
-
/0{3}-\d{2}-\d{4}/,
-
/\d{3}-0{2}-\d{4}/,
-
/\d{3}-\d{2}-0{4}/,
-
/666-\d{2}-\d{4}/,
-
/9\d{2}-\d{2}-\d{4}/
-
]
-
-
1
class << self
-
-
1
def valid
-
_translate('valid')
-
end
-
-
1
def invalid
-
_translate('invalid')
-
end
-
-
1
def ssn_valid
-
ssn = regexify(/[0-8]\d{2}-\d{2}-\d{4}/)
-
# We could still have all 0s in one segment or another
-
INVALID_SSN.any? { |regex| regex =~ ssn } ? ssn_valid : ssn
-
end
-
-
1
private
-
-
1
def _translate(key)
-
parse("id_number.#{key}")
-
end
-
end
-
-
end
-
end
-
1
module Faker
-
1
class Internet < Base
-
1
class << self
-
-
1
def email(name = nil)
-
[user_name(name), domain_name].join('@')
-
end
-
-
1
def free_email(name = nil)
-
[user_name(name), fetch('internet.free_email')].join('@')
-
end
-
-
1
def safe_email(name = nil)
-
[user_name(name), 'example.'+ sample(%w[org com net])].join('@')
-
end
-
-
1
def user_name(specifier = nil, separators = %w(. _))
-
with_locale(:en) do
-
if specifier.respond_to?(:scan)
-
return specifier.scan(/\w+/).shuffle.join(sample(separators)).downcase
-
elsif specifier.kind_of?(Integer)
-
# If specifier is Integer and has large value, Argument error exception is raised to overcome memory full error
-
raise ArgumentError, "Given argument is too large" if specifier > 10**6
-
tries = 0 # Don't try forever in case we get something like 1_000_000.
-
begin
-
result = user_name(nil, separators)
-
tries += 1
-
end while result.length < specifier && tries < 7
-
return result * (specifier/result.length + 1) if specifier > 0
-
elsif specifier.kind_of?(Range)
-
tries = 0
-
begin
-
result = user_name(specifier.min, separators)
-
tries += 1
-
end while !specifier.include?(result.length) && tries < 7
-
return result[0...specifier.max]
-
end
-
-
sample([
-
Char.prepare(Name.first_name),
-
[Name.first_name, Name.last_name].map{ |name|
-
Char.prepare(name)
-
}.join(sample(separators))
-
])
-
end
-
end
-
-
1
def password(min_length = 8, max_length = 16, mix_case = true, special_chars = false)
-
temp = Lorem.characters(min_length)
-
diff_length = max_length - min_length
-
if diff_length > 0
-
diff_rand = rand(diff_length + 1)
-
temp += Lorem.characters(diff_rand)
-
end
-
-
if mix_case
-
temp.chars.each_with_index do |char, index|
-
temp[index] = char.upcase if index.even?
-
end
-
end
-
-
if special_chars
-
chars = %w(! @ # $ % ^ & *)
-
rand(1..min_length).times do |i|
-
temp[i] = chars[rand(chars.length)]
-
end
-
end
-
-
temp
-
end
-
-
1
def domain_name
-
with_locale(:en) { [Char.prepare(domain_word), domain_suffix].join('.') }
-
end
-
-
1
def fix_umlauts(string='')
-
Char.fix_umlauts(string)
-
end
-
-
1
def domain_word
-
with_locale(:en) { Char.prepare(Company.name.split(' ').first) }
-
end
-
-
1
def domain_suffix
-
fetch('internet.domain_suffix')
-
end
-
-
1
def mac_address(prefix='')
-
prefix_digits = prefix.split(':').map{ |d| d.to_i(16) }
-
address_digits = (6 - prefix_digits.size).times.map{ rand(256) }
-
(prefix_digits + address_digits).map{ |d| '%02x' % d }.join(':')
-
end
-
-
1
def ip_v4_address
-
ary = (2..254).to_a
-
[ sample(ary), sample(ary), sample(ary), sample(ary) ].join('.')
-
end
-
-
1
def private_ip_v4_address
-
begin
-
addr = ip_v4_address
-
end while !private_net_checker[addr]
-
addr
-
end
-
-
1
def public_ip_v4_address
-
begin
-
addr = ip_v4_address
-
end while reserved_net_checker[addr]
-
addr
-
end
-
-
1
def private_nets_regex
-
[
-
/^10\./, # 10.0.0.0 – 10.255.255.255
-
/^100\.(6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./, # 100.64.0.0 – 100.127.255.255
-
/^127\./, # 127.0.0.0 – 127.255.255.255
-
/^169\.254\./, # 169.254.0.0 – 169.254.255.255
-
/^172\.(1[6-9]|2\d|3[0-1])\./, # 172.16.0.0 – 172.31.255.255
-
/^192\.0\.0\./, # 192.0.0.0 – 192.0.0.255
-
/^192\.168\./, # 192.168.0.0 – 192.168.255.255
-
/^198\.(1[8-9])\./ # 198.18.0.0 – 198.19.255.255
-
]
-
end
-
-
1
def private_net_checker
-
lambda { |addr| private_nets_regex.any? { |net| net =~ addr } }
-
end
-
-
1
def reserved_nets_regex
-
[
-
/^0\./, # 0.0.0.0 – 0.255.255.255
-
/^192\.0\.2\./, # 192.0.2.0 – 192.0.2.255
-
/^192\.88\.99\./, # 192.88.99.0 – 192.88.99.255
-
/^198\.51\.100\./, # 198.51.100.0 – 198.51.100.255
-
/^203\.0\.113\./, # 203.0.113.0 – 203.0.113.255
-
/^(22[4-9]|23\d)\./, # 224.0.0.0 – 239.255.255.255
-
/^(24\d|25[0-5])\./ # 240.0.0.0 – 255.255.255.254 and 255.255.255.255
-
]
-
end
-
-
1
def reserved_net_checker
-
->(addr){ (private_nets_regex + reserved_nets_regex).any? { |net| net =~ addr } }
-
end
-
-
1
def ip_v4_cidr
-
"#{ip_v4_address}/#{1 + rand(31)}"
-
end
-
-
1
def ip_v6_address
-
(1..8).map { rand(65536).to_s(16) }.join(':')
-
end
-
-
1
def ip_v6_cidr
-
"#{ip_v6_address}/#{1 + rand(127)}"
-
end
-
-
1
def url(host = domain_name, path = "/#{user_name}", scheme = 'http')
-
"#{scheme}://#{host}#{path}"
-
end
-
-
1
def slug(words = nil, glue = nil)
-
glue ||= sample(%w[- _ .])
-
(words || Faker::Lorem::words(2).join(' ')).gsub(' ', glue).downcase
-
end
-
-
1
def device_token
-
shuffle(rand(16 ** 64).to_s(16).rjust(64, '0').chars.to_a).join
-
end
-
-
1
def user_agent(vendor = nil)
-
agent_hash = translate('faker.internet.user_agent')
-
agents = vendor.respond_to?(:to_sym) && agent_hash[vendor.to_sym] || agent_hash[sample(agent_hash.keys)]
-
sample(agents)
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Job < Base
-
1
flexible :job
-
-
1
class << self
-
-
1
def title
-
parse('job.title')
-
end
-
-
1
def field; fetch('job.field'); end
-
1
def key_skill; fetch('job.key_skills'); end
-
-
end
-
end
-
end
-
1
module Faker
-
1
class LeagueOfLegends < Base
-
1
class << self
-
1
def champion
-
fetch('league_of_legends.champion')
-
end
-
-
1
def location
-
fetch('league_of_legends.location')
-
end
-
-
1
def quote
-
fetch('league_of_legends.quote')
-
end
-
-
1
def summoner_spell
-
fetch('league_of_legends.summoner_spell')
-
end
-
-
1
def masteries
-
fetch('league_of_legends.masteries')
-
end
-
-
1
def rank
-
fetch('league_of_legends.rank')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class LordOfTheRings < Base
-
1
class << self
-
1
def character
-
fetch('lord_of_the_rings.characters')
-
end
-
-
1
def location
-
fetch('lord_of_the_rings.locations')
-
end
-
end
-
end
-
end
-
1
module Faker
-
# Based on Perl's Text::Lorem
-
1
class Lorem < Base
-
1
CHARACTERS = ('0'..'9').to_a + ('a'..'z').to_a
-
-
1
class << self
-
1
def word
-
sample(translate('faker.lorem.words'))
-
end
-
-
1
def words(num = 3, supplemental = false)
-
resolved_num = resolve(num)
-
word_list = (
-
translate('faker.lorem.words') +
-
(supplemental ? translate('faker.lorem.supplemental') : [])
-
)
-
word_list = word_list * ((resolved_num / word_list.length) + 1)
-
shuffle(word_list)[0, resolved_num]
-
end
-
-
1
def character
-
sample(CHARACTERS)
-
end
-
-
1
def characters(char_count = 255)
-
char_count = resolve(char_count)
-
return '' if char_count.to_i < 1
-
Array.new(char_count) { sample(CHARACTERS) }.join
-
end
-
-
1
def sentence(word_count = 4, supplemental = false, random_words_to_add = 6)
-
words(word_count + rand(random_words_to_add.to_i), supplemental).join(' ').capitalize + '.'
-
end
-
-
1
def sentences(sentence_count = 3, supplemental = false)
-
1.upto(resolve(sentence_count)).collect { sentence(3, supplemental) }
-
end
-
-
1
def paragraph(sentence_count = 3, supplemental = false, random_sentences_to_add = 3)
-
sentences(resolve(sentence_count) + rand(random_sentences_to_add.to_i), supplemental).join(' ')
-
end
-
-
1
def paragraphs(paragraph_count = 3, supplemental = false)
-
1.upto(resolve(paragraph_count)).collect { paragraph(3, supplemental) }
-
end
-
-
1
def question(word_count = 4, supplemental = false, random_words_to_add = 6)
-
words(word_count + rand(random_words_to_add.to_i), supplemental).join(' ').capitalize + '?'
-
end
-
-
1
def questions(question_count = 3, supplemental = false)
-
1.upto(resolve(question_count)).collect { question(3, supplemental) }
-
end
-
-
1
private
-
-
# If an array or range is passed, a random value will be selected.
-
# All other values are simply returned.
-
1
def resolve(value)
-
case value
-
when Array then sample(value)
-
when Range then rand value
-
else value
-
end
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class LoremPixel < Base
-
1
class << self
-
1
SUPPORTED_CATEGORIES = %w(abstract animals business cats city food nightlife fashion people nature sports technics transport)
-
-
1
def image(size = '300x300', is_gray = false, category = nil, number = nil, text = nil)
-
raise ArgumentError, 'Size should be specified in format 300x300' unless size.match(/^[0-9]+x[0-9]+$/)
-
raise ArgumentError, "Supported categories are #{SUPPORTED_CATEGORIES.join(', ')}" unless category.nil? || SUPPORTED_CATEGORIES.include?(category)
-
raise ArgumentError, 'Category required when number is passed' if !number.nil? && category.nil?
-
raise ArgumentError, 'Number must be between 1 and 10' unless number.nil? || (1..10).include?(number)
-
raise ArgumentError, 'Category and number must be passed when text is passed' if !text.nil? && number.nil? && category.nil?
-
-
url_parts = ['http://lorempixel.com']
-
url_parts << 'g' if is_gray
-
url_parts += size.split('x')
-
url_parts += [category, number, text].compact
-
url_parts.join('/')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Lovecraft < Base
-
1
class << self
-
1
def location
-
fetch('lovecraft.location')
-
end
-
-
1
def fhtagn(number_of = 1)
-
number_of.times.collect { fetch('lovecraft.fhtagn') }.join(". ")
-
end
-
-
1
def deity
-
fetch('lovecraft.deity')
-
end
-
-
1
def tome
-
fetch('lovecraft.tome')
-
end
-
-
1
def sentence(word_count = 4, random_words_to_add = 6)
-
words(word_count + rand(random_words_to_add.to_i).to_i, true).join(' ').capitalize + '.'
-
end
-
-
1
def word
-
random_word = sample(translate('faker.lovecraft.words'))
-
random_word.match(/\s/) ? word : random_word
-
end
-
-
1
def words(num = 3, spaces_allowed = false)
-
resolved_num = resolve(num)
-
word_list = translate('faker.lovecraft.words')
-
word_list = word_list * ((resolved_num / word_list.length) + 1)
-
-
return shuffle(word_list)[0, resolved_num] if spaces_allowed
-
words = shuffle(word_list)[0, resolved_num]
-
words.each_with_index { |w, i| words[i] = word if w.match(/\s/) }
-
end
-
-
-
1
def sentences(sentence_count = 3)
-
[].tap do |sentences|
-
1.upto(resolve(sentence_count)) do
-
sentences << sentence(3)
-
end
-
end
-
end
-
-
1
def paragraph(sentence_count = 3, random_sentences_to_add = 3)
-
sentences(resolve(sentence_count) + rand(random_sentences_to_add.to_i).to_i).join(' ')
-
end
-
-
1
def paragraphs(paragraph_count = 3)
-
[].tap do |paragraphs|
-
1.upto(resolve(paragraph_count)) do
-
paragraphs << paragraph(3)
-
end
-
end
-
end
-
-
1
private
-
-
# If an array or range is passed, a random value will be selected.
-
# All other values are simply returned.
-
1
def resolve(value)
-
case value
-
when Array then sample(value)
-
when Range then rand value
-
else value
-
end
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Markdown < Base
-
1
class << self
-
-
1
def headers
-
"#{fetch('markdown.headers')} #{Lorem.word.capitalize}"
-
end
-
-
1
def emphasis
-
paragraph = Faker::Lorem.paragraph(3)
-
words = paragraph.split(' ')
-
position = rand(0..words.length - 1)
-
formatting = fetch('markdown.emphasis')
-
words[position] = "#{formatting}#{words[position]}#{formatting}"
-
words.join(' ')
-
end
-
-
1
def ordered_list
-
number = rand(1..10)
-
-
result = []
-
number.times do |i|
-
result << "#{i.to_s}. #{Faker::Lorem.sentence(1)} \n"
-
end
-
result.join('')
-
end
-
-
1
def unordered_list
-
number = rand(1..10)
-
-
result = []
-
number.times do |i|
-
result << "* #{Faker::Lorem.sentence(1)} \n"
-
end
-
result.join('')
-
end
-
-
1
def inline_code
-
"`#{Faker::Lorem.sentence(1)}`"
-
end
-
-
1
def block_code
-
"```ruby\n#{Lorem.sentence(1)}\n```"
-
end
-
-
1
def table
-
table = []
-
3.times do
-
table << "#{Lorem.word} | #{Lorem.word} | #{Lorem.word}"
-
end
-
table.join("\n")
-
end
-
-
1
def random
-
send(available_methods[rand(0..available_methods.length - 1)])
-
end
-
-
1
private
-
-
1
def available_methods
-
Markdown.public_methods(false) - Base.methods
-
end
-
-
end
-
end
-
end
-
1
module Faker
-
1
class Matz < Base
-
1
class << self
-
1
def quote
-
fetch('matz.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Measurement < Base
-
1
class << self
-
1
ALL = "all"
-
1
NONE = "none"
-
-
1
def height(amount = rand(10))
-
ensure_valid_amount(amount)
-
if amount == ALL
-
make_plural(fetch('measurement.height'))
-
elsif amount == NONE
-
fetch('measurement.height')
-
else
-
"#{amount.to_s} #{check_for_plural(fetch('measurement.height'), amount)}"
-
end
-
end
-
-
1
def length(amount = rand(10))
-
ensure_valid_amount(amount)
-
if amount == ALL
-
make_plural(fetch('measurement.length'))
-
elsif amount == NONE
-
fetch('measurement.length')
-
else
-
"#{amount.to_s} #{check_for_plural(fetch('measurement.length'), amount)}"
-
end
-
end
-
-
1
def volume(amount = rand(10))
-
ensure_valid_amount(amount)
-
if amount == ALL
-
make_plural(fetch('measurement.volume'))
-
elsif amount == NONE
-
fetch('measurement.volume')
-
else
-
"#{amount.to_s} #{check_for_plural(fetch('measurement.volume'), amount)}"
-
end
-
end
-
-
1
def weight(amount = rand(10))
-
ensure_valid_amount(amount)
-
if amount == ALL
-
make_plural(fetch('measurement.weight'))
-
elsif amount == NONE
-
fetch('measurement.weight')
-
else
-
"#{amount.to_s} #{check_for_plural(fetch('measurement.weight'), amount)}"
-
end
-
end
-
-
1
def metric_height(amount = rand(10))
-
ensure_valid_amount(amount)
-
if amount == ALL
-
make_plural(fetch('measurement.height'))
-
elsif amount == NONE
-
fetch('measurement.height')
-
else
-
"#{amount.to_s} #{check_for_plural(fetch('measurement.height'), amount)}"
-
end
-
end
-
-
1
def metric_length(amount = rand(10))
-
ensure_valid_amount(amount)
-
if amount == ALL
-
make_plural(fetch('measurement.length'))
-
elsif amount == NONE
-
fetch('measurement.length')
-
else
-
"#{amount.to_s} #{check_for_plural(fetch('measurement.length'), amount)}"
-
end
-
end
-
-
1
def metric_volume(amount = rand(10))
-
ensure_valid_amount(amount)
-
if amount == ALL
-
make_plural(fetch('measurement.volume'))
-
elsif amount == NONE
-
fetch('measurement.volume')
-
else
-
"#{amount.to_s} #{check_for_plural(fetch('measurement.volume'), amount)}"
-
end
-
end
-
-
1
def metric_weight(amount = rand(10))
-
ensure_valid_amount(amount)
-
if amount == ALL
-
make_plural(fetch('measurement.weight'))
-
elsif amount == NONE
-
fetch('measurement.weight')
-
else
-
"#{amount.to_s} #{check_for_plural(fetch('measurement.weight'), amount)}"
-
end
-
end
-
-
1
private
-
-
1
def ensure_valid_amount(amount)
-
unless amount == NONE || amount == ALL || amount.is_a?(Integer) || amount.is_a?(Float)
-
raise ArgumentError, 'invalid amount'
-
end
-
end
-
-
1
def check_for_plural(text, number)
-
if number && number != 1
-
make_plural(text)
-
else
-
text
-
end
-
end
-
-
1
def make_plural(text)
-
case text
-
when "foot"
-
"feet"
-
when "inch"
-
"inches"
-
when "fluid ounce"
-
"fluid ounces"
-
when "metric ton"
-
"metric tons"
-
else
-
"#{text}s"
-
end
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class MostInterestingManInTheWorld < Base
-
1
class << self
-
1
def quote
-
fetch('most_interesting_man_in_the_world.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Movie < Base
-
1
class << self
-
1
def quote
-
fetch('movie.quote')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Music < Base
-
1
class << self
-
1
def key
-
sample(keys) + sample(key_variants)
-
end
-
-
1
def chord
-
key + sample(chord_types)
-
end
-
-
1
def instrument
-
fetch('music.instruments')
-
end
-
-
1
def keys
-
['C', 'D', 'E', 'F', 'G', 'A', 'B']
-
end
-
-
1
def key_variants
-
['b', '#', '']
-
end
-
-
1
def key_types
-
['', 'm']
-
end
-
-
1
def chord_types
-
['', 'maj', '6', 'maj7', 'm', 'm7', '-7', '7', 'dom7', 'dim', 'dim7', 'm7b5']
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Name < Base
-
1
flexible :name
-
-
1
class << self
-
-
1
def name
-
parse('name.name')
-
end
-
-
1
def name_with_middle
-
parse('name.name_with_middle')
-
end
-
-
1
def first_name
-
fetch('name.first_name')
-
end
-
-
1
def last_name
-
fetch('name.last_name')
-
end
-
-
1
def prefix
-
fetch('name.prefix')
-
end
-
-
1
def suffix
-
fetch('name.suffix')
-
end
-
-
# Generate a buzzword-laden job title
-
# Wordlist from http://www.bullshitjob.com/title/
-
1
def title
-
"#{fetch('name.title.descriptor')} #{fetch('name.title.level')} #{fetch('name.title.job')}"
-
end
-
-
1
def job_titles
-
fetch_all('name.title.job')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Number < Base
-
1
class << self
-
1
def number(digits=10)
-
num = ''
-
if digits > 1
-
num = non_zero_digit
-
digits -= 1
-
end
-
num + leading_zero_number(digits)
-
end
-
-
1
def leading_zero_number(digits=10)
-
(1..digits).collect {digit}.join
-
end
-
-
1
def decimal_part(digits=10)
-
num = ''
-
if digits > 1
-
num = non_zero_digit
-
digits -= 1
-
end
-
leading_zero_number(digits) + num
-
end
-
-
1
def decimal(l_digits=5, r_digits=2)
-
l_d = self.number(l_digits)
-
r_d = self.decimal_part(r_digits)
-
"#{l_d}.#{r_d}"
-
end
-
-
1
def non_zero_digit
-
(rand(9) + 1).to_s
-
end
-
-
1
def digit
-
rand(10).to_s
-
end
-
-
1
def hexadecimal(digits=6)
-
hex = ""
-
digits.times { hex += rand(15).to_s(16) }
-
hex
-
end
-
-
1
def normal(mean=1, standard_deviation=1)
-
theta = 2 * Math::PI * rand
-
rho = Math.sqrt(-2 * Math.log(1 - rand))
-
scale = standard_deviation * rho
-
mean + scale * Math.cos(theta)
-
end
-
-
1
def between(from = 1.00, to = 5000.00)
-
Faker::Base::rand_in_range(from, to)
-
end
-
-
1
def positive(from = 1.00, to = 5000.00)
-
random_number = between(from, to)
-
greater_than_zero(random_number)
-
end
-
-
1
def negative(from = -5000.00, to = -1.00)
-
random_number = between(from, to)
-
less_than_zero(random_number)
-
end
-
-
1
private
-
-
1
def greater_than_zero(number)
-
should_be(number, :>)
-
end
-
-
1
def less_than_zero(number)
-
should_be(number, :<)
-
end
-
-
1
def should_be(number, method_to_compare)
-
if number.send(method_to_compare, 0)
-
number
-
else
-
number * -1
-
end
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Omniauth < Base
-
1
require 'time'
-
1
attr_reader :name,
-
:first_name,
-
:last_name
-
-
1
def initialize
-
@name = "#{Name.first_name} #{Name.last_name}"
-
@first_name = name.split(' ').first
-
@last_name = name.split(' ').last
-
end
-
-
1
class << self
-
1
def google
-
uid = Number.number(9)
-
auth = Omniauth.new()
-
email = "#{auth.first_name.downcase}@example.com"
-
{
-
provider: "google_oauth2",
-
uid: uid,
-
info: {
-
name: auth.name,
-
first_name: auth.first_name,
-
last_name: auth.last_name,
-
email: email,
-
image: image
-
},
-
credentials: {
-
token: Crypto.md5,
-
refresh_token: Crypto.md5,
-
expires_at: Time.forward.to_i,
-
expires: true
-
},
-
extra: {
-
raw_info: {
-
sub: uid,
-
email: email,
-
email_verified: random_boolean,
-
name: auth.name,
-
given_name: auth.first_name,
-
family_name: auth.last_name,
-
profile: "https://plus.google.com/#{uid}",
-
picture: image,
-
gender: gender,
-
birthday: Date.backward(36400).strftime("%Y-%m-%d"),
-
local: "en",
-
hd: "#{Company.name.downcase}.com"
-
},
-
},
-
id_info: {
-
"iss" => "accounts.google.com",
-
"at_hash" => Crypto.md5,
-
"email_verified" => "true",
-
"sub" => Number.number(28).to_s,
-
"azp" => "APP_ID",
-
"email" => email,
-
"aud" => "APP_ID",
-
"iat" => Number.number(10),
-
"exp" => Time.forward.to_i.to_s,
-
"openid_id" => "https://www.google.com/accounts/o8/id?id=#{uid}"
-
}
-
}
-
end
-
-
1
def facebook
-
uid = Number.number(7)
-
auth = Omniauth.new()
-
username = "#{auth.first_name.downcase[0]}#{auth.last_name.downcase}"
-
email = "#{auth.first_name.downcase}@#{auth.last_name.downcase}.com"
-
{
-
provider: "facebook",
-
uid: uid,
-
info: {
-
email: email,
-
name: auth.name,
-
first_name: auth.first_name,
-
last_name: auth.last_name,
-
image: image,
-
verified: random_boolean
-
},
-
credentials: {
-
token: Crypto.md5,
-
expires_at: Time.forward.to_i,
-
expires: true
-
},
-
extra: {
-
raw_info: {
-
id: uid,
-
name: auth.name,
-
first_name: auth.first_name,
-
last_name: auth.last_name,
-
link: "http://www.facebook.com/#{username}",
-
username: username,
-
location: {
-
id: Number.number(9),
-
name: city_state
-
},
-
gender: gender,
-
email: email,
-
timezone: timezone,
-
locale: 'en_US',
-
verified: random_boolean,
-
updated_time: Time.backward.iso8601
-
}
-
}
-
}
-
end
-
-
1
def twitter
-
uid = Number.number(6)
-
auth = Omniauth.new()
-
location = city_state
-
description = Lorem.sentence
-
{
-
provider: "twitter",
-
uid: uid,
-
info: {
-
nickname: auth.name.downcase.gsub(' ', ''),
-
name: auth.name,
-
location: location,
-
image: image,
-
description: description,
-
urls: {
-
Website: nil,
-
Twitter: "https://twitter.com/#{auth.name.downcase.gsub(' ', '')}"
-
}
-
},
-
credentials: {
-
token: Crypto.md5,
-
secret: Crypto.md5
-
},
-
extra: {
-
access_token: "",
-
raw_info: {
-
name: auth.name,
-
listed_count: random_number_from_range(1..10),
-
profile_sidebar_border_color: Color.hex_color,
-
url: nil,
-
lang: 'en',
-
statuses_count: random_number_from_range(1..1000),
-
profile_image_url: image,
-
profile_background_image_url_https: image,
-
location: location,
-
time_zone: Address.city,
-
follow_request_sent: random_boolean,
-
id: uid,
-
profile_background_tile: random_boolean,
-
profile_sidebar_fill_color: Color.hex_color,
-
followers_count: random_number_from_range(1..10000),
-
default_profile_image: random_boolean,
-
screen_name: '',
-
following: random_boolean,
-
utc_offset: timezone,
-
verified: random_boolean,
-
favourites_count: random_number_from_range(1..10),
-
profile_background_color: Color.hex_color,
-
is_translator: random_boolean,
-
friends_count: random_number_from_range(1..10000),
-
notifications: random_boolean,
-
geo_enabled: random_boolean,
-
profile_background_image_url: image,
-
protected: random_boolean,
-
description: description,
-
profile_link_color: Color.hex_color,
-
created_at: Time.backward.strftime("%a %b %d %H:%M:%S %z %Y"),
-
id_str: uid,
-
profile_image_url_https: image,
-
default_profile: random_boolean,
-
profile_use_background_image: random_boolean,
-
entities: {
-
description: {
-
urls: []
-
}
-
},
-
profile_text_color: Color.hex_color,
-
contributors_enabled: random_boolean
-
}
-
}
-
}
-
end
-
-
1
def linkedin
-
uid = Number.number(6)
-
auth = Omniauth.new()
-
first_name = auth.first_name.downcase
-
last_name = auth.last_name.downcase
-
email = "#{first_name}@#{last_name}.com"
-
location = city_state
-
description = Lorem.sentence
-
token = Crypto.md5
-
secret = Crypto.md5
-
industry = Commerce.department
-
url = "http://www.linkedin.com/in/#{first_name}#{last_name}"
-
{
-
"provider" => "linkedin",
-
"uid" => uid,
-
"info" => {
-
"name" => auth.name,
-
"email" => email,
-
"nickname" => auth.name,
-
"first_name" => auth.first_name,
-
"last_name" => auth.last_name,
-
"location" => location,
-
"description" => description,
-
"image" => image,
-
"phone" => PhoneNumber.phone_number,
-
"headline" => description,
-
"industry" => industry,
-
"urls" => {
-
"public_profile" => url
-
}
-
},
-
"credentials" => {
-
"token" => token,
-
"secret" => secret
-
},
-
"extra" => {
-
"access_token" => {
-
"token" => token,
-
"secret" => secret,
-
"consumer" => nil,
-
"params" => {
-
oauth_token: token,
-
oauth_token_secret: secret,
-
oauth_expires_in: Time.forward.to_i,
-
oauth_authorization_expires_in: Time.forward.to_i,
-
},
-
"response" => nil
-
},
-
"raw_info" => {
-
"firstName" => auth.first_name,
-
"headline" => description,
-
"id" => uid,
-
"industry" => industry,
-
"lastName" => auth.last_name,
-
"location" => {
-
"country" => { "code" => Address.country_code.downcase },
-
"name" => city_state.split(', ').first,
-
},
-
"pictureUrl" => image,
-
"publicProfileUrl" => url
-
}
-
}
-
}
-
end
-
-
1
def github
-
uid = Number.number(8)
-
auth = Omniauth.new()
-
first_name = auth.first_name.downcase
-
last_name = auth.last_name.downcase
-
login = "#{first_name}-#{last_name}"
-
html_url = "https://github.com/#{login}"
-
api_url = "https://api.github.com/users/#{login}"
-
email = "#{first_name}@example.com"
-
-
{
-
provider: "github",
-
uid: uid,
-
info: {
-
nickname: login,
-
email: email,
-
name: auth.name,
-
image: image,
-
urls:{
-
GitHub: html_url
-
}
-
},
-
credentials: {
-
token: Crypto.md5,
-
expires: false
-
},
-
extra: {
-
raw_info: {
-
login: login,
-
id: uid,
-
avatar_url: image,
-
gravatar_id: "",
-
url: api_url,
-
html_url: html_url,
-
followers_url: "#{api_url}/followers",
-
following_url: "#{api_url}/following{/other_user}",
-
gists_url: "#{api_url}/gists{/gist_id}",
-
starred_url: "#{api_url}/starred{/owner}{/repo}",
-
subscriptions_url: "#{api_url}/subscriptions",
-
organizations_url: "#{api_url}/orgs",
-
repos_url: "#{api_url}/repos",
-
events_url: "#{api_url}/events{/privacy}",
-
received_events_url: "#{api_url}/received_events",
-
type: "User",
-
site_admin: random_boolean,
-
name: auth.name,
-
company: nil,
-
blog: nil,
-
location: city_state,
-
email: email,
-
hireable: nil,
-
bio: nil,
-
public_repos: random_number_from_range(1..1000),
-
public_gists: random_number_from_range(1..1000),
-
followers: random_number_from_range(1..1000),
-
following: random_number_from_range(1..1000),
-
created_at: Time.backward(36400).iso8601,
-
updated_at: Time.backward(2).iso8601
-
}
-
}
-
}
-
-
end
-
-
1
private
-
-
1
def gender
-
shuffle(["male", "female"]).pop
-
end
-
-
1
def timezone
-
shuffle((-12..12).to_a).pop
-
end
-
-
1
def image
-
Placeholdit.image
-
end
-
-
1
def city_state
-
"#{Address.city}, #{Address.state}"
-
end
-
-
1
def random_number_from_range(range)
-
shuffle(range.to_a).pop
-
end
-
-
1
def random_boolean
-
shuffle([true, false]).pop
-
end
-
-
end
-
end
-
end
-
1
module Faker
-
1
class Overwatch < Base
-
1
class << self
-
1
def hero
-
fetch('overwatch.heroes')
-
end
-
-
1
def location
-
fetch('overwatch.locations')
-
end
-
-
1
def quote
-
fetch('overwatch.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class PhoneNumber < Base
-
1
class << self
-
1
def phone_number
-
parse('phone_number.formats')
-
end
-
-
1
def cell_phone
-
parse('cell_phone.formats')
-
end
-
-
# US only
-
1
def area_code
-
begin
-
fetch('phone_number.area_code')
-
rescue I18n::MissingTranslationData
-
nil
-
end
-
end
-
-
# US only
-
1
def exchange_code
-
begin
-
fetch('phone_number.exchange_code')
-
rescue I18n::MissingTranslationData
-
nil
-
end
-
end
-
-
# US only
-
# Can be used for both extensions and last four digits of phone number.
-
# Since extensions can be of variable length, this method taks a length parameter
-
1
def subscriber_number(length = 4)
-
begin
-
rand.to_s[2..(1 + length)]
-
rescue I18n::MissingTranslationData
-
nil
-
end
-
end
-
-
1
alias_method :extension, :subscriber_number
-
end
-
end
-
end
-
1
module Faker
-
1
class Placeholdit < Base
-
1
class << self
-
1
SUPPORTED_FORMATS = %w(png jpg gif jpeg)
-
-
1
def image(size = '300x300', format = 'png', background_color = nil, text_color = nil, text = nil)
-
raise ArgumentError, "Size should be specified in format 300x300" unless size.match(/^[0-9]+x[0-9]+$/)
-
raise ArgumentError, "Supported formats are #{SUPPORTED_FORMATS.join(', ')}" unless SUPPORTED_FORMATS.include?(format)
-
raise ArgumentError, "background_color must be a hex value without '#'" unless background_color.nil? || background_color.match(/((?:^\h{3}$)|(?:^\h{6}$)){1}(?!.*\H)/)
-
raise ArgumentError, "text_color must be a hex value without '#'" unless text_color.nil? || text_color.match(/((?:^\h{3}$)|(?:^\h{6}$)){1}(?!.*\H)/)
-
-
image_url = "https://placehold.it/#{size}.#{format}"
-
image_url += "/#{background_color}" if background_color
-
image_url += "/#{text_color}" if text_color
-
image_url += "?text=#{text}" if text
-
image_url
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Pokemon < Base
-
1
class << self
-
1
def name
-
fetch('pokemon.names')
-
end
-
-
1
def location
-
fetch('pokemon.locations')
-
end
-
-
1
def move
-
fetch('pokemon.moves')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class RickAndMorty < Base
-
1
class << self
-
1
def character
-
fetch('rick_and_morty.characters')
-
end
-
-
1
def location
-
fetch('rick_and_morty.locations')
-
end
-
-
1
def quote
-
fetch('rick_and_morty.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Robin < Base
-
1
class << self
-
1
def quote
-
fetch('robin.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class RockBand < Base
-
1
class << self
-
1
def name
-
fetch('rock_band.name')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class RuPaul < Base
-
1
flexible :rupaul
-
-
1
class << self
-
1
def quote
-
fetch('rupaul.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Seinfeld < Base
-
1
class << self
-
1
def character
-
fetch('seinfeld.character')
-
end
-
-
1
def quote
-
fetch('seinfeld.quote')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Shakespeare < Base
-
1
class << self
-
-
1
def hamlet_quote
-
sample(hamlet)
-
end
-
-
1
def as_you_like_it_quote
-
sample(as_you_like_it)
-
end
-
-
1
def king_richard_iii_quote
-
sample(king_richard_iii)
-
end
-
-
1
def romeo_and_juliet_quote
-
sample(romeo_and_juliet)
-
end
-
-
1
def hamlet
-
["To be, or not to be: that is the question.",
-
"Neither a borrower nor a lender be; For loan oft loses both itself and friend, and borrowing dulls the edge of husbandry.",
-
"This above all: to thine own self be true.",
-
"Though this be madness, yet there is method in 't.",
-
"That it should come to this!.",
-
"There is nothing either good or bad, but thinking makes it so.",
-
"What a piece of work is man! how noble in reason! how infinite in faculty! in form and moving how express and admirable! in action how like an angel! in apprehension how like a god! the beauty of the world, the paragon of animals! .",
-
"The lady doth protest too much, methinks.",
-
"In my mind's eye.",
-
"A little more than kin, and less than kind.",
-
"The play 's the thing wherein I'll catch the conscience of the king.",
-
"And it must follow, as the night the day, thou canst not then be false to any man.",
-
"Brevity is the soul of wit.",
-
"Doubt that the sun doth move, doubt truth to be a liar, but never doubt I love.",
-
"Rich gifts wax poor when givers prove unkind.",
-
"Do you think I am easier to be played on than a pipe?",
-
"I will speak daggers to her, but use none.",
-
"When sorrows come, they come not single spies, but in battalions."]
-
end
-
-
-
1
def as_you_like_it
-
["All the world 's a stage, and all the men and women merely players. They have their exits and their entrances; And one man in his time plays many parts.",
-
"Can one desire too much of a good thing?.",
-
"I like this place and willingly could waste my time in it.",
-
"How bitter a thing it is to look into happiness through another man's eyes!",
-
"Blow, blow, thou winter wind! Thou art not so unkind as man's ingratitude.",
-
"True is it that we have seen better days.",
-
"For ever and a day.",
-
"The fool doth think he is wise, but the wise man knows himself to be a fool."]
-
end
-
-
-
1
def king_richard_iii
-
["Now is the winter of our discontent.",
-
"A horse! a horse! my kingdom for a horse!.",
-
"Conscience is but a word that cowards use, devised at first to keep the strong in awe.",
-
"So wise so young, they say, do never live long.",
-
"Off with his head!",
-
"An honest tale speeds best, being plainly told.",
-
"The king's name is a tower of strength.",
-
"The world is grown so bad, that wrens make prey where eagles dare not perch."]
-
end
-
-
1
def romeo_and_juliet
-
["O Romeo, Romeo! wherefore art thou Romeo?.",
-
"It is the east, and Juliet is the sun.",
-
"Good Night, Good night! Parting is such sweet sorrow, that I shall say good night till it be morrow.",
-
"What's in a name? That which we call a rose by any other name would smell as sweet.",
-
"Wisely and slow; they stumble that run fast.",
-
"Tempt not a desperate man.",
-
"For you and I are past our dancing days.",
-
"O! she doth teach the torches to burn bright.",
-
"It seems she hangs upon the cheek of night like a rich jewel in an Ethiope's ear.",
-
"See, how she leans her cheek upon her hand! O that I were a glove upon that hand, that I might touch that cheek!.",
-
"Not stepping o'er the bounds of modesty."]
-
end
-
-
end
-
end
-
end
-
-
#encoding: utf-8
-
#frozen_string_literal: true
-
-
1
module Faker
-
-
1
class Simpsons < Base
-
-
1
def self.character
-
fetch('simpsons.characters')
-
end
-
-
1
def self.location
-
fetch('simpsons.locations')
-
end
-
-
1
def self.quote
-
fetch('simpsons.quotes')
-
end
-
-
end #class Simpsons
-
-
end #module Faker
-
1
module Faker
-
1
class SlackEmoji < Base
-
1
class << self
-
-
1
def people
-
fetch('slack_emoji.people')
-
end
-
-
1
def nature
-
fetch('slack_emoji.nature')
-
end
-
-
1
def food_and_drink
-
fetch('slack_emoji.food_and_drink')
-
end
-
-
1
def celebration
-
fetch('slack_emoji.celebration')
-
end
-
-
1
def activity
-
fetch('slack_emoji.activity')
-
end
-
-
1
def travel_and_places
-
fetch('slack_emoji.travel_and_places')
-
end
-
-
1
def objects_and_symbols
-
fetch('slack_emoji.objects_and_symbols')
-
end
-
-
1
def custom
-
fetch('slack_emoji.custom')
-
end
-
-
1
def emoji
-
parse('slack_emoji.emoji')
-
end
-
-
end
-
end
-
end
-
1
module Faker
-
1
class Space < Base
-
1
flexible :space
-
1
class << self
-
1
def planet
-
fetch('space.planet')
-
end
-
-
1
def moon
-
fetch('space.moon')
-
end
-
-
1
def galaxy
-
fetch('space.galaxy')
-
end
-
-
1
def nebula
-
fetch('space.nebula')
-
end
-
-
1
def star_cluster
-
fetch('space.star_cluster')
-
end
-
-
1
def constellation
-
fetch('space.constellation')
-
end
-
-
1
def star
-
fetch('space.star')
-
end
-
-
1
def agency
-
fetch('space.agency')
-
end
-
-
1
def agency_abv
-
fetch('space.agency_abv')
-
end
-
-
1
def nasa_space_craft
-
fetch('space.nasa_space_craft')
-
end
-
-
1
def company
-
fetch('space.company')
-
end
-
-
1
def distance_measurement
-
rand(10..100).to_s + ' ' + fetch('space.distance_measurement')
-
end
-
-
1
def meteorite
-
fetch('space.meteorite')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class StarTrek < Base
-
1
class << self
-
1
def character
-
fetch('star_trek.character')
-
end
-
-
1
def location
-
fetch('star_trek.location')
-
end
-
-
1
def specie
-
fetch('star_trek.specie')
-
end
-
-
1
def villain
-
fetch('star_trek.villain')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class StarWars < Base
-
1
class << self
-
1
def character
-
sample(characters)
-
end
-
-
1
def droid
-
sample(droids)
-
end
-
-
1
def planet
-
sample(planets)
-
end
-
-
1
def quote
-
sample(quotes)
-
end
-
-
1
def specie
-
sample(species)
-
end
-
-
1
def vehicle
-
sample(vehicles)
-
end
-
-
1
def wookiee_sentence
-
sentence = sample(wookiee_words).capitalize
-
-
rand(0..10).times { sentence += " " + sample(wookiee_words)}
-
-
sentence + sample(['.','?','!'])
-
end
-
-
1
def characters
-
['Padme Amidala', 'Jar Jar Binks', 'Borvo the Hutt', 'Darth Caedus', 'Boba Fett', 'Jabba the Hutt', 'Obi-Wan Kenobi', 'Darth Maul', 'Leia Organa', 'Sheev Palpatine',
-
'Kylo Ren', 'Darth Sidious', 'Anakin Skywalker', 'Luke Skywalker', 'Ben Solo', 'Han Solo', 'Darth Vader', 'Watto', 'Mace Windu', 'Yoda', 'Count Dooku', 'Sebulba',
-
'Qui-Gon Jinn', 'Chewbacca', 'Jango Fett', 'Lando Calrissian', 'Bail Organa', 'Wedge Antilles', 'Poe Dameron', 'Ki-Adi-Mundi', 'Nute Gunray', 'Panaka', 'Rune Haako']
-
end
-
-
1
def droids
-
['2-1B', '4-LOM', 'ASP', 'B2-RP', 'B1', 'BD-3000', 'FA-4', 'GH-7', 'GNK', 'LM-432', 'ID9', '11-4D', '2-1B', '327-T', '4-LOM', 'B4-D4',
-
'NR-N99', 'C-3PO', 'R2-D2', 'BB-8', 'R2-Q5']
-
end
-
-
1
def planets
-
['Alderaan', 'Bespin', 'Coruscant', 'DQar', 'Dagobah', 'Endor', 'Geonosis', 'Hoth',
-
'Hosnian Prime', 'Jakku', 'Kamino', 'Kashyyyk', 'Lothal', 'Mustafar', 'Naboo',
-
'Sullust', 'Takodana', 'Tatooine', 'Utapau', 'Yavin']
-
end
-
-
1
def quotes
-
["Never tell me the odds!", "Well, you said you wanted to be around when I made a mistake.", "You will never find a more wretched hive of scum and villainy. We must be cautious.", "Wars not make one great.",
-
"You do have your moments. Not many, but you have them.", "Now, witness the power of this fully operational battle station.", "No reward is worth this.", "Shut him up or shut him down.",
-
"I have a bad feeling about this.", "Who\'s the more foolish; the fool, or the fool who follows him?", "Would somebody get this big walking carpet out of my way?", "I find your lack of faith disturbing.",
-
"If they follow standard Imperial procedure, they\'ll dump their garbage before they go to light-speed.", "Only at the end do you realize the power of the Dark Side.", "Bounty hunters! We don\'t need this scum.",
-
"It\'s not impossible. I used to bullseye womp rats in my T-16 back home, they\'re not much bigger than two meters.", "Strike me down, and I will become more powerful than you could possibly imagine.",
-
"You know, that little droid is going to cause me a lot of trouble.", "If you\'re saying that coming here was a bad idea, I\'m starting to agree with you.", "You\'ll find I\'m full of surprises!",
-
"Aren\'t you a little short for a Stormtrooper?", "You are unwise to lower your defenses!", "R2-D2, you know better than to trust a strange computer!", "Truly wonderful, the mind of a child is.",
-
"That is why you fail.", "A Jedi uses the Force for knowledge and defense, never for attack.", "Adventure. Excitement. A Jedi craves not these things.", "Judge me by my size, do you?",
-
"Fear is the path to the dark side... fear leads to anger... anger leads to hate... hate leads to suffering.", "Do. Or do not. There is no try."]
-
end
-
-
1
def species
-
['Ewok', 'Hutt', 'Gungan', 'Ithorian', 'Jawa', 'Neimoidian', 'Sullustan', 'Wookiee', 'Mon Calamari']
-
end
-
-
1
def vehicles
-
['V-Wing Fighter', 'ATT Battle Tank', 'Naboo N-1 Starfighter', 'Vulture Droid', 'Republic Cruiser', 'Naboo Royal Starship', 'Gungan Bongo Submarine', 'Flash Speeder', 'Trade Federation Battleship', 'Millennium Falcon',
-
'Sith Infiltrator', 'AT-ST Walker', 'TIE Bomber', 'Imperial Shuttle', 'Sandcrawler', 'TIE Interceptor', 'Speeder Bike', 'Death Star', 'AT-AT Walker', 'Imperial Star Destroyer', 'X-Wing Fighter']
-
end
-
-
1
def wookiee_words
-
['wyaaaaaa', 'ruh', 'huewaa', 'muaa', 'mumwa', 'wua', 'ga', 'ma', 'ahuma', 'ooma', 'youw', 'kabukk', 'wyogg',
-
'gwyaaaag', 'roooarrgh', 'ur', 'ru', 'roo', 'hnn-rowr', 'yrroonn', 'nng', 'rarr']
-
end
-
-
1
alias_method :wookie_sentence, :wookiee_sentence
-
1
alias_method :wookie_words, :wookiee_words
-
end
-
end
-
end
-
1
module Faker
-
1
class Superhero < Base
-
1
class << self
-
1
def power
-
fetch('superhero.power')
-
end
-
-
1
def prefix
-
fetch('superhero.prefix')
-
end
-
-
1
def suffix
-
fetch('superhero.suffix')
-
end
-
-
1
def descriptor
-
fetch('superhero.descriptor')
-
end
-
-
1
def name
-
parse('superhero.name')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Team < Base
-
1
flexible :team
-
-
1
class << self
-
1
def name
-
parse('team.name')
-
end
-
-
1
def creature
-
fetch('team.creature')
-
end
-
-
1
def state
-
fetch('address.state')
-
end
-
-
1
def mascot
-
fetch('team.mascot')
-
end
-
end
-
-
end
-
end
-
1
module Faker
-
1
class TheFreshPrinceOfBelAir < Base
-
1
class << self
-
1
def character
-
fetch('the_fresh_prince_of_bel_air.characters')
-
end
-
-
1
def celebrity
-
fetch('the_fresh_prince_of_bel_air.celebrities')
-
end
-
-
1
def quote
-
fetch('the_fresh_prince_of_bel_air.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Time < Faker::Date
-
1
TIME_RANGES = {
-
:all => (0..23),
-
:day => (9..17),
-
:night => (18..23),
-
:morning => (6..11),
-
:afternoon => (12..17),
-
:evening => (17..21),
-
:midnight => (0..4)
-
}
-
-
1
class << self
-
1
def between(from, to, period = :all, format = nil)
-
time = period == :between ? rand(from..to) : date_with_random_time(super(from, to), period)
-
time_with_format(time, format)
-
end
-
-
1
def forward(days = 365, period = :all, format = nil)
-
time_with_format(date_with_random_time(super(days), period), format)
-
end
-
-
1
def backward(days = 365, period = :all, format = nil)
-
time_with_format(date_with_random_time(super(days), period), format)
-
end
-
-
1
private
-
-
1
def date_with_random_time(date, period)
-
::Time.local(date.year, date.month, date.day, hours(period), minutes, seconds)
-
end
-
-
1
def time_with_format(time, format)
-
format.nil? ? time : I18n.l( DateTime.parse(time.to_s), :format => format )
-
end
-
-
1
def hours(period)
-
raise ArgumentError, 'invalid period' unless TIME_RANGES.has_key? period
-
sample(TIME_RANGES[period].to_a)
-
end
-
-
1
def minutes
-
seconds
-
end
-
-
1
def seconds
-
sample((0..59).to_a)
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class TwinPeaks < Base
-
1
class << self
-
1
def character
-
fetch('twin_peaks.characters')
-
end
-
-
1
def location
-
fetch('twin_peaks.locations')
-
end
-
-
1
def quote
-
fetch('twin_peaks.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Twitter < Base
-
1
class << self
-
1
def user(include_status: true, include_email: false)
-
user_id = id
-
background_image_url = Faker::LoremPixel.image('600x400') # TODO: Make the dimensions change
-
profile_image_url = Faker::Avatar.image(user_id, '48x48')
-
user = {
-
id: user_id,
-
id_str: user_id.to_s,
-
contributors_enabled: Faker::Boolean.boolean(0.1),
-
created_at: created_at,
-
default_profile_image: Faker::Boolean.boolean(0.1),
-
default_profile: Faker::Boolean.boolean(0.1),
-
description: Faker::Lorem.sentence,
-
entities: user_entities,
-
favourites_count: Faker::Number.between(1, 100_000),
-
follow_request_sent: false,
-
followers_count: Faker::Number.between(1, 10_000_000),
-
following: false,
-
friends_count: Faker::Number.between(1, 100_000),
-
geo_enabled: Faker::Boolean.boolean(0.1),
-
is_translation_enabled: Faker::Boolean.boolean(0.1),
-
is_translator: Faker::Boolean.boolean(0.1),
-
lang: Faker::Address.country_code,
-
listed_count: Faker::Number.between(1, 1000),
-
location: "#{Faker::Address.city}, #{Faker::Address.state_abbr}, #{Faker::Address.country_code}",
-
name: Faker::Name.name,
-
notifications: false,
-
profile_background_color: Faker::Color.hex_color,
-
profile_background_image_url_https: background_image_url,
-
profile_background_image_url: background_image_url.sub('https://', 'http://'),
-
profile_background_tile: Faker::Boolean.boolean(0.1),
-
profile_banner_url: Faker::LoremPixel.image('1500x500'),
-
profile_image_url_https: profile_image_url,
-
profile_image_url: profile_image_url.sub('https://', 'http://'),
-
profile_link_color: Faker::Color.hex_color,
-
profile_sidebar_border_color: Faker::Color.hex_color,
-
profile_sidebar_fill_color: Faker::Color.hex_color,
-
profile_text_color: Faker::Color.hex_color,
-
profile_use_background_image: Faker::Boolean.boolean(0.4),
-
protected: Faker::Boolean.boolean(0.1),
-
screen_name: screen_name,
-
statuses_count: Faker::Number.between(1, 100_000),
-
time_zone: Faker::Address.time_zone,
-
url: Faker::Internet.url('example.com'),
-
utc_offset: utc_offset,
-
verified: Faker::Boolean.boolean(0.1)
-
}
-
user[:status] = Faker::Twitter.status(include_user: false) if include_status
-
user[:email] = Faker::Internet.safe_email if include_email
-
user
-
end
-
-
1
def status(include_user: true, include_photo: false)
-
status_id = id
-
status = {
-
id: status_id,
-
id_str: status_id.to_s,
-
contributors: nil,
-
coordinates: nil,
-
created_at: created_at,
-
entities: status_entities(include_photo: include_photo),
-
favorite_count: Faker::Number.between(1, 10_000),
-
favorited: false,
-
geo: nil,
-
in_reply_to_screen_name: nil,
-
in_reply_to_status_id: nil,
-
in_reply_to_user_id_str: nil,
-
in_reply_to_user_id: nil,
-
is_quote_status: false,
-
lang: Faker::Address.country_code,
-
nil: nil,
-
place: nil,
-
possibly_sensitive: Faker::Boolean.boolean(0.1),
-
retweet_count: Faker::Number.between(1, 10_000),
-
retweeted_status: nil,
-
retweeted: false,
-
source: "<a href=\"#{Faker::Internet.url('example.com')}\" rel=\"nofollow\">#{Faker::Company.name}</a>",
-
text: Faker::Lorem.sentence,
-
truncated: false
-
}
-
status[:user] = Faker::Twitter.user(include_status: false) if include_user
-
status[:text] = "#{status[:text]} #{status[:entities][:media].first[:url]}" if include_photo
-
status
-
end
-
-
1
def screen_name
-
Faker::Internet.user_name(nil, ['_'])[0...20]
-
end
-
-
1
private
-
-
1
def id
-
Faker::Number.between(1, 9_223_372_036_854_775_807)
-
end
-
-
1
def created_at
-
Faker::Date.between('2006-03-21', ::Date.today).strftime('%a %b %d %H:%M:%S %z %Y')
-
end
-
-
1
def utc_offset
-
Faker::Number.between(-43_200, 50_400)
-
end
-
-
1
def user_entities
-
{
-
url: {
-
urls: []
-
},
-
description: {
-
urls: []
-
}
-
}
-
end
-
-
1
def status_entities(include_photo: false)
-
entities = {
-
hashtags: [],
-
symbols: [],
-
user_mentions: [],
-
urls: []
-
}
-
entities[:media] = [photo_entity] if include_photo
-
entities
-
end
-
-
1
def photo_entity
-
# TODO: Dynamic image sizes
-
# TODO: Return accurate indices
-
media_url = Faker::LoremPixel.image('1064x600')
-
media_id = id
-
{
-
id: media_id,
-
id_str: media_id.to_s,
-
indices: [
-
103,
-
126
-
],
-
media_url: media_url.sub('https://', 'http://'),
-
media_url_https: media_url,
-
url: Faker::Internet.url('example.com'),
-
display_url: 'example.com',
-
expanded_url: Faker::Internet.url('example.com'),
-
type: 'photo',
-
sizes: {
-
medium: {
-
w: 1064,
-
h: 600,
-
resize: 'fit'
-
},
-
large: {
-
w: 1064,
-
h: 600,
-
resize: 'fit'
-
},
-
small: {
-
w: 680,
-
h: 383,
-
resize: 'fit'
-
},
-
thumb: {
-
w: 150,
-
h: 150,
-
resize: 'crop'
-
}
-
}
-
}
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class UmphreysMcgee < Base
-
1
class << self
-
1
def song
-
fetch('umphreys_mcgee.song')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class University < Base
-
1
flexible :university
-
-
1
class << self
-
1
def name
-
parse('university.name')
-
end
-
-
1
def prefix
-
fetch('university.prefix')
-
end
-
-
1
def suffix
-
fetch('university.suffix')
-
end
-
-
1
def greek_organization
-
organization = ''
-
3.times do |e|
-
organization = organization + sample(greek_alphabet)
-
end
-
organization
-
end
-
-
1
def greek_alphabet
-
['Α', 'B', 'Γ', 'Δ', 'E', 'Z', 'H', 'Θ', '|', 'K', 'Λ', 'M', 'N', 'Ξ',
-
'O', 'Π', 'P', 'Σ', 'T', 'Y', 'Φ', 'X', 'Ψ', 'Ω']
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Vehicle < Base
-
1
VIN_CHARS = '0123456789.ABCDEFGH..JKLMN.P.R..STUVWXYZ'
-
1
VIN_MAP = '0123456789X'
-
1
VIN_WEIGHTS = '8765432X098765432'
-
-
1
class << self
-
#ISO 3779
-
1
def vin
-
_, wmi, wmi_ext = sample(fetch_all('vehicle.manufacture'))
-
-
c = VIN_CHARS.split('').reject{ |n| n == '.'}
-
vehicle_identification_number = wmi.split('').concat( Array.new(14) { sample(c) } )
-
(12..14).to_a.each_with_index { |n, i| vehicle_identification_number[n] = wmi_ext[i] } unless wmi_ext.nil?
-
vehicle_identification_number[10] = fetch('vehicle.year')
-
vehicle_identification_number[8] = vin_checksum(vehicle_identification_number)
-
-
vehicle_identification_number.join.upcase
-
end
-
-
1
def manufacture
-
sample(fetch_all('vehicle.manufacture')).first
-
end
-
-
1
private
-
-
1
def calculate_vin_weight(character, i)
-
(VIN_CHARS.index(character) % 10) * VIN_MAP.index(VIN_WEIGHTS[i])
-
end
-
-
1
def vin_checksum(vehicle_identification_number)
-
VIN_MAP[vehicle_identification_number.each_with_index.map(&method(:calculate_vin_weight)).inject(:+) % 11]
-
end
-
-
end
-
end
-
end
-
1
module Faker
-
1
class VentureBros < Base
-
1
class << self
-
1
def character
-
fetch('venture_bros.character')
-
end
-
-
1
def organization
-
fetch('venture_bros.organization')
-
end
-
-
1
def vehicle
-
fetch('venture_bros.vehicle')
-
end
-
-
1
def quote
-
fetch('venture_bros.quote')
-
end
-
end
-
end
-
end
-
1
module Faker #:nodoc:
-
1
VERSION = "1.8.4"
-
end
-
1
module Faker
-
1
class Witcher < Base
-
1
class << self
-
1
def character
-
fetch('witcher.characters')
-
end
-
-
1
def witcher
-
fetch('witcher.witchers')
-
end
-
-
1
def school
-
fetch('witcher.schools')
-
end
-
-
1
def location
-
fetch('witcher.locations')
-
end
-
-
1
def quote
-
fetch('witcher.quotes')
-
end
-
-
1
def monster
-
fetch('witcher.monsters')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class WorldOfWarcraft < Base
-
1
class << self
-
1
def hero
-
fetch('world_of_warcraft.hero')
-
end
-
-
1
def quote
-
fetch('world_of_warcraft.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Yoda < Base
-
1
class << self
-
# from: http://morecoolquotes.com/famous-yoda-quotes/
-
1
def quote
-
fetch('yoda.quotes')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Zelda < Base
-
1
flexible :space
-
1
class << self
-
1
def game
-
fetch('zelda.games')
-
end
-
-
1
def character
-
fetch('zelda.characters')
-
end
-
-
1
def location
-
fetch('zelda.locations')
-
end
-
end
-
end
-
end
-
# coding: utf-8
-
1
module Faker
-
1
module Char
-
1
def self.prepare(string)
-
result = romanize_cyrillic string
-
result = fix_umlauts result
-
result.gsub(/\W/, '').downcase
-
end
-
-
1
def self.fix_umlauts(string)
-
string.gsub(/[äöüß]/i) do |match|
-
case match.downcase
-
when "ä" 'ae'
-
when "ö" 'oe'
-
when "ü" 'ue'
-
when "ß" 'ss'
-
end
-
end
-
end
-
-
1
def self.romanize_cyrillic(string)
-
if Faker::Config.locale == "uk"
-
# Based on conventions abopted by BGN/PCGN for Ukrainian
-
uk_chars = {
-
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'h', 'ґ' => 'g', 'д' => 'd',
-
'е' => 'e', 'є' => 'ye', 'ж' => 'zh', 'з' => 'z', 'и' => 'y', 'і' => 'i',
-
'ї' => 'yi', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n',
-
'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u',
-
'ф' => 'f', 'х' => 'kh', 'ц' => 'ts', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'shch',
-
'ю' => 'yu', 'я' => 'ya',
-
'А' => 'a', 'Б' => 'b', 'В' => 'v', 'Г' => 'h', 'Ґ' => 'g', 'Д' => 'd',
-
'Е' => 'e', 'Є' => 'ye', 'Ж' => 'zh', 'З' => 'z', 'И' => 'y', 'І' => 'i',
-
'Ї' => 'yi', 'Й' => 'y', 'К' => 'k', 'Л' => 'l', 'М' => 'm', 'Н' => 'n',
-
'О' => 'o', 'П' => 'p', 'Р' => 'r', 'С' => 's', 'Т' => 't', 'У' => 'u',
-
'Ф' => 'f', 'Х' => 'kh', 'Ц' => 'ts', 'Ч' => 'ch', 'Ш' => 'sh', 'Щ' => 'shch',
-
'Ю' => 'yu', 'Я' => 'ya',
-
'ь' => '' # Ignore symbol, because its standard presentation is not allowed in URLs
-
}
-
return string.gsub(/[а-яА-ЯіїєґІЇЄҐ]/, uk_chars)
-
end
-
string
-
end
-
end
-
end
-
1
module Faker
-
1
class UniqueGenerator
-
1
def initialize(generator, max_retries)
-
@generator = generator
-
@max_retries = max_retries
-
@previous_results = Hash.new { |hash, key| hash[key] = Set.new }
-
end
-
-
1
def method_missing(name, *arguments)
-
@max_retries.times do
-
result = @generator.public_send(name, *arguments)
-
-
next if @previous_results[[name, arguments]].include?(result)
-
-
@previous_results[[name, arguments]] << result
-
return result
-
end
-
-
raise RetryLimitExceeded
-
end
-
-
1
RetryLimitExceeded = Class.new(StandardError)
-
-
1
def clear
-
@previous_results.clear
-
end
-
-
1
def self.clear
-
ObjectSpace.each_object(self, &:clear)
-
end
-
end
-
end
-
1
require 'global_id/global_id'
-
-
1
autoload :SignedGlobalID, 'global_id/signed_global_id'
-
-
1
class GlobalID
-
1
autoload :Locator, 'global_id/locator'
-
1
autoload :Identification, 'global_id/identification'
-
1
autoload :Verifier, 'global_id/verifier'
-
end
-
1
require 'active_support'
-
1
require 'active_support/core_ext/string/inflections' # For #model_class constantize
-
1
require 'active_support/core_ext/array/access'
-
1
require 'active_support/core_ext/object/try' # For #find
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'global_id/uri/gid'
-
-
1
class GlobalID
-
1
class << self
-
1
attr_reader :app
-
-
1
def create(model, options = {})
-
if app = options.fetch(:app) { GlobalID.app }
-
params = options.except(:app, :verifier, :for)
-
new URI::GID.create(app, model, params), options
-
else
-
raise ArgumentError, 'An app is required to create a GlobalID. ' \
-
'Pass the :app option or set the default GlobalID.app.'
-
end
-
end
-
-
1
def find(gid, options = {})
-
parse(gid, options).try(:find, options)
-
end
-
-
1
def parse(gid, options = {})
-
gid.is_a?(self) ? gid : new(gid, options)
-
rescue URI::Error
-
parse_encoded_gid(gid, options)
-
end
-
-
1
def app=(app)
-
1
@app = URI::GID.validate_app(app)
-
end
-
-
1
private
-
1
def parse_encoded_gid(gid, options)
-
new(Base64.urlsafe_decode64(repad_gid(gid)), options) rescue nil
-
end
-
-
# We removed the base64 padding character = during #to_param, now we're adding it back so decoding will work
-
1
def repad_gid(gid)
-
padding_chars = gid.length.modulo(4).zero? ? 0 : (4 - gid.length.modulo(4))
-
gid + ('=' * padding_chars)
-
end
-
end
-
-
1
attr_reader :uri
-
1
delegate :app, :model_name, :model_id, :params, :to_s, to: :uri
-
-
1
def initialize(gid, options = {})
-
@uri = gid.is_a?(URI::GID) ? gid : URI::GID.parse(gid)
-
end
-
-
1
def find(options = {})
-
Locator.locate self, options
-
end
-
-
1
def model_class
-
model_name.constantize
-
end
-
-
1
def ==(other)
-
other.is_a?(GlobalID) && @uri == other.uri
-
end
-
-
1
def to_param
-
# remove the = padding character for a prettier param -- it'll be added back in parse_encoded_gid
-
Base64.urlsafe_encode64(to_s).sub(/=+$/, '')
-
end
-
end
-
1
require 'active_support/concern'
-
-
1
class GlobalID
-
1
module Identification
-
1
extend ActiveSupport::Concern
-
-
1
def to_global_id(options = {})
-
@global_id ||= GlobalID.create(self, options)
-
end
-
1
alias to_gid to_global_id
-
-
1
def to_gid_param(options = {})
-
to_global_id(options).to_param
-
end
-
-
1
def to_signed_global_id(options = {})
-
SignedGlobalID.create(self, options)
-
end
-
1
alias to_sgid to_signed_global_id
-
-
1
def to_sgid_param(options = {})
-
to_signed_global_id(options).to_param
-
end
-
end
-
end
-
1
begin
-
1
require 'rails/railtie'
-
rescue LoadError
-
else
-
1
require 'global_id'
-
1
require 'active_support'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
class GlobalID
-
# = GlobalID Railtie
-
# Set up the signed GlobalID verifier and include Active Record support.
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.global_id = ActiveSupport::OrderedOptions.new
-
-
1
initializer 'global_id' do |app|
-
-
1
app.config.global_id.app ||= app.railtie_name.remove('_application').dasherize
-
1
GlobalID.app = app.config.global_id.app
-
-
1
app.config.global_id.expires_in ||= 1.month
-
1
SignedGlobalID.expires_in = app.config.global_id.expires_in
-
-
1
config.after_initialize do
-
1
app.config.global_id.verifier ||= begin
-
1
GlobalID::Verifier.new(app.key_generator.generate_key('signed_global_ids'))
-
rescue ArgumentError
-
nil
-
end
-
1
SignedGlobalID.verifier = app.config.global_id.verifier
-
end
-
-
1
ActiveSupport.on_load(:active_record) do
-
1
require 'global_id/identification'
-
1
send :include, GlobalID::Identification
-
end
-
end
-
end
-
end
-
-
end
-
1
require 'global_id'
-
1
require 'active_support/message_verifier'
-
1
require 'time'
-
-
1
class SignedGlobalID < GlobalID
-
1
class ExpiredMessage < StandardError; end
-
-
1
class << self
-
1
attr_accessor :verifier
-
-
1
def parse(sgid, options = {})
-
super verify(sgid.to_s, options), options
-
end
-
-
# Grab the verifier from options and fall back to SignedGlobalID.verifier.
-
# Raise ArgumentError if neither is available.
-
1
def pick_verifier(options)
-
options.fetch :verifier do
-
verifier || raise(ArgumentError, 'Pass a `verifier:` option with an `ActiveSupport::MessageVerifier` instance, or set a default SignedGlobalID.verifier.')
-
end
-
end
-
-
1
attr_accessor :expires_in
-
-
1
DEFAULT_PURPOSE = "default"
-
-
1
def pick_purpose(options)
-
options.fetch :for, DEFAULT_PURPOSE
-
end
-
-
1
private
-
1
def verify(sgid, options)
-
metadata = pick_verifier(options).verify(sgid)
-
-
raise_if_expired(metadata['expires_at'])
-
-
metadata['gid'] if pick_purpose(options) == metadata['purpose']
-
rescue ActiveSupport::MessageVerifier::InvalidSignature, ExpiredMessage
-
nil
-
end
-
-
1
def raise_if_expired(expires_at)
-
if expires_at && Time.now.utc > Time.iso8601(expires_at)
-
raise ExpiredMessage, 'This signed global id has expired.'
-
end
-
end
-
end
-
-
1
attr_reader :verifier, :purpose, :expires_at
-
-
1
def initialize(gid, options = {})
-
super
-
@verifier = self.class.pick_verifier(options)
-
@purpose = self.class.pick_purpose(options)
-
@expires_at = pick_expiration(options)
-
end
-
-
1
def to_s
-
@sgid ||= @verifier.generate(to_h)
-
end
-
1
alias to_param to_s
-
-
1
def to_h
-
# Some serializers decodes symbol keys to symbols, others to strings.
-
# Using string keys remedies that.
-
{ 'gid' => @uri.to_s, 'purpose' => purpose, 'expires_at' => encoded_expiration }
-
end
-
-
1
def ==(other)
-
super && @purpose == other.purpose
-
end
-
-
1
private
-
1
def encoded_expiration
-
expires_at.utc.iso8601(3) if expires_at
-
end
-
-
1
def pick_expiration(options)
-
return options[:expires_at] if options.key?(:expires_at)
-
-
if expires_in = options.fetch(:expires_in) { self.class.expires_in }
-
expires_in.from_now
-
end
-
end
-
end
-
1
require 'uri/generic'
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module URI
-
1
class GID < Generic
-
# URI::GID encodes an app unique reference to a specific model as an URI.
-
# It has the components: app name, model class name, model id and params.
-
# All components except params are required.
-
#
-
# The URI format looks like "gid://app/model_name/model_id".
-
#
-
# Simple metadata can be stored in params. Useful if your app has multiple databases,
-
# for instance, and you need to find out which one to look up the model in.
-
#
-
# Params will be encoded as query parameters like so
-
# "gid://app/model_name/model_id?key=value&another_key=another_value".
-
#
-
# Params won't be typecast, they're always strings.
-
# For convenience params can be accessed using both strings and symbol keys.
-
#
-
# Multi value params aren't supported. Any params encoding multiple values under
-
# the same key will return only the last value. For example, when decoding
-
# params like "key=first_value&key=last_value" key will only be last_value.
-
#
-
# Read the documentation for +parse+, +create+ and +build+ for more.
-
1
alias :app :host
-
1
attr_reader :model_name, :model_id, :params
-
-
# Raised when creating a Global ID for a model without an id
-
1
class MissingModelIdError < URI::InvalidComponentError; end
-
-
1
class << self
-
# Validates +app+'s as URI hostnames containing only alphanumeric characters
-
# and hyphens. An ArgumentError is raised if +app+ is invalid.
-
#
-
# URI::GID.validate_app('bcx') # => 'bcx'
-
# URI::GID.validate_app('foo-bar') # => 'foo-bar'
-
#
-
# URI::GID.validate_app(nil) # => ArgumentError
-
# URI::GID.validate_app('foo/bar') # => ArgumentError
-
1
def validate_app(app)
-
1
parse("gid://#{app}/Model/1").app
-
rescue URI::Error
-
raise ArgumentError, 'Invalid app name. ' \
-
'App names must be valid URI hostnames: alphanumeric and hyphen characters only.'
-
end
-
-
# Create a new URI::GID by parsing a gid string with argument check.
-
#
-
# URI::GID.parse 'gid://bcx/Person/1?key=value'
-
#
-
# This differs from URI() and URI.parse which do not check arguments.
-
#
-
# URI('gid://bcx') # => URI::GID instance
-
# URI.parse('gid://bcx') # => URI::GID instance
-
# URI::GID.parse('gid://bcx/') # => raises URI::InvalidComponentError
-
1
def parse(uri)
-
1
generic_components = URI.split(uri) << nil << true # nil parser, true arg_check
-
1
new(*generic_components)
-
end
-
-
# Shorthand to build a URI::GID from an app, a model and optional params.
-
#
-
# URI::GID.create('bcx', Person.find(5), database: 'superhumans')
-
1
def create(app, model, params = nil)
-
build app: app, model_name: model.class.name, model_id: model.id, params: params
-
end
-
-
# Create a new URI::GID from components with argument check.
-
#
-
# The allowed components are app, model_name, model_id and params, which can be
-
# either a hash or an array.
-
#
-
# Using a hash:
-
#
-
# URI::GID.build(app: 'bcx', model_name: 'Person', model_id: '1', params: { key: 'value' })
-
#
-
# Using an array, the arguments must be in order [app, model_name, model_id, params]:
-
#
-
# URI::GID.build(['bcx', 'Person', '1', key: 'value'])
-
1
def build(args)
-
parts = Util.make_components_hash(self, args)
-
parts[:host] = parts[:app]
-
parts[:path] = "/#{parts[:model_name]}/#{CGI.escape(parts[:model_id].to_s)}"
-
-
if parts[:params] && !parts[:params].empty?
-
parts[:query] = URI.encode_www_form(parts[:params])
-
end
-
-
super parts
-
end
-
end
-
-
1
def to_s
-
# Implement #to_s to avoid no implicit conversion of nil into string when path is nil
-
"gid://#{app}#{path}#{'?' + query if query}"
-
end
-
-
1
protected
-
1
def set_path(path)
-
1
set_model_components(path) unless defined?(@model_name) && @model_id
-
1
super
-
end
-
-
# Ruby 2.2 uses #query= instead of #set_query
-
1
def query=(query)
-
1
set_params parse_query_params(query)
-
1
super
-
end
-
-
# Ruby 2.1 or less uses #set_query to assign the query
-
1
def set_query(query)
-
set_params parse_query_params(query)
-
super
-
end
-
-
1
def set_params(params)
-
1
@params = params
-
end
-
-
1
private
-
1
COMPONENT = [ :scheme, :app, :model_name, :model_id, :params ].freeze
-
-
# Extracts model_name and model_id from the URI path.
-
1
PATH_REGEXP = %r(\A/([^/]+)/?([^/]+)?\z)
-
-
1
def check_host(host)
-
1
validate_component(host)
-
1
super
-
end
-
-
1
def check_path(path)
-
1
validate_component(path)
-
1
set_model_components(path, true)
-
end
-
-
1
def check_scheme(scheme)
-
1
if scheme == 'gid'
-
1
super
-
else
-
raise URI::BadURIError, "Not a gid:// URI scheme: #{inspect}"
-
end
-
end
-
-
1
def set_model_components(path, validate = false)
-
1
_, model_name, model_id = path.match(PATH_REGEXP).to_a
-
1
model_id = CGI.unescape(model_id) if model_id
-
-
1
validate_component(model_name) && validate_model_id(model_id, model_name) if validate
-
-
1
@model_name = model_name
-
1
@model_id = model_id
-
end
-
-
1
def validate_component(component)
-
3
return component unless component.blank?
-
-
raise URI::InvalidComponentError,
-
"Expected a URI like gid://app/Person/1234: #{inspect}"
-
end
-
-
1
def validate_model_id(model_id, model_name)
-
1
return model_id unless model_id.blank?
-
-
raise MissingModelIdError, "Unable to create a Global ID for " \
-
"#{model_name} without a model id."
-
end
-
-
1
def parse_query_params(query)
-
1
Hash[URI.decode_www_form(query)].with_indifferent_access if query
-
end
-
end
-
-
1
@@schemes['GID'] = GID
-
end
-
1
require 'active_support'
-
1
require 'active_support/message_verifier'
-
-
1
class GlobalID
-
1
class Verifier < ActiveSupport::MessageVerifier
-
1
private
-
1
def encode(data)
-
::Base64.urlsafe_encode64(data)
-
end
-
-
1
def decode(data)
-
::Base64.urlsafe_decode64(data)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'haml/version'
-
-
# The module that contains everything Haml-related:
-
#
-
# * {Haml::Parser} is Haml's parser.
-
# * {Haml::Compiler} is Haml's compiler.
-
# * {Haml::Engine} is the class used to render Haml within Ruby code.
-
# * {Haml::Options} is where Haml's runtime options are defined.
-
# * {Haml::Error} is raised when Haml encounters an error.
-
#
-
# Also see the {file:REFERENCE.md full Haml reference}.
-
1
module Haml
-
-
1
def self.init_rails(*args)
-
# Maintain this as a no-op for any libraries that may be depending on the
-
# previous definition here.
-
end
-
-
end
-
-
1
require 'haml/util'
-
1
require 'haml/engine'
-
1
require 'haml/railtie' if defined?(Rails::Railtie)
-
# frozen_string_literal: true
-
1
module Haml
-
1
module AttributeBuilder
-
# https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
-
1
INVALID_ATTRIBUTE_NAME_REGEX = /[ \0"'>\/=]/
-
-
1
class << self
-
1
def build_attributes(is_html, attr_wrapper, escape_attrs, hyphenate_data_attrs, attributes = {})
-
# @TODO this is an absolutely ridiculous amount of arguments. At least
-
# some of this needs to be moved into an instance method.
-
31
join_char = hyphenate_data_attrs ? '-' : '_'
-
-
31
attributes.each do |key, value|
-
31
if value.is_a?(Hash)
-
data_attributes = attributes.delete(key)
-
data_attributes = flatten_data_attributes(data_attributes, '', join_char)
-
data_attributes = build_data_keys(data_attributes, hyphenate_data_attrs, key)
-
verify_attribute_names!(data_attributes.keys)
-
attributes = data_attributes.merge(attributes)
-
end
-
end
-
-
31
result = attributes.collect do |attr, value|
-
31
next if value.nil?
-
-
31
value = filter_and_join(value, ' ') if attr == 'class'
-
31
value = filter_and_join(value, '_') if attr == 'id'
-
-
31
if value == true
-
next " #{attr}" if is_html
-
next " #{attr}=#{attr_wrapper}#{attr}#{attr_wrapper}"
-
elsif value == false
-
next
-
end
-
-
31
value =
-
if escape_attrs == :once
-
Haml::Helpers.escape_once(value.to_s)
-
elsif escape_attrs
-
31
Haml::Helpers.html_escape(value.to_s)
-
else
-
value.to_s
-
end
-
31
" #{attr}=#{attr_wrapper}#{value}#{attr_wrapper}"
-
end
-
31
result.compact!
-
31
result.sort!
-
31
result.join
-
end
-
-
# @return [String, nil]
-
1
def filter_and_join(value, separator)
-
23
return '' if (value.respond_to?(:empty?) && value.empty?)
-
-
23
if value.is_a?(Array)
-
value = value.flatten
-
value.map! {|item| item ? item.to_s : nil}
-
value.compact!
-
value = value.join(separator)
-
else
-
23
value = value ? value.to_s : nil
-
end
-
23
!value.nil? && !value.empty? && value
-
end
-
-
# Merges two attribute hashes.
-
# This is the same as `to.merge!(from)`,
-
# except that it merges id, class, and data attributes.
-
#
-
# ids are concatenated with `"_"`,
-
# and classes are concatenated with `" "`.
-
# data hashes are simply merged.
-
#
-
# Destructively modifies `to`.
-
#
-
# @param to [{String => String,Hash}] The attribute hash to merge into
-
# @param from [{String => Object}] The attribute hash to merge from
-
# @return [{String => String,Hash}] `to`, after being merged
-
1
def merge_attributes!(to, from)
-
5
from.keys.each do |key|
-
8
to[key] = merge_value(key, to[key], from[key])
-
end
-
5
to
-
end
-
-
# Merge multiple values to one attribute value. No destructive operation.
-
#
-
# @param key [String]
-
# @param values [Array<Object>]
-
# @return [String,Hash]
-
1
def merge_values(key, *values)
-
values.inject(nil) do |to, from|
-
merge_value(key, to, from)
-
end
-
end
-
-
1
def verify_attribute_names!(attribute_names)
-
159
attribute_names.each do |attribute_name|
-
31
if attribute_name =~ INVALID_ATTRIBUTE_NAME_REGEX
-
raise InvalidAttributeNameError.new("Invalid attribute name '#{attribute_name}' was rendered")
-
end
-
end
-
end
-
-
1
private
-
-
# Merge a couple of values to one attribute value. No destructive operation.
-
#
-
# @param to [String,Hash,nil]
-
# @param from [Object]
-
# @return [String,Hash]
-
1
def merge_value(key, to, from)
-
8
if from.kind_of?(Hash) || to.kind_of?(Hash)
-
from = { nil => from } if !from.is_a?(Hash)
-
to = { nil => to } if !to.is_a?(Hash)
-
to.merge(from)
-
8
elsif key == 'id'
-
merged_id = filter_and_join(from, '_')
-
if to && merged_id
-
merged_id = "#{to}_#{merged_id}"
-
elsif to || merged_id
-
merged_id ||= to
-
end
-
merged_id
-
8
elsif key == 'class'
-
merged_class = filter_and_join(from, ' ')
-
if to && merged_class
-
merged_class = (merged_class.split(' ') | to.split(' ')).sort.join(' ')
-
elsif to || merged_class
-
merged_class ||= to
-
end
-
merged_class
-
else
-
8
from
-
end
-
end
-
-
1
def build_data_keys(data_hash, hyphenate, attr_name="data")
-
Hash[data_hash.map do |name, value|
-
if name == nil
-
[attr_name, value]
-
elsif hyphenate
-
["#{attr_name}-#{name.to_s.tr('_', '-')}", value]
-
else
-
["#{attr_name}-#{name}", value]
-
end
-
end]
-
end
-
-
1
def flatten_data_attributes(data, key, join_char, seen = [])
-
return {key => data} unless data.is_a?(Hash)
-
-
return {key => nil} if seen.include? data.object_id
-
seen << data.object_id
-
-
data.sort {|x, y| x[0].to_s <=> y[0].to_s}.inject({}) do |hash, (k, v)|
-
joined = key == '' ? k : [key, k].join(join_char)
-
hash.merge! flatten_data_attributes(v, joined, join_char, seen)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'haml/attribute_parser'
-
-
1
module Haml
-
1
class AttributeCompiler
-
# @param type [Symbol] :static or :dynamic
-
# @param key [String]
-
# @param value [String] Actual string value for :static type, value's Ruby literal for :dynamic type.
-
1
class AttributeValue < Struct.new(:type, :key, :value)
-
# @return [String] A Ruby literal of value.
-
1
def to_literal
-
62
case type
-
when :static
-
62
Haml::Util.inspect_obj(value)
-
when :dynamic
-
value
-
end
-
end
-
-
# Key's substring before a hyphen. This is necessary because values with the same
-
# base_key can conflict by Haml::AttributeBuidler#build_data_keys.
-
1
def base_key
-
31
key.split('-', 2).first
-
end
-
end
-
-
# Returns a script to render attributes on runtime.
-
#
-
# @param attributes [Hash]
-
# @param object_ref [String,:nil]
-
# @param dynamic_attributes [DynamicAttributes]
-
# @return [String] Attributes rendering code
-
1
def self.runtime_build(attributes, object_ref, dynamic_attributes)
-
"_hamlout.attributes(#{Haml::Util.inspect_obj(attributes)}, #{object_ref},#{dynamic_attributes.to_literal})"
-
end
-
-
# @param options [Haml::Options]
-
1
def initialize(options)
-
22
@is_html = [:html4, :html5].include?(options[:format])
-
22
@attr_wrapper = options[:attr_wrapper]
-
22
@escape_attrs = options[:escape_attrs]
-
22
@hyphenate_data_attrs = options[:hyphenate_data_attrs]
-
end
-
-
# Returns Temple expression to render attributes.
-
#
-
# @param attributes [Hash]
-
# @param object_ref [String,:nil]
-
# @param dynamic_attributes [DynamicAttributes]
-
# @return [Array] Temple expression
-
1
def compile(attributes, object_ref, dynamic_attributes)
-
159
if object_ref != :nil || !AttributeParser.available?
-
return [:dynamic, AttributeCompiler.runtime_build(attributes, object_ref, dynamic_attributes)]
-
end
-
-
159
parsed_hashes = [dynamic_attributes.new, dynamic_attributes.old].compact.map do |attribute_hash|
-
unless (hash = AttributeParser.parse(attribute_hash))
-
return [:dynamic, AttributeCompiler.runtime_build(attributes, object_ref, dynamic_attributes)]
-
end
-
hash
-
end
-
159
attribute_values = build_attribute_values(attributes, parsed_hashes)
-
159
AttributeBuilder.verify_attribute_names!(attribute_values.map(&:key))
-
-
159
values_by_base_key = attribute_values.group_by(&:base_key)
-
[:multi, *values_by_base_key.keys.sort.map { |base_key|
-
31
compile_attribute_values(values_by_base_key[base_key])
-
159
}]
-
end
-
-
1
private
-
-
# Returns array of AttributeValue instances from static attributes and dynamic_attributes. For each key,
-
# the values' order in returned value is preserved in the same order as Haml::Buffer#attributes's merge order.
-
#
-
# @param attributes [{ String => String }]
-
# @param parsed_hashes [{ String => String }]
-
# @return [Array<AttributeValue>]
-
1
def build_attribute_values(attributes, parsed_hashes)
-
159
[].tap do |attribute_values|
-
159
attributes.each do |key, static_value|
-
31
attribute_values << AttributeValue.new(:static, key, static_value)
-
end
-
159
parsed_hashes.each do |parsed_hash|
-
parsed_hash.each do |key, dynamic_value|
-
attribute_values << AttributeValue.new(:dynamic, key, dynamic_value)
-
end
-
end
-
end
-
end
-
-
# Compiles attribute values with the same base_key to Temple expression.
-
#
-
# @param values [Array<AttributeValue>] `base_key`'s results are the same. `key`'s result may differ.
-
# @return [Array] Temple expression
-
1
def compile_attribute_values(values)
-
31
if values.map(&:key).uniq.size == 1
-
31
compile_attribute(values.first.key, values)
-
else
-
runtime_build(values)
-
end
-
end
-
-
# @param values [Array<AttributeValue>]
-
# @return [Array] Temple expression
-
1
def runtime_build(values)
-
hash_content = values.group_by(&:key).map do |key, values_for_key|
-
"#{frozen_string(key)} => #{merged_value(key, values_for_key)}"
-
end.join(', ')
-
[:dynamic, "_hamlout.attributes({ #{hash_content} }, nil)"]
-
end
-
-
# Renders attribute values statically.
-
#
-
# @param values [Array<AttributeValue>]
-
# @return [Array] Temple expression
-
1
def static_build(values)
-
31
hash_content = values.group_by(&:key).map do |key, values_for_key|
-
31
"#{frozen_string(key)} => #{merged_value(key, values_for_key)}"
-
end.join(', ')
-
-
31
arguments = [@is_html, @attr_wrapper, @escape_attrs, @hyphenate_data_attrs]
-
31
code = "::Haml::AttributeBuilder.build_attributes"\
-
124
"(#{arguments.map { |a| Haml::Util.inspect_obj(a) }.join(', ')}, { #{hash_content} })"
-
31
[:static, eval(code).to_s]
-
end
-
-
# @param key [String]
-
# @param values [Array<AttributeValue>]
-
# @return [String]
-
1
def merged_value(key, values)
-
31
if values.size == 1
-
31
values.first.to_literal
-
else
-
"::Haml::AttributeBuilder.merge_values(#{frozen_string(key)}, #{values.map(&:to_literal).join(', ')})"
-
end
-
end
-
-
# @param str [String]
-
# @return [String]
-
1
def frozen_string(str)
-
31
"#{Haml::Util.inspect_obj(str)}.freeze"
-
end
-
-
# Compiles attribute values for one key to Temple expression that generates ` key='value'`.
-
#
-
# @param key [String]
-
# @param values [Array<AttributeValue>]
-
# @return [Array] Temple expression
-
1
def compile_attribute(key, values)
-
62
if values.all? { |v| Temple::StaticAnalyzer.static?(v.to_literal) }
-
31
return static_build(values)
-
end
-
-
case key
-
when 'id', 'class'
-
compile_id_or_class_attribute(key, values)
-
else
-
compile_common_attribute(key, values)
-
end
-
end
-
-
# @param id_or_class [String] "id" or "class"
-
# @param values [Array<AttributeValue>]
-
# @return [Array] Temple expression
-
1
def compile_id_or_class_attribute(id_or_class, values)
-
var = unique_name
-
[:multi,
-
[:code, "#{var} = (#{merged_value(id_or_class, values)})"],
-
[:case, var,
-
['Hash, Array', runtime_build([AttributeValue.new(:dynamic, id_or_class, var)])],
-
['false, nil', [:multi]],
-
[:else, [:multi,
-
[:static, " #{id_or_class}=#{@attr_wrapper}"],
-
[:escape, @escape_attrs, [:dynamic, var]],
-
[:static, @attr_wrapper]],
-
]
-
],
-
]
-
end
-
-
# @param key [String] Not "id" or "class"
-
# @param values [Array<AttributeValue>]
-
# @return [Array] Temple expression
-
1
def compile_common_attribute(key, values)
-
var = unique_name
-
[:multi,
-
[:code, "#{var} = (#{merged_value(key, values)})"],
-
[:case, var,
-
['Hash', runtime_build([AttributeValue.new(:dynamic, key, var)])],
-
['true', true_value(key)],
-
['false, nil', [:multi]],
-
[:else, [:multi,
-
[:static, " #{key}=#{@attr_wrapper}"],
-
[:escape, @escape_attrs, [:dynamic, var]],
-
[:static, @attr_wrapper]],
-
]
-
],
-
]
-
end
-
-
1
def true_value(key)
-
if @is_html
-
[:static, " #{key}"]
-
else
-
[:static, " #{key}=#{@attr_wrapper}#{key}#{@attr_wrapper}"]
-
end
-
end
-
-
1
def unique_name
-
@unique_name ||= 0
-
"_haml_attribute_compiler#{@unique_name += 1}"
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
begin
-
1
require 'ripper'
-
rescue LoadError
-
end
-
-
1
module Haml
-
# Haml::AttriubuteParser parses Hash literal to { String (key name) => String (value literal) }.
-
1
module AttributeParser
-
1
class UnexpectedTokenError < StandardError; end
-
1
class UnexpectedKeyError < StandardError; end
-
-
# Indices in Ripper tokens
-
1
TYPE = 1
-
1
TEXT = 2
-
-
1
IGNORED_TYPES = %i[on_sp on_ignored_nl]
-
-
1
class << self
-
# @return [Boolean] - return true if AttributeParser.parse can be used.
-
1
def available?
-
159
defined?(Ripper) && Temple::StaticAnalyzer.available?
-
end
-
-
# @param [String] exp - Old attributes literal or Hash literal generated from new attributes.
-
# @return [Hash<String, String>,nil] - Return parsed attribute Hash whose values are Ruby literals, or return nil if argument is not a single Hash literal.
-
1
def parse(exp)
-
return nil unless hash_literal?(exp)
-
-
hash = {}
-
each_attribute(exp) do |key, value|
-
hash[key] = value
-
end
-
hash
-
rescue UnexpectedTokenError, UnexpectedKeyError
-
nil
-
end
-
-
1
private
-
-
# @param [String] exp - Ruby expression
-
# @return [Boolean] - Return true if exp is a single Hash literal
-
1
def hash_literal?(exp)
-
return false if Temple::StaticAnalyzer.syntax_error?(exp)
-
sym, body = Ripper.sexp(exp)
-
sym == :program && body.is_a?(Array) && body.size == 1 && body[0] && body[0][0] == :hash
-
end
-
-
# @param [Array] tokens - Ripper tokens. Scanned tokens will be destructively removed from this argument.
-
# @return [String] - attribute name in String
-
1
def shift_key!(tokens)
-
while !tokens.empty? && IGNORED_TYPES.include?(tokens.first[TYPE])
-
tokens.shift # ignore spaces
-
end
-
-
_, type, first_text = tokens.shift
-
case type
-
when :on_label # `key:`
-
first_text.tr(':', '')
-
when :on_symbeg # `:key =>`, `:'key' =>` or `:"key" =>`
-
key = tokens.shift[TEXT]
-
if first_text != ':' # `:'key'` or `:"key"`
-
expect_string_end!(tokens.shift)
-
end
-
shift_hash_rocket!(tokens)
-
key
-
when :on_tstring_beg # `"key":`, `'key':` or `"key" =>`
-
key = tokens.shift[TEXT]
-
next_token = tokens.shift
-
if next_token[TYPE] != :on_label_end # on_label_end is `":` or `':`, so `"key" =>`
-
expect_string_end!(next_token)
-
shift_hash_rocket!(tokens)
-
end
-
key
-
else
-
raise UnexpectedKeyError.new("unexpected token is given!: #{first_text} (#{type})")
-
end
-
end
-
-
# @param [Array] token - Ripper token
-
1
def expect_string_end!(token)
-
if token[TYPE] != :on_tstring_end
-
raise UnexpectedTokenError
-
end
-
end
-
-
# @param [Array] tokens - Ripper tokens
-
1
def shift_hash_rocket!(tokens)
-
until tokens.empty?
-
_, type, str = tokens.shift
-
break if type == :on_op && str == '=>'
-
end
-
end
-
-
# @param [String] hash_literal
-
# @param [Proc] block - that takes [String, String] as arguments
-
1
def each_attribute(hash_literal, &block)
-
all_tokens = Ripper.lex(hash_literal.strip)
-
all_tokens = all_tokens[1...-1] || [] # strip tokens for brackets
-
-
each_balaned_tokens(all_tokens) do |tokens|
-
key = shift_key!(tokens)
-
value = tokens.map(&:last).join.strip
-
block.call(key, value)
-
end
-
end
-
-
# @param [Array] tokens - Ripper tokens
-
# @param [Proc] block - that takes balanced Ripper tokens as arguments
-
1
def each_balaned_tokens(tokens, &block)
-
attr_tokens = []
-
open_tokens = Hash.new { |h, k| h[k] = 0 }
-
-
tokens.each do |token|
-
case token[TYPE]
-
when :on_comma
-
if open_tokens.values.all?(&:zero?)
-
block.call(attr_tokens)
-
attr_tokens = []
-
next
-
end
-
when :on_lbracket
-
open_tokens[:array] += 1
-
when :on_rbracket
-
open_tokens[:array] -= 1
-
when :on_lbrace
-
open_tokens[:block] += 1
-
when :on_rbrace
-
open_tokens[:block] -= 1
-
when :on_lparen
-
open_tokens[:paren] += 1
-
when :on_rparen
-
open_tokens[:paren] -= 1
-
when :on_embexpr_beg
-
open_tokens[:embexpr] += 1
-
when :on_embexpr_end
-
open_tokens[:embexpr] -= 1
-
when *IGNORED_TYPES
-
next if attr_tokens.empty?
-
end
-
-
attr_tokens << token
-
end
-
block.call(attr_tokens) unless attr_tokens.empty?
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module Haml
-
# This class is used only internally. It holds the buffer of HTML that
-
# is eventually output as the resulting document.
-
# It's called from within the precompiled code,
-
# and helps reduce the amount of processing done within `instance_eval`ed code.
-
1
class Buffer
-
1
include Haml::Helpers
-
1
include Haml::Util
-
-
# The string that holds the compiled HTML. This is aliased as
-
# `_erbout` for compatibility with ERB-specific code.
-
#
-
# @return [String]
-
1
attr_accessor :buffer
-
-
# The options hash passed in from {Haml::Engine}.
-
#
-
# @return [{String => Object}]
-
# @see Haml::Options#for_buffer
-
1
attr_accessor :options
-
-
# The {Buffer} for the enclosing Haml document.
-
# This is set for partials and similar sorts of nested templates.
-
# It's `nil` at the top level (see \{#toplevel?}).
-
#
-
# @return [Buffer]
-
1
attr_accessor :upper
-
-
# nil if there's no capture_haml block running,
-
# and the position at which it's beginning the capture if there is one.
-
#
-
# @return [Fixnum, nil]
-
1
attr_accessor :capture_position
-
-
# @return [Boolean]
-
# @see #active?
-
1
attr_writer :active
-
-
# @return [Boolean] Whether or not the format is XHTML
-
1
def xhtml?
-
not html?
-
end
-
-
# @return [Boolean] Whether or not the format is any flavor of HTML
-
1
def html?
-
html4? or html5?
-
end
-
-
# @return [Boolean] Whether or not the format is HTML4
-
1
def html4?
-
@options[:format] == :html4
-
end
-
-
# @return [Boolean] Whether or not the format is HTML5.
-
1
def html5?
-
@options[:format] == :html5
-
end
-
-
# @return [Boolean] Whether or not this buffer is a top-level template,
-
# as opposed to a nested partial
-
1
def toplevel?
-
663
upper.nil?
-
end
-
-
# Whether or not this buffer is currently being used to render a Haml template.
-
# Returns `false` if a subtemplate is being rendered,
-
# even if it's a subtemplate of this buffer's template.
-
#
-
# @return [Boolean]
-
1
def active?
-
344
@active
-
end
-
-
# @return [Fixnum] The current indentation level of the document
-
1
def tabulation
-
@real_tabs + @tabulation
-
end
-
-
# Sets the current tabulation of the document.
-
#
-
# @param val [Fixnum] The new tabulation
-
1
def tabulation=(val)
-
val = val - @real_tabs
-
@tabulation = val > -1 ? val : 0
-
end
-
-
# @param upper [Buffer] The parent buffer
-
# @param options [{Symbol => Object}] An options hash.
-
# See {Haml::Engine#options\_for\_buffer}
-
1
def initialize(upper = nil, options = {})
-
118
@active = true
-
118
@upper = upper
-
118
@options = Options.buffer_defaults
-
118
@options = @options.merge(options) unless options.empty?
-
118
@buffer = new_encoded_string
-
118
@tabulation = 0
-
-
# The number of tabs that Engine thinks we should have
-
# @real_tabs + @tabulation is the number of tabs actually output
-
118
@real_tabs = 0
-
end
-
-
# Appends text to the buffer, properly tabulated.
-
# Also modifies the document's indentation.
-
#
-
# @param text [String] The text to append
-
# @param tab_change [Fixnum] The number of tabs by which to increase
-
# or decrease the document's indentation
-
# @param dont_tab_up [Boolean] If true, don't indent the first line of `text`
-
1
def push_text(text, tab_change, dont_tab_up)
-
if @tabulation > 0
-
# Have to push every line in by the extra user set tabulation.
-
# Don't push lines with just whitespace, though,
-
# because that screws up precompiled indentation.
-
text.gsub!(/^(?!\s+$)/m, tabs)
-
text.sub!(tabs, '') if dont_tab_up
-
end
-
-
@real_tabs += tab_change
-
@buffer << text
-
end
-
-
# Modifies the indentation of the document.
-
#
-
# @param tab_change [Fixnum] The number of tabs by which to increase
-
# or decrease the document's indentation
-
1
def adjust_tabs(tab_change)
-
@real_tabs += tab_change
-
end
-
-
1
def attributes(class_id, obj_ref, *attributes_hashes)
-
attributes = class_id
-
attributes_hashes.each do |old|
-
AttributeBuilder.merge_attributes!(attributes, Hash[old.map {|k, v| [k.to_s, v]}])
-
end
-
AttributeBuilder.merge_attributes!(attributes, parse_object_ref(obj_ref)) if obj_ref
-
AttributeBuilder.build_attributes(
-
html?, @options[:attr_wrapper], @options[:escape_attrs], @options[:hyphenate_data_attrs], attributes)
-
end
-
-
# Remove the whitespace from the right side of the buffer string.
-
# Doesn't do anything if we're at the beginning of a capture_haml block.
-
1
def rstrip!
-
if capture_position.nil?
-
buffer.rstrip!
-
return
-
end
-
-
buffer << buffer.slice!(capture_position..-1).rstrip
-
end
-
-
# Works like #{find_and_preserve}, but allows the first newline after a
-
# preserved opening tag to remain unencoded, and then outdents the content.
-
# This change was motivated primarily by the change in Rails 3.2.3 to emit
-
# a newline after textarea helpers.
-
#
-
# @param input [String] The text to process
-
# @since Haml 4.0.1
-
# @private
-
1
def fix_textareas!(input)
-
663
return input unless toplevel? && input.include?('<textarea'.freeze)
-
-
pattern = /<(textarea)([^>]*)>(\n|
)(.*?)<\/textarea>/im
-
input.gsub!(pattern) do |s|
-
match = pattern.match(s)
-
content = match[4]
-
if match[3] == '
'
-
content.sub!(/\A /, ' ')
-
else
-
content.sub!(/\A[ ]*/, '')
-
end
-
"<#{match[1]}#{match[2]}>\n#{content}</#{match[1]}>"
-
end
-
input
-
end
-
-
1
private
-
-
1
def new_encoded_string
-
118
"".encode(options[:encoding])
-
end
-
-
1
@@tab_cache = {}
-
# Gets `count` tabs. Mostly for internal use.
-
1
def tabs(count = 0)
-
tabs = [count + @tabulation, 0].max
-
@@tab_cache[tabs] ||= ' ' * tabs
-
end
-
-
# Takes an array of objects and uses the class and id of the first
-
# one to create an attributes hash.
-
# The second object, if present, is used as a prefix,
-
# just like you can do with `dom_id()` and `dom_class()` in Rails
-
1
def parse_object_ref(ref)
-
prefix = ref[1]
-
ref = ref[0]
-
# Let's make sure the value isn't nil. If it is, return the default Hash.
-
return {} if ref.nil?
-
class_name =
-
if ref.respond_to?(:haml_object_ref)
-
ref.haml_object_ref
-
else
-
underscore(ref.class)
-
end
-
ref_id =
-
if ref.respond_to?(:to_key)
-
key = ref.to_key
-
key.join('_') unless key.nil?
-
else
-
ref.id
-
end
-
id = "#{class_name}_#{ref_id || 'new'}"
-
if prefix
-
class_name = "#{ prefix }_#{ class_name}"
-
id = "#{ prefix }_#{ id }"
-
end
-
-
{ 'id'.freeze => id, 'class'.freeze => class_name }
-
end
-
-
# Changes a word from camel case to underscores.
-
# Based on the method of the same name in Rails' Inflector,
-
# but copied here so it'll run properly without Rails.
-
1
def underscore(camel_cased_word)
-
word = camel_cased_word.to_s.dup
-
word.gsub!(/::/, '_')
-
word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
-
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
-
word.tr!('-', '_')
-
word.downcase!
-
word
-
end
-
end
-
end
-
# frozen_string_literal: false
-
1
require 'haml/attribute_builder'
-
1
require 'haml/attribute_compiler'
-
1
require 'haml/temple_line_counter'
-
-
1
module Haml
-
1
class Compiler
-
1
include Haml::Util
-
-
1
attr_accessor :options
-
-
1
def initialize(options)
-
22
@options = Options.wrap(options)
-
22
@to_merge = []
-
22
@temple = [:multi]
-
22
@node = nil
-
22
@filters = Filters.defined.merge(options[:filters])
-
22
@attribute_compiler = AttributeCompiler.new(@options)
-
end
-
-
1
def call(node)
-
22
compile(node)
-
22
@temple
-
end
-
-
1
def compile(node)
-
298
parent, @node = @node, node
-
298
if node.children.empty?
-
188
send(:"compile_#{node.type}")
-
else
-
496
send(:"compile_#{node.type}") {node.children.each {|c| compile c}}
-
end
-
ensure
-
298
@node = parent
-
end
-
-
1
private
-
-
1
def compile_root
-
22
@output_line = 1
-
22
yield if block_given?
-
22
flush_merged_text
-
end
-
-
1
def compile_plain
-
7
push_text("#{@node.value[:text]}\n")
-
end
-
-
1
def nuke_inner_whitespace?(node)
-
281
if node.value && node.value[:nuke_inner_whitespace]
-
true
-
281
elsif node.parent
-
195
nuke_inner_whitespace?(node.parent)
-
else
-
86
false
-
end
-
end
-
-
1
def compile_script(&block)
-
86
push_script(@node.value[:text],
-
:preserve_script => @node.value[:preserve],
-
:escape_html => @node.value[:escape_html],
-
:nuke_inner_whitespace => nuke_inner_whitespace?(@node),
-
&block)
-
end
-
-
1
def compile_silent_script
-
15
return if @options.suppress_eval
-
15
push_silent(@node.value[:text])
-
15
keyword = @node.value[:keyword]
-
-
15
if block_given?
-
13
yield
-
13
push_silent("end", :can_suppress) unless @node.value[:dont_push_end]
-
2
elsif keyword == "end"
-
if @node.parent.children.last.equal?(@node)
-
# Since this "end" is ending the block,
-
# we don't need to generate an additional one
-
@node.parent.value[:dont_push_end] = true
-
end
-
# Don't restore dont_* for end because it isn't a conditional branch.
-
end
-
end
-
-
1
def compile_haml_comment; end
-
-
1
def compile_tag
-
159
t = @node.value
-
-
# Get rid of whitespace outside of the tag if we need to
-
159
rstrip_buffer! if t[:nuke_outer_whitespace]
-
-
159
if @options.suppress_eval
-
object_ref = :nil
-
parse = false
-
value = t[:parse] ? nil : t[:value]
-
dynamic_attributes = Haml::Parser::DynamicAttributes.new
-
preserve_script = false
-
else
-
159
object_ref = t[:object_ref]
-
159
parse = t[:parse]
-
159
value = t[:value]
-
159
dynamic_attributes = t[:dynamic_attributes]
-
159
preserve_script = t[:preserve_script]
-
end
-
-
159
if @options[:trace]
-
t[:attributes].merge!({"data-trace" => @options.filename.split('/views').last << ":" << @node.line.to_s})
-
end
-
-
159
push_text("<#{t[:name]}")
-
159
push_temple(@attribute_compiler.compile(t[:attributes], object_ref, dynamic_attributes))
-
159
push_text(
-
if t[:self_closing] && @options.xhtml?
-
" />#{"\n" unless t[:nuke_outer_whitespace]}"
-
else
-
159
">#{"\n" unless (t[:self_closing] && @options.html?) ? t[:nuke_outer_whitespace] : (!block_given? || t[:preserve_tag] || t[:nuke_inner_whitespace])}"
-
end
-
)
-
-
159
if value && !parse
-
38
push_text("#{value}</#{t[:name]}>#{"\n" unless t[:nuke_outer_whitespace]}")
-
end
-
-
159
return if t[:self_closing]
-
-
147
if value.nil?
-
71
yield if block_given?
-
71
rstrip_buffer! if t[:nuke_inner_whitespace]
-
71
push_text("</#{t[:name]}>#{"\n" unless t[:nuke_outer_whitespace]}")
-
71
return
-
end
-
-
76
if parse
-
38
push_script(value, t.merge(:in_tag => true))
-
38
push_text("</#{t[:name]}>#{"\n" unless t[:nuke_outer_whitespace]}")
-
end
-
end
-
-
1
def compile_comment
-
7
condition = "#{@node.value[:conditional]}>" if @node.value[:conditional]
-
7
revealed = @node.value[:revealed]
-
-
7
open = "<!--#{condition}#{'<!-->' if revealed}"
-
-
7
close = "#{'<!--' if revealed}#{'<![endif]' if condition}-->"
-
-
7
unless block_given?
-
7
push_text("#{open} ")
-
-
7
if @node.value[:parse]
-
push_script(@node.value[:text], :in_tag => true, :nuke_inner_whitespace => true)
-
else
-
7
push_text(@node.value[:text])
-
end
-
-
7
push_text(" #{close}\n")
-
7
return
-
end
-
-
push_text("#{open}\n")
-
yield if block_given?
-
push_text("#{close}\n")
-
end
-
-
1
def compile_doctype
-
1
doctype = text_for_doctype
-
1
push_text("#{doctype}\n") if doctype
-
end
-
-
1
def compile_filter
-
unless filter = @filters[@node.value[:name]]
-
name = @node.value[:name]
-
if ["maruku", "textile"].include?(name)
-
raise Error.new(Error.message(:install_haml_contrib, name), @node.line - 1)
-
else
-
raise Error.new(Error.message(:filter_not_defined, name), @node.line - 1)
-
end
-
end
-
filter.internal_compile(self, @node.value[:text])
-
end
-
-
1
def text_for_doctype
-
1
if @node.value[:type] == "xml"
-
return nil if @options.html?
-
wrapper = @options.attr_wrapper
-
return "<?xml version=#{wrapper}1.0#{wrapper} encoding=#{wrapper}#{@node.value[:encoding] || "utf-8"}#{wrapper} ?>"
-
end
-
-
1
if @options.html5?
-
1
'<!DOCTYPE html>'
-
else
-
if @options.xhtml?
-
if @node.value[:version] == "1.1"
-
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'
-
elsif @node.value[:version] == "5"
-
'<!DOCTYPE html>'
-
else
-
case @node.value[:type]
-
when "strict"; '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
-
when "frameset"; '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">'
-
when "mobile"; '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">'
-
when "rdfa"; '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">'
-
when "basic"; '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">'
-
else '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
-
end
-
end
-
-
elsif @options.html4?
-
case @node.value[:type]
-
when "strict"; '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'
-
when "frameset"; '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'
-
else '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">'
-
end
-
end
-
end
-
end
-
-
# Evaluates `text` in the context of the scope object, but
-
# does not output the result.
-
1
def push_silent(text, can_suppress = false)
-
36
flush_merged_text
-
36
return if can_suppress && @options.suppress_eval?
-
36
newline = (text == "end") ? ";" : "\n"
-
36
@temple << [:code, "#{resolve_newlines}#{text}#{newline}"]
-
36
@output_line = @output_line + text.count("\n") + newline.count("\n")
-
end
-
-
# Adds `text` to `@buffer`.
-
1
def push_text(text)
-
576
@to_merge << [:text, text]
-
end
-
-
1
def push_temple(temple)
-
159
flush_merged_text
-
159
@temple.concat([[:newline]] * resolve_newlines.count("\n"))
-
159
@temple << temple
-
159
@output_line += TempleLineCounter.count_lines(temple)
-
end
-
-
1
def flush_merged_text
-
221
return if @to_merge.empty?
-
-
204
@to_merge.each do |type, val|
-
696
case type
-
when :text
-
576
@temple << [:static, val]
-
when :script
-
120
@temple << [:dynamic, val]
-
else
-
raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Compiler@to_merge.")
-
end
-
end
-
-
204
@to_merge = []
-
end
-
-
# Causes `text` to be evaluated in the context of
-
# the scope object and the result to be added to `@buffer`.
-
#
-
# If `opts[:preserve_script]` is true, Haml::Helpers#find_and_preserve is run on
-
# the result before it is added to `@buffer`
-
1
def push_script(text, opts = {})
-
124
return if @options.suppress_eval?
-
-
124
no_format = !(opts[:preserve_script] || opts[:preserve_tag] || opts[:escape_html])
-
-
124
unless block_given?
-
120
push_generated_script(no_format ? "(#{text}\n).to_s" : build_script_formatter("(#{text}\n)", opts))
-
120
push_text("\n") unless opts[:in_tag] || opts[:nuke_inner_whitespace]
-
120
return
-
end
-
-
4
flush_merged_text
-
4
push_silent "haml_temp = #{text}"
-
4
yield
-
4
push_silent('end', :can_suppress) unless @node.value[:dont_push_end]
-
4
@temple << [:dynamic, no_format ? 'haml_temp.to_s;' : build_script_formatter('haml_temp', opts)]
-
end
-
-
1
def build_script_formatter(text, opts)
-
124
text = "(#{text}).to_s"
-
124
if opts[:escape_html]
-
124
text = "::Haml::Helpers.html_escape(#{text})"
-
end
-
124
if opts[:nuke_inner_whitespace]
-
text = "(#{text}).strip"
-
end
-
124
if opts[:preserve_tag]
-
text = "::Haml::Helpers.preserve(#{text})"
-
elsif opts[:preserve_script]
-
text = "::Haml::Helpers.find_and_preserve(#{text}, _hamlout.options[:preserve])"
-
end
-
124
"_hamlout.fix_textareas!(#{text});"
-
end
-
-
1
def push_generated_script(text)
-
120
@to_merge << [:script, resolve_newlines + text]
-
120
@output_line += text.count("\n")
-
end
-
-
1
def resolve_newlines
-
315
diff = @node.line - @output_line
-
315
return "" if diff <= 0
-
144
@output_line = @node.line
-
144
"\n" * diff
-
end
-
-
# Get rid of and whitespace at the end of the buffer
-
# or the merged text
-
1
def rstrip_buffer!(index = -1)
-
last = @to_merge[index]
-
if last.nil?
-
push_silent("_hamlout.rstrip!", false)
-
return
-
end
-
-
case last.first
-
when :text
-
last[1].rstrip!
-
if last[1].empty?
-
@to_merge.slice! index
-
rstrip_buffer! index
-
end
-
when :script
-
last[1].gsub!(/\(haml_temp, (.*?)\);$/, '(haml_temp.rstrip, \1);')
-
rstrip_buffer! index - 1
-
else
-
raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Compiler@to_merge.")
-
end
-
end
-
end
-
end
-
# frozen_string_literal: false
-
1
require 'forwardable'
-
-
1
require 'haml/parser'
-
1
require 'haml/compiler'
-
1
require 'haml/options'
-
1
require 'haml/helpers'
-
1
require 'haml/buffer'
-
1
require 'haml/filters'
-
1
require 'haml/error'
-
1
require 'haml/temple_engine'
-
-
1
module Haml
-
# This is the frontend for using Haml programmatically.
-
# It can be directly used by the user by creating a
-
# new instance and calling \{#render} to render the template.
-
# For example:
-
#
-
# template = File.read('templates/really_cool_template.haml')
-
# haml_engine = Haml::Engine.new(template)
-
# output = haml_engine.render
-
# puts output
-
1
class Engine
-
1
extend Forwardable
-
1
include Haml::Util
-
-
# The Haml::Options instance.
-
# See {file:REFERENCE.md#options the Haml options documentation}.
-
#
-
# @return Haml::Options
-
1
attr_accessor :options
-
-
# The indentation used in the Haml document,
-
# or `nil` if the indentation is ambiguous
-
# (for example, for a single-level document).
-
#
-
# @return [String]
-
1
attr_accessor :indentation
-
-
# Tilt currently depends on these moved methods, provide a stable API
-
1
def_delegators :compiler, :precompiled, :precompiled_method_return_value
-
-
1
def options_for_buffer
-
@options.for_buffer
-
end
-
-
# Precompiles the Haml template.
-
#
-
# @param template [String] The Haml template
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:REFERENCE.md#options the Haml options documentation}
-
# @raise [Haml::Error] if there's a Haml syntax error in the template
-
1
def initialize(template, options = {})
-
22
@options = Options.new(options)
-
-
22
@template = check_haml_encoding(template) do |msg, line|
-
raise Haml::Error.new(msg, line)
-
end
-
-
22
@temple_engine = TempleEngine.new(options)
-
22
@temple_engine.compile(@template)
-
end
-
-
# Deprecated API for backword compatibility
-
1
def compiler
-
22
@temple_engine
-
end
-
-
# Processes the template and returns the result as a string.
-
#
-
# `scope` is the context in which the template is evaluated.
-
# If it's a `Binding`, Haml uses it as the second argument to `Kernel#eval`;
-
# otherwise, Haml just uses its `#instance_eval` context.
-
#
-
# Note that Haml modifies the evaluation context
-
# (either the scope object or the `self` object of the scope binding).
-
# It extends {Haml::Helpers}, and various instance variables are set
-
# (all prefixed with `haml_`).
-
# For example:
-
#
-
# s = "foobar"
-
# Haml::Engine.new("%p= upcase").render(s) #=> "<p>FOOBAR</p>"
-
#
-
# # s now extends Haml::Helpers
-
# s.respond_to?(:html_attrs) #=> true
-
#
-
# `locals` is a hash of local variables to make available to the template.
-
# For example:
-
#
-
# Haml::Engine.new("%p= foo").render(Object.new, :foo => "Hello, world!") #=> "<p>Hello, world!</p>"
-
#
-
# If a block is passed to render,
-
# that block is run when `yield` is called
-
# within the template.
-
#
-
# Due to some Ruby quirks,
-
# if `scope` is a `Binding` object and a block is given,
-
# the evaluation context may not be quite what the user expects.
-
# In particular, it's equivalent to passing `eval("self", scope)` as `scope`.
-
# This won't have an effect in most cases,
-
# but if you're relying on local variables defined in the context of `scope`,
-
# they won't work.
-
#
-
# @param scope [Binding, Object] The context in which the template is evaluated
-
# @param locals [{Symbol => Object}] Local variables that will be made available
-
# to the template
-
# @param block [#to_proc] A block that can be yielded to within the template
-
# @return [String] The rendered template
-
1
def render(scope = Object.new, locals = {}, &block)
-
parent = scope.instance_variable_defined?(:@haml_buffer) ? scope.instance_variable_get(:@haml_buffer) : nil
-
buffer = Haml::Buffer.new(parent, @options.for_buffer)
-
-
if scope.is_a?(Binding)
-
scope_object = eval("self", scope)
-
scope = scope_object.instance_eval{binding} if block_given?
-
else
-
scope_object = scope
-
scope = scope_object.instance_eval{binding}
-
end
-
-
set_locals(locals.merge(:_hamlout => buffer, :_erbout => buffer.buffer), scope, scope_object)
-
-
scope_object.extend(Haml::Helpers)
-
scope_object.instance_variable_set(:@haml_buffer, buffer)
-
begin
-
eval(@temple_engine.precompiled_with_return_value, scope, @options.filename, @options.line)
-
rescue ::SyntaxError => e
-
raise SyntaxError, e.message
-
end
-
ensure
-
# Get rid of the current buffer
-
scope_object.instance_variable_set(:@haml_buffer, buffer.upper) if buffer
-
end
-
1
alias_method :to_html, :render
-
-
# Returns a proc that, when called,
-
# renders the template and returns the result as a string.
-
#
-
# `scope` works the same as it does for render.
-
#
-
# The first argument of the returned proc is a hash of local variable names to values.
-
# However, due to an unfortunate Ruby quirk,
-
# the local variables which can be assigned must be pre-declared.
-
# This is done with the `local_names` argument.
-
# For example:
-
#
-
# # This works
-
# Haml::Engine.new("%p= foo").render_proc(Object.new, :foo).call :foo => "Hello!"
-
# #=> "<p>Hello!</p>"
-
#
-
# # This doesn't
-
# Haml::Engine.new("%p= foo").render_proc.call :foo => "Hello!"
-
# #=> NameError: undefined local variable or method `foo'
-
#
-
# The proc doesn't take a block; any yields in the template will fail.
-
#
-
# @param scope [Binding, Object] The context in which the template is evaluated
-
# @param local_names [Array<Symbol>] The names of the locals that can be passed to the proc
-
# @return [Proc] The proc that will run the template
-
1
def render_proc(scope = Object.new, *local_names)
-
if scope.is_a?(Binding)
-
scope_object = eval("self", scope)
-
else
-
scope_object = scope
-
scope = scope_object.instance_eval{binding}
-
end
-
-
begin
-
eval("Proc.new { |*_haml_locals| _haml_locals = _haml_locals[0] || {};" <<
-
@temple_engine.precompiled_with_ambles(local_names) << "}\n", scope, @options.filename, @options.line)
-
rescue ::SyntaxError => e
-
raise SyntaxError, e.message
-
end
-
end
-
-
# Defines a method on `object` with the given name
-
# that renders the template and returns the result as a string.
-
#
-
# If `object` is a class or module,
-
# the method will instead be defined as an instance method.
-
# For example:
-
#
-
# t = Time.now
-
# Haml::Engine.new("%p\n Today's date is\n .date= self.to_s").def_method(t, :render)
-
# t.render #=> "<p>\n Today's date is\n <div class='date'>Fri Nov 23 18:28:29 -0800 2007</div>\n</p>\n"
-
#
-
# Haml::Engine.new(".upcased= upcase").def_method(String, :upcased_div)
-
# "foobar".upcased_div #=> "<div class='upcased'>FOOBAR</div>\n"
-
#
-
# The first argument of the defined method is a hash of local variable names to values.
-
# However, due to an unfortunate Ruby quirk,
-
# the local variables which can be assigned must be pre-declared.
-
# This is done with the `local_names` argument.
-
# For example:
-
#
-
# # This works
-
# obj = Object.new
-
# Haml::Engine.new("%p= foo").def_method(obj, :render, :foo)
-
# obj.render(:foo => "Hello!") #=> "<p>Hello!</p>"
-
#
-
# # This doesn't
-
# obj = Object.new
-
# Haml::Engine.new("%p= foo").def_method(obj, :render)
-
# obj.render(:foo => "Hello!") #=> NameError: undefined local variable or method `foo'
-
#
-
# Note that Haml modifies the evaluation context
-
# (either the scope object or the `self` object of the scope binding).
-
# It extends {Haml::Helpers}, and various instance variables are set
-
# (all prefixed with `haml_`).
-
#
-
# @param object [Object, Module] The object on which to define the method
-
# @param name [String, Symbol] The name of the method to define
-
# @param local_names [Array<Symbol>] The names of the locals that can be passed to the proc
-
1
def def_method(object, name, *local_names)
-
method = object.is_a?(Module) ? :module_eval : :instance_eval
-
-
object.send(method, "def #{name}(_haml_locals = {}); #{@temple_engine.precompiled_with_ambles(local_names)}; end",
-
@options.filename, @options.line)
-
end
-
-
1
private
-
-
1
def set_locals(locals, scope, scope_object)
-
scope_object.instance_variable_set :@_haml_locals, locals
-
set_locals = locals.keys.map { |k| "#{k} = @_haml_locals[#{k.inspect}]" }.join("\n")
-
eval(set_locals, scope)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module Haml
-
# An exception raised by Haml code.
-
1
class Error < StandardError
-
-
1
MESSAGES = {
-
:bad_script_indent => '"%s" is indented at wrong level: expected %d, but was at %d.',
-
:cant_run_filter => 'Can\'t run "%s" filter; you must require its dependencies first',
-
:cant_use_tabs_and_spaces => "Indentation can't use both tabs and spaces.",
-
:deeper_indenting => "The line was indented %d levels deeper than the previous line.",
-
:filter_not_defined => 'Filter "%s" is not defined.',
-
:gem_install_filter_deps => '"%s" filter\'s %s dependency missing: try installing it or adding it to your Gemfile',
-
:illegal_element => "Illegal element: classes and ids must have values.",
-
:illegal_nesting_content => "Illegal nesting: nesting within a tag that already has content is illegal.",
-
:illegal_nesting_header => "Illegal nesting: nesting within a header command is illegal.",
-
:illegal_nesting_line => "Illegal nesting: content can't be both given on the same line as %%%s and nested within it.",
-
:illegal_nesting_plain => "Illegal nesting: nesting within plain text is illegal.",
-
:illegal_nesting_self_closing => "Illegal nesting: nesting within a self-closing tag is illegal.",
-
:inconsistent_indentation => "Inconsistent indentation: %s used for indentation, but the rest of the document was indented using %s.",
-
:indenting_at_start => "Indenting at the beginning of the document is illegal.",
-
:install_haml_contrib => 'To use the "%s" filter, please install the haml-contrib gem.',
-
:invalid_attribute_list => 'Invalid attribute list: %s.',
-
:invalid_filter_name => 'Invalid filter name ":%s".',
-
:invalid_tag => 'Invalid tag: "%s".',
-
:missing_if => 'Got "%s" with no preceding "if"',
-
:no_ruby_code => "There's no Ruby code for %s to evaluate.",
-
:self_closing_content => "Self-closing tags can't have content.",
-
:unbalanced_brackets => 'Unbalanced brackets.',
-
:no_end => <<-END
-
You don't need to use "- end" in Haml. Un-indent to close a block:
-
- if foo?
-
%strong Foo!
-
- else
-
Not foo.
-
%p This line is un-indented, so it isn't part of the "if" block
-
END
-
}
-
-
1
def self.message(key, *args)
-
string = MESSAGES[key] or raise "[HAML BUG] No error messages for #{key}"
-
(args.empty? ? string : string % args).rstrip
-
end
-
-
# The line of the template on which the error occurred.
-
#
-
# @return [Fixnum]
-
1
attr_reader :line
-
-
# @param message [String] The error message
-
# @param line [Fixnum] See \{#line}
-
1
def initialize(message = nil, line = nil)
-
super(message)
-
@line = line
-
end
-
end
-
-
# SyntaxError is the type of exception raised when Haml encounters an
-
# ill-formatted document.
-
# It's not particularly interesting,
-
# except in that it's a subclass of {Haml::Error}.
-
1
class SyntaxError < Error; end
-
-
1
class InvalidAttributeNameError < SyntaxError; end
-
end
-
# frozen_string_literal: true
-
1
module Haml
-
# Like Temple::Filters::Escapable, but with support for escaping by
-
# Haml::Herlpers.html_escape and Haml::Herlpers.escape_once.
-
1
class Escapable < Temple::Filter
-
1
def initialize(*)
-
22
super
-
22
@escape_code = "::Haml::Helpers.html_escape((%s))"
-
22
@escaper = eval("proc {|v| #{@escape_code % 'v'} }")
-
22
@once_escape_code = "::Haml::Helpers.escape_once((%s))"
-
22
@once_escaper = eval("proc {|v| #{@once_escape_code % 'v'} }")
-
22
@escape = false
-
end
-
-
1
def on_escape(flag, exp)
-
old = @escape
-
@escape = flag
-
compile(exp)
-
ensure
-
@escape = old
-
end
-
-
# The same as Haml::AttributeBuilder.build_attributes
-
1
def on_static(value)
-
607
[:static,
-
if @escape == :once
-
@once_escaper[value]
-
elsif @escape
-
@escaper[value]
-
else
-
607
value
-
end
-
]
-
end
-
-
# The same as Haml::AttributeBuilder.build_attributes
-
1
def on_dynamic(value)
-
124
[:dynamic,
-
if @escape == :once
-
@once_escape_code % value
-
elsif @escape
-
@escape_code % value
-
else
-
124
"(#{value}).to_s"
-
end
-
]
-
end
-
end
-
end
-
# frozen_string_literal: false
-
1
require "tilt"
-
-
1
module Haml
-
# The module containing the default Haml filters,
-
# as well as the base module, {Haml::Filters::Base}.
-
#
-
# @see Haml::Filters::Base
-
1
module Filters
-
-
1
extend self
-
-
# @return [{String => Haml::Filters::Base}] a hash mapping filter names to
-
# classes.
-
1
attr_reader :defined
-
1
@defined = {}
-
-
# Loads an external template engine from
-
# [Tilt](https://github.com/rtomayko/tilt) as a filter. This method is used
-
# internally by Haml to set up filters for Sass, SCSS, Less, Coffeescript,
-
# and others. It's left public to make it easy for developers to add their
-
# own Tilt-based filters if they choose.
-
#
-
# @return [Module] The generated filter.
-
# @param [Hash] options Options for generating the filter module.
-
# @option options [Boolean] :precompiled Whether the filter should be
-
# precompiled. Erb, Nokogiri and Builder use this, for example.
-
# @option options [Class] :template_class The Tilt template class to use,
-
# in the event it can't be inferred from an extension.
-
# @option options [String] :extension The extension associated with the
-
# content, for example "markdown". This lets Tilt choose the preferred
-
# engine when there are more than one.
-
# @option options [String,Array<String>] :alias Any aliases for the filter.
-
# For example, :coffee is also available as :coffeescript.
-
# @option options [String] :extend The name of a module to extend when
-
# defining the filter. Defaults to "Plain". This allows filters such as
-
# Coffee to "inherit" from Javascript, wrapping its output in script tags.
-
# @since 4.0
-
1
def register_tilt_filter(name, options = {})
-
6
if constants.map(&:to_s).include?(name.to_s)
-
raise "#{name} filter already defined"
-
end
-
-
6
filter = const_set(name, Module.new)
-
6
filter.extend const_get(options[:extend] || "Plain")
-
6
filter.extend TiltFilter
-
6
filter.extend PrecompiledTiltFilter if options.has_key? :precompiled
-
-
6
if options.has_key? :template_class
-
filter.template_class = options[:template_class]
-
else
-
12
filter.tilt_extension = options.fetch(:extension) { name.downcase }
-
end
-
-
# All ":coffeescript" as alias for ":coffee", etc.
-
6
if options.has_key?(:alias)
-
2
[options[:alias]].flatten.each {|x| Filters.defined[x.to_s] = filter}
-
end
-
6
filter
-
end
-
-
# Removes a filter from Haml. If the filter was removed, it returns
-
# the Module that was removed upon success, or nil on failure. If you try
-
# to redefine a filter, Haml will raise an error. Use this method first to
-
# explicitly remove the filter before redefining it.
-
# @return Module The filter module that has been removed
-
# @since 4.0
-
1
def remove_filter(name)
-
defined.delete name.to_s.downcase
-
if constants.map(&:to_s).include?(name.to_s)
-
remove_const name.to_sym
-
end
-
end
-
-
# The base module for Haml filters.
-
# User-defined filters should be modules including this module.
-
# The name of the filter is taken by downcasing the module name.
-
# For instance, if the module is named `FooBar`, the filter will be `:foobar`.
-
#
-
# A user-defined filter should override either \{#render} or {\#compile}.
-
# \{#render} is the most common.
-
# It takes a string, the filter source,
-
# and returns another string, the result of the filter.
-
# For example, the following will define a filter named `:sass`:
-
#
-
# module Haml::Filters::Sass
-
# include Haml::Filters::Base
-
#
-
# def render(text)
-
# ::Sass::Engine.new(text).render
-
# end
-
# end
-
#
-
# For details on overriding \{#compile}, see its documentation.
-
#
-
# Note that filters overriding \{#render} automatically support `#{}`
-
# for interpolating Ruby code.
-
# Those overriding \{#compile} will need to add such support manually
-
# if it's desired.
-
1
module Base
-
# This method is automatically called when {Base} is included in a module.
-
# It automatically defines a filter
-
# with the downcased name of that module.
-
# For example, if the module is named `FooBar`, the filter will be `:foobar`.
-
#
-
# @param base [Module, Class] The module that this is included in
-
1
def self.included(base)
-
14
Filters.defined[base.name.split("::").last.downcase] = base
-
14
base.extend(base)
-
end
-
-
# Takes the source text that should be passed to the filter
-
# and returns the result of running the filter on that string.
-
#
-
# This should be overridden in most individual filter modules
-
# to render text with the given filter.
-
# If \{#compile} is overridden, however, \{#render} doesn't need to be.
-
#
-
# @param text [String] The source text for the filter to process
-
# @return [String] The filtered result
-
# @raise [Haml::Error] if it's not overridden
-
1
def render(text)
-
raise Error.new("#{self.inspect}#render not defined!")
-
end
-
-
# Same as \{#render}, but takes a {Haml::Engine} options hash as well.
-
# It's only safe to rely on options made available in {Haml::Engine#options\_for\_buffer}.
-
#
-
# @see #render
-
# @param text [String] The source text for the filter to process
-
# @return [String] The filtered result
-
# @raise [Haml::Error] if it or \{#render} isn't overridden
-
1
def render_with_options(text, options)
-
render(text)
-
end
-
-
# Same as \{#compile}, but requires the necessary files first.
-
# *This is used by {Haml::Engine} and is not intended to be overridden or used elsewhere.*
-
#
-
# @see #compile
-
1
def internal_compile(*args)
-
compile(*args)
-
end
-
-
# This should be overridden when a filter needs to have access to the Haml
-
# evaluation context. Rather than applying a filter to a string at
-
# compile-time, \{#compile} uses the {Haml::Compiler} instance to compile
-
# the string to Ruby code that will be executed in the context of the
-
# active Haml template.
-
#
-
# Warning: the {Haml::Compiler} interface is neither well-documented
-
# nor guaranteed to be stable.
-
# If you want to make use of it, you'll probably need to look at the
-
# source code and should test your filter when upgrading to new Haml
-
# versions.
-
#
-
# @param compiler [Haml::Compiler] The compiler instance
-
# @param text [String] The text of the filter
-
# @raise [Haml::Error] if none of \{#compile}, \{#render}, and
-
# \{#render_with_options} are overridden
-
1
def compile(compiler, text)
-
filter = self
-
compiler.instance_eval do
-
if contains_interpolation?(text)
-
return if options[:suppress_eval]
-
-
text = unescape_interpolation(text, options[:escape_html]).gsub(/(\\+)n/) do |s|
-
escapes = $1.size
-
next s if escapes % 2 == 0
-
"#{'\\' * (escapes - 1)}\n"
-
end
-
# We need to add a newline at the beginning to get the
-
# filter lines to line up (since the Haml filter contains
-
# a line that doesn't show up in the source, namely the
-
# filter name). Then we need to escape the trailing
-
# newline so that the whole filter block doesn't take up
-
# too many.
-
text = %[\n#{text.sub(/\n"\Z/, "\\n\"")}]
-
push_script <<RUBY.rstrip, :escape_html => false
-
find_and_preserve(#{filter.inspect}.render_with_options(#{text}, _hamlout.options))
-
RUBY
-
return
-
end
-
-
rendered = Haml::Helpers::find_and_preserve(filter.render_with_options(text, compiler.options), compiler.options[:preserve])
-
rendered.rstrip!
-
push_text("#{rendered}\n")
-
end
-
end
-
end
-
-
# Does not parse the filtered text.
-
# This is useful for large blocks of text without HTML tags, when you don't
-
# want lines starting with `.` or `-` to be parsed.
-
1
module Plain
-
1
include Base
-
-
# @see Base#render
-
1
def render(text); text; end
-
end
-
-
# Surrounds the filtered text with `<script>` and CDATA tags. Useful for
-
# including inline Javascript.
-
1
module Javascript
-
1
include Base
-
-
# @see Base#render_with_options
-
1
def render_with_options(text, options)
-
indent = options[:cdata] ? ' ' : ' ' # 4 or 2 spaces
-
if options[:format] == :html5
-
type = ''
-
else
-
type = " type=#{options[:attr_wrapper]}text/javascript#{options[:attr_wrapper]}"
-
end
-
-
text = text.rstrip
-
text.gsub!("\n", "\n#{indent}")
-
-
%!<script#{type}>\n#{" //<![CDATA[\n" if options[:cdata]}#{indent}#{text}\n#{" //]]>\n" if options[:cdata]}</script>!
-
end
-
end
-
-
# Surrounds the filtered text with `<style>` and CDATA tags. Useful for
-
# including inline CSS.
-
1
module Css
-
1
include Base
-
-
# @see Base#render_with_options
-
1
def render_with_options(text, options)
-
indent = options[:cdata] ? ' ' : ' ' # 4 or 2 spaces
-
if options[:format] == :html5
-
type = ''
-
else
-
type = " type=#{options[:attr_wrapper]}text/css#{options[:attr_wrapper]}"
-
end
-
-
text = text.rstrip
-
text.gsub!("\n", "\n#{indent}")
-
-
%(<style#{type}>\n#{" /*<![CDATA[*/\n" if options[:cdata]}#{indent}#{text}\n#{" /*]]>*/\n" if options[:cdata]}</style>)
-
end
-
end
-
-
# Surrounds the filtered text with CDATA tags.
-
1
module Cdata
-
1
include Base
-
-
# @see Base#render
-
1
def render(text)
-
text = "\n#{text}"
-
text.rstrip!
-
text.gsub!("\n", "\n ")
-
"<![CDATA[#{text}\n]]>"
-
end
-
end
-
-
# Works the same as {Plain}, but HTML-escapes the text before placing it in
-
# the document.
-
1
module Escaped
-
1
include Base
-
-
# @see Base#render
-
1
def render(text)
-
Haml::Helpers.html_escape text
-
end
-
end
-
-
# Parses the filtered text with the normal Ruby interpreter. Creates an IO
-
# object named `haml_io`, anything written to it is output into the Haml
-
# document. In previous version this filter redirected any output to `$stdout`
-
# to the Haml document, this was not threadsafe and has been removed, you
-
# should use `haml_io` instead.
-
#
-
# Not available if the {file:REFERENCE.md#suppress_eval-option `:suppress_eval`}
-
# option is set to true. The Ruby code is evaluated in the same context as
-
# the Haml template.
-
1
module Ruby
-
1
include Base
-
1
require 'stringio'
-
-
# @see Base#compile
-
1
def compile(compiler, text)
-
return if compiler.options[:suppress_eval]
-
compiler.instance_eval do
-
push_silent <<-FIRST.tr("\n", ';') + text + <<-LAST.tr("\n", ';')
-
begin
-
haml_io = StringIO.new(_hamlout.buffer, 'a')
-
FIRST
-
ensure
-
haml_io.close
-
haml_io = nil
-
end
-
LAST
-
end
-
end
-
end
-
-
# Inserts the filtered text into the template with whitespace preserved.
-
# `preserve`d blocks of text aren't indented, and newlines are replaced with
-
# the HTML escape code for newlines, to preserve nice-looking output.
-
#
-
# @see Haml::Helpers#preserve
-
1
module Preserve
-
1
include Base
-
-
# @see Base#render
-
1
def render(text)
-
Haml::Helpers.preserve text
-
end
-
end
-
-
# @private
-
1
module TiltFilter
-
1
extend self
-
1
attr_accessor :tilt_extension, :options
-
1
attr_writer :template_class
-
-
1
def template_class
-
(@template_class if defined? @template_class) or begin
-
@template_class = Tilt["t.#{tilt_extension}"] or
-
raise Error.new(Error.message(:cant_run_filter, tilt_extension))
-
rescue LoadError => e
-
dep = e.message.split('--').last.strip
-
raise Error.new(Error.message(:gem_install_filter_deps, tilt_extension, dep))
-
end
-
end
-
-
1
def self.extended(base)
-
7
base.options = {}
-
# There's a bug in 1.9.2 where the same parse tree cannot be shared
-
# across several singleton classes -- this bug is fixed in 1.9.3.
-
# We work around this by using a string eval instead of a block eval
-
# so that a new parse tree is created for each singleton class.
-
7
base.instance_eval %Q{
-
include Base
-
-
def render_with_options(text, compiler_options)
-
text = template_class.new(nil, 1, options) {text}.render
-
super(text, compiler_options)
-
end
-
}
-
end
-
end
-
-
# @private
-
1
module PrecompiledTiltFilter
-
1
def precompiled(text)
-
template_class.new(nil, 1, options) { text }.send(:precompiled, {}).first
-
end
-
-
1
def compile(compiler, text)
-
return if compiler.options[:suppress_eval]
-
compiler.send(:push_script, precompiled(text))
-
end
-
end
-
-
# @!parse module Sass; end
-
1
register_tilt_filter "Sass", :extend => "Css"
-
-
# @!parse module Scss; end
-
1
register_tilt_filter "Scss", :extend => "Css"
-
-
# @!parse module Less; end
-
1
register_tilt_filter "Less", :extend => "Css"
-
-
# @!parse module Markdown; end
-
1
register_tilt_filter "Markdown"
-
-
# @!parse module Erb; end
-
1
register_tilt_filter "Erb", :precompiled => true
-
-
# @!parse module Coffee; end
-
1
register_tilt_filter "Coffee", :alias => "coffeescript", :extend => "Javascript"
-
-
# Parses the filtered text with ERB.
-
# Not available if the {file:REFERENCE.md#suppress_eval-option
-
# `:suppress_eval`} option is set to true. Embedded Ruby code is evaluated
-
# in the same context as the Haml template.
-
1
module Erb
-
1
class << self
-
1
def precompiled(text)
-
#workaround for https://github.com/rtomayko/tilt/pull/183
-
require 'erubis' if (defined?(::Erubis) && !defined?(::Erubis::Eruby))
-
super.sub(/^#coding:.*?\n/, '')
-
end
-
end
-
end
-
end
-
end
-
-
# These filters have been demoted to Haml Contrib but are still included by
-
# default in Haml 4.0. Still, we rescue from load error if for some reason
-
# haml-contrib is not installed.
-
1
begin
-
1
require "haml/filters/maruku"
-
require "haml/filters/textile"
-
rescue LoadError
-
end
-
# frozen_string_literal: true
-
1
module Haml
-
# Ruby code generator, which is a limited version of Temple::Generator.
-
# Limit methods since Haml doesn't need most of them.
-
1
class Generator
-
1
include Temple::Mixins::CompiledDispatcher
-
1
include Temple::Mixins::Options
-
-
1
define_options freeze_static: RUBY_VERSION >= '2.1'
-
-
1
def call(exp)
-
22
compile(exp)
-
end
-
-
1
def on_multi(*exp)
-
417
exp.map { |e| compile(e) }.join('; ')
-
end
-
-
1
def on_static(text)
-
165
concat(options[:freeze_static] ? "#{Util.inspect_obj(text)}.freeze" : Util.inspect_obj(text))
-
end
-
-
1
def on_dynamic(code)
-
124
concat(code)
-
end
-
-
1
def on_code(exp)
-
36
exp
-
end
-
-
1
def on_newline
-
70
"\n"
-
end
-
-
1
private
-
-
1
def concat(str)
-
289
"_hamlout.buffer << (#{str});"
-
end
-
end
-
end
-
# frozen_string_literal: false
-
1
require 'erb'
-
-
1
module Haml
-
# This module contains various helpful methods to make it easier to do various tasks.
-
# {Haml::Helpers} is automatically included in the context
-
# that a Haml template is parsed in, so all these methods are at your
-
# disposal from within the template.
-
1
module Helpers
-
# An object that raises an error when \{#to\_s} is called.
-
# It's used to raise an error when the return value of a helper is used
-
# when it shouldn't be.
-
1
class ErrorReturn
-
1
def initialize(method)
-
@message = <<MESSAGE
-
#{method} outputs directly to the Haml template.
-
Disregard its return value and use the - operator,
-
or use capture_haml to get the value as a String.
-
MESSAGE
-
end
-
-
# Raises an error.
-
#
-
# @raise [Haml::Error] The error
-
1
def to_s
-
raise Haml::Error.new(@message)
-
rescue Haml::Error => e
-
e.backtrace.shift
-
-
# If the ErrorReturn is used directly in the template,
-
# we don't want Haml's stuff to get into the backtrace,
-
# so we get rid of the format_script line.
-
#
-
# We also have to subtract one from the Haml line number
-
# since the value is passed to format_script the line after
-
# it's actually used.
-
if e.backtrace.first =~ /^\(eval\):\d+:in `format_script/
-
e.backtrace.shift
-
e.backtrace.first.gsub!(/^\(haml\):(\d+)/) {|s| "(haml):#{$1.to_i - 1}"}
-
end
-
raise e
-
end
-
-
# @return [String] A human-readable string representation
-
1
def inspect
-
"Haml::Helpers::ErrorReturn(#{@message.inspect})"
-
end
-
end
-
-
1
self.extend self
-
-
1
@@action_view_defined = false
-
-
# @return [Boolean] Whether or not ActionView is loaded
-
1
def self.action_view?
-
@@action_view_defined
-
end
-
-
# Note: this does **not** need to be called when using Haml helpers
-
# normally in Rails.
-
#
-
# Initializes the current object as though it were in the same context
-
# as a normal ActionView instance using Haml.
-
# This is useful if you want to use the helpers in a context
-
# other than the normal setup with ActionView.
-
# For example:
-
#
-
# context = Object.new
-
# class << context
-
# include Haml::Helpers
-
# end
-
# context.init_haml_helpers
-
# context.haml_tag :p, "Stuff"
-
#
-
1
def init_haml_helpers
-
@haml_buffer = Haml::Buffer.new(haml_buffer, Options.new.for_buffer)
-
nil
-
end
-
-
# Runs a block of code in a non-Haml context
-
# (i.e. \{#is\_haml?} will return false).
-
#
-
# This is mainly useful for rendering sub-templates such as partials in a non-Haml language,
-
# particularly where helpers may behave differently when run from Haml.
-
#
-
# Note that this is automatically applied to Rails partials.
-
#
-
# @yield A block which won't register as Haml
-
1
def non_haml
-
8
was_active = @haml_buffer.active?
-
8
@haml_buffer.active = false
-
8
yield
-
ensure
-
8
@haml_buffer.active = was_active
-
end
-
-
# Uses \{#preserve} to convert any newlines inside whitespace-sensitive tags
-
# into the HTML entities for endlines.
-
#
-
# @param tags [Array<String>] Tags that should have newlines escaped
-
#
-
# @overload find_and_preserve(input, tags = haml_buffer.options[:preserve])
-
# Escapes newlines within a string.
-
#
-
# @param input [String] The string within which to escape newlines
-
# @overload find_and_preserve(tags = haml_buffer.options[:preserve])
-
# Escapes newlines within a block of Haml code.
-
#
-
# @yield The block within which to escape newlines
-
1
def find_and_preserve(input = nil, tags = haml_buffer.options[:preserve], &block)
-
return find_and_preserve(capture_haml(&block), input || tags) if block
-
tags = tags.each_with_object('') do |t, s|
-
s << '|' unless s.empty?
-
s << Regexp.escape(t)
-
end
-
re = /<(#{tags})([^>]*)>(.*?)(<\/\1>)/im
-
input.to_s.gsub(re) do |s|
-
s =~ re # Can't rely on $1, etc. existing since Rails' SafeBuffer#gsub is incompatible
-
"<#{$1}#{$2}>#{preserve($3)}</#{$1}>"
-
end
-
end
-
-
# Takes any string, finds all the newlines, and converts them to
-
# HTML entities so they'll render correctly in
-
# whitespace-sensitive tags without screwing up the indentation.
-
#
-
# @overload preserve(input)
-
# Escapes newlines within a string.
-
#
-
# @param input [String] The string within which to escape all newlines
-
# @overload preserve
-
# Escapes newlines within a block of Haml code.
-
#
-
# @yield The block within which to escape newlines
-
1
def preserve(input = nil, &block)
-
return preserve(capture_haml(&block)) if block
-
s = input.to_s.chomp("\n")
-
s.gsub!(/\n/, '
')
-
s.delete!("\r")
-
s
-
end
-
1
alias_method :flatten, :preserve
-
-
# Takes an `Enumerable` object and a block
-
# and iterates over the enum,
-
# yielding each element to a Haml block
-
# and putting the result into `<li>` elements.
-
# This creates a list of the results of the block.
-
# For example:
-
#
-
# = list_of([['hello'], ['yall']]) do |i|
-
# = i[0]
-
#
-
# Produces:
-
#
-
# <li>hello</li>
-
# <li>yall</li>
-
#
-
# And:
-
#
-
# = list_of({:title => 'All the stuff', :description => 'A book about all the stuff.'}) do |key, val|
-
# %h3= key.humanize
-
# %p= val
-
#
-
# Produces:
-
#
-
# <li>
-
# <h3>Title</h3>
-
# <p>All the stuff</p>
-
# </li>
-
# <li>
-
# <h3>Description</h3>
-
# <p>A book about all the stuff.</p>
-
# </li>
-
#
-
# While:
-
#
-
# = list_of(["Home", "About", "Contact", "FAQ"], {class: "nav", role: "nav"}) do |item|
-
# %a{ href="#" }= item
-
#
-
# Produces:
-
#
-
# <li class='nav' role='nav'>
-
# <a href='#'>Home</a>
-
# </li>
-
# <li class='nav' role='nav'>
-
# <a href='#'>About</a>
-
# </li>
-
# <li class='nav' role='nav'>
-
# <a href='#'>Contact</a>
-
# </li>
-
# <li class='nav' role='nav'>
-
# <a href='#'>FAQ</a>
-
# </li>
-
#
-
# `[[class", "nav"], [role", "nav"]]` could have been used instead of `{class: "nav", role: "nav"}` (or any enumerable collection where each pair of items responds to #to_s)
-
#
-
# @param enum [Enumerable] The list of objects to iterate over
-
# @param [Enumerable<#to_s,#to_s>] opts Each key/value pair will become an attribute pair for each list item element.
-
# @yield [item] A block which contains Haml code that goes within list items
-
# @yieldparam item An element of `enum`
-
1
def list_of(enum, opts={}, &block)
-
opts_attributes = opts.each_with_object('') {|(k, v), s| s << " #{k}='#{v}'"}
-
enum.each_with_object('') do |i, ret|
-
result = capture_haml(i, &block)
-
-
if result.count("\n") > 1
-
result.gsub!("\n", "\n ")
-
result = "\n #{result.strip!}\n"
-
else
-
result.strip!
-
end
-
-
ret << "\n" unless ret.empty?
-
ret << %Q!<li#{opts_attributes}>#{result}</li>!
-
end
-
end
-
-
# Returns a hash containing default assignments for the `xmlns`, `lang`, and `xml:lang`
-
# attributes of the `html` HTML element.
-
# For example,
-
#
-
# %html{html_attrs}
-
#
-
# becomes
-
#
-
# <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en-US' lang='en-US'>
-
#
-
# @param lang [String] The value of `xml:lang` and `lang`
-
# @return [{#to_s => String}] The attribute hash
-
1
def html_attrs(lang = 'en-US')
-
if haml_buffer.options[:format] == :xhtml
-
{:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang}
-
else
-
{:lang => lang}
-
end
-
end
-
-
# Increments the number of tabs the buffer automatically adds
-
# to the lines of the template.
-
# For example:
-
#
-
# %h1 foo
-
# - tab_up
-
# %p bar
-
# - tab_down
-
# %strong baz
-
#
-
# Produces:
-
#
-
# <h1>foo</h1>
-
# <p>bar</p>
-
# <strong>baz</strong>
-
#
-
# @param i [Fixnum] The number of tabs by which to increase the indentation
-
# @see #tab_down
-
1
def tab_up(i = 1)
-
haml_buffer.tabulation += i
-
end
-
-
# Decrements the number of tabs the buffer automatically adds
-
# to the lines of the template.
-
#
-
# @param i [Fixnum] The number of tabs by which to decrease the indentation
-
# @see #tab_up
-
1
def tab_down(i = 1)
-
haml_buffer.tabulation -= i
-
end
-
-
# Sets the number of tabs the buffer automatically adds
-
# to the lines of the template,
-
# but only for the duration of the block.
-
# For example:
-
#
-
# %h1 foo
-
# - with_tabs(2) do
-
# %p bar
-
# %strong baz
-
#
-
# Produces:
-
#
-
# <h1>foo</h1>
-
# <p>bar</p>
-
# <strong>baz</strong>
-
#
-
#
-
# @param i [Fixnum] The number of tabs to use
-
# @yield A block in which the indentation will be `i` spaces
-
1
def with_tabs(i)
-
old_tabs = haml_buffer.tabulation
-
haml_buffer.tabulation = i
-
yield
-
ensure
-
haml_buffer.tabulation = old_tabs
-
end
-
-
# Surrounds a block of Haml code with strings,
-
# with no whitespace in between.
-
# For example:
-
#
-
# = surround '(', ')' do
-
# %a{:href => "food"} chicken
-
#
-
# Produces:
-
#
-
# (<a href='food'>chicken</a>)
-
#
-
# and
-
#
-
# = surround '*' do
-
# %strong angry
-
#
-
# Produces:
-
#
-
# *<strong>angry</strong>*
-
#
-
# @param front [String] The string to add before the Haml
-
# @param back [String] The string to add after the Haml
-
# @yield A block of Haml to surround
-
1
def surround(front, back = front, &block)
-
output = capture_haml(&block)
-
-
"#{front}#{output.chomp}#{back}\n"
-
end
-
-
# Prepends a string to the beginning of a Haml block,
-
# with no whitespace between.
-
# For example:
-
#
-
# = precede '*' do
-
# %span.small Not really
-
#
-
# Produces:
-
#
-
# *<span class='small'>Not really</span>
-
#
-
# @param str [String] The string to add before the Haml
-
# @yield A block of Haml to prepend to
-
1
def precede(str, &block)
-
"#{str}#{capture_haml(&block).chomp}\n"
-
end
-
-
# Appends a string to the end of a Haml block,
-
# with no whitespace between.
-
# For example:
-
#
-
# click
-
# = succeed '.' do
-
# %a{:href=>"thing"} here
-
#
-
# Produces:
-
#
-
# click
-
# <a href='thing'>here</a>.
-
#
-
# @param str [String] The string to add after the Haml
-
# @yield A block of Haml to append to
-
1
def succeed(str, &block)
-
"#{capture_haml(&block).chomp}#{str}\n"
-
end
-
-
# Captures the result of a block of Haml code,
-
# gets rid of the excess indentation,
-
# and returns it as a string.
-
# For example, after the following,
-
#
-
# .foo
-
# - foo = capture_haml(13) do |a|
-
# %p= a
-
#
-
# the local variable `foo` would be assigned to `"<p>13</p>\n"`.
-
#
-
# @param args [Array] Arguments to pass into the block
-
# @yield [args] A block of Haml code that will be converted to a string
-
# @yieldparam args [Array] `args`
-
1
def capture_haml(*args, &block)
-
8
buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer
-
8
with_haml_buffer(buffer) do
-
8
position = haml_buffer.buffer.length
-
-
8
haml_buffer.capture_position = position
-
8
value = block.call(*args)
-
-
8
captured = haml_buffer.buffer.slice!(position..-1)
-
-
8
if captured == '' and value != haml_buffer.buffer
-
captured = (value.is_a?(String) ? value : nil)
-
end
-
-
8
captured
-
end
-
ensure
-
8
haml_buffer.capture_position = nil
-
end
-
-
# Outputs text directly to the Haml buffer, with the proper indentation.
-
#
-
# @param text [#to_s] The text to output
-
1
def haml_concat(text = "")
-
haml_internal_concat text
-
ErrorReturn.new("haml_concat")
-
end
-
-
# Internal method to write directly to the buffer with control of
-
# whether the first line should be indented, and if there should be a
-
# final newline.
-
#
-
# Lines added will have the proper indentation. This can be controlled
-
# for the first line.
-
#
-
# Used by #haml_concat and #haml_tag.
-
#
-
# @param text [#to_s] The text to output
-
# @param newline [Boolean] Whether to add a newline after the text
-
# @param indent [Boolean] Whether to add indentation to the first line
-
1
def haml_internal_concat(text = "", newline = true, indent = true)
-
if haml_buffer.tabulation == 0
-
haml_buffer.buffer << "#{text}#{"\n" if newline}"
-
else
-
haml_buffer.buffer << %[#{haml_indent if indent}#{text.to_s.gsub("\n", "\n#{haml_indent}")}#{"\n" if newline}]
-
end
-
end
-
1
private :haml_internal_concat
-
-
# Allows writing raw content. `haml_internal_concat_raw` isn't
-
# effected by XSS mods. Used by #haml_tag to write the actual tags.
-
1
alias :haml_internal_concat_raw :haml_internal_concat
-
-
# @return [String] The indentation string for the current line
-
1
def haml_indent
-
' ' * haml_buffer.tabulation
-
end
-
-
# Creates an HTML tag with the given name and optionally text and attributes.
-
# Can take a block that will run between the opening and closing tags.
-
# If the block is a Haml block or outputs text using \{#haml\_concat},
-
# the text will be properly indented.
-
#
-
# `name` can be a string using the standard Haml class/id shorthand
-
# (e.g. "span#foo.bar", "#foo").
-
# Just like standard Haml tags, these class and id values
-
# will be merged with manually-specified attributes.
-
#
-
# `flags` is a list of symbol flags
-
# like those that can be put at the end of a Haml tag
-
# (`:/`, `:<`, and `:>`).
-
# Currently, only `:/` and `:<` are supported.
-
#
-
# `haml_tag` outputs directly to the buffer;
-
# its return value should not be used.
-
# If you need to get the results as a string,
-
# use \{#capture\_haml\}.
-
#
-
# For example,
-
#
-
# haml_tag :table do
-
# haml_tag :tr do
-
# haml_tag 'td.cell' do
-
# haml_tag :strong, "strong!"
-
# haml_concat "data"
-
# end
-
# haml_tag :td do
-
# haml_concat "more_data"
-
# end
-
# end
-
# end
-
#
-
# outputs
-
#
-
# <table>
-
# <tr>
-
# <td class='cell'>
-
# <strong>
-
# strong!
-
# </strong>
-
# data
-
# </td>
-
# <td>
-
# more_data
-
# </td>
-
# </tr>
-
# </table>
-
#
-
# @param name [#to_s] The name of the tag
-
#
-
# @overload haml_tag(name, *rest, attributes = {})
-
# @yield The block of Haml code within the tag
-
# @overload haml_tag(name, text, *flags, attributes = {})
-
# @param text [#to_s] The text within the tag
-
# @param flags [Array<Symbol>] Haml end-of-tag flags
-
1
def haml_tag(name, *rest, &block)
-
ret = ErrorReturn.new("haml_tag")
-
-
text = rest.shift.to_s unless [Symbol, Hash, NilClass].any? {|t| rest.first.is_a? t}
-
flags = []
-
flags << rest.shift while rest.first.is_a? Symbol
-
attrs = (rest.shift || {})
-
attrs.keys.each {|key| attrs[key.to_s] = attrs.delete(key)} unless attrs.empty?
-
name, attrs = merge_name_and_attributes(name.to_s, attrs)
-
-
attributes = Haml::AttributeBuilder.build_attributes(haml_buffer.html?,
-
haml_buffer.options[:attr_wrapper],
-
haml_buffer.options[:escape_attrs],
-
haml_buffer.options[:hyphenate_data_attrs],
-
attrs)
-
-
if text.nil? && block.nil? && (haml_buffer.options[:autoclose].include?(name) || flags.include?(:/))
-
haml_internal_concat_raw "<#{name}#{attributes}#{' /' if haml_buffer.options[:format] == :xhtml}>"
-
return ret
-
end
-
-
if flags.include?(:/)
-
raise Error.new(Error.message(:self_closing_content)) if text
-
raise Error.new(Error.message(:illegal_nesting_self_closing)) if block
-
end
-
-
tag = "<#{name}#{attributes}>"
-
end_tag = "</#{name}>"
-
if block.nil?
-
text = text.to_s
-
if text.include?("\n")
-
haml_internal_concat_raw tag
-
tab_up
-
haml_internal_concat text
-
tab_down
-
haml_internal_concat_raw end_tag
-
else
-
haml_internal_concat_raw tag, false
-
haml_internal_concat text, false, false
-
haml_internal_concat_raw end_tag, true, false
-
end
-
return ret
-
end
-
-
if text
-
raise Error.new(Error.message(:illegal_nesting_line, name))
-
end
-
-
if flags.include?(:<)
-
haml_internal_concat_raw tag, false
-
haml_internal_concat "#{capture_haml(&block).strip}", false, false
-
haml_internal_concat_raw end_tag, true, false
-
return ret
-
end
-
-
haml_internal_concat_raw tag
-
tab_up
-
block.call
-
tab_down
-
haml_internal_concat_raw end_tag
-
-
ret
-
end
-
-
# Conditionally wrap a block in an element. If `condition` is `true` then
-
# this method renders the tag described by the arguments in `tag` (using
-
# \{#haml_tag}) with the given block inside, otherwise it just renders the block.
-
#
-
# For example,
-
#
-
# - haml_tag_if important, '.important' do
-
# %p
-
# A (possibly) important paragraph.
-
#
-
# will produce
-
#
-
# <div class='important'>
-
# <p>
-
# A (possibly) important paragraph.
-
# </p>
-
# </div>
-
#
-
# if `important` is truthy, and just
-
#
-
# <p>
-
# A (possibly) important paragraph.
-
# </p>
-
#
-
# otherwise.
-
#
-
# Like \{#haml_tag}, `haml_tag_if` outputs directly to the buffer and its
-
# return value should not be used. Use \{#capture_haml} if you need to use
-
# its results as a string.
-
#
-
# @param condition The condition to test to determine whether to render
-
# the enclosing tag
-
# @param tag Definition of the enclosing tag. See \{#haml_tag} for details
-
# (specifically the form that takes a block)
-
1
def haml_tag_if(condition, *tag)
-
if condition
-
haml_tag(*tag){ yield }
-
else
-
yield
-
end
-
ErrorReturn.new("haml_tag_if")
-
end
-
-
# Characters that need to be escaped to HTML entities from user input
-
1
HTML_ESCAPE = { '&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => ''' }
-
-
1
HTML_ESCAPE_REGEX = /['"><&]/
-
-
# Returns a copy of `text` with ampersands, angle brackets and quotes
-
# escaped into HTML entities.
-
#
-
# Note that if ActionView is loaded and XSS protection is enabled
-
# (as is the default for Rails 3.0+, and optional for version 2.3.5+),
-
# this won't escape text declared as "safe".
-
#
-
# @param text [String] The string to sanitize
-
# @return [String] The sanitized string
-
1
def html_escape(text)
-
197
ERB::Util.html_escape(text)
-
end
-
-
1
HTML_ESCAPE_ONCE_REGEX = /['"><]|&(?!(?:[a-zA-Z]+|#(?:\d+|[xX][0-9a-fA-F]+));)/
-
-
# Escapes HTML entities in `text`, but without escaping an ampersand
-
# that is already part of an escaped entity.
-
#
-
# @param text [String] The string to sanitize
-
# @return [String] The sanitized string
-
1
def escape_once(text)
-
text = text.to_s
-
text.gsub(HTML_ESCAPE_ONCE_REGEX, HTML_ESCAPE)
-
end
-
-
# Returns whether or not the current template is a Haml template.
-
#
-
# This function, unlike other {Haml::Helpers} functions,
-
# also works in other `ActionView` templates,
-
# where it will always return false.
-
#
-
# @return [Boolean] Whether or not the current template is a Haml template
-
1
def is_haml?
-
320
!@haml_buffer.nil? && @haml_buffer.active?
-
end
-
-
# Returns whether or not `block` is defined directly in a Haml template.
-
#
-
# @param block [Proc] A Ruby block
-
# @return [Boolean] Whether or not `block` is defined directly in a Haml template
-
1
def block_is_haml?(block)
-
8
eval('!!defined?(_hamlout)', block.binding)
-
end
-
-
1
private
-
-
# Parses the tag name used for \{#haml\_tag}
-
# and merges it with the Ruby attributes hash.
-
1
def merge_name_and_attributes(name, attributes_hash = {})
-
# skip merging if no ids or classes found in name
-
return name, attributes_hash unless name =~ /^(.+?)?([\.#].*)$/
-
-
return $1 || "div", AttributeBuilder.merge_attributes!(
-
Haml::Parser.parse_class_and_id($2), attributes_hash)
-
end
-
-
# Runs a block of code with the given buffer as the currently active buffer.
-
#
-
# @param buffer [Haml::Buffer] The Haml buffer to use temporarily
-
# @yield A block in which the given buffer should be used
-
1
def with_haml_buffer(buffer)
-
8
@haml_buffer, old_buffer = buffer, @haml_buffer
-
8
old_buffer.active, old_was_active = false, old_buffer.active? if old_buffer
-
8
@haml_buffer.active, was_active = true, @haml_buffer.active?
-
8
yield
-
ensure
-
8
@haml_buffer.active = was_active
-
8
old_buffer.active = old_was_active if old_buffer
-
8
@haml_buffer = old_buffer
-
end
-
-
# The current {Haml::Buffer} object.
-
#
-
# @return [Haml::Buffer]
-
1
def haml_buffer
-
462
@haml_buffer if defined? @haml_buffer
-
end
-
-
# Gives a proc the same local `_hamlout` and `_erbout` variables
-
# that the current template has.
-
#
-
# @param proc [#call] The proc to bind
-
# @return [Proc] A new proc with the new variables bound
-
1
def haml_bind_proc(&proc)
-
_hamlout = haml_buffer
-
#double assignment is to avoid warnings
-
_erbout = _erbout = _hamlout.buffer
-
proc { |*args| proc.call(*args) }
-
end
-
end
-
end
-
-
# @private
-
1
class Object
-
# Haml overrides various `ActionView` helpers,
-
# which call an \{#is\_haml?} method
-
# to determine whether or not the current context object
-
# is a proper Haml context.
-
# Because `ActionView` helpers may be included in non-`ActionView::Base` classes,
-
# it's a good idea to define \{#is\_haml?} for all objects.
-
1
def is_haml?
-
144
false
-
end
-
end
-
-
# frozen_string_literal: true
-
1
module Haml
-
1
module Helpers
-
1
@@action_view_defined = true
-
-
# This module contains various useful helper methods
-
# that either tie into ActionView or the rest of the ActionPack stack,
-
# or are only useful in that context.
-
# Thus, the methods defined here are only available
-
# if ActionView is installed.
-
1
module ActionViewExtensions
-
# Returns a value for the "class" attribute
-
# unique to this controller/action pair.
-
# This can be used to target styles specifically at this action or controller.
-
# For example, if the current action were `EntryController#show`,
-
#
-
# %div{:class => page_class} My Div
-
#
-
# would become
-
#
-
# <div class="entry show">My Div</div>
-
#
-
# Then, in a stylesheet (shown here as [Sass](http://sass-lang.com)),
-
# you could refer to this specific action:
-
#
-
# .entry.show
-
# font-weight: bold
-
#
-
# or to all actions in the entry controller:
-
#
-
# .entry
-
# color: #00f
-
#
-
# @return [String] The class name for the current page
-
1
def page_class
-
"#{controller.controller_name} #{controller.action_name}"
-
end
-
1
alias_method :generate_content_class_names, :page_class
-
-
# Treats all input to \{Haml::Helpers#haml\_concat} within the block
-
# as being HTML safe for Rails' XSS protection.
-
# This is useful for wrapping blocks of code that concatenate HTML en masse.
-
#
-
# This has no effect if Rails' XSS protection isn't enabled.
-
#
-
# @yield A block in which all input to `#haml_concat` is treated as raw.
-
# @see Haml::Util#rails_xss_safe?
-
1
def with_raw_haml_concat
-
old = instance_variable_defined?(:@_haml_concat_raw) ? @_haml_concat_raw : false
-
@_haml_concat_raw = true
-
yield
-
ensure
-
@_haml_concat_raw = old
-
end
-
end
-
-
1
include ActionViewExtensions
-
end
-
end
-
# frozen_string_literal: true
-
1
module Haml
-
1
module Helpers
-
1
module ActionViewMods
-
1
def render(*args, &block)
-
8
options = args.first
-
-
# If render :layout is used with a block, it concats rather than returning
-
# a string so we need it to keep thinking it's Haml until it hits the
-
# sub-render.
-
8
if is_haml? && !(options.is_a?(Hash) && options[:layout] && block_given?)
-
16
return non_haml { super }
-
end
-
super
-
end
-
-
1
def output_buffer
-
return haml_buffer.buffer if is_haml?
-
super
-
end
-
-
1
def output_buffer=(new_buffer)
-
if is_haml?
-
if Haml::Util.rails_xss_safe? && new_buffer.is_a?(ActiveSupport::SafeBuffer)
-
new_buffer = String.new(new_buffer)
-
end
-
haml_buffer.buffer = new_buffer
-
else
-
super
-
end
-
end
-
end
-
1
ActionView::Base.send(:prepend, ActionViewMods)
-
end
-
end
-
-
1
module ActionView
-
1
module Helpers
-
1
module CaptureHelper
-
1
def capture_with_haml(*args, &block)
-
8
if Haml::Helpers.block_is_haml?(block)
-
#double assignment is to avoid warnings
-
8
_hamlout = _hamlout = eval('_hamlout', block.binding) # Necessary since capture_haml checks _hamlout
-
-
8
capture_haml(*args, &block)
-
else
-
capture_without_haml(*args, &block)
-
end
-
end
-
1
alias_method :capture_without_haml, :capture
-
1
alias_method :capture, :capture_with_haml
-
end
-
-
1
module TagHelper
-
1
def content_tag_with_haml(name, *args, &block)
-
456
return content_tag_without_haml(name, *args, &block) unless is_haml?
-
-
312
preserve = haml_buffer.options.fetch(:preserve, %w[textarea pre code]).include?(name.to_s)
-
-
312
if block_given? && block_is_haml?(block) && preserve
-
return content_tag_without_haml(name, *args) {preserve(&block)}
-
end
-
-
312
content = content_tag_without_haml(name, *args, &block)
-
312
content = Haml::Helpers.preserve(content) if preserve && content
-
312
content
-
end
-
-
1
alias_method :content_tag_without_haml, :content_tag
-
1
alias_method :content_tag, :content_tag_with_haml
-
end
-
-
1
module HamlSupport
-
1
include Haml::Helpers
-
-
1
def haml_buffer
-
@template_object.send :haml_buffer
-
end
-
-
1
def is_haml?
-
@template_object.send :is_haml?
-
end
-
end
-
-
1
module Tags
-
1
class TextArea
-
1
include HamlSupport
-
end
-
end
-
-
1
class InstanceTag
-
1
include HamlSupport
-
-
1
def content_tag(*args, &block)
-
html_tag = content_tag_with_haml(*args, &block)
-
return html_tag unless respond_to?(:error_wrapping)
-
return error_wrapping(html_tag) if method(:error_wrapping).arity == 1
-
return html_tag unless object.respond_to?(:errors) && object.errors.respond_to?(:on)
-
return error_wrapping(html_tag, object.errors.on(@method_name))
-
end
-
end
-
-
1
module FormTagHelper
-
1
def form_tag_with_haml(url_for_options = {}, options = {}, *parameters_for_url, &proc)
-
if is_haml?
-
wrap_block = block_given? && block_is_haml?(proc)
-
if wrap_block
-
oldproc = proc
-
proc = haml_bind_proc do |*args|
-
concat "\n"
-
with_tabs(1) {oldproc.call(*args)}
-
end
-
end
-
res = form_tag_without_haml(url_for_options, options, *parameters_for_url, &proc) << "\n"
-
res << "\n" if wrap_block
-
res
-
else
-
form_tag_without_haml(url_for_options, options, *parameters_for_url, &proc)
-
end
-
end
-
1
alias_method :form_tag_without_haml, :form_tag
-
1
alias_method :form_tag, :form_tag_with_haml
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module ActionView
-
1
module Helpers
-
1
module CaptureHelper
-
1
def with_output_buffer_with_haml_xss(*args, &block)
-
res = with_output_buffer_without_haml_xss(*args, &block)
-
case res
-
when Array; res.map {|s| Haml::Util.html_safe(s)}
-
when String; Haml::Util.html_safe(res)
-
else; res
-
end
-
end
-
1
alias_method :with_output_buffer_without_haml_xss, :with_output_buffer
-
1
alias_method :with_output_buffer, :with_output_buffer_with_haml_xss
-
end
-
-
1
module FormTagHelper
-
1
def form_tag_with_haml_xss(*args, &block)
-
res = form_tag_without_haml_xss(*args, &block)
-
res = Haml::Util.html_safe(res) unless block_given?
-
res
-
end
-
1
alias_method :form_tag_without_haml_xss, :form_tag
-
1
alias_method :form_tag, :form_tag_with_haml_xss
-
end
-
-
1
module FormHelper
-
1
def form_for_with_haml_xss(*args, &block)
-
8
res = form_for_without_haml_xss(*args, &block)
-
8
return Haml::Util.html_safe(res) if res.is_a?(String)
-
return res
-
end
-
1
alias_method :form_for_without_haml_xss, :form_for
-
1
alias_method :form_for, :form_for_with_haml_xss
-
end
-
-
1
module TextHelper
-
1
def concat_with_haml_xss(string)
-
if is_haml?
-
haml_buffer.buffer.concat(haml_xss_html_escape(string))
-
else
-
concat_without_haml_xss(string)
-
end
-
end
-
1
alias_method :concat_without_haml_xss, :concat
-
1
alias_method :concat, :concat_with_haml_xss
-
-
1
def safe_concat_with_haml_xss(string)
-
if is_haml?
-
haml_buffer.buffer.concat(string)
-
else
-
safe_concat_without_haml_xss(string)
-
end
-
end
-
1
alias_method :safe_concat_without_haml_xss, :safe_concat
-
1
alias_method :safe_concat, :safe_concat_with_haml_xss
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'action_view'
-
-
1
module Haml
-
-
1
class ErubisTemplateHandler < ActionView::Template::Handlers::Erubis
-
-
1
def initialize(*args, &blk)
-
@newline_pending = 0
-
super
-
end
-
end
-
-
1
class SafeErubisTemplate < Tilt::ErubisTemplate
-
-
1
def initialize_engine
-
end
-
-
1
def prepare
-
@options.merge! :engine_class => Haml::ErubisTemplateHandler
-
super
-
end
-
-
1
def precompiled_preamble(locals)
-
[super, "@output_buffer = ActionView::OutputBuffer.new;"].join("\n")
-
end
-
-
1
def precompiled_postamble(locals)
-
[super, '@output_buffer.to_s'].join("\n")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module Haml
-
1
module Helpers
-
# This module overrides Haml helpers to work properly
-
# in the context of ActionView.
-
# Currently it's only used for modifying the helpers
-
# to work with Rails' XSS protection methods.
-
1
module XssMods
-
1
def self.included(base)
-
%w[html_escape find_and_preserve preserve list_of surround
-
precede succeed capture_haml haml_concat haml_internal_concat haml_indent
-
1
escape_once].each do |name|
-
12
base.send(:alias_method, "#{name}_without_haml_xss", name)
-
12
base.send(:alias_method, name, "#{name}_with_haml_xss")
-
end
-
end
-
-
# Don't escape text that's already safe,
-
# output is always HTML safe
-
1
def html_escape_with_haml_xss(text)
-
694
str = text.to_s
-
694
return text if str.html_safe?
-
197
Haml::Util.html_safe(html_escape_without_haml_xss(str))
-
end
-
-
# Output is always HTML safe
-
1
def find_and_preserve_with_haml_xss(*args, &block)
-
Haml::Util.html_safe(find_and_preserve_without_haml_xss(*args, &block))
-
end
-
-
# Output is always HTML safe
-
1
def preserve_with_haml_xss(*args, &block)
-
Haml::Util.html_safe(preserve_without_haml_xss(*args, &block))
-
end
-
-
# Output is always HTML safe
-
1
def list_of_with_haml_xss(*args, &block)
-
Haml::Util.html_safe(list_of_without_haml_xss(*args, &block))
-
end
-
-
# Input is escaped, output is always HTML safe
-
1
def surround_with_haml_xss(front, back = front, &block)
-
Haml::Util.html_safe(
-
surround_without_haml_xss(
-
haml_xss_html_escape(front),
-
haml_xss_html_escape(back),
-
&block))
-
end
-
-
# Input is escaped, output is always HTML safe
-
1
def precede_with_haml_xss(str, &block)
-
Haml::Util.html_safe(precede_without_haml_xss(haml_xss_html_escape(str), &block))
-
end
-
-
# Input is escaped, output is always HTML safe
-
1
def succeed_with_haml_xss(str, &block)
-
Haml::Util.html_safe(succeed_without_haml_xss(haml_xss_html_escape(str), &block))
-
end
-
-
# Output is always HTML safe
-
1
def capture_haml_with_haml_xss(*args, &block)
-
8
Haml::Util.html_safe(capture_haml_without_haml_xss(*args, &block))
-
end
-
-
# Input will be escaped unless this is in a `with_raw_haml_concat`
-
# block. See #Haml::Helpers::ActionViewExtensions#with_raw_haml_concat.
-
1
def haml_concat_with_haml_xss(text = "")
-
raw = instance_variable_defined?(:@_haml_concat_raw) ? @_haml_concat_raw : false
-
if raw
-
haml_internal_concat_raw text
-
else
-
haml_internal_concat text
-
end
-
ErrorReturn.new("haml_concat")
-
end
-
-
# Input is escaped
-
1
def haml_internal_concat_with_haml_xss(text="", newline=true, indent=true)
-
haml_internal_concat_without_haml_xss(haml_xss_html_escape(text), newline, indent)
-
end
-
1
private :haml_internal_concat_with_haml_xss
-
-
# Output is always HTML safe
-
1
def haml_indent_with_haml_xss
-
Haml::Util.html_safe(haml_indent_without_haml_xss)
-
end
-
-
# Output is always HTML safe
-
1
def escape_once_with_haml_xss(*args)
-
Haml::Util.html_safe(escape_once_without_haml_xss(*args))
-
end
-
-
1
private
-
-
# Escapes the HTML in the text if and only if
-
# Rails XSS protection is enabled *and* the `:escape_html` option is set.
-
1
def haml_xss_html_escape(text)
-
return text unless Haml::Util.rails_xss_safe? && haml_buffer.options[:escape_html]
-
html_escape(text)
-
end
-
end
-
-
1
class ErrorReturn
-
# Any attempt to treat ErrorReturn as a string should cause it to blow up.
-
1
alias_method :html_safe, :to_s
-
1
alias_method :html_safe?, :to_s
-
1
alias_method :html_safe!, :to_s
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module Haml
-
# This class encapsulates all of the configuration options that Haml
-
# understands. Please see the {file:REFERENCE.md#options Haml Reference} to
-
# learn how to set the options.
-
1
class Options
-
-
1
@valid_formats = [:html4, :html5, :xhtml]
-
-
1
@buffer_option_keys = [:autoclose, :preserve, :attr_wrapper, :format,
-
:encoding, :escape_html, :escape_attrs, :hyphenate_data_attrs, :cdata]
-
-
# The default option values.
-
# @return Hash
-
1
def self.defaults
-
1373
@defaults ||= Haml::TempleEngine.options.to_hash.merge(encoding: 'UTF-8')
-
end
-
-
# An array of valid values for the `:format` option.
-
# @return Array
-
1
def self.valid_formats
-
66
@valid_formats
-
end
-
-
# An array of keys that will be used to provide a hash of options to
-
# {Haml::Buffer}.
-
# @return Hash
-
1
def self.buffer_option_keys
-
23
@buffer_option_keys
-
end
-
-
# Returns a subset of defaults: those that {Haml::Buffer} cares about.
-
# @return [{Symbol => Object}] The options hash
-
1
def self.buffer_defaults
-
@buffer_defaults ||= buffer_option_keys.inject({}) do |hash, key|
-
9
hash.merge(key => defaults[key])
-
363
end
-
end
-
-
1
def self.wrap(options)
-
44
if options.is_a?(Options)
-
options
-
else
-
44
Options.new(options)
-
end
-
end
-
-
# The character that should wrap element attributes. This defaults to `'`
-
# (an apostrophe). Characters of this type within the attributes will be
-
# escaped (e.g. by replacing them with `'`) if the character is an
-
# apostrophe or a quotation mark.
-
1
attr_reader :attr_wrapper
-
-
# A list of tag names that should be automatically self-closed if they have
-
# no content. This can also contain regular expressions that match tag names
-
# (or any object which responds to `#===`). Defaults to `['meta', 'img',
-
# 'link', 'br', 'hr', 'input', 'area', 'param', 'col', 'base']`.
-
1
attr_accessor :autoclose
-
-
# The encoding to use for the HTML output.
-
# This can be a string or an `Encoding` Object. Note that Haml **does not**
-
# automatically re-encode Ruby values; any strings coming from outside the
-
# application should be converted before being passed into the Haml
-
# template. Defaults to `Encoding.default_internal`; if that's not set,
-
# defaults to the encoding of the Haml template; if that's `US-ASCII`,
-
# defaults to `"UTF-8"`.
-
1
attr_reader :encoding
-
-
# Sets whether or not to escape HTML-sensitive characters in attributes. If
-
# this is true, all HTML-sensitive characters in attributes are escaped. If
-
# it's set to false, no HTML-sensitive characters in attributes are escaped.
-
# If it's set to `:once`, existing HTML escape sequences are preserved, but
-
# other HTML-sensitive characters are escaped.
-
#
-
# Defaults to `true`.
-
1
attr_accessor :escape_attrs
-
-
# Sets whether or not to escape HTML-sensitive characters in script. If this
-
# is true, `=` behaves like {file:REFERENCE.md#escaping_html `&=`};
-
# otherwise, it behaves like {file:REFERENCE.md#unescaping_html `!=`}. Note
-
# that if this is set, `!=` should be used for yielding to subtemplates and
-
# rendering partials. See also {file:REFERENCE.md#escaping_html Escaping HTML} and
-
# {file:REFERENCE.md#unescaping_html Unescaping HTML}.
-
#
-
# Defaults to false.
-
1
attr_accessor :escape_html
-
-
# The name of the Haml file being parsed.
-
# This is only used as information when exceptions are raised. This is
-
# automatically assigned when working through ActionView, so it's really
-
# only useful for the user to assign when dealing with Haml programatically.
-
1
attr_accessor :filename
-
-
# If set to `true`, Haml will convert underscores to hyphens in all
-
# {file:REFERENCE.md#html5_custom_data_attributes Custom Data Attributes} As
-
# of Haml 4.0, this defaults to `true`.
-
1
attr_accessor :hyphenate_data_attrs
-
-
# The line offset of the Haml template being parsed. This is useful for
-
# inline templates, similar to the last argument to `Kernel#eval`.
-
1
attr_accessor :line
-
-
# Determines the output format. The default is `:html5`. The other options
-
# are `:html4` and `:xhtml`. If the output is set to XHTML, then Haml
-
# automatically generates self-closing tags and wraps the output of the
-
# Javascript and CSS-like filters inside CDATA. When the output is set to
-
# `:html5` or `:html4`, XML prologs are ignored. In all cases, an appropriate
-
# doctype is generated from `!!!`.
-
#
-
# If the mime_type of the template being rendered is `text/xml` then a
-
# format of `:xhtml` will be used even if the global output format is set to
-
# `:html4` or `:html5`.
-
1
attr :format
-
-
# The mime type that the rendered document will be served with. If this is
-
# set to `text/xml` then the format will be overridden to `:xhtml` even if
-
# it has set to `:html4` or `:html5`.
-
1
attr_accessor :mime_type
-
-
# A list of tag names that should automatically have their newlines
-
# preserved using the {Haml::Helpers#preserve} helper. This means that any
-
# content given on the same line as the tag will be preserved. For example,
-
# `%textarea= "Foo\nBar"` compiles to `<textarea>Foo
Bar</textarea>`.
-
# Defaults to `['textarea', 'pre']`. See also
-
# {file:REFERENCE.md#whitespace_preservation Whitespace Preservation}.
-
1
attr_accessor :preserve
-
-
# If set to `true`, all tags are treated as if both
-
# {file:REFERENCE.md#whitespace_removal__and_ whitespace removal} options
-
# were present. Use with caution as this may cause whitespace-related
-
# formatting errors.
-
#
-
# Defaults to `false`.
-
1
attr_reader :remove_whitespace
-
-
# Whether or not attribute hashes and Ruby scripts designated by `=` or `~`
-
# should be evaluated. If this is `true`, said scripts are rendered as empty
-
# strings.
-
#
-
# Defaults to `false`.
-
1
attr_accessor :suppress_eval
-
-
# Whether to include CDATA sections around javascript and css blocks when
-
# using the `:javascript` or `:css` filters.
-
#
-
# This option also affects the `:sass`, `:scss`, `:less` and `:coffeescript`
-
# filters.
-
#
-
# Defaults to `false` for html, `true` for xhtml. Cannot be changed when using
-
# xhtml.
-
1
attr_accessor :cdata
-
-
# The parser class to use. Defaults to Haml::Parser.
-
1
attr_accessor :parser_class
-
-
# The compiler class to use. Defaults to Haml::Compiler.
-
1
attr_accessor :compiler_class
-
-
# Enable template tracing. If true, it will add a 'data-trace' attribute to
-
# each tag generated by Haml. The value of the attribute will be the
-
# source template name and the line number from which the tag was generated,
-
# separated by a colon. On Rails applications, the path given will be a
-
# relative path as from the views directory. On non-Rails applications,
-
# the path will be the full path.
-
1
attr_accessor :trace
-
-
# Key is filter name in String and value is Class to use. Defaults to {}.
-
1
attr_accessor :filters
-
-
1
def initialize(values = {}, &block)
-
1672
defaults.each {|k, v| instance_variable_set :"@#{k}", v}
-
1364
values.each {|k, v| send("#{k}=", v) if defaults.has_key?(k) && !v.nil?}
-
88
yield if block_given?
-
end
-
-
# Retrieve an option value.
-
# @param key The value to retrieve.
-
1
def [](key)
-
247
send key
-
end
-
-
# Set an option value.
-
# @param key The key to set.
-
# @param value The value to set for the key.
-
1
def []=(key, value)
-
send "#{key}=", value
-
end
-
-
1
[:escape_attrs, :hyphenate_data_attrs, :remove_whitespace, :suppress_eval].each do |method|
-
4
class_eval(<<-END)
-
def #{method}?
-
!! @#{method}
-
end
-
END
-
end
-
-
# @return [Boolean] Whether or not the format is XHTML.
-
1
def xhtml?
-
34
not html?
-
end
-
-
# @return [Boolean] Whether or not the format is any flavor of HTML.
-
1
def html?
-
46
html4? or html5?
-
end
-
-
# @return [Boolean] Whether or not the format is HTML4.
-
1
def html4?
-
46
format == :html4
-
end
-
-
# @return [Boolean] Whether or not the format is HTML5.
-
1
def html5?
-
47
format == :html5
-
end
-
-
1
def attr_wrapper=(value)
-
66
@attr_wrapper = value || self.class.defaults[:attr_wrapper]
-
end
-
-
# Undef :format to suppress warning. It's defined above with the `:attr`
-
# macro in order to make it appear in Yard's list of instance attributes.
-
1
undef :format
-
1
def format
-
137
mime_type == "text/xml" ? :xhtml : @format
-
end
-
-
1
def format=(value)
-
66
unless self.class.valid_formats.include?(value)
-
raise Haml::Error, "Invalid output format #{value.inspect}"
-
end
-
66
@format = value
-
end
-
-
1
undef :cdata
-
1
def cdata
-
22
xhtml? || @cdata
-
end
-
-
1
def remove_whitespace=(value)
-
66
@remove_whitespace = value
-
end
-
-
1
def encoding=(value)
-
return unless value
-
@encoding = value.is_a?(Encoding) ? value.name : value.to_s
-
@encoding = "UTF-8" if @encoding.upcase == "US-ASCII"
-
end
-
-
# Returns a non-default subset of options: those that {Haml::Buffer} cares about.
-
# All of the values here are such that when `#inspect` is called on the hash,
-
# it can be `Kernel#eval`ed to get the same result back.
-
#
-
# See {file:REFERENCE.md#options the Haml options documentation}.
-
#
-
# @return [{Symbol => Object}] The options hash
-
1
def for_buffer
-
22
self.class.buffer_option_keys.inject({}) do |hash, key|
-
198
value = public_send(key)
-
198
if self.class.buffer_defaults[key] != value
-
hash[key] = value
-
end
-
198
hash
-
end
-
end
-
-
1
private
-
-
1
def defaults
-
1364
self.class.defaults
-
end
-
end
-
end
-
# frozen_string_literal: false
-
1
require 'strscan'
-
-
1
module Haml
-
1
class Parser
-
1
include Haml::Util
-
-
1
attr_reader :root
-
-
# Designates an XHTML/XML element.
-
1
ELEMENT = ?%
-
-
# Designates a `<div>` element with the given class.
-
1
DIV_CLASS = ?.
-
-
# Designates a `<div>` element with the given id.
-
1
DIV_ID = ?#
-
-
# Designates an XHTML/XML comment.
-
1
COMMENT = ?/
-
-
# Designates an XHTML doctype or script that is never HTML-escaped.
-
1
DOCTYPE = ?!
-
-
# Designates script, the result of which is output.
-
1
SCRIPT = ?=
-
-
# Designates script that is always HTML-escaped.
-
1
SANITIZE = ?&
-
-
# Designates script, the result of which is flattened and output.
-
1
FLAT_SCRIPT = ?~
-
-
# Designates script which is run but not output.
-
1
SILENT_SCRIPT = ?-
-
-
# When following SILENT_SCRIPT, designates a comment that is not output.
-
1
SILENT_COMMENT = ?#
-
-
# Designates a non-parsed line.
-
1
ESCAPE = ?\\
-
-
# Designates a block of filtered text.
-
1
FILTER = ?:
-
-
# Designates a non-parsed line. Not actually a character.
-
1
PLAIN_TEXT = -1
-
-
# Keeps track of the ASCII values of the characters that begin a
-
# specially-interpreted line.
-
1
SPECIAL_CHARACTERS = [
-
ELEMENT,
-
DIV_CLASS,
-
DIV_ID,
-
COMMENT,
-
DOCTYPE,
-
SCRIPT,
-
SANITIZE,
-
FLAT_SCRIPT,
-
SILENT_SCRIPT,
-
ESCAPE,
-
FILTER
-
]
-
-
# The value of the character that designates that a line is part
-
# of a multiline string.
-
1
MULTILINE_CHAR_VALUE = ?|
-
-
# Regex to check for blocks with spaces around arguments. Not to be confused
-
# with multiline script.
-
# For example:
-
# foo.each do | bar |
-
# = bar
-
#
-
1
BLOCK_WITH_SPACES = /do\s*\|\s*[^\|]*\s+\|\z/
-
-
1
MID_BLOCK_KEYWORDS = %w[else elsif rescue ensure end when]
-
1
START_BLOCK_KEYWORDS = %w[if begin case unless]
-
# Try to parse assignments to block starters as best as possible
-
1
START_BLOCK_KEYWORD_REGEX = /(?:\w+(?:,\s*\w+)*\s*=\s*)?(#{START_BLOCK_KEYWORDS.join('|')})/
-
1
BLOCK_KEYWORD_REGEX = /^-?\s*(?:(#{MID_BLOCK_KEYWORDS.join('|')})|#{START_BLOCK_KEYWORD_REGEX.source})\b/
-
-
# The Regex that matches a Doctype command.
-
1
DOCTYPE_REGEX = /(\d(?:\.\d)?)?\s*([a-z]*)\s*([^ ]+)?/i
-
-
# The Regex that matches a literal string or symbol value
-
1
LITERAL_VALUE_REGEX = /:(\w*)|(["'])((?!\\|\#\{|\#@|\#\$|\2).|\\.)*\2/
-
-
1
ID_KEY = 'id'.freeze
-
1
CLASS_KEY = 'class'.freeze
-
-
1
def initialize(options)
-
22
@options = Options.wrap(options)
-
# Record the indent levels of "if" statements to validate the subsequent
-
# elsif and else statements are indented at the appropriate level.
-
22
@script_level_stack = []
-
22
@template_index = 0
-
22
@template_tabs = 0
-
end
-
-
1
def call(template)
-
22
match = template.rstrip.scan(/(([ \t]+)?(.*?))(?:\Z|\r\n|\r|\n)/m)
-
# discard the last match which is always blank
-
22
match.pop
-
22
@template = match.each_with_index.map do |(full, whitespace, text), index|
-
295
Line.new(whitespace, text.rstrip, full, index, self, false)
-
end
-
# Append special end-of-document marker
-
22
@template << Line.new(nil, '-#', '-#', @template.size, self, true)
-
-
22
@root = @parent = ParseNode.new(:root)
-
22
@flat = false
-
22
@filter_buffer = nil
-
22
@indentation = nil
-
22
@line = next_line
-
-
22
raise SyntaxError.new(Error.message(:indenting_at_start), @line.index) if @line.tabs != 0
-
-
22
loop do
-
298
next_line
-
-
276
process_indent(@line) unless @line.text.empty?
-
-
276
if flat?
-
text = @line.full.dup
-
text = "" unless text.gsub!(/^#{@flat_spaces}/, '')
-
@filter_buffer << "#{text}\n"
-
@line = @next_line
-
next
-
end
-
-
276
@tab_up = nil
-
276
process_line(@line) unless @line.text.empty?
-
276
if block_opened? || @tab_up
-
89
@template_tabs += 1
-
89
@parent = @parent.children.last
-
end
-
-
276
if !flat? && @next_line.tabs - @line.tabs > 1
-
raise SyntaxError.new(Error.message(:deeper_indenting, @next_line.tabs - @line.tabs), @next_line.index)
-
end
-
-
276
@line = @next_line
-
end
-
# Close all the open tags
-
22
close until @parent.type == :root
-
22
@root
-
rescue Haml::Error => e
-
e.backtrace.unshift "#{@options.filename}:#{(e.line ? e.line + 1 : @line.index + 1) + @options.line - 1}"
-
raise
-
end
-
-
1
def compute_tabs(line)
-
300
return 0 if line.text.empty? || !line.whitespace
-
-
207
if @indentation.nil?
-
14
@indentation = line.whitespace
-
-
14
if @indentation.include?(?\s) && @indentation.include?(?\t)
-
raise SyntaxError.new(Error.message(:cant_use_tabs_and_spaces), line.index)
-
end
-
-
14
@flat_spaces = @indentation * (@template_tabs+1) if flat?
-
14
return 1
-
end
-
-
193
tabs = line.whitespace.length / @indentation.length
-
193
return tabs if line.whitespace == @indentation * tabs
-
return @template_tabs + 1 if flat? && line.whitespace =~ /^#{@flat_spaces}/
-
-
message = Error.message(:inconsistent_indentation,
-
human_indentation(line.whitespace),
-
human_indentation(@indentation)
-
)
-
raise SyntaxError.new(message, line.index)
-
end
-
-
1
private
-
-
# @private
-
1
class Line < Struct.new(:whitespace, :text, :full, :index, :parser, :eod)
-
1
alias_method :eod?, :eod
-
-
# @private
-
1
def tabs
-
3063
@tabs ||= parser.compute_tabs(self)
-
end
-
-
1
def strip!(from)
-
self.text = text[from..-1]
-
self.text.lstrip!
-
self
-
end
-
end
-
-
# @private
-
1
class ParseNode < Struct.new(:type, :line, :value, :parent, :children)
-
1
def initialize(*args)
-
298
super
-
298
self.children ||= []
-
end
-
-
1
def inspect
-
%Q[(#{type} #{value.inspect}#{children.each_with_object('') {|c, s| s << "\n#{c.inspect.gsub!(/^/, ' ')}"}})]
-
end
-
end
-
-
# @param [String] new - Hash literal including dynamic values.
-
# @param [String] old - Hash literal including dynamic values or Ruby literal of multiple Hashes which MUST be interpreted as method's last arguments.
-
1
class DynamicAttributes < Struct.new(:new, :old)
-
1
def old=(value)
-
unless value =~ /\A{.*}\z/m
-
raise ArgumentError.new('Old attributes must start with "{" and end with "}"')
-
end
-
super
-
end
-
-
# This will be a literal for Haml::Buffer#attributes's last argument, `attributes_hashes`.
-
1
def to_literal
-
[new, stripped_old].compact.join(', ')
-
end
-
-
1
private
-
-
# For `%foo{ { foo: 1 }, bar: 2 }`, :old is "{ { foo: 1 }, bar: 2 }" and this method returns " { foo: 1 }, bar: 2 " for last argument.
-
1
def stripped_old
-
return nil if old.nil?
-
old.sub!(/\A{/, '').sub!(/}\z/m, '')
-
end
-
end
-
-
# Processes and deals with lowering indentation.
-
1
def process_indent(line)
-
276
return unless line.tabs <= @template_tabs && @template_tabs > 0
-
-
222
to_close = @template_tabs - line.tabs
-
288
to_close.times {|i| close unless to_close - 1 - i == 0 && continuation_script?(line.text)}
-
end
-
-
1
def continuation_script?(text)
-
50
text[0] == SILENT_SCRIPT && mid_block_keyword?(text)
-
end
-
-
1
def mid_block_keyword?(text)
-
4
MID_BLOCK_KEYWORDS.include?(block_keyword(text))
-
end
-
-
# Processes a single line of Haml.
-
#
-
# This method doesn't return anything; it simply processes the line and
-
# adds the appropriate code to `@precompiled`.
-
1
def process_line(line)
-
276
case line.text[0]
-
6
when DIV_CLASS; push div(line)
-
when DIV_ID
-
9
return push plain(line) if %w[{ @ $].include?(line.text[1])
-
9
push div(line)
-
144
when ELEMENT; push tag(line)
-
7
when COMMENT; push comment(line.text[1..-1].lstrip)
-
when SANITIZE
-
return push plain(line.strip!(3), :escape_html) if line.text[1, 2] == '=='
-
return push script(line.strip!(2), :escape_html) if line.text[1] == SCRIPT
-
return push flat_script(line.strip!(2), :escape_html) if line.text[1] == FLAT_SCRIPT
-
return push plain(line.strip!(1), :escape_html) if line.text[1] == ?\s || line.text[1..2] == '#{'
-
push plain(line)
-
when SCRIPT
-
86
return push plain(line.strip!(2)) if line.text[1] == SCRIPT
-
86
line.text = line.text[1..-1]
-
86
push script(line)
-
when FLAT_SCRIPT; push flat_script(line.strip!(1))
-
when SILENT_SCRIPT
-
16
return push haml_comment(line.text[2..-1]) if line.text[1] == SILENT_COMMENT
-
15
push silent_script(line)
-
when FILTER; push filter(line.text[1..-1].downcase)
-
when DOCTYPE
-
1
return push doctype(line.text) if line.text[0, 3] == '!!!'
-
return push plain(line.strip!(3), false) if line.text[1, 2] == '=='
-
return push script(line.strip!(2), false) if line.text[1] == SCRIPT
-
return push flat_script(line.strip!(2), false) if line.text[1] == FLAT_SCRIPT
-
return push plain(line.strip!(1), false) if line.text[1] == ?\s || line.text[1..2] == '#{'
-
push plain(line)
-
when ESCAPE
-
1
line.text = line.text[1..-1]
-
1
push plain(line)
-
6
else; push plain(line)
-
end
-
end
-
-
1
def block_keyword(text)
-
105
return unless keyword = text.scan(BLOCK_KEYWORD_REGEX)[0]
-
7
keyword[0] || keyword[1]
-
end
-
-
1
def push(node)
-
276
@parent.children << node
-
276
node.parent = @parent
-
end
-
-
1
def plain(line, escape_html = nil)
-
7
if block_opened?
-
raise SyntaxError.new(Error.message(:illegal_nesting_plain), @next_line.index)
-
end
-
-
7
unless contains_interpolation?(line.text)
-
7
return ParseNode.new(:plain, line.index + 1, :text => line.text)
-
end
-
-
escape_html = @options.escape_html if escape_html.nil?
-
line.text = unescape_interpolation(line.text, escape_html)
-
script(line, false)
-
end
-
-
1
def script(line, escape_html = nil, preserve = false)
-
86
raise SyntaxError.new(Error.message(:no_ruby_code, '=')) if line.text.empty?
-
86
line = handle_ruby_multiline(line)
-
86
escape_html = @options.escape_html if escape_html.nil?
-
-
86
keyword = block_keyword(line.text)
-
86
check_push_script_stack(keyword)
-
-
86
ParseNode.new(:script, line.index + 1, :text => line.text, :escape_html => escape_html,
-
:preserve => preserve, :keyword => keyword)
-
end
-
-
1
def flat_script(line, escape_html = nil)
-
raise SyntaxError.new(Error.message(:no_ruby_code, '~')) if line.text.empty?
-
script(line, escape_html, :preserve)
-
end
-
-
1
def silent_script(line)
-
15
raise SyntaxError.new(Error.message(:no_end), line.index) if line.text[1..-1].strip == 'end'
-
-
15
line = handle_ruby_multiline(line)
-
15
keyword = block_keyword(line.text)
-
-
15
check_push_script_stack(keyword)
-
-
15
if ["else", "elsif", "when"].include?(keyword)
-
1
if @script_level_stack.empty?
-
raise Haml::SyntaxError.new(Error.message(:missing_if, keyword), @line.index)
-
end
-
-
1
if keyword == 'when' and !@script_level_stack.last[2]
-
if @script_level_stack.last[1] + 1 == @line.tabs
-
@script_level_stack.last[1] += 1
-
end
-
@script_level_stack.last[2] = true
-
end
-
-
1
if @script_level_stack.last[1] != @line.tabs
-
message = Error.message(:bad_script_indent, keyword, @script_level_stack.last[1], @line.tabs)
-
raise Haml::SyntaxError.new(message, @line.index)
-
end
-
end
-
-
15
ParseNode.new(:silent_script, @line.index + 1,
-
:text => line.text[1..-1], :keyword => keyword)
-
end
-
-
1
def check_push_script_stack(keyword)
-
101
if ["if", "case", "unless"].include?(keyword)
-
# @script_level_stack contents are arrays of form
-
# [:keyword, stack_level, other_info]
-
5
@script_level_stack.push([keyword.to_sym, @line.tabs])
-
5
@script_level_stack.last << false if keyword == 'case'
-
5
@tab_up = true
-
end
-
end
-
-
1
def haml_comment(text)
-
1
if filter_opened?
-
@flat = true
-
@filter_buffer = String.new
-
@filter_buffer << "#{text}\n" unless text.empty?
-
text = @filter_buffer
-
# If we don't know the indentation by now, it'll be set in Line#tabs
-
@flat_spaces = @indentation * (@template_tabs+1) if @indentation
-
end
-
-
1
ParseNode.new(:haml_comment, @line.index + 1, :text => text)
-
end
-
-
1
def tag(line)
-
tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace,
-
159
nuke_inner_whitespace, action, value, last_line = parse_tag(line.text)
-
-
159
preserve_tag = @options.preserve.include?(tag_name)
-
159
nuke_inner_whitespace ||= preserve_tag
-
159
escape_html = (action == '&' || (action != '!' && @options.escape_html))
-
-
159
case action
-
11
when '/'; self_closing = true
-
when '~'; parse = preserve_script = true
-
when '='
-
38
parse = true
-
38
if value[0] == ?=
-
value = unescape_interpolation(value[1..-1].strip, escape_html)
-
escape_html = false
-
end
-
when '&', '!'
-
if value[0] == ?= || value[0] == ?~
-
parse = true
-
preserve_script = (value[0] == ?~)
-
if value[1] == ?=
-
value = unescape_interpolation(value[2..-1].strip, escape_html)
-
escape_html = false
-
else
-
value = value[1..-1].strip
-
end
-
elsif contains_interpolation?(value)
-
value = unescape_interpolation(value, escape_html)
-
parse = true
-
escape_html = false
-
end
-
else
-
110
if contains_interpolation?(value)
-
value = unescape_interpolation(value, escape_html)
-
parse = true
-
escape_html = false
-
end
-
end
-
-
159
attributes = Parser.parse_class_and_id(attributes)
-
159
dynamic_attributes = DynamicAttributes.new
-
-
159
if attributes_hashes[:new]
-
static_attributes, attributes_hash = attributes_hashes[:new]
-
AttributeBuilder.merge_attributes!(attributes, static_attributes) if static_attributes
-
dynamic_attributes.new = attributes_hash
-
end
-
-
159
if attributes_hashes[:old]
-
5
static_attributes = parse_static_hash(attributes_hashes[:old])
-
5
AttributeBuilder.merge_attributes!(attributes, static_attributes) if static_attributes
-
5
dynamic_attributes.old = attributes_hashes[:old] unless static_attributes || @options.suppress_eval
-
end
-
-
159
raise SyntaxError.new(Error.message(:illegal_nesting_self_closing), @next_line.index) if block_opened? && self_closing
-
159
raise SyntaxError.new(Error.message(:no_ruby_code, action), last_line - 1) if parse && value.empty?
-
159
raise SyntaxError.new(Error.message(:self_closing_content), last_line - 1) if self_closing && !value.empty?
-
-
159
if block_opened? && !value.empty? && !is_ruby_multiline?(value)
-
raise SyntaxError.new(Error.message(:illegal_nesting_line, tag_name), @next_line.index)
-
end
-
-
263
self_closing ||= !!(!block_opened? && value.empty? && @options.autoclose.any? {|t| t === tag_name})
-
159
value = nil if value.empty? && (block_opened? || self_closing)
-
159
line.text = value
-
159
line = handle_ruby_multiline(line) if parse
-
-
159
ParseNode.new(:tag, line.index + 1, :name => tag_name, :attributes => attributes,
-
:dynamic_attributes => dynamic_attributes, :self_closing => self_closing,
-
:nuke_inner_whitespace => nuke_inner_whitespace,
-
:nuke_outer_whitespace => nuke_outer_whitespace, :object_ref => object_ref,
-
:escape_html => escape_html, :preserve_tag => preserve_tag,
-
:preserve_script => preserve_script, :parse => parse, :value => line.text)
-
end
-
-
# Renders a line that creates an XHTML tag and has an implicit div because of
-
# `.` or `#`.
-
1
def div(line)
-
15
line.text = "%div#{line.text}"
-
15
tag(line)
-
end
-
-
# Renders an XHTML comment.
-
1
def comment(text)
-
7
if text[0..1] == '!['
-
revealed = true
-
text = text[1..-1]
-
else
-
7
revealed = false
-
end
-
-
7
conditional, text = balance(text, ?[, ?]) if text[0] == ?[
-
7
text.strip!
-
-
7
if contains_interpolation?(text)
-
parse = true
-
text = unescape_interpolation(text)
-
else
-
7
parse = false
-
end
-
-
7
if block_opened? && !text.empty?
-
raise SyntaxError.new(Haml::Error.message(:illegal_nesting_content), @next_line.index)
-
end
-
-
7
ParseNode.new(:comment, @line.index + 1, :conditional => conditional, :text => text, :revealed => revealed, :parse => parse)
-
end
-
-
# Renders an XHTML doctype or XML shebang.
-
1
def doctype(text)
-
1
raise SyntaxError.new(Error.message(:illegal_nesting_header), @next_line.index) if block_opened?
-
1
version, type, encoding = text[3..-1].strip.downcase.scan(DOCTYPE_REGEX)[0]
-
1
ParseNode.new(:doctype, @line.index + 1, :version => version, :type => type, :encoding => encoding)
-
end
-
-
1
def filter(name)
-
raise Error.new(Error.message(:invalid_filter_name, name)) unless name =~ /^\w+$/
-
-
if filter_opened?
-
@flat = true
-
@filter_buffer = String.new
-
# If we don't know the indentation by now, it'll be set in Line#tabs
-
@flat_spaces = @indentation * (@template_tabs+1) if @indentation
-
end
-
-
ParseNode.new(:filter, @line.index + 1, :name => name, :text => @filter_buffer)
-
end
-
-
1
def close
-
89
node, @parent = @parent, @parent.parent
-
89
@template_tabs -= 1
-
89
send("close_#{node.type}", node) if respond_to?("close_#{node.type}", :include_private)
-
end
-
-
1
def close_filter(_)
-
close_flat_section
-
end
-
-
1
def close_haml_comment(_)
-
close_flat_section
-
end
-
-
1
def close_flat_section
-
@flat = false
-
@flat_spaces = nil
-
@filter_buffer = nil
-
end
-
-
1
def close_silent_script(node)
-
18
@script_level_stack.pop if ["if", "case", "unless"].include? node.value[:keyword]
-
-
# Post-process case statements to normalize the nesting of "when" clauses
-
18
return unless node.value[:keyword] == "case"
-
return unless first = node.children.first
-
return unless first.type == :silent_script && first.value[:keyword] == "when"
-
return if first.children.empty?
-
# If the case node has a "when" child with children, it's the
-
# only child. Then we want to put everything nested beneath it
-
# beneath the case itself (just like "if").
-
node.children = [first, *first.children]
-
first.children = []
-
end
-
-
1
alias :close_script :close_silent_script
-
-
# This is a class method so it can be accessed from {Haml::Helpers}.
-
#
-
# Iterates through the classes and ids supplied through `.`
-
# and `#` syntax, and returns a hash with them as attributes,
-
# that can then be merged with another attributes hash.
-
1
def self.parse_class_and_id(list)
-
159
attributes = {}
-
159
return attributes if list.empty?
-
-
21
list.scan(/([#.])([-:_a-zA-Z0-9\@]+)/) do |type, property|
-
23
case type
-
when '.'
-
9
if attributes[CLASS_KEY]
-
attributes[CLASS_KEY] += " "
-
else
-
9
attributes[CLASS_KEY] = ""
-
end
-
9
attributes[CLASS_KEY] += property
-
14
when '#'; attributes[ID_KEY] = property
-
end
-
end
-
21
attributes
-
end
-
-
# This method doesn't use Haml::AttributeParser because currently it depends on Ripper and Rubinius doesn't provide it.
-
# Ideally this logic should be placed in Haml::AttributeParser instead of here and this method should use it.
-
#
-
# @param [String] text - Hash literal or text inside old attributes
-
# @return [Hash,nil] - Return nil if text is not static Hash literal
-
1
def parse_static_hash(text)
-
5
attributes = {}
-
5
return attributes if text.empty?
-
-
5
text = text[1...-1] # strip brackets
-
5
scanner = StringScanner.new(text)
-
5
scanner.scan(/\s+/)
-
5
until scanner.eos?
-
8
return unless key = scanner.scan(LITERAL_VALUE_REGEX)
-
8
return unless scanner.scan(/\s*=>\s*/)
-
8
return unless value = scanner.scan(LITERAL_VALUE_REGEX)
-
8
return unless scanner.scan(/\s*(?:,|$)\s*/)
-
8
attributes[eval(key).to_s] = eval(value).to_s
-
end
-
5
attributes
-
end
-
-
# Parses a line into tag_name, attributes, attributes_hash, object_ref, action, value
-
1
def parse_tag(text)
-
159
match = text.scan(/%([-:\w]+)([-:\w.#\@]*)(.+)?/)[0]
-
159
raise SyntaxError.new(Error.message(:invalid_tag, text)) unless match
-
-
159
tag_name, attributes, rest = match
-
-
159
if !attributes.empty? && (attributes =~ /[.#](\.|#|\z)/)
-
raise SyntaxError.new(Error.message(:illegal_element))
-
end
-
-
159
new_attributes_hash = old_attributes_hash = last_line = nil
-
159
object_ref = :nil
-
159
attributes_hashes = {}
-
159
while rest && !rest.empty?
-
87
case rest[0]
-
when ?{
-
5
break if old_attributes_hash
-
5
old_attributes_hash, rest, last_line = parse_old_attributes(rest)
-
5
attributes_hashes[:old] = old_attributes_hash
-
when ?(
-
break if new_attributes_hash
-
new_attributes_hash, rest, last_line = parse_new_attributes(rest)
-
attributes_hashes[:new] = new_attributes_hash
-
when ?[
-
break unless object_ref == :nil
-
object_ref, rest = balance(rest, ?[, ?])
-
82
else; break
-
end
-
end
-
-
159
if rest && !rest.empty?
-
82
nuke_whitespace, action, value = rest.scan(/(<>|><|[><])?([=\/\~&!])?(.*)?/)[0]
-
82
if nuke_whitespace
-
nuke_outer_whitespace = nuke_whitespace.include? '>'
-
nuke_inner_whitespace = nuke_whitespace.include? '<'
-
end
-
end
-
-
159
if @options.remove_whitespace
-
nuke_outer_whitespace = true
-
nuke_inner_whitespace = true
-
end
-
-
159
if value.nil?
-
77
value = ''
-
else
-
82
value.strip!
-
end
-
159
[tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace,
-
nuke_inner_whitespace, action, value, last_line || @line.index + 1]
-
end
-
-
# @return [String] attributes_hash - Hash literal starting with `{` and ending with `}`
-
# @return [String] rest
-
# @return [Integer] last_line
-
1
def parse_old_attributes(text)
-
5
text = text.dup
-
5
last_line = @line.index + 1
-
-
5
begin
-
5
attributes_hash, rest = balance(text, ?{, ?})
-
rescue SyntaxError => e
-
if text.strip[-1] == ?, && e.message == Error.message(:unbalanced_brackets)
-
text << "\n#{@next_line.text}"
-
last_line += 1
-
next_line
-
retry
-
end
-
-
raise e
-
end
-
-
5
return attributes_hash, rest, last_line
-
end
-
-
# @return [Array<Hash,String,nil>] - [static_attributs (Hash), dynamic_attributes (nil or String starting with `{` and ending with `}`)]
-
# @return [String] rest
-
# @return [Integer] last_line
-
1
def parse_new_attributes(text)
-
scanner = StringScanner.new(text)
-
last_line = @line.index + 1
-
attributes = {}
-
-
scanner.scan(/\(\s*/)
-
loop do
-
name, value = parse_new_attribute(scanner)
-
break if name.nil?
-
-
if name == false
-
scanned = Haml::Util.balance(text, ?(, ?))
-
text = scanned ? scanned.first : text
-
raise Haml::SyntaxError.new(Error.message(:invalid_attribute_list, text.inspect), last_line - 1)
-
end
-
attributes[name] = value
-
scanner.scan(/\s*/)
-
-
if scanner.eos?
-
text << " #{@next_line.text}"
-
last_line += 1
-
next_line
-
scanner.scan(/\s*/)
-
end
-
end
-
-
static_attributes = {}
-
dynamic_attributes = "{"
-
attributes.each do |name, (type, val)|
-
if type == :static
-
static_attributes[name] = val
-
else
-
dynamic_attributes << "#{inspect_obj(name)} => #{val},"
-
end
-
end
-
dynamic_attributes << "}"
-
dynamic_attributes = nil if dynamic_attributes == "{}"
-
-
return [static_attributes, dynamic_attributes], scanner.rest, last_line
-
end
-
-
1
def parse_new_attribute(scanner)
-
unless name = scanner.scan(/[-:\w]+/)
-
return if scanner.scan(/\)/)
-
return false
-
end
-
-
scanner.scan(/\s*/)
-
return name, [:static, true] unless scanner.scan(/=/) #/end
-
-
scanner.scan(/\s*/)
-
unless quote = scanner.scan(/["']/)
-
return false unless var = scanner.scan(/(@@?|\$)?\w+/)
-
return name, [:dynamic, var]
-
end
-
-
re = /((?:\\.|\#(?!\{)|[^#{quote}\\#])*)(#{quote}|#\{)/
-
content = []
-
loop do
-
return false unless scanner.scan(re)
-
content << [:str, scanner[1].gsub(/\\(.)/, '\1')]
-
break if scanner[2] == quote
-
content << [:ruby, balance(scanner, ?{, ?}, 1).first[0...-1]]
-
end
-
-
return name, [:static, content.first[1]] if content.size == 1
-
return name, [:dynamic,
-
%!"#{content.each_with_object('') {|(t, v), s| s << (t == :str ? inspect_obj(v)[1...-1] : "\#{#{v}}")}}"!]
-
end
-
-
1
def next_line
-
339
line = @template.shift || raise(StopIteration)
-
-
# `flat?' here is a little outdated,
-
# so we have to manually check if either the previous or current line
-
# closes the flat block, as well as whether a new block is opened.
-
317
line_defined = instance_variable_defined?(:@line)
-
317
@line.tabs if line_defined
-
unless (flat? && !closes_flat?(line) && !closes_flat?(@line)) ||
-
317
(line_defined && @line.text[0] == ?: && line.full =~ %r[^#{@line.full[/^\s+/]}\s])
-
317
return next_line if line.text.empty?
-
-
300
handle_multiline(line)
-
end
-
-
300
@next_line = line
-
end
-
-
1
def closes_flat?(line)
-
line && !line.text.empty? && line.full !~ /^#{@flat_spaces}/
-
end
-
-
1
def handle_multiline(line)
-
300
return unless is_multiline?(line.text)
-
3
line.text.slice!(-1)
-
3
loop do
-
3
new_line = @template.first
-
3
break if new_line.eod?
-
3
next @template.shift if new_line.text.strip.empty?
-
3
break unless is_multiline?(new_line.text.strip)
-
line.text << new_line.text.strip[0...-1]
-
@template.shift
-
end
-
end
-
-
# Checks whether or not `line` is in a multiline sequence.
-
1
def is_multiline?(text)
-
303
text && text.length > 1 && text[-1] == MULTILINE_CHAR_VALUE && text[-2] == ?\s && text !~ BLOCK_WITH_SPACES
-
end
-
-
1
def handle_ruby_multiline(line)
-
139
line.text.rstrip!
-
139
return line unless is_ruby_multiline?(line.text)
-
begin
-
# Use already fetched @next_line in the first loop. Otherwise, fetch next
-
2
new_line = new_line.nil? ? @next_line : @template.shift
-
2
break if new_line.eod?
-
2
next if new_line.text.empty?
-
2
line.text << " #{new_line.text.rstrip}"
-
2
end while is_ruby_multiline?(new_line.text)
-
2
next_line
-
2
line
-
end
-
-
# `text' is a Ruby multiline block if it:
-
# - ends with a comma
-
# - but not "?," which is a character literal
-
# (however, "x?," is a method call and not a literal)
-
# - and not "?\," which is a character literal
-
1
def is_ruby_multiline?(text)
-
143
text && text.length > 1 && text[-1] == ?, &&
-
4
!((text[-3, 2] =~ /\W\?/) || text[-3, 2] == "?\\")
-
end
-
-
1
def balance(*args)
-
5
Haml::Util.balance(*args) or raise(SyntaxError.new(Error.message(:unbalanced_brackets)))
-
end
-
-
1
def block_opened?
-
845
@next_line.tabs > @line.tabs
-
end
-
-
# Same semantics as block_opened?, except that block_opened? uses Line#tabs,
-
# which doesn't interact well with filter lines
-
1
def filter_opened?
-
1
@next_line.full =~ (@indentation ? /^#{@indentation * (@template_tabs + 1)}/ : /^\s/)
-
end
-
-
1
def flat?
-
883
@flat
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module Haml
-
-
# This module makes Haml work with Rails using the template handler API.
-
1
class Plugin
-
1
def handles_encoding?; true; end
-
-
1
def compile(template)
-
22
options = Haml::Template.options.dup
-
22
if template.respond_to?(:type)
-
22
options[:mime_type] = template.type
-
elsif template.respond_to? :mime_type
-
options[:mime_type] = template.mime_type
-
end
-
22
options[:filename] = template.identifier
-
22
Haml::Engine.new(template.source, options).compiler.precompiled_with_ambles(
-
[],
-
after_preamble: '@output_buffer = output_buffer ||= ActionView::OutputBuffer.new if defined?(ActionView::OutputBuffer)',
-
)
-
end
-
-
1
def self.call(template)
-
22
new.compile(template)
-
end
-
-
1
def cache_fragment(block, name = {}, options = nil)
-
@view.fragment_for(block, name, options) do
-
eval("_hamlout.buffer", block.binding)
-
end
-
end
-
end
-
end
-
-
1
ActionView::Template.register_template_handler(:haml, Haml::Plugin)
-
# frozen_string_literal: true
-
1
require 'haml/template/options'
-
-
# check for a compatible Rails version when Haml is loaded
-
1
if (activesupport_spec = Gem.loaded_specs['activesupport'])
-
1
if activesupport_spec.version.to_s < '3.2'
-
raise Exception.new("\n\n** Haml now requires Rails 3.2 and later. Use Haml version 4.0.4\n\n")
-
end
-
end
-
-
1
module Haml
-
1
module Filters
-
1
module RailsErb
-
1
extend Plain
-
1
extend TiltFilter
-
1
extend PrecompiledTiltFilter
-
end
-
end
-
-
1
class Railtie < ::Rails::Railtie
-
1
initializer :haml do |app|
-
1
ActiveSupport.on_load(:action_view) do
-
1
require "haml/template"
-
-
1
if defined?(::Sass::Rails::SassTemplate) && app.config.assets.enabled
-
require "haml/sass_rails_filter"
-
end
-
-
1
if defined? Erubi
-
require "haml/helpers/safe_erubi_template"
-
Haml::Filters::RailsErb.template_class = Haml::SafeErubiTemplate
-
else
-
1
require "haml/helpers/safe_erubis_template"
-
1
Haml::Filters::RailsErb.template_class = Haml::SafeErubisTemplate
-
end
-
1
Haml::Template.options[:filters] = { 'erb' => Haml::Filters::RailsErb }
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'haml/template/options'
-
1
if defined?(ActiveSupport)
-
1
ActiveSupport.on_load(:action_view) do
-
2
require 'haml/helpers/action_view_mods'
-
2
require 'haml/helpers/action_view_extensions'
-
end
-
else
-
require 'haml/helpers/action_view_mods'
-
require 'haml/helpers/action_view_extensions'
-
end
-
1
require 'haml/helpers/xss_mods'
-
1
require 'haml/helpers/action_view_xss_mods'
-
-
1
module Haml
-
1
class TempleEngine
-
1
def precompiled_method_return_value_with_haml_xss
-
22
"::Haml::Util.html_safe(#{precompiled_method_return_value_without_haml_xss})"
-
end
-
1
alias_method :precompiled_method_return_value_without_haml_xss, :precompiled_method_return_value
-
1
alias_method :precompiled_method_return_value, :precompiled_method_return_value_with_haml_xss
-
end
-
-
1
module Helpers
-
1
include Haml::Helpers::XssMods
-
end
-
-
1
module Util
-
1
undef :rails_xss_safe? if defined? rails_xss_safe?
-
1
def rails_xss_safe?; true; end
-
end
-
-
end
-
-
-
1
Haml::Template.options[:escape_html] = true
-
-
1
require 'haml/plugin'
-
# frozen_string_literal: true
-
# We keep options in its own self-contained file
-
# so that we can load it independently in Rails 3,
-
# where the full template stuff is lazy-loaded.
-
-
1
module Haml
-
1
module Template
-
1
extend self
-
-
1
class Options < Hash
-
1
def []=(key, value)
-
46
super
-
46
if Haml::Options.buffer_defaults.key?(key)
-
1
Haml::Options.buffer_defaults[key] = value
-
end
-
end
-
end
-
-
1
@options = ::Haml::Template::Options.new
-
# The options hash for Haml when used within Rails.
-
# See {file:REFERENCE.md#options the Haml options documentation}.
-
#
-
# @return [Haml::Template::Options<Symbol => Object>]
-
1
attr_accessor :options
-
end
-
end
-
# frozen_string_literal: false
-
1
require 'temple'
-
1
require 'haml/escapable'
-
1
require 'haml/generator'
-
-
1
module Haml
-
1
class TempleEngine < Temple::Engine
-
1
define_options(
-
attr_wrapper: "'",
-
autoclose: %w(area base basefont br col command embed frame
-
hr img input isindex keygen link menuitem meta
-
param source track wbr),
-
encoding: nil,
-
escape_attrs: true,
-
escape_html: false,
-
filename: '(haml)',
-
format: :html5,
-
hyphenate_data_attrs: true,
-
line: 1,
-
mime_type: 'text/html',
-
preserve: %w(textarea pre code),
-
remove_whitespace: false,
-
suppress_eval: false,
-
cdata: false,
-
parser_class: ::Haml::Parser,
-
compiler_class: ::Haml::Compiler,
-
trace: false,
-
filters: {},
-
)
-
-
23
use :Parser, -> { options[:parser_class] }
-
23
use :Compiler, -> { options[:compiler_class] }
-
1
use Escapable
-
1
filter :ControlFlow
-
1
filter :MultiFlattener
-
1
filter :StaticMerger
-
1
use Generator
-
-
1
def compile(template)
-
22
initialize_encoding(template, options[:encoding])
-
22
@precompiled = call(template)
-
end
-
-
# The source code that is evaluated to produce the Haml document.
-
#
-
# This is automatically converted to the correct encoding
-
# (see {file:REFERENCE.md#encodings the `:encoding` option}).
-
#
-
# @return [String]
-
1
def precompiled
-
22
encoding = Encoding.find(@encoding || '')
-
22
return @precompiled.force_encoding(encoding) if encoding == Encoding::ASCII_8BIT
-
22
return @precompiled.encode(encoding)
-
end
-
-
1
def precompiled_with_return_value
-
"#{precompiled};#{precompiled_method_return_value}"
-
end
-
-
# The source code that is evaluated to produce the Haml document.
-
#
-
# This is automatically converted to the correct encoding
-
# (see {file:REFERENCE.md#encodings the `:encoding` option}).
-
#
-
# @return [String]
-
1
def precompiled_with_ambles(local_names, after_preamble: '')
-
22
preamble = <<END.tr!("\n", ';')
-
begin
-
extend Haml::Helpers
-
_hamlout = @haml_buffer = Haml::Buffer.new(haml_buffer, #{Options.new(options).for_buffer.inspect})
-
_erbout = _hamlout.buffer
-
#{after_preamble}
-
END
-
22
postamble = <<END.tr!("\n", ';')
-
#{precompiled_method_return_value}
-
ensure
-
@haml_buffer = @haml_buffer.upper if @haml_buffer
-
end
-
END
-
22
"#{preamble}#{locals_code(local_names)}#{precompiled}#{postamble}"
-
end
-
-
1
private
-
-
1
def initialize_encoding(template, given_value)
-
22
if given_value
-
@encoding = given_value
-
else
-
22
@encoding = Encoding.default_internal || template.encoding
-
end
-
end
-
-
# Returns the string used as the return value of the precompiled method.
-
# This method exists so it can be monkeypatched to return modified values.
-
1
def precompiled_method_return_value
-
22
"_erbout"
-
end
-
-
1
def locals_code(names)
-
22
names = names.keys if Hash === names
-
-
22
names.each_with_object('') do |name, code|
-
# Can't use || because someone might explicitly pass in false with a symbol
-
sym_local = "_haml_locals[#{inspect_obj(name.to_sym)}]"
-
str_local = "_haml_locals[#{inspect_obj(name.to_s)}]"
-
code << "#{name} = #{sym_local}.nil? ? #{str_local} : #{sym_local};"
-
end
-
end
-
-
1
def inspect_obj(obj)
-
case obj
-
when String
-
%Q!"#{obj.gsub(/[\x00-\x7F]+/) {|s| s.inspect[1...-1]}}"!
-
when Symbol
-
":#{inspect_obj(obj.to_s)}"
-
else
-
obj.inspect
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module Haml
-
# A module to count lines of expected code. This would be faster than actual code generation
-
# and counting newlines in it.
-
1
module TempleLineCounter
-
1
class UnexpectedExpression < StandardError; end
-
-
1
def self.count_lines(exp)
-
190
type, *args = exp
-
190
case type
-
when :multi
-
190
args.map { |a| count_lines(a) }.reduce(:+) || 0
-
when :dynamic, :code
-
args.first.count("\n")
-
when :static
-
31
0 # It has not real newline "\n" but escaped "\\n".
-
when :case
-
arg, *cases = args
-
arg.count("\n") + cases.map do |cond, e|
-
(cond == :else ? 0 : cond.count("\n")) + count_lines(e)
-
end.reduce(:+)
-
when :escape
-
count_lines(args[1])
-
else
-
raise UnexpectedExpression.new("[HAML BUG] Unexpected Temple expression '#{type}' is given!")
-
end
-
end
-
end
-
end
-
# frozen_string_literal: false
-
-
1
begin
-
1
require 'erubis/tiny'
-
rescue LoadError
-
require 'erb'
-
end
-
1
require 'set'
-
1
require 'stringio'
-
1
require 'strscan'
-
-
1
module Haml
-
# A module containing various useful functions.
-
1
module Util
-
1
extend self
-
-
# Silence all output to STDERR within a block.
-
#
-
# @yield A block in which no output will be printed to STDERR
-
1
def silence_warnings
-
the_real_stderr, $stderr = $stderr, StringIO.new
-
yield
-
ensure
-
$stderr = the_real_stderr
-
end
-
-
## Rails XSS Safety
-
-
# Whether or not ActionView's XSS protection is available and enabled,
-
# as is the default for Rails 3.0+, and optional for version 2.3.5+.
-
# Overridden in haml/template.rb if this is the case.
-
#
-
# @return [Boolean]
-
1
def rails_xss_safe?
-
false
-
end
-
-
# Returns the given text, marked as being HTML-safe.
-
# With older versions of the Rails XSS-safety mechanism,
-
# this destructively modifies the HTML-safety of `text`.
-
#
-
# It only works if you are using ActiveSupport or the parameter `text`
-
# implements the #html_safe method.
-
#
-
# @param text [String, nil]
-
# @return [String, nil] `text`, marked as HTML-safe
-
1
def html_safe(text)
-
331
return unless text
-
331
text.html_safe
-
end
-
-
# Checks that the encoding of a string is valid
-
# and cleans up potential encoding gotchas like the UTF-8 BOM.
-
# If it's not, yields an error string describing the invalid character
-
# and the line on which it occurs.
-
#
-
# @param str [String] The string of which to check the encoding
-
# @yield [msg] A block in which an encoding error can be raised.
-
# Only yields if there is an encoding error
-
# @yieldparam msg [String] The error message to be raised
-
# @return [String] `str`, potentially with encoding gotchas like BOMs removed
-
1
def check_encoding(str)
-
22
if str.valid_encoding?
-
# Get rid of the Unicode BOM if possible
-
# Shortcut for UTF-8 which might be the majority case
-
22
if str.encoding == Encoding::UTF_8
-
22
return str.gsub(/\A\uFEFF/, '')
-
elsif str.encoding.name =~ /^UTF-(16|32)(BE|LE)?$/
-
return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding)), '')
-
else
-
return str
-
end
-
end
-
-
encoding = str.encoding
-
newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding(Encoding::ASCII_8BIT))
-
str.force_encoding(Encoding::ASCII_8BIT).split(newlines).each_with_index do |line, i|
-
begin
-
line.encode(encoding)
-
rescue Encoding::UndefinedConversionError => e
-
yield <<MSG.rstrip, i + 1
-
Invalid #{encoding.name} character #{e.error_char.dump}
-
MSG
-
end
-
end
-
return str
-
end
-
-
# Like {\#check\_encoding}, but also checks for a Ruby-style `-# coding:` comment
-
# at the beginning of the template and uses that encoding if it exists.
-
#
-
# The Haml encoding rules are simple.
-
# If a `-# coding:` comment exists,
-
# we assume that that's the original encoding of the document.
-
# Otherwise, we use whatever encoding Ruby has.
-
#
-
# Haml uses the same rules for parsing coding comments as Ruby.
-
# This means that it can understand Emacs-style comments
-
# (e.g. `-*- encoding: "utf-8" -*-`),
-
# and also that it cannot understand non-ASCII-compatible encodings
-
# such as `UTF-16` and `UTF-32`.
-
#
-
# @param str [String] The Haml template of which to check the encoding
-
# @yield [msg] A block in which an encoding error can be raised.
-
# Only yields if there is an encoding error
-
# @yieldparam msg [String] The error message to be raised
-
# @return [String] The original string encoded properly
-
# @raise [ArgumentError] if the document declares an unknown encoding
-
1
def check_haml_encoding(str, &block)
-
22
str = str.dup if str.frozen?
-
-
22
bom, encoding = parse_haml_magic_comment(str)
-
22
if encoding; str.force_encoding(encoding)
-
elsif bom; str.force_encoding(Encoding::UTF_8)
-
end
-
-
22
return check_encoding(str, &block)
-
end
-
-
# Like `Object#inspect`, but preserves non-ASCII characters rather than escaping them.
-
# This is necessary so that the precompiled Haml template can be `#encode`d into `@options[:encoding]`
-
# before being evaluated.
-
#
-
# @param obj {Object}
-
# @return {String}
-
1
def inspect_obj(obj)
-
382
case obj
-
when String
-
578
%Q!"#{obj.gsub(/[\x00-\x7F]+/) {|s| s.inspect[1...-1]}}"!
-
when Symbol
-
":#{inspect_obj(obj.to_s)}"
-
else
-
93
obj.inspect
-
end
-
end
-
-
# Scans through a string looking for the interoplation-opening `#{`
-
# and, when it's found, yields the scanner to the calling code
-
# so it can handle it properly.
-
#
-
# The scanner will have any backslashes immediately in front of the `#{`
-
# as the second capture group (`scan[2]`),
-
# and the text prior to that as the first (`scan[1]`).
-
#
-
# @yieldparam scan [StringScanner] The scanner scanning through the string
-
# @return [String] The text remaining in the scanner after all `#{`s have been processed
-
1
def handle_interpolation(str)
-
scan = StringScanner.new(str)
-
yield scan while scan.scan(/(.*?)(\\*)#([\{@$])/)
-
scan.rest
-
end
-
-
# Moves a scanner through a balanced pair of characters.
-
# For example:
-
#
-
# Foo (Bar (Baz bang) bop) (Bang (bop bip))
-
# ^ ^
-
# from to
-
#
-
# @param scanner [StringScanner] The string scanner to move
-
# @param start [String] The character opening the balanced pair.
-
# @param finish [String] The character closing the balanced pair.
-
# @param count [Fixnum] The number of opening characters matched
-
# before calling this method
-
# @return [(String, String)] The string matched within the balanced pair
-
# and the rest of the string.
-
# `["Foo (Bar (Baz bang) bop)", " (Bang (bop bip))"]` in the example above.
-
1
def balance(scanner, start, finish, count = 0)
-
5
str = ''
-
5
scanner = StringScanner.new(scanner) unless scanner.is_a? StringScanner
-
5
regexp = Regexp.new("(.*?)[\\#{start.chr}\\#{finish.chr}]", Regexp::MULTILINE)
-
5
while scanner.scan(regexp)
-
10
str << scanner.matched
-
10
count += 1 if scanner.matched[-1] == start
-
10
count -= 1 if scanner.matched[-1] == finish
-
10
return [str.strip, scanner.rest] if count == 0
-
end
-
end
-
-
# Formats a string for use in error messages about indentation.
-
#
-
# @param indentation [String] The string used for indentation
-
# @return [String] The name of the indentation (e.g. `"12 spaces"`, `"1 tab"`)
-
1
def human_indentation(indentation)
-
if !indentation.include?(?\t)
-
noun = 'space'
-
elsif !indentation.include?(?\s)
-
noun = 'tab'
-
else
-
return indentation.inspect
-
end
-
-
singular = indentation.length == 1
-
"#{indentation.length} #{noun}#{'s' unless singular}"
-
end
-
-
1
def contains_interpolation?(str)
-
124
/#[\{$@]/ === str
-
end
-
-
1
def unescape_interpolation(str, escape_html = nil)
-
res = ''
-
rest = Haml::Util.handle_interpolation str.dump do |scan|
-
escapes = (scan[2].size - 1) / 2
-
char = scan[3] # '{', '@' or '$'
-
res << scan.matched[0...-3 - escapes]
-
if escapes % 2 == 1
-
res << "\##{char}"
-
else
-
interpolated = if char == '{'
-
balance(scan, ?{, ?}, 1)[0][0...-1]
-
else
-
scan.scan(/\w+/)
-
end
-
content = eval('"' + interpolated + '"')
-
content.prepend(char) if char == '@' || char == '$'
-
content = "Haml::Helpers.html_escape((#{content}))" if escape_html
-
-
res << "\#{#{content}}"
-
end
-
end
-
res + rest
-
end
-
-
1
private
-
-
# Parses a magic comment at the beginning of a Haml file.
-
# The parsing rules are basically the same as Ruby's.
-
#
-
# @return [(Boolean, String or nil)]
-
# Whether the document begins with a UTF-8 BOM,
-
# and the declared encoding of the document (or nil if none is declared)
-
1
def parse_haml_magic_comment(str)
-
22
scanner = StringScanner.new(str.dup.force_encoding(Encoding::ASCII_8BIT))
-
22
bom = scanner.scan(/\xEF\xBB\xBF/n)
-
22
return bom unless scanner.scan(/-\s*#\s*/n)
-
if coding = try_parse_haml_emacs_magic_comment(scanner)
-
return bom, coding
-
end
-
-
return bom unless scanner.scan(/.*?coding[=:]\s*([\w-]+)/in)
-
return bom, scanner[1]
-
end
-
-
1
def try_parse_haml_emacs_magic_comment(scanner)
-
pos = scanner.pos
-
return unless scanner.scan(/.*?-\*-\s*/n)
-
# From Ruby's parse.y
-
return unless scanner.scan(/([^\s'":;]+)\s*:\s*("(?:\\.|[^"])*"|[^"\s;]+?)[\s;]*-\*-/n)
-
name, val = scanner[1], scanner[2]
-
return unless name =~ /(en)?coding/in
-
val = $1 if val =~ /^"(.*)"$/n
-
return val
-
ensure
-
scanner.pos = pos
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module Haml
-
1
VERSION = "5.0.1"
-
end
-
1
require 'i18n/version'
-
1
require 'i18n/exceptions'
-
1
require 'i18n/interpolate/ruby'
-
-
1
module I18n
-
1
autoload :Backend, 'i18n/backend'
-
1
autoload :Config, 'i18n/config'
-
1
autoload :Gettext, 'i18n/gettext'
-
1
autoload :Locale, 'i18n/locale'
-
1
autoload :Tests, 'i18n/tests'
-
-
1
RESERVED_KEYS = [:scope, :default, :separator, :resolve, :object, :fallback, :fallback_in_progress, :format, :cascade, :throw, :raise, :deep_interpolation]
-
1
RESERVED_KEYS_PATTERN = /%\{(#{RESERVED_KEYS.join("|")})\}/
-
-
1
module Base
-
# Gets I18n configuration object.
-
1
def config
-
421
Thread.current[:i18n_config] ||= I18n::Config.new
-
end
-
-
# Sets I18n configuration object.
-
1
def config=(value)
-
132
Thread.current[:i18n_config] = value
-
end
-
-
# Write methods which delegates to the configuration object
-
%w(locale backend default_locale available_locales default_separator
-
1
exception_handler load_path enforce_available_locales).each do |method|
-
8
module_eval <<-DELEGATORS, __FILE__, __LINE__ + 1
-
def #{method}
-
config.#{method}
-
end
-
-
def #{method}=(value)
-
config.#{method} = (value)
-
end
-
DELEGATORS
-
end
-
-
# Tells the backend to reload translations. Used in situations like the
-
# Rails development environment. Backends can implement whatever strategy
-
# is useful.
-
1
def reload!
-
1
config.clear_available_locales_set
-
1
config.backend.reload!
-
end
-
-
# Translates, pluralizes and interpolates a given key using a given locale,
-
# scope, and default, as well as interpolation values.
-
#
-
# *LOOKUP*
-
#
-
# Translation data is organized as a nested hash using the upper-level keys
-
# as namespaces. <em>E.g.</em>, ActionView ships with the translation:
-
# <tt>:date => {:formats => {:short => "%b %d"}}</tt>.
-
#
-
# Translations can be looked up at any level of this hash using the key argument
-
# and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt>
-
# returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>.
-
#
-
# Key can be either a single key or a dot-separated key (both Strings and Symbols
-
# work). <em>E.g.</em>, the short format can be looked up using both:
-
# I18n.t 'date.formats.short'
-
# I18n.t :'date.formats.short'
-
#
-
# Scope can be either a single key, a dot-separated key or an array of keys
-
# or dot-separated keys. Keys and scopes can be combined freely. So these
-
# examples will all look up the same short date format:
-
# I18n.t 'date.formats.short'
-
# I18n.t 'formats.short', :scope => 'date'
-
# I18n.t 'short', :scope => 'date.formats'
-
# I18n.t 'short', :scope => %w(date formats)
-
#
-
# *INTERPOLATION*
-
#
-
# Translations can contain interpolation variables which will be replaced by
-
# values passed to #translate as part of the options hash, with the keys matching
-
# the interpolation variable names.
-
#
-
# <em>E.g.</em>, with a translation <tt>:foo => "foo %{bar}"</tt> the option
-
# value for the key +bar+ will be interpolated into the translation:
-
# I18n.t :foo, :bar => 'baz' # => 'foo baz'
-
#
-
# *PLURALIZATION*
-
#
-
# Translation data can contain pluralized translations. Pluralized translations
-
# are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>.
-
#
-
# Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English
-
# pluralization rules. Other algorithms can be supported by custom backends.
-
#
-
# This returns the singular version of a pluralized translation:
-
# I18n.t :foo, :count => 1 # => 'Foo'
-
#
-
# These both return the plural version of a pluralized translation:
-
# I18n.t :foo, :count => 0 # => 'Foos'
-
# I18n.t :foo, :count => 2 # => 'Foos'
-
#
-
# The <tt>:count</tt> option can be used both for pluralization and interpolation.
-
# <em>E.g.</em>, with the translation
-
# <tt>:foo => ['%{count} foo', '%{count} foos']</tt>, count will
-
# be interpolated to the pluralized translation:
-
# I18n.t :foo, :count => 1 # => '1 foo'
-
#
-
# *DEFAULTS*
-
#
-
# This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found:
-
# I18n.t :foo, :default => 'default'
-
#
-
# This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no
-
# translation for <tt>:foo</tt> was found:
-
# I18n.t :foo, :default => :bar
-
#
-
# Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt>
-
# or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found.
-
# I18n.t :foo, :default => [:bar, 'default']
-
#
-
# *BULK LOOKUP*
-
#
-
# This returns an array with the translations for <tt>:foo</tt> and <tt>:bar</tt>.
-
# I18n.t [:foo, :bar]
-
#
-
# Can be used with dot-separated nested keys:
-
# I18n.t [:'baz.foo', :'baz.bar']
-
#
-
# Which is the same as using a scope option:
-
# I18n.t [:foo, :bar], :scope => :baz
-
#
-
# *LAMBDAS*
-
#
-
# Both translations and defaults can be given as Ruby lambdas. Lambdas will be
-
# called and passed the key and options.
-
#
-
# E.g. assuming the key <tt>:salutation</tt> resolves to:
-
# lambda { |key, options| options[:gender] == 'm' ? "Mr. %{options[:name]}" : "Mrs. %{options[:name]}" }
-
#
-
# Then <tt>I18n.t(:salutation, :gender => 'w', :name => 'Smith') will result in "Mrs. Smith".
-
#
-
# It is recommended to use/implement lambdas in an "idempotent" way. E.g. when
-
# a cache layer is put in front of I18n.translate it will generate a cache key
-
# from the argument values passed to #translate. Therefor your lambdas should
-
# always return the same translations/values per unique combination of argument
-
# values.
-
1
def translate(*args)
-
30
options = args.last.is_a?(Hash) ? args.pop.dup : {}
-
30
key = args.shift
-
30
backend = config.backend
-
30
locale = options.delete(:locale) || config.locale
-
30
handling = options.delete(:throw) && :throw || options.delete(:raise) && :raise # TODO deprecate :raise
-
-
30
enforce_available_locales!(locale)
-
30
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
-
-
30
result = catch(:exception) do
-
30
if key.is_a?(Array)
-
key.map { |k| backend.translate(locale, k, options) }
-
else
-
30
backend.translate(locale, key, options)
-
end
-
end
-
30
result.is_a?(MissingTranslation) ? handle_exception(handling, result, locale, key, options) : result
-
end
-
1
alias :t :translate
-
-
# Wrapper for <tt>translate</tt> that adds <tt>:raise => true</tt>. With
-
# this option, if no translation is found, it will raise <tt>I18n::MissingTranslationData</tt>
-
1
def translate!(key, options={})
-
translate(key, options.merge(:raise => true))
-
end
-
1
alias :t! :translate!
-
-
# Returns true if a translation exists for a given key, otherwise returns false.
-
1
def exists?(key, locale = config.locale)
-
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
-
config.backend.exists?(locale, key)
-
end
-
-
# Transliterates UTF-8 characters to ASCII. By default this method will
-
# transliterate only Latin strings to an ASCII approximation:
-
#
-
# I18n.transliterate("Ærøskøbing")
-
# # => "AEroskobing"
-
#
-
# I18n.transliterate("日本語")
-
# # => "???"
-
#
-
# It's also possible to add support for per-locale transliterations. I18n
-
# expects transliteration rules to be stored at
-
# <tt>i18n.transliterate.rule</tt>.
-
#
-
# Transliteration rules can either be a Hash or a Proc. Procs must accept a
-
# single string argument. Hash rules inherit the default transliteration
-
# rules, while Procs do not.
-
#
-
# *Examples*
-
#
-
# Setting a Hash in <locale>.yml:
-
#
-
# i18n:
-
# transliterate:
-
# rule:
-
# ü: "ue"
-
# ö: "oe"
-
#
-
# Setting a Hash using Ruby:
-
#
-
# store_translations(:de, :i18n => {
-
# :transliterate => {
-
# :rule => {
-
# "ü" => "ue",
-
# "ö" => "oe"
-
# }
-
# }
-
# )
-
#
-
# Setting a Proc:
-
#
-
# translit = lambda {|string| MyTransliterator.transliterate(string) }
-
# store_translations(:xx, :i18n => {:transliterate => {:rule => translit})
-
#
-
# Transliterating strings:
-
#
-
# I18n.locale = :en
-
# I18n.transliterate("Jürgen") # => "Jurgen"
-
# I18n.locale = :de
-
# I18n.transliterate("Jürgen") # => "Juergen"
-
# I18n.transliterate("Jürgen", :locale => :en) # => "Jurgen"
-
# I18n.transliterate("Jürgen", :locale => :de) # => "Juergen"
-
1
def transliterate(*args)
-
options = args.pop.dup if args.last.is_a?(Hash)
-
key = args.shift
-
locale = options && options.delete(:locale) || config.locale
-
handling = options && (options.delete(:throw) && :throw || options.delete(:raise) && :raise)
-
replacement = options && options.delete(:replacement)
-
enforce_available_locales!(locale)
-
config.backend.transliterate(locale, key, replacement)
-
rescue I18n::ArgumentError => exception
-
handle_exception(handling, exception, locale, key, options || {})
-
end
-
-
# Localizes certain objects, such as dates and numbers to local formatting.
-
1
def localize(object, options = nil)
-
options = options ? options.dup : {}
-
locale = options.delete(:locale) || config.locale
-
format = options.delete(:format) || :default
-
enforce_available_locales!(locale)
-
config.backend.localize(locale, object, format, options)
-
end
-
1
alias :l :localize
-
-
# Executes block with given I18n.locale set.
-
1
def with_locale(tmp_locale = nil)
-
if tmp_locale
-
current_locale = self.locale
-
self.locale = tmp_locale
-
end
-
yield
-
ensure
-
self.locale = current_locale if tmp_locale
-
end
-
-
# Merges the given locale, key and scope into a single array of keys.
-
# Splits keys that contain dots into multiple keys. Makes sure all
-
# keys are Symbols.
-
1
def normalize_keys(locale, key, scope, separator = nil)
-
30
separator ||= I18n.default_separator
-
-
30
keys = []
-
30
keys.concat normalize_key(locale, separator)
-
30
keys.concat normalize_key(scope, separator)
-
30
keys.concat normalize_key(key, separator)
-
30
keys
-
end
-
-
# Returns true when the passed locale, which can be either a String or a
-
# Symbol, is in the list of available locales. Returns false otherwise.
-
1
def locale_available?(locale)
-
30
I18n.config.available_locales_set.include?(locale)
-
end
-
-
# Raises an InvalidLocale exception when the passed locale is not available.
-
1
def enforce_available_locales!(locale)
-
30
if config.enforce_available_locales
-
30
raise I18n::InvalidLocale.new(locale) if !locale_available?(locale)
-
end
-
end
-
-
1
private
-
-
# Any exceptions thrown in translate will be sent to the @@exception_handler
-
# which can be a Symbol, a Proc or any other Object unless they're forced to
-
# be raised or thrown (MissingTranslation).
-
#
-
# If exception_handler is a Symbol then it will simply be sent to I18n as
-
# a method call. A Proc will simply be called. In any other case the
-
# method #call will be called on the exception_handler object.
-
#
-
# Examples:
-
#
-
# I18n.exception_handler = :custom_exception_handler # this is the default
-
# I18n.custom_exception_handler(exception, locale, key, options) # will be called like this
-
#
-
# I18n.exception_handler = lambda { |*args| ... } # a lambda
-
# I18n.exception_handler.call(exception, locale, key, options) # will be called like this
-
#
-
# I18n.exception_handler = I18nExceptionHandler.new # an object
-
# I18n.exception_handler.call(exception, locale, key, options) # will be called like this
-
1
def handle_exception(handling, exception, locale, key, options)
-
4
case handling
-
when :raise
-
raise exception.respond_to?(:to_exception) ? exception.to_exception : exception
-
when :throw
-
4
throw :exception, exception
-
else
-
case handler = options[:exception_handler] || config.exception_handler
-
when Symbol
-
send(handler, exception, locale, key, options)
-
else
-
handler.call(exception, locale, key, options)
-
end
-
end
-
end
-
-
1
def normalize_key(key, separator)
-
92
normalized_key_cache[separator][key] ||=
-
case key
-
when Array
-
3
key.map { |k| normalize_key(k, separator) }.flatten
-
else
-
22
keys = key.to_s.split(separator)
-
22
keys.delete('')
-
74
keys.map! { |k| k.to_sym }
-
22
keys
-
end
-
end
-
-
1
def normalized_key_cache
-
93
@normalized_key_cache ||= Hash.new { |h,k| h[k] = {} }
-
end
-
end
-
-
1
extend Base
-
end
-
1
module I18n
-
1
module Backend
-
1
autoload :Base, 'i18n/backend/base'
-
1
autoload :InterpolationCompiler, 'i18n/backend/interpolation_compiler'
-
1
autoload :Cache, 'i18n/backend/cache'
-
1
autoload :Cascade, 'i18n/backend/cascade'
-
1
autoload :Chain, 'i18n/backend/chain'
-
1
autoload :Fallbacks, 'i18n/backend/fallbacks'
-
1
autoload :Flatten, 'i18n/backend/flatten'
-
1
autoload :Gettext, 'i18n/backend/gettext'
-
1
autoload :KeyValue, 'i18n/backend/key_value'
-
1
autoload :Memoize, 'i18n/backend/memoize'
-
1
autoload :Metadata, 'i18n/backend/metadata'
-
1
autoload :Pluralization, 'i18n/backend/pluralization'
-
1
autoload :Simple, 'i18n/backend/simple'
-
1
autoload :Transliterator, 'i18n/backend/transliterator'
-
end
-
end
-
1
require 'yaml'
-
1
require 'i18n/core_ext/hash'
-
1
require 'i18n/core_ext/kernel/suppress_warnings'
-
-
1
module I18n
-
1
module Backend
-
1
module Base
-
1
include I18n::Backend::Transliterator
-
-
# Accepts a list of paths to translation files. Loads translations from
-
# plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml
-
# for details.
-
1
def load_translations(*filenames)
-
1
filenames = I18n.load_path if filenames.empty?
-
64
filenames.flatten.each { |filename| load_file(filename) }
-
end
-
-
# This method receives a locale, a data hash and options for storing translations.
-
# Should be implemented
-
1
def store_translations(locale, data, options = {})
-
raise NotImplementedError
-
end
-
-
1
def translate(locale, key, options = {})
-
30
raise InvalidLocale.new(locale) unless locale
-
30
entry = lookup(locale, key, options[:scope], options) unless key.nil?
-
-
30
if entry.nil? && options.key?(:default)
-
16
entry = default(locale, key, options[:default], options)
-
else
-
14
entry = resolve(locale, key, entry, options)
-
end
-
-
30
if entry.nil?
-
4
if (options.key?(:default) && !options[:default].nil?) || !options.key?(:default)
-
4
throw(:exception, I18n::MissingTranslation.new(locale, key, options))
-
end
-
end
-
-
26
entry = entry.dup if entry.is_a?(String)
-
-
26
count = options[:count]
-
26
entry = pluralize(locale, entry, count) if count
-
-
26
deep_interpolation = options[:deep_interpolation]
-
26
values = options.except(*RESERVED_KEYS)
-
26
if values
-
26
entry = if deep_interpolation
-
deep_interpolate(locale, entry, values)
-
else
-
26
interpolate(locale, entry, values)
-
end
-
end
-
26
entry
-
end
-
-
1
def exists?(locale, key)
-
lookup(locale, key) != nil
-
end
-
-
# Acts the same as +strftime+, but uses a localized version of the
-
# format string. Takes a key from the date/time formats translations as
-
# a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>).
-
1
def localize(locale, object, format = :default, options = {})
-
if object.nil? && options.include?(:default)
-
return options[:default]
-
end
-
raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)
-
-
if Symbol === format
-
key = format
-
type = object.respond_to?(:sec) ? 'time' : 'date'
-
options = options.merge(:raise => true, :object => object, :locale => locale)
-
format = I18n.t(:"#{type}.formats.#{key}", options)
-
end
-
-
format = translate_localization_format(locale, object, format, options)
-
object.strftime(format)
-
end
-
-
# Returns an array of locales for which translations are available
-
# ignoring the reserved translation meta data key :i18n.
-
1
def available_locales
-
raise NotImplementedError
-
end
-
-
1
def reload!
-
end
-
-
1
protected
-
-
# The method which actually looks up for the translation in the store.
-
1
def lookup(locale, key, scope = [], options = {})
-
raise NotImplementedError
-
end
-
-
# Evaluates defaults.
-
# If given subject is an Array, it walks the array and returns the
-
# first translation that can be resolved. Otherwise it tries to resolve
-
# the translation directly.
-
1
def default(locale, object, subject, options = {})
-
54
options = options.dup.reject { |key, value| key == :default }
-
16
case subject
-
when Array
-
subject.each do |item|
-
20
result = resolve(locale, object, item, options) and return result
-
16
end and nil
-
else
-
resolve(locale, object, subject, options)
-
end
-
end
-
-
# Resolves a translation.
-
# If the given subject is a Symbol, it will be translated with the
-
# given options. If it is a Proc then it will be evaluated. All other
-
# subjects will be returned directly.
-
1
def resolve(locale, object, subject, options = {})
-
34
return subject if options[:resolve] == false
-
34
result = catch(:exception) do
-
34
case subject
-
when Symbol
-
10
I18n.translate(subject, options.merge(:locale => locale, :throw => true))
-
when Proc
-
date_or_time = options.delete(:object) || object
-
resolve(locale, object, subject.call(date_or_time, options))
-
else
-
24
subject
-
end
-
end
-
34
result unless result.is_a?(MissingTranslation)
-
end
-
-
# Picks a translation from a pluralized mnemonic subkey according to English
-
# pluralization rules :
-
# - It will pick the :one subkey if count is equal to 1.
-
# - It will pick the :other subkey otherwise.
-
# - It will pick the :zero subkey in the special case where count is
-
# equal to 0 and there is a :zero subkey present. This behaviour is
-
# not standard with regards to the CLDR pluralization rules.
-
# Other backends can implement more flexible or complex pluralization rules.
-
1
def pluralize(locale, entry, count)
-
8
return entry unless entry.is_a?(Hash) && count
-
-
key = :zero if count == 0 && entry.has_key?(:zero)
-
key ||= count == 1 ? :one : :other
-
raise InvalidPluralizationData.new(entry, count, key) unless entry.has_key?(key)
-
entry[key]
-
end
-
-
# Interpolates values into a given string.
-
#
-
# interpolate "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X'
-
# # => "file test.txt opened by %{user}"
-
1
def interpolate(locale, string, values = {})
-
26
if string.is_a?(::String) && !values.empty?
-
20
I18n.interpolate(string, values)
-
else
-
6
string
-
end
-
end
-
-
# Deep interpolation
-
#
-
# deep_interpolate { people: { ann: "Ann is %{ann}", john: "John is %{john}" } },
-
# ann: 'good', john: 'big'
-
# #=> { people: { ann: "Ann is good", john: "John is big" } }
-
1
def deep_interpolate(locale, data, values = {})
-
return data if values.empty?
-
-
case data
-
when ::String
-
I18n.interpolate(data, values)
-
when ::Hash
-
data.each_with_object({}) do |(k, v), result|
-
result[k] = deep_interpolate(locale, v, values)
-
end
-
when ::Array
-
data.map do |v|
-
deep_interpolate(locale, v, values)
-
end
-
else
-
data
-
end
-
end
-
-
# Loads a single translations file by delegating to #load_rb or
-
# #load_yml depending on the file extension and directly merges the
-
# data to the existing translations. Raises I18n::UnknownFileType
-
# for all other file extensions.
-
1
def load_file(filename)
-
63
type = File.extname(filename).tr('.', '').downcase
-
63
raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}", true)
-
63
data = send(:"load_#{type}", filename)
-
63
unless data.is_a?(Hash)
-
raise InvalidLocaleData.new(filename, 'expects it to return a hash, but does not')
-
end
-
126
data.each { |locale, d| store_translations(locale, d || {}) }
-
end
-
-
# Loads a plain Ruby translations file. eval'ing the file must yield
-
# a Hash containing translation data with locales as toplevel keys.
-
1
def load_rb(filename)
-
eval(IO.read(filename), binding, filename)
-
end
-
-
# Loads a YAML translations file. The data must have locales as
-
# toplevel keys.
-
1
def load_yml(filename)
-
63
begin
-
63
YAML.load_file(filename)
-
rescue TypeError, ScriptError, StandardError => e
-
raise InvalidLocaleData.new(filename, e.inspect)
-
end
-
end
-
-
1
def translate_localization_format(locale, object, format, options)
-
format.to_s.gsub(/%[aAbBpP]/) do |match|
-
case match
-
when '%a' then I18n.t(:"date.abbr_day_names", :locale => locale, :format => format)[object.wday]
-
when '%A' then I18n.t(:"date.day_names", :locale => locale, :format => format)[object.wday]
-
when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon]
-
when '%B' then I18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon]
-
when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).upcase if object.respond_to? :hour
-
when '%P' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).downcase if object.respond_to? :hour
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module I18n
-
1
module Backend
-
# A simple backend that reads translations from YAML files and stores them in
-
# an in-memory hash. Relies on the Base backend.
-
#
-
# The implementation is provided by a Implementation module allowing to easily
-
# extend Simple backend's behavior by including modules. E.g.:
-
#
-
# module I18n::Backend::Pluralization
-
# def pluralize(*args)
-
# # extended pluralization logic
-
# super
-
# end
-
# end
-
#
-
# I18n::Backend::Simple.include(I18n::Backend::Pluralization)
-
1
class Simple
-
3
(class << self; self; end).class_eval { public :include }
-
-
1
module Implementation
-
1
include Base
-
-
1
def initialized?
-
32
@initialized ||= false
-
end
-
-
# Stores translations for the given locale in memory.
-
# This uses a deep merge for the translations hash, so existing
-
# translations will be overwritten by new ones only at the deepest
-
# level of the hash.
-
1
def store_translations(locale, data, options = {})
-
63
locale = locale.to_sym
-
63
translations[locale] ||= {}
-
63
data = data.deep_symbolize_keys
-
63
translations[locale].deep_merge!(data)
-
end
-
-
# Get available locales from the translations hash
-
1
def available_locales
-
1
init_translations unless initialized?
-
1
translations.inject([]) do |locales, (locale, data)|
-
46
locales << locale unless (data.keys - [:i18n]).empty?
-
46
locales
-
end
-
end
-
-
# Clean up translations hash and set initialized to false on reload!
-
1
def reload!
-
3
@initialized = false
-
3
@translations = nil
-
3
super
-
end
-
-
1
protected
-
-
1
def init_translations
-
1
load_translations
-
1
@initialized = true
-
end
-
-
1
def translations
-
157
@translations ||= {}
-
end
-
-
# Looks up a translation from the translations hash. Returns nil if
-
# either key is nil, or locale, scope or key do not exist as a key in the
-
# nested translations hash. Splits keys or scopes containing dots
-
# into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as
-
# <tt>%w(currency format)</tt>.
-
1
def lookup(locale, key, scope = [], options = {})
-
30
init_translations unless initialized?
-
30
keys = I18n.normalize_keys(locale, key, scope, options[:separator])
-
-
30
keys.inject(translations) do |result, _key|
-
100
_key = _key.to_sym
-
100
return nil unless result.is_a?(Hash) && result.has_key?(_key)
-
80
result = result[_key]
-
80
result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol)
-
80
result
-
end
-
end
-
end
-
-
1
include Implementation
-
end
-
end
-
end
-
# encoding: utf-8
-
1
module I18n
-
1
module Backend
-
1
module Transliterator
-
1
DEFAULT_REPLACEMENT_CHAR = "?"
-
-
# Given a locale and a UTF-8 string, return the locale's ASCII
-
# approximation for the string.
-
1
def transliterate(locale, string, replacement = nil)
-
@transliterators ||= {}
-
@transliterators[locale] ||= Transliterator.get I18n.t(:'i18n.transliterate.rule',
-
:locale => locale, :resolve => false, :default => {})
-
@transliterators[locale].transliterate(string, replacement)
-
end
-
-
# Get a transliterator instance.
-
1
def self.get(rule = nil)
-
if !rule || rule.kind_of?(Hash)
-
HashTransliterator.new(rule)
-
elsif rule.kind_of? Proc
-
ProcTransliterator.new(rule)
-
else
-
raise I18n::ArgumentError, "Transliteration rule must be a proc or a hash."
-
end
-
end
-
-
# A transliterator which accepts a Proc as its transliteration rule.
-
1
class ProcTransliterator
-
1
def initialize(rule)
-
@rule = rule
-
end
-
-
1
def transliterate(string, replacement = nil)
-
@rule.call(string)
-
end
-
end
-
-
# A transliterator which accepts a Hash of characters as its translation
-
# rule.
-
1
class HashTransliterator
-
1
DEFAULT_APPROXIMATIONS = {
-
"À"=>"A", "Á"=>"A", "Â"=>"A", "Ã"=>"A", "Ä"=>"A", "Å"=>"A", "Æ"=>"AE",
-
"Ç"=>"C", "È"=>"E", "É"=>"E", "Ê"=>"E", "Ë"=>"E", "Ì"=>"I", "Í"=>"I",
-
"Î"=>"I", "Ï"=>"I", "Ð"=>"D", "Ñ"=>"N", "Ò"=>"O", "Ó"=>"O", "Ô"=>"O",
-
"Õ"=>"O", "Ö"=>"O", "×"=>"x", "Ø"=>"O", "Ù"=>"U", "Ú"=>"U", "Û"=>"U",
-
"Ü"=>"U", "Ý"=>"Y", "Þ"=>"Th", "ß"=>"ss", "à"=>"a", "á"=>"a", "â"=>"a",
-
"ã"=>"a", "ä"=>"a", "å"=>"a", "æ"=>"ae", "ç"=>"c", "è"=>"e", "é"=>"e",
-
"ê"=>"e", "ë"=>"e", "ì"=>"i", "í"=>"i", "î"=>"i", "ï"=>"i", "ð"=>"d",
-
"ñ"=>"n", "ò"=>"o", "ó"=>"o", "ô"=>"o", "õ"=>"o", "ö"=>"o", "ø"=>"o",
-
"ù"=>"u", "ú"=>"u", "û"=>"u", "ü"=>"u", "ý"=>"y", "þ"=>"th", "ÿ"=>"y",
-
"Ā"=>"A", "ā"=>"a", "Ă"=>"A", "ă"=>"a", "Ą"=>"A", "ą"=>"a", "Ć"=>"C",
-
"ć"=>"c", "Ĉ"=>"C", "ĉ"=>"c", "Ċ"=>"C", "ċ"=>"c", "Č"=>"C", "č"=>"c",
-
"Ď"=>"D", "ď"=>"d", "Đ"=>"D", "đ"=>"d", "Ē"=>"E", "ē"=>"e", "Ĕ"=>"E",
-
"ĕ"=>"e", "Ė"=>"E", "ė"=>"e", "Ę"=>"E", "ę"=>"e", "Ě"=>"E", "ě"=>"e",
-
"Ĝ"=>"G", "ĝ"=>"g", "Ğ"=>"G", "ğ"=>"g", "Ġ"=>"G", "ġ"=>"g", "Ģ"=>"G",
-
"ģ"=>"g", "Ĥ"=>"H", "ĥ"=>"h", "Ħ"=>"H", "ħ"=>"h", "Ĩ"=>"I", "ĩ"=>"i",
-
"Ī"=>"I", "ī"=>"i", "Ĭ"=>"I", "ĭ"=>"i", "Į"=>"I", "į"=>"i", "İ"=>"I",
-
"ı"=>"i", "IJ"=>"IJ", "ij"=>"ij", "Ĵ"=>"J", "ĵ"=>"j", "Ķ"=>"K", "ķ"=>"k",
-
"ĸ"=>"k", "Ĺ"=>"L", "ĺ"=>"l", "Ļ"=>"L", "ļ"=>"l", "Ľ"=>"L", "ľ"=>"l",
-
"Ŀ"=>"L", "ŀ"=>"l", "Ł"=>"L", "ł"=>"l", "Ń"=>"N", "ń"=>"n", "Ņ"=>"N",
-
"ņ"=>"n", "Ň"=>"N", "ň"=>"n", "ʼn"=>"'n", "Ŋ"=>"NG", "ŋ"=>"ng",
-
"Ō"=>"O", "ō"=>"o", "Ŏ"=>"O", "ŏ"=>"o", "Ő"=>"O", "ő"=>"o", "Œ"=>"OE",
-
"œ"=>"oe", "Ŕ"=>"R", "ŕ"=>"r", "Ŗ"=>"R", "ŗ"=>"r", "Ř"=>"R", "ř"=>"r",
-
"Ś"=>"S", "ś"=>"s", "Ŝ"=>"S", "ŝ"=>"s", "Ş"=>"S", "ş"=>"s", "Š"=>"S",
-
"š"=>"s", "Ţ"=>"T", "ţ"=>"t", "Ť"=>"T", "ť"=>"t", "Ŧ"=>"T", "ŧ"=>"t",
-
"Ũ"=>"U", "ũ"=>"u", "Ū"=>"U", "ū"=>"u", "Ŭ"=>"U", "ŭ"=>"u", "Ů"=>"U",
-
"ů"=>"u", "Ű"=>"U", "ű"=>"u", "Ų"=>"U", "ų"=>"u", "Ŵ"=>"W", "ŵ"=>"w",
-
"Ŷ"=>"Y", "ŷ"=>"y", "Ÿ"=>"Y", "Ź"=>"Z", "ź"=>"z", "Ż"=>"Z", "ż"=>"z",
-
"Ž"=>"Z", "ž"=>"z"
-
}.freeze
-
-
1
def initialize(rule = nil)
-
@rule = rule
-
add_default_approximations
-
add rule if rule
-
end
-
-
1
def transliterate(string, replacement = nil)
-
replacement ||= DEFAULT_REPLACEMENT_CHAR
-
string.gsub(/[^\x00-\x7f]/u) do |char|
-
approximations[char] || replacement
-
end
-
end
-
-
1
private
-
-
1
def approximations
-
@approximations ||= {}
-
end
-
-
1
def add_default_approximations
-
DEFAULT_APPROXIMATIONS.each do |key, value|
-
approximations[key] = value
-
end
-
end
-
-
# Add transliteration rules to the approximations hash.
-
1
def add(hash)
-
hash.each do |key, value|
-
approximations[key.to_s] = value.to_s
-
end
-
end
-
end
-
end
-
end
-
end
-
1
class Hash
-
def slice(*keep_keys)
-
h = self.class.new
-
keep_keys.each { |key| h[key] = fetch(key) if has_key?(key) }
-
h
-
1
end unless Hash.method_defined?(:slice)
-
-
def except(*less_keys)
-
slice(*keys - less_keys)
-
1
end unless Hash.method_defined?(:except)
-
-
def deep_symbolize_keys
-
inject({}) { |result, (key, value)|
-
value = value.deep_symbolize_keys if value.is_a?(Hash)
-
result[(key.to_sym rescue key) || key] = value
-
result
-
}
-
1
end unless Hash.method_defined?(:deep_symbolize_keys)
-
-
# deep_merge_hash! by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
-
1
MERGER = proc do |key, v1, v2|
-
Hash === v1 && Hash === v2 ? v1.merge(v2, &MERGER) : v2
-
end
-
-
def deep_merge!(data)
-
merge!(data, &MERGER)
-
1
end unless Hash.method_defined?(:deep_merge!)
-
end
-
-
1
module Kernel
-
1
def suppress_warnings
-
original_verbosity, $VERBOSE = $VERBOSE, nil
-
yield
-
ensure
-
$VERBOSE = original_verbosity
-
end
-
end
-
1
require 'cgi'
-
-
1
module I18n
-
# Handles exceptions raised in the backend. All exceptions except for
-
# MissingTranslationData exceptions are re-thrown. When a MissingTranslationData
-
# was caught the handler returns an error message string containing the key/scope.
-
# Note that the exception handler is not called when the option :throw was given.
-
1
class ExceptionHandler
-
1
include Module.new {
-
1
def call(exception, locale, key, options)
-
case exception
-
when MissingTranslation
-
exception.message
-
when Exception
-
raise exception
-
else
-
throw :exception, exception
-
end
-
end
-
}
-
end
-
-
1
class ArgumentError < ::ArgumentError; end
-
-
1
class InvalidLocale < ArgumentError
-
1
attr_reader :locale
-
1
def initialize(locale)
-
@locale = locale
-
super "#{locale.inspect} is not a valid locale"
-
end
-
end
-
-
1
class InvalidLocaleData < ArgumentError
-
1
attr_reader :filename
-
1
def initialize(filename, exception_message)
-
@filename, @exception_message = filename, exception_message
-
super "can not load translations from #{filename}: #{exception_message}"
-
end
-
end
-
-
1
class MissingTranslation < ArgumentError
-
1
module Base
-
1
attr_reader :locale, :key, :options
-
-
1
def initialize(locale, key, options = {})
-
4
@key, @locale, @options = key, locale, options.dup
-
8
options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) }
-
end
-
-
1
def keys
-
@keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys|
-
keys << 'no key' if keys.size < 2
-
end
-
end
-
-
1
def message
-
"translation missing: #{keys.join('.')}"
-
end
-
1
alias :to_s :message
-
-
1
def to_exception
-
MissingTranslationData.new(locale, key, options)
-
end
-
end
-
-
1
include Base
-
end
-
-
1
class MissingTranslationData < ArgumentError
-
1
include MissingTranslation::Base
-
end
-
-
1
class InvalidPluralizationData < ArgumentError
-
1
attr_reader :entry, :count, :key
-
1
def initialize(entry, count, key)
-
@entry, @count, @key = entry, count, key
-
super "translation data #{entry.inspect} can not be used with :count => #{count}. key '#{key}' is missing."
-
end
-
end
-
-
1
class MissingInterpolationArgument < ArgumentError
-
1
attr_reader :key, :values, :string
-
1
def initialize(key, values, string)
-
@key, @values, @string = key, values, string
-
super "missing interpolation argument #{key.inspect} in #{string.inspect} (#{values.inspect} given)"
-
end
-
end
-
-
1
class ReservedInterpolationKey < ArgumentError
-
1
attr_reader :key, :string
-
1
def initialize(key, string)
-
@key, @string = key, string
-
super "reserved key #{key.inspect} used in #{string.inspect}"
-
end
-
end
-
-
1
class UnknownFileType < ArgumentError
-
1
attr_reader :type, :filename
-
1
def initialize(type, filename)
-
@type, @filename = type, filename
-
super "can not load translations from #{filename}, the file type #{type} is not known"
-
end
-
end
-
end
-
# heavily based on Masao Mutoh's gettext String interpolation extension
-
# http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb
-
-
1
module I18n
-
1
INTERPOLATION_PATTERN = Regexp.union(
-
/%%/,
-
/%\{(\w+)\}/, # matches placeholders like "%{foo}"
-
/%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%<foo>.d"
-
)
-
-
1
class << self
-
# Return String or raises MissingInterpolationArgument exception.
-
# Missing argument's logic is handled by I18n.config.missing_interpolation_argument_handler.
-
1
def interpolate(string, values)
-
20
raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN
-
20
raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
-
20
interpolate_hash(string, values)
-
end
-
-
1
def interpolate_hash(string, values)
-
20
string.gsub(INTERPOLATION_PATTERN) do |match|
-
6
if match == '%%'
-
'%'
-
else
-
6
key = ($1 || $2 || match.tr("%{}", "")).to_sym
-
6
value = if values.key?(key)
-
6
values[key]
-
else
-
config.missing_interpolation_argument_handler.call(key, values, string)
-
end
-
6
value = value.call(values) if value.respond_to?(:call)
-
6
$3 ? sprintf("%#{$3}", value) : value
-
end
-
end
-
end
-
end
-
end
-
1
module I18n
-
1
VERSION = "0.8.6"
-
end
-
1
require 'jbuilder/jbuilder'
-
1
require 'jbuilder/blank'
-
1
require 'jbuilder/key_formatter'
-
1
require 'jbuilder/errors'
-
1
require 'multi_json'
-
1
require 'ostruct'
-
-
1
class Jbuilder
-
1
@@key_formatter = nil
-
1
@@ignore_nil = false
-
-
1
def initialize(options = {})
-
@attributes = {}
-
-
@key_formatter = options.fetch(:key_formatter){ @@key_formatter ? @@key_formatter.clone : nil}
-
@ignore_nil = options.fetch(:ignore_nil, @@ignore_nil)
-
-
yield self if ::Kernel.block_given?
-
end
-
-
# Yields a builder and automatically turns the result into a JSON string
-
1
def self.encode(*args, &block)
-
new(*args, &block).target!
-
end
-
-
1
BLANK = Blank.new
-
1
NON_ENUMERABLES = [ ::Struct, ::OpenStruct ].to_set
-
-
1
def set!(key, value = BLANK, *args)
-
result = if ::Kernel.block_given?
-
if !_blank?(value)
-
# json.comments @post.comments { |comment| ... }
-
# { "comments": [ { ... }, { ... } ] }
-
_scope{ array! value, &::Proc.new }
-
else
-
# json.comments { ... }
-
# { "comments": ... }
-
_merge_block(key){ yield self }
-
end
-
elsif args.empty?
-
if ::Jbuilder === value
-
# json.age 32
-
# json.person another_jbuilder
-
# { "age": 32, "person": { ... }
-
value.attributes!
-
else
-
# json.age 32
-
# { "age": 32 }
-
value
-
end
-
elsif _is_collection?(value)
-
# json.comments @post.comments, :content, :created_at
-
# { "comments": [ { "content": "hello", "created_at": "..." }, { "content": "world", "created_at": "..." } ] }
-
_scope{ array! value, *args }
-
else
-
# json.author @post.creator, :name, :email_address
-
# { "author": { "name": "David", "email_address": "david@loudthinking.com" } }
-
_merge_block(key){ extract! value, *args }
-
end
-
-
_set_value key, result
-
end
-
-
1
def method_missing(*args)
-
if ::Kernel.block_given?
-
set!(*args, &::Proc.new)
-
else
-
set!(*args)
-
end
-
end
-
-
# Specifies formatting to be applied to the key. Passing in a name of a function
-
# will cause that function to be called on the key. So :upcase will upper case
-
# the key. You can also pass in lambdas for more complex transformations.
-
#
-
# Example:
-
#
-
# json.key_format! :upcase
-
# json.author do
-
# json.name "David"
-
# json.age 32
-
# end
-
#
-
# { "AUTHOR": { "NAME": "David", "AGE": 32 } }
-
#
-
# You can pass parameters to the method using a hash pair.
-
#
-
# json.key_format! camelize: :lower
-
# json.first_name "David"
-
#
-
# { "firstName": "David" }
-
#
-
# Lambdas can also be used.
-
#
-
# json.key_format! ->(key){ "_" + key }
-
# json.first_name "David"
-
#
-
# { "_first_name": "David" }
-
#
-
1
def key_format!(*args)
-
@key_formatter = KeyFormatter.new(*args)
-
end
-
-
# Same as the instance method key_format! except sets the default.
-
1
def self.key_format(*args)
-
@@key_formatter = KeyFormatter.new(*args)
-
end
-
-
# If you want to skip adding nil values to your JSON hash. This is useful
-
# for JSON clients that don't deal well with nil values, and would prefer
-
# not to receive keys which have null values.
-
#
-
# Example:
-
# json.ignore_nil! false
-
# json.id User.new.id
-
#
-
# { "id": null }
-
#
-
# json.ignore_nil!
-
# json.id User.new.id
-
#
-
# {}
-
#
-
1
def ignore_nil!(value = true)
-
@ignore_nil = value
-
end
-
-
# Same as instance method ignore_nil! except sets the default.
-
1
def self.ignore_nil(value = true)
-
@@ignore_nil = value
-
end
-
-
# Turns the current element into an array and yields a builder to add a hash.
-
#
-
# Example:
-
#
-
# json.comments do
-
# json.child! { json.content "hello" }
-
# json.child! { json.content "world" }
-
# end
-
#
-
# { "comments": [ { "content": "hello" }, { "content": "world" } ]}
-
#
-
# More commonly, you'd use the combined iterator, though:
-
#
-
# json.comments(@post.comments) do |comment|
-
# json.content comment.formatted_content
-
# end
-
1
def child!
-
@attributes = [] unless ::Array === @attributes
-
@attributes << _scope{ yield self }
-
end
-
-
# Turns the current element into an array and iterates over the passed collection, adding each iteration as
-
# an element of the resulting array.
-
#
-
# Example:
-
#
-
# json.array!(@people) do |person|
-
# json.name person.name
-
# json.age calculate_age(person.birthday)
-
# end
-
#
-
# [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ]
-
#
-
# If you are using Ruby 1.9+, you can use the call syntax instead of an explicit extract! call:
-
#
-
# json.(@people) { |person| ... }
-
#
-
# It's generally only needed to use this method for top-level arrays. If you have named arrays, you can do:
-
#
-
# json.people(@people) do |person|
-
# json.name person.name
-
# json.age calculate_age(person.birthday)
-
# end
-
#
-
# { "people": [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ] }
-
#
-
# If you omit the block then you can set the top level array directly:
-
#
-
# json.array! [1, 2, 3]
-
#
-
# [1,2,3]
-
1
def array!(collection = [], *attributes)
-
array = if collection.nil?
-
[]
-
elsif ::Kernel.block_given?
-
_map_collection(collection, &::Proc.new)
-
elsif attributes.any?
-
_map_collection(collection) { |element| extract! element, *attributes }
-
else
-
collection.to_a
-
end
-
-
merge! array
-
end
-
-
# Extracts the mentioned attributes or hash elements from the passed object and turns them into attributes of the JSON.
-
#
-
# Example:
-
#
-
# @person = Struct.new(:name, :age).new('David', 32)
-
#
-
# or you can utilize a Hash
-
#
-
# @person = { name: 'David', age: 32 }
-
#
-
# json.extract! @person, :name, :age
-
#
-
# { "name": David", "age": 32 }, { "name": Jamie", "age": 31 }
-
#
-
# You can also use the call syntax instead of an explicit extract! call:
-
#
-
# json.(@person, :name, :age)
-
1
def extract!(object, *attributes)
-
if ::Hash === object
-
_extract_hash_values(object, attributes)
-
else
-
_extract_method_values(object, attributes)
-
end
-
end
-
-
1
def call(object, *attributes)
-
if ::Kernel.block_given?
-
array! object, &::Proc.new
-
else
-
extract! object, *attributes
-
end
-
end
-
-
# Returns the nil JSON.
-
1
def nil!
-
@attributes = nil
-
end
-
-
1
alias_method :null!, :nil!
-
-
# Returns the attributes of the current builder.
-
1
def attributes!
-
@attributes
-
end
-
-
# Merges hash or array into current builder.
-
1
def merge!(hash_or_array)
-
@attributes = _merge_values(@attributes, hash_or_array)
-
end
-
-
# Encodes the current builder as JSON.
-
1
def target!
-
::MultiJson.dump(@attributes)
-
end
-
-
1
private
-
-
1
def _extract_hash_values(object, attributes)
-
attributes.each{ |key| _set_value key, object.fetch(key) }
-
end
-
-
1
def _extract_method_values(object, attributes)
-
attributes.each{ |key| _set_value key, object.public_send(key) }
-
end
-
-
1
def _merge_block(key)
-
current_value = _blank? ? BLANK : @attributes.fetch(_key(key), BLANK)
-
raise NullError.build(key) if current_value.nil?
-
new_value = _scope{ yield self }
-
_merge_values(current_value, new_value)
-
end
-
-
1
def _merge_values(current_value, updates)
-
if _blank?(updates)
-
current_value
-
elsif _blank?(current_value) || updates.nil? || current_value.empty? && ::Array === updates
-
updates
-
elsif ::Array === current_value && ::Array === updates
-
current_value + updates
-
elsif ::Hash === current_value && ::Hash === updates
-
current_value.merge(updates)
-
else
-
raise MergeError.build(current_value, updates)
-
end
-
end
-
-
1
def _key(key)
-
@key_formatter ? @key_formatter.format(key) : key.to_s
-
end
-
-
1
def _set_value(key, value)
-
raise NullError.build(key) if @attributes.nil?
-
raise ArrayError.build(key) if ::Array === @attributes
-
return if @ignore_nil && value.nil? or _blank?(value)
-
@attributes = {} if _blank?
-
@attributes[_key(key)] = value
-
end
-
-
1
def _map_collection(collection)
-
collection.map do |element|
-
_scope{ yield element }
-
end - [BLANK]
-
end
-
-
1
def _scope
-
parent_attributes, parent_formatter = @attributes, @key_formatter
-
@attributes = BLANK
-
yield
-
@attributes
-
ensure
-
@attributes, @key_formatter = parent_attributes, parent_formatter
-
end
-
-
1
def _is_collection?(object)
-
_object_respond_to?(object, :map, :count) && NON_ENUMERABLES.none?{ |klass| klass === object }
-
end
-
-
1
def _blank?(value=@attributes)
-
BLANK == value
-
end
-
-
1
def _object_respond_to?(object, *methods)
-
methods.all?{ |m| object.respond_to?(m) }
-
end
-
end
-
-
1
require 'jbuilder/railtie' if defined?(Rails)
-
1
class Jbuilder
-
1
class Blank
-
1
def ==(other)
-
super || Blank === other
-
end
-
-
1
def empty?
-
true
-
end
-
end
-
end
-
1
require 'jbuilder/jbuilder'
-
-
1
dependency_tracker = false
-
-
1
begin
-
1
require 'action_view'
-
1
require 'action_view/dependency_tracker'
-
1
dependency_tracker = ::ActionView::DependencyTracker
-
rescue LoadError
-
begin
-
require 'cache_digests'
-
dependency_tracker = ::CacheDigests::DependencyTracker
-
rescue LoadError
-
end
-
end
-
-
1
if dependency_tracker
-
1
class Jbuilder
-
1
module DependencyTrackerMethods
-
# Matches:
-
# json.partial! "messages/message"
-
# json.partial!('messages/message')
-
#
-
1
DIRECT_RENDERS = /
-
\w+\.partial! # json.partial!
-
\(?\s* # optional parenthesis
-
(['"])([^'"]+)\1 # quoted value
-
/x
-
-
# Matches:
-
# json.partial! partial: "comments/comment"
-
# json.comments @post.comments, partial: "comments/comment", as: :comment
-
# json.array! @posts, partial: "posts/post", as: :post
-
# = render partial: "account"
-
#
-
1
INDIRECT_RENDERS = /
-
(?::partial\s*=>|partial:) # partial: or :partial =>
-
\s* # optional whitespace
-
(['"])([^'"]+)\1 # quoted value
-
/x
-
-
1
def dependencies
-
direct_dependencies + indirect_dependencies + explicit_dependencies
-
end
-
-
1
private
-
-
1
def direct_dependencies
-
source.scan(DIRECT_RENDERS).map(&:second)
-
end
-
-
1
def indirect_dependencies
-
source.scan(INDIRECT_RENDERS).map(&:second)
-
end
-
end
-
end
-
-
1
::Jbuilder::DependencyTracker = Class.new(dependency_tracker::ERBTracker)
-
1
::Jbuilder::DependencyTracker.send :include, ::Jbuilder::DependencyTrackerMethods
-
1
dependency_tracker.register_tracker :jbuilder, ::Jbuilder::DependencyTracker
-
end
-
1
require 'jbuilder/jbuilder'
-
-
1
class Jbuilder
-
1
class NullError < ::NoMethodError
-
1
def self.build(key)
-
message = "Failed to add #{key.to_s.inspect} property to null object"
-
new(message)
-
end
-
end
-
-
1
class ArrayError < ::StandardError
-
1
def self.build(key)
-
message = "Failed to add #{key.to_s.inspect} property to an array"
-
new(message)
-
end
-
end
-
-
1
class MergeError < ::StandardError
-
1
def self.build(current_value, updates)
-
message = "Can't merge #{updates.inspect} into #{current_value.inspect}"
-
new(message)
-
end
-
end
-
end
-
1
Jbuilder = Class.new(begin
-
1
require 'active_support/proxy_object'
-
1
ActiveSupport::ProxyObject
-
rescue LoadError
-
require 'active_support/basic_object'
-
ActiveSupport::BasicObject
-
end)
-
1
require 'jbuilder/jbuilder'
-
1
require 'action_dispatch/http/mime_type'
-
1
require 'active_support/cache'
-
-
1
class JbuilderTemplate < Jbuilder
-
1
class << self
-
1
attr_accessor :template_lookup_options
-
end
-
-
1
self.template_lookup_options = { handlers: [:jbuilder] }
-
-
1
def initialize(context, *args)
-
@context = context
-
@cached_root = nil
-
super(*args)
-
end
-
-
1
def partial!(*args)
-
if args.one? && _is_active_model?(args.first)
-
_render_active_model_partial args.first
-
else
-
_render_explicit_partial(*args)
-
end
-
end
-
-
# Caches the json constructed within the block passed. Has the same signature as the `cache` helper
-
# method in `ActionView::Helpers::CacheHelper` and so can be used in the same way.
-
#
-
# Example:
-
#
-
# json.cache! ['v1', @person], expires_in: 10.minutes do
-
# json.extract! @person, :name, :age
-
# end
-
1
def cache!(key=nil, options={})
-
if @context.controller.perform_caching
-
value = _cache_fragment_for(key, options) do
-
_scope { yield self }
-
end
-
-
merge! value
-
else
-
yield
-
end
-
end
-
-
# Caches the json structure at the root using a string rather than the hash structure. This is considerably
-
# faster, but the drawback is that it only works, as the name hints, at the root. So you cannot
-
# use this approach to cache deeper inside the hierarchy, like in partials or such. Continue to use #cache! there.
-
#
-
# Example:
-
#
-
# json.cache_root! @person do
-
# json.extract! @person, :name, :age
-
# end
-
#
-
# # json.extra 'This will not work either, the root must be exclusive'
-
1
def cache_root!(key=nil, options={})
-
if @context.controller.perform_caching
-
raise "cache_root! can't be used after JSON structures have been defined" if @attributes.present?
-
-
@cached_root = _cache_fragment_for([ :root, key ], options) { yield; target! }
-
else
-
yield
-
end
-
end
-
-
# Conditionally caches the json depending in the condition given as first parameter. Has the same
-
# signature as the `cache` helper method in `ActionView::Helpers::CacheHelper` and so can be used in
-
# the same way.
-
#
-
# Example:
-
#
-
# json.cache_if! !admin?, @person, expires_in: 10.minutes do
-
# json.extract! @person, :name, :age
-
# end
-
1
def cache_if!(condition, *args)
-
condition ? cache!(*args, &::Proc.new) : yield
-
end
-
-
1
def target!
-
@cached_root || super
-
end
-
-
1
def array!(collection = [], *args)
-
options = args.first
-
-
if args.one? && _partial_options?(options)
-
partial! options.merge(collection: collection)
-
else
-
super
-
end
-
end
-
-
1
def set!(name, object = BLANK, *args)
-
options = args.first
-
-
if args.one? && _partial_options?(options)
-
_set_inline_partial name, object, options
-
else
-
super
-
end
-
end
-
-
1
private
-
-
1
def _render_partial_with_options(options)
-
options.reverse_merge! locals: {}
-
options.reverse_merge! ::JbuilderTemplate.template_lookup_options
-
as = options[:as]
-
-
if as && options.key?(:collection)
-
as = as.to_sym
-
collection = options.delete(:collection)
-
locals = options.delete(:locals)
-
array! collection do |member|
-
member_locals = locals.clone
-
member_locals.merge! collection: collection
-
member_locals.merge! as => member
-
_render_partial options.merge(locals: member_locals)
-
end
-
else
-
_render_partial options
-
end
-
end
-
-
1
def _render_partial(options)
-
options[:locals].merge! json: self
-
@context.render options
-
end
-
-
1
def _cache_fragment_for(key, options, &block)
-
key = _cache_key(key, options)
-
_read_fragment_cache(key, options) || _write_fragment_cache(key, options, &block)
-
end
-
-
1
def _read_fragment_cache(key, options = nil)
-
@context.controller.instrument_fragment_cache :read_fragment, key do
-
::Rails.cache.read(key, options)
-
end
-
end
-
-
1
def _write_fragment_cache(key, options = nil)
-
@context.controller.instrument_fragment_cache :write_fragment, key do
-
yield.tap do |value|
-
::Rails.cache.write(key, value, options)
-
end
-
end
-
end
-
-
1
def _cache_key(key, options)
-
name_options = options.slice(:skip_digest, :virtual_path)
-
key = _fragment_name_with_digest(key, name_options)
-
-
if @context.respond_to?(:fragment_cache_key)
-
key = @context.fragment_cache_key(key)
-
else
-
key = url_for(key).split('://', 2).last if ::Hash === key
-
end
-
-
::ActiveSupport::Cache.expand_cache_key(key, :jbuilder)
-
end
-
-
1
def _fragment_name_with_digest(key, options)
-
if @context.respond_to?(:cache_fragment_name)
-
# Current compatibility, fragment_name_with_digest is private again and cache_fragment_name
-
# should be used instead.
-
@context.cache_fragment_name(key, options)
-
elsif @context.respond_to?(:fragment_name_with_digest)
-
# Backwards compatibility for period of time when fragment_name_with_digest was made public.
-
@context.fragment_name_with_digest(key)
-
else
-
key
-
end
-
end
-
-
1
def _partial_options?(options)
-
::Hash === options && options.key?(:as) && options.key?(:partial)
-
end
-
-
1
def _is_active_model?(object)
-
object.class.respond_to?(:model_name) && object.respond_to?(:to_partial_path)
-
end
-
-
1
def _set_inline_partial(name, object, options)
-
value = if object.nil?
-
[]
-
elsif _is_collection?(object)
-
_scope{ _render_partial_with_options options.merge(collection: object) }
-
else
-
locals = ::Hash[options[:as], object]
-
_scope{ _render_partial_with_options options.merge(locals: locals) }
-
end
-
-
set! name, value
-
end
-
-
1
def _render_explicit_partial(name_or_options, locals = {})
-
case name_or_options
-
when ::Hash
-
# partial! partial: 'name', foo: 'bar'
-
options = name_or_options
-
else
-
# partial! 'name', locals: {foo: 'bar'}
-
if locals.one? && (locals.keys.first == :locals)
-
options = locals.merge(partial: name_or_options)
-
else
-
options = { partial: name_or_options, locals: locals }
-
end
-
# partial! 'name', foo: 'bar'
-
as = locals.delete(:as)
-
options[:as] = as if as.present?
-
options[:collection] = locals[:collection] if locals.key?(:collection)
-
end
-
-
_render_partial_with_options options
-
end
-
-
1
def _render_active_model_partial(object)
-
@context.render object, json: self
-
end
-
end
-
-
1
class JbuilderHandler
-
1
cattr_accessor :default_format
-
1
self.default_format = Mime[:json]
-
-
1
def self.call(template)
-
# this juggling is required to keep line numbers right in the error
-
%{__already_defined = defined?(json); json||=JbuilderTemplate.new(self); #{template.source}
-
json.target! unless (__already_defined && __already_defined != "method")}
-
end
-
end
-
1
require 'jbuilder/jbuilder'
-
1
require 'active_support/core_ext/array'
-
-
1
class Jbuilder
-
1
class KeyFormatter
-
1
def initialize(*args)
-
@format = {}
-
@cache = {}
-
-
options = args.extract_options!
-
args.each do |name|
-
@format[name] = []
-
end
-
options.each do |name, parameters|
-
@format[name] = parameters
-
end
-
end
-
-
1
def initialize_copy(original)
-
@cache = {}
-
end
-
-
1
def format(key)
-
@cache[key] ||= @format.inject(key.to_s) do |result, args|
-
func, args = args
-
if ::Proc === func
-
func.call result, *args
-
else
-
result.send func, *args
-
end
-
end
-
end
-
end
-
end
-
1
require 'rails/railtie'
-
1
require 'jbuilder/jbuilder_template'
-
-
1
class Jbuilder
-
1
class Railtie < ::Rails::Railtie
-
1
initializer :jbuilder do
-
1
ActiveSupport.on_load :action_view do
-
1
ActionView::Template.register_template_handler :jbuilder, JbuilderHandler
-
1
require 'jbuilder/dependency_tracker'
-
end
-
-
1
if Rails::VERSION::MAJOR >= 5
-
module ::ActionController
-
module ApiRendering
-
include ActionView::Rendering
-
end
-
end
-
-
ActiveSupport.on_load :action_controller do
-
if self == ActionController::API
-
include ActionController::Helpers
-
include ActionController::ImplicitRender
-
end
-
end
-
end
-
end
-
-
1
if Rails::VERSION::MAJOR >= 4
-
1
generators do |app|
-
Rails::Generators.configure! app.config.generators
-
Rails::Generators.hidden_namespaces.uniq!
-
require 'generators/rails/scaffold_controller_generator'
-
end
-
end
-
end
-
end
-
1
require 'rails/dom/testing/assertions/selector_assertions'
-
-
1
module Rails::Dom::Testing::Assertions::SelectorAssertions
-
# Selects content from a JQuery response. Patterned loosely on
-
# assert_select_rjs.
-
#
-
# === Narrowing down
-
#
-
# With no arguments, asserts that one or more method calls are made.
-
#
-
# Use the +method+ argument to narrow down the assertion to only
-
# statements that call that specific method.
-
#
-
# Use the +opt+ argument to narrow down the assertion to only statements
-
# that pass +opt+ as the first argument.
-
#
-
# Use the +id+ argument to narrow down the assertion to only statements
-
# that invoke methods on the result of using that identifier as a
-
# selector.
-
#
-
# === Using blocks
-
#
-
# Without a block, +assert_select_jquery_ merely asserts that the
-
# response contains one or more statements that match the conditions
-
# specified above
-
#
-
# With a block +assert_select_jquery_ also asserts that the method call
-
# passes a javascript escaped string containing HTML. All such HTML
-
# fragments are selected and passed to the block. Nested assertions are
-
# supported.
-
#
-
# === Examples
-
#
-
# # asserts that the #notice element is hidden
-
# assert_select :hide, '#notice'
-
#
-
# # asserts that the #cart element is shown with a blind parameter
-
# assert_select :show, :blind, '#cart'
-
#
-
# # asserts that #cart content contains a #current_item
-
# assert_select :html, '#cart' do
-
# assert_select '#current_item'
-
# end
-
#
-
# # asserts that #product append to a #product_list
-
# assert_select_jquery :appendTo, '#product_list' do
-
# assert_select '.product'
-
# end
-
-
1
PATTERN_HTML = "['\"]((\\\\\"|[^\"])*)['\"]"
-
1
PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
-
1
SKELETAL_PATTERN = "(?:jQuery|\\$)\\(%s\\)\\.%s\\(%s\\);"
-
-
1
def assert_select_jquery(*args, &block)
-
jquery_method = args.first.is_a?(Symbol) ? args.shift : nil
-
jquery_opt = args.first.is_a?(Symbol) ? args.shift : nil
-
id = args.first.is_a?(String) ? escape_id(args.shift) : nil
-
-
target_pattern = "['\"]#{id || '.*'}['\"]"
-
method_pattern = "#{jquery_method || '\\w+'}"
-
argument_pattern = jquery_opt ? "['\"]#{jquery_opt}['\"].*" : PATTERN_HTML
-
-
# $("#id").show('blind', 1000);
-
# $("#id").html("<div>something</div>");
-
# $("#id").replaceWith("<div>something</div>");
-
target_as_receiver_pattern = SKELETAL_PATTERN % [target_pattern, method_pattern, argument_pattern]
-
-
# $("<div>something</div>").appendTo("#id");
-
# $("<div>something</div>").prependTo("#id");
-
target_as_argument_pattern = SKELETAL_PATTERN % [argument_pattern, method_pattern, target_pattern]
-
-
# $("#id").remove();
-
# $("#id").hide();
-
argumentless_pattern = SKELETAL_PATTERN % [target_pattern, method_pattern, '']
-
-
patterns = [target_as_receiver_pattern, target_as_argument_pattern]
-
patterns << argumentless_pattern unless jquery_opt
-
-
matched_pattern = nil
-
patterns.each do |pattern|
-
if response.body.match(Regexp.new(pattern))
-
matched_pattern = pattern
-
break
-
end
-
end
-
-
unless matched_pattern
-
opts = [jquery_method, jquery_opt, id].compact
-
flunk "No JQuery call matches #{opts.inspect}"
-
end
-
-
if block_given?
-
@selected ||= nil
-
fragments = Nokogiri::HTML::Document.new
-
-
if matched_pattern
-
response.body.scan(Regexp.new(matched_pattern)).each do |match|
-
flunk 'This function can\'t have HTML argument' if match.is_a?(String)
-
-
doc = Nokogiri::HTML::Document.parse(unescape_js(match.first))
-
doc.root.children.each do |child|
-
fragments << child if child.element?
-
end
-
end
-
end
-
-
begin
-
in_scope, @selected = @selected, fragments
-
yield
-
ensure
-
@selected = in_scope
-
end
-
end
-
end
-
-
1
private
-
-
# Unescapes a JS string.
-
1
def unescape_js(js_string)
-
# js encodes double quotes and line breaks.
-
unescaped= js_string.gsub('\"', '"')
-
unescaped.gsub!('\\\'', "'")
-
unescaped.gsub!(/\\\//, '/')
-
unescaped.gsub!('\n', "\n")
-
unescaped.gsub!('\076', '>')
-
unescaped.gsub!('\074', '<')
-
# js encodes non-ascii characters.
-
unescaped.gsub!(PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
-
unescaped
-
end
-
-
1
def escape_id(selector)
-
return unless selector
-
-
id = selector.gsub('[', '\[')
-
id.gsub!(']', '\]')
-
-
id
-
end
-
end
-
1
require 'jquery/assert_select' if ::Rails.env.test?
-
1
require 'jquery/rails/engine'
-
1
require 'jquery/rails/version'
-
-
1
module Jquery
-
1
module Rails
-
end
-
end
-
1
module Jquery
-
1
module Rails
-
1
class Engine < ::Rails::Engine
-
end
-
end
-
end
-
1
module Jquery
-
1
module Rails
-
1
VERSION = "4.3.1"
-
1
JQUERY_VERSION = "1.12.4"
-
1
JQUERY_2_VERSION = "2.2.4"
-
1
JQUERY_3_VERSION = "3.2.1"
-
1
JQUERY_UJS_VERSION = "1.2.2"
-
end
-
end
-
1
require 'set'
-
1
module Launchy
-
#
-
# Application is the base class of all the application types that launchy may
-
# invoke. It essentially defines the public api of the launchy system.
-
#
-
# Every class that inherits from Application must define:
-
#
-
# 1. A constructor taking no parameters
-
# 2. An instance method 'open' taking a string or URI as the first parameter and a
-
# hash as the second
-
# 3. A class method 'handles?' that takes a String and returns true if that
-
# class can handle the input.
-
1
class Application
-
1
extend DescendantTracker
-
-
1
class << self
-
# Find the application that handles the given uri.
-
#
-
# returns the Class that can handle the uri
-
1
def handling( uri )
-
klass = find_child( :handles?, uri )
-
return klass if klass
-
raise ApplicationNotFoundError, "No application found to handle '#{uri}'"
-
end
-
-
#
-
# Find the given executable in the available paths
-
1
def find_executable( bin, *paths )
-
paths = ENV['PATH'].split( File::PATH_SEPARATOR ) if paths.empty?
-
paths.each do |path|
-
file = File.join( path, bin )
-
if File.executable?( file ) then
-
Launchy.log "#{self.name} : found executable #{file}"
-
return file
-
end
-
end
-
Launchy.log "#{self.name} : Unable to find `#{bin}' in #{paths.join(", ")}"
-
return nil
-
end
-
end
-
-
1
attr_reader :host_os_family
-
1
attr_reader :ruby_engine
-
1
attr_reader :runner
-
-
1
def initialize
-
@host_os_family = Launchy::Detect::HostOsFamily.detect
-
@ruby_engine = Launchy::Detect::RubyEngine.detect
-
@runner = Launchy::Detect::Runner.detect
-
end
-
-
1
def find_executable( bin, *paths )
-
Application.find_executable( bin, *paths )
-
end
-
-
1
def run( cmd, *args )
-
runner.run( cmd, *args )
-
end
-
end
-
end
-
1
require 'launchy/applications/browser'
-
1
class Launchy::Application
-
#
-
# The class handling the browser application and all of its schemes
-
#
-
1
class Browser < Launchy::Application
-
1
def self.schemes
-
%w[ http https ftp file ]
-
end
-
-
1
def self.handles?( uri )
-
return true if schemes.include?( uri.scheme )
-
return true if File.exist?( uri.path )
-
end
-
-
1
def windows_app_list
-
[ 'start "launchy" /b' ]
-
end
-
-
1
def cygwin_app_list
-
[ 'cmd /C start "launchy" /b' ]
-
end
-
-
# hardcode this to open?
-
1
def darwin_app_list
-
[ find_executable( "open" ) ]
-
end
-
-
1
def nix_app_list
-
nix_de = Launchy::Detect::NixDesktopEnvironment.detect
-
list = nix_de.browsers
-
list.find_all { |argv| argv.valid? }
-
end
-
-
# use a call back mechanism to get the right app_list that is decided by the
-
# host_os_family class.
-
1
def app_list
-
host_os_family.app_list( self )
-
end
-
-
1
def browser_env
-
return [] unless ENV['BROWSER']
-
browser_env = ENV['BROWSER'].split( File::PATH_SEPARATOR )
-
browser_env.flatten!
-
browser_env.delete_if { |b| b.nil? || (b.strip.size == 0) }
-
return browser_env
-
end
-
-
# Get the full commandline of what we are going to add the uri to
-
1
def browser_cmdline
-
browser_env.each do |p|
-
Launchy.log "#{self.class.name} : possibility from BROWSER environment variable : #{p}"
-
end
-
app_list.each do |p|
-
Launchy.log "#{self.class.name} : possibility from app_list : #{p}"
-
end
-
-
possibilities = (browser_env + app_list).flatten
-
-
if browser = possibilities.shift then
-
Launchy.log "#{self.class.name} : Using browser value '#{browser}'"
-
return browser
-
end
-
raise Launchy::CommandNotFoundError, "Unable to find a browser command. If this is unexpected, #{Launchy.bug_report_message}"
-
end
-
-
1
def cmd_and_args( uri, options = {} )
-
cmd = browser_cmdline
-
args = [ uri.to_s ]
-
if cmd =~ /%s/ then
-
cmd.gsub!( /%s/, args.shift )
-
end
-
return [cmd, args]
-
end
-
-
# final assembly of the command and do %s substitution
-
# http://www.catb.org/~esr/BROWSER/index.html
-
1
def open( uri, options = {} )
-
cmd, args = cmd_and_args( uri, options )
-
run( cmd, args )
-
end
-
end
-
end
-
1
module Launchy
-
1
class Argv
-
1
attr_reader :argv
-
1
def initialize( *args )
-
@argv = args.flatten
-
end
-
-
1
def to_s
-
@argv.join(' ')
-
end
-
-
1
def to_str
-
to_s
-
end
-
-
1
def [](idx)
-
@argv[idx]
-
end
-
-
1
def valid?
-
(not blank?) && executable?
-
end
-
-
1
def blank?
-
@argv.empty? || (@argv.first.strip.size == 0)
-
end
-
-
1
def executable?
-
::Launchy::Application.find_executable( @argv.first )
-
end
-
-
1
def ==( other )
-
@argv == other.argv
-
end
-
end
-
end
-
1
require 'optparse'
-
-
1
module Launchy
-
1
class Cli
-
-
1
attr_reader :options
-
1
def initialize
-
@options = {}
-
end
-
-
1
def parser
-
@parser ||= OptionParser.new do |op|
-
op.banner = "Usage: launchy [options] thing-to-launch"
-
-
op.separator ""
-
op.separator "Launch Options:"
-
-
op.on( "-a", "--application APPLICATION",
-
"Explicitly specify the application class to use in the launch") do |app|
-
@options[:application] = app
-
end
-
-
op.on( "-d", "--debug",
-
"Force debug. Output lots of information.") do |d|
-
@options[:debug] = true
-
end
-
-
op.on( "-e", "--engine RUBY_ENGINE",
-
"Force launchy to behave as if it was on a particular ruby engine.") do |e|
-
@options[:ruby_engine] = e
-
end
-
-
op.on( "-n", "--dry-run", "Don't launchy, print the command to be executed on stdout" ) do |x|
-
@options[:dry_run] = true
-
end
-
-
op.on( "-o", "--host-os HOST_OS",
-
"Force launchy to behave as if it was on a particular host os.") do |os|
-
@options[:host_os] = os
-
end
-
-
-
op.separator ""
-
op.separator "Standard Options:"
-
-
op.on( "-h", "--help", "Print this message.") do |h|
-
$stdout.puts op.to_s
-
exit 0
-
end
-
-
op.on( "-v", "--version", "Output the version of Launchy") do |v|
-
$stdout.puts "Launchy version #{Launchy::VERSION}"
-
exit 0
-
end
-
-
end
-
end
-
-
1
def parse( argv, env )
-
parser.parse!( argv )
-
return true
-
rescue ::OptionParser::ParseError => pe
-
error_output( pe )
-
end
-
-
1
def good_run( argv, env )
-
if parse( argv, env ) then
-
Launchy.open( argv.shift, options ) { |e| error_output( e ) }
-
return true
-
else
-
return false
-
end
-
end
-
-
1
def error_output( error )
-
$stderr.puts "ERROR: #{error}"
-
Launchy.log "ERROR: #{error}"
-
error.backtrace.each do |bt|
-
Launchy.log bt
-
end
-
$stderr.puts "Try `#{parser.program_name} --help' for more information."
-
return false
-
end
-
-
1
def run( argv = ARGV, env = ENV )
-
exit 1 unless good_run( argv, env )
-
end
-
end
-
end
-
1
module Launchy
-
#
-
# This class is deprecated and will be removed
-
#
-
1
class Browser
-
1
def self.run( *args )
-
Browser.new.visit( args[0] )
-
end
-
-
1
def visit( url )
-
_warn "You made a call to a deprecated Launchy API. This call should be changed to 'Launchy.open( uri )'"
-
report_caller_context( caller )
-
-
::Launchy.open( url )
-
end
-
-
1
private
-
-
1
def find_caller_context( stack )
-
caller_file = stack.find do |line|
-
not line.index( __FILE__ )
-
end
-
if caller_file then
-
caller_fname, caller_line, _ = caller_file.split(":")
-
if File.readable?( caller_fname ) then
-
caller_lines = IO.readlines( caller_fname )
-
context = [ caller_file ]
-
context << caller_lines[(caller_line.to_i)-3, 5]
-
return context.flatten
-
end
-
end
-
return []
-
end
-
-
1
def report_caller_context( stack )
-
context = find_caller_context( stack )
-
if context.size > 0 then
-
_warn "I think I was able to find the location that needs to be fixed. Please go look at:"
-
_warn
-
context.each do |line|
-
_warn line.rstrip
-
end
-
_warn
-
_warn "If this is not the case, please file a bug. #{Launchy.bug_report_message}"
-
end
-
end
-
-
1
def _warn( msg = "" )
-
warn "WARNING: #{msg}"
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Launchy
-
#
-
# Use by either
-
#
-
# class Foo
-
# extend DescendantTracker
-
# end
-
#
-
# or
-
#
-
# class Foo
-
# class << self
-
# include DescendantTracker
-
# end
-
# end
-
#
-
# It will track all the classes that inherit from the extended class and keep
-
# them in a Set that is available via the 'children' method.
-
#
-
1
module DescendantTracker
-
1
def inherited( klass )
-
17
return unless klass.instance_of?( Class )
-
17
self.children << klass
-
end
-
-
#
-
# The list of children that are registered
-
#
-
1
def children
-
17
unless defined? @children
-
5
@children = Array.new
-
end
-
17
return @children
-
end
-
-
#
-
# Find one of the child classes by calling the given method
-
# and passing all the rest of the parameters to that method in
-
# each child
-
1
def find_child( method, *args )
-
children.find do |child|
-
Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}"
-
child.send( method, *args )
-
end
-
end
-
end
-
end
-
1
module Launchy
-
1
module Detect
-
end
-
end
-
-
1
require 'launchy/detect/host_os'
-
1
require 'launchy/detect/host_os_family'
-
1
require 'launchy/detect/ruby_engine'
-
1
require 'launchy/detect/nix_desktop_environment'
-
1
require 'launchy/detect/runner'
-
1
require 'rbconfig'
-
-
1
module Launchy::Detect
-
1
class HostOs
-
-
1
attr_reader :host_os
-
1
alias to_s host_os
-
1
alias to_str host_os
-
-
1
def initialize( host_os = nil )
-
@host_os = host_os
-
-
if not @host_os then
-
if @host_os = override_host_os then
-
Launchy.log "Using LAUNCHY_HOST_OS override value of '#{Launchy.host_os}'"
-
else
-
@host_os = default_host_os
-
end
-
end
-
end
-
-
1
def default_host_os
-
::RbConfig::CONFIG['host_os']
-
end
-
-
1
def override_host_os
-
Launchy.host_os
-
end
-
-
end
-
-
end
-
1
module Launchy::Detect
-
# Detect the current host os family
-
#
-
# If the current host familiy cannot be detected then return
-
# HostOsFamily::Unknown
-
1
class HostOsFamily
-
1
class NotFoundError < Launchy::Error; end
-
1
extend ::Launchy::DescendantTracker
-
-
1
class << self
-
-
1
def detect( host_os = HostOs.new )
-
found = find_child( :matches?, host_os )
-
return found.new( host_os ) if found
-
raise NotFoundError, "Unknown OS family for host os '#{host_os}'. #{Launchy.bug_report_message}"
-
end
-
-
1
def matches?( host_os )
-
matching_regex.match( host_os.to_s )
-
end
-
-
1
def windows?() self == Windows; end
-
1
def darwin?() self == Darwin; end
-
1
def nix?() self == Nix; end
-
1
def cygwin?() self == Cygwin; end
-
end
-
-
-
1
attr_reader :host_os
-
1
def initialize( host_os = HostOs.new )
-
@host_os = host_os
-
end
-
-
1
def windows?() self.class.windows?; end
-
1
def darwin?() self.class.darwin?; end
-
1
def nix?() self.class.nix?; end
-
1
def cygwin?() self.class.cygwin?; end
-
-
#---------------------------
-
# All known host os families
-
#---------------------------
-
#
-
1
class Windows < HostOsFamily
-
1
def self.matching_regex
-
/(mingw|mswin|windows)/i
-
end
-
1
def app_list( app ) app.windows_app_list; end
-
end
-
-
1
class Darwin < HostOsFamily
-
1
def self.matching_regex
-
/(darwin|mac os)/i
-
end
-
1
def app_list( app ) app.darwin_app_list; end
-
end
-
-
1
class Nix < HostOsFamily
-
1
def self.matching_regex
-
/(linux|bsd|aix|solaris)/i
-
end
-
1
def app_list( app ) app.nix_app_list; end
-
end
-
-
1
class Cygwin < HostOsFamily
-
1
def self.matching_regex
-
/cygwin/i
-
end
-
1
def app_list( app ) app.cygwin_app_list; end
-
end
-
end
-
end
-
1
module Launchy::Detect
-
#
-
# Detect the current desktop environment for *nix machines
-
# Currently this is Linux centric. The detection is based upon the detection
-
# used by xdg-open from http://portland.freedesktop.org/
-
1
class NixDesktopEnvironment
-
1
class NotFoundError < Launchy::Error; end
-
-
1
extend ::Launchy::DescendantTracker
-
-
# Detect the current *nix desktop environment
-
#
-
# If the current dekstop environment be detected, the return
-
# NixDekstopEnvironment::Unknown
-
1
def self.detect
-
found = find_child( :is_current_desktop_environment? )
-
Launchy.log("Current Desktop environment not found. #{Launchy.bug_report_message}") unless found
-
return found
-
end
-
-
1
def self.fallback_browsers
-
%w[ firefox iceweasel seamonkey opera mozilla netscape galeon ].map { |x| ::Launchy::Argv.new( x ) }
-
end
-
-
1
def self.browsers
-
[ browser, fallback_browsers ].flatten
-
end
-
-
#---------------------------------------
-
# The list of known desktop environments
-
#---------------------------------------
-
-
1
class Kde < NixDesktopEnvironment
-
1
def self.is_current_desktop_environment?
-
ENV['KDE_FULL_SESSION']
-
end
-
-
1
def self.browser
-
::Launchy::Argv.new( %w[ kfmclient openURL ] )
-
end
-
end
-
-
1
class Gnome < NixDesktopEnvironment
-
1
def self.is_current_desktop_environment?
-
ENV['GNOME_DESKTOP_SESSION_ID'] &&
-
Launchy::Application.find_executable( 'gnome-open' )
-
end
-
-
1
def self.browser
-
::Launchy::Argv.new( 'gnome-open' )
-
end
-
end
-
-
1
class Xfce < NixDesktopEnvironment
-
1
def self.is_current_desktop_environment?
-
if Launchy::Application.find_executable( 'xprop' ) then
-
%x[ xprop -root _DT_SAVE_MODE].include?("xfce")
-
else
-
false
-
end
-
end
-
-
1
def self.browser
-
::Launchy::Argv.new( %w[ exo-open --launch WebBrowser ] )
-
end
-
end
-
-
# Fall back environment as the last case
-
1
class Xdg < NixDesktopEnvironment
-
1
def self.is_current_desktop_environment?
-
Launchy::Application.find_executable( browser )
-
end
-
-
1
def self.browser
-
::Launchy::Argv.new( 'xdg-open' )
-
end
-
end
-
-
# The one that is found when all else fails. And this must be declared last
-
1
class NotFound < NixDesktopEnvironment
-
1
def self.is_current_desktop_environment?
-
true
-
end
-
-
1
def self.browser
-
::Launchy::Argv.new
-
end
-
end
-
-
end
-
end
-
-
1
module Launchy::Detect
-
1
class RubyEngine
-
1
class NotFoundError < Launchy::Error; end
-
-
1
extend ::Launchy::DescendantTracker
-
-
# Detect the current ruby engine.
-
#
-
# If the current ruby engine cannot be detected, the return
-
# RubyEngine::Unknown
-
1
def self.detect( ruby_engine = RubyEngine.new )
-
found = find_child( :is_current_engine?, ruby_engine.to_s )
-
return found if found
-
raise NotFoundError, "#{ruby_engine_error_message( ruby_engine )} #{Launchy.bug_report_message}"
-
end
-
-
1
def self.ruby_engine_error_message( ruby_engine )
-
msg = "Unkonwn RUBY_ENGINE "
-
if ruby_engine then
-
msg += " '#{ruby_engine}'."
-
elsif defined?( RUBY_ENGINE ) then
-
msg += " '#{RUBY_ENGINE}'."
-
else
-
msg = "RUBY_ENGINE not defined for #{RUBY_DESCRIPTION}."
-
end
-
return msg
-
end
-
-
1
def self.is_current_engine?( ruby_engine )
-
return ruby_engine == self.engine_name
-
end
-
-
1
def self.mri?() self == Mri; end
-
1
def self.jruby?() self == Jruby; end
-
1
def self.rbx?() self == Rbx; end
-
1
def self.macruby?() self == MacRuby; end
-
-
1
attr_reader :ruby_engine
-
1
alias to_s ruby_engine
-
1
def initialize( ruby_engine = Launchy.ruby_engine )
-
if ruby_engine then
-
@ruby_engine = ruby_engine
-
else
-
@ruby_engine = defined?( RUBY_ENGINE ) ? RUBY_ENGINE : "ruby"
-
end
-
end
-
-
-
#-------------------------------
-
# The list of known ruby engines
-
#-------------------------------
-
-
#
-
# This is the ruby engine if the RUBY_ENGINE constant is not defined
-
1
class Mri < RubyEngine
-
1
def self.engine_name() "ruby"; end
-
1
def self.is_current_engine?( ruby_engine )
-
if ruby_engine then
-
super( ruby_engine )
-
else
-
return true if not Launchy.ruby_engine and not defined?( RUBY_ENGINE )
-
end
-
end
-
end
-
-
1
class Jruby < RubyEngine
-
1
def self.engine_name() "jruby"; end
-
end
-
-
1
class Rbx < RubyEngine
-
1
def self.engine_name() "rbx"; end
-
end
-
-
1
class MacRuby < RubyEngine
-
1
def self.engine_name() "macruby"; end
-
end
-
end
-
end
-
1
require 'shellwords'
-
1
require 'stringio'
-
-
1
module Launchy::Detect
-
1
class Runner
-
1
class NotFoundError < Launchy::Error; end
-
-
1
extend ::Launchy::DescendantTracker
-
-
# Detect the current command runner
-
#
-
# This will return an instance of the Runner to be used to do the
-
# application launching.
-
#
-
# If a runner cannot be detected then raise Runner::NotFoundError
-
#
-
# The runner rules are, in order:
-
#
-
# 1) If you are on windows, you use the Windows Runner no matter what
-
# 2) If you are using the jruby engine, use the Jruby Runner. Unless rule
-
# (1) took effect
-
# 3) Use Forkable (barring rules (1) and (2))
-
1
def self.detect
-
host_os_family = Launchy::Detect::HostOsFamily.detect
-
ruby_engine = Launchy::Detect::RubyEngine.detect
-
-
return Windows.new if host_os_family.windows?
-
if ruby_engine.jruby? then
-
return Jruby.new
-
end
-
return Forkable.new
-
end
-
-
#
-
# cut it down to just the shell commands that will be passed to exec or
-
# posix_spawn. The cmd argument is split according to shell rules and the
-
# args are not escaped because they whole set is passed to system as *args
-
# and in that case system shell escaping rules are not done.
-
#
-
1
def shell_commands( cmd, args )
-
cmdline = [ cmd.to_s.shellsplit ]
-
cmdline << args.flatten.collect{ |a| a.to_s }
-
return commandline_normalize( cmdline )
-
end
-
-
1
def commandline_normalize( cmdline )
-
c = cmdline.flatten!
-
c = c.find_all { |a| (not a.nil?) and ( a.size > 0 ) }
-
Launchy.log "commandline_normalized => #{c.join(' ')}"
-
return c
-
end
-
-
1
def dry_run( cmd, *args )
-
shell_commands(cmd, args).join(" ")
-
end
-
-
1
def run( cmd, *args )
-
raise Launchy::CommandNotFoundError, "No command found to run with args '#{args.join(' ')}'. If this is unexpected, #{Launchy.bug_report_message}" unless cmd
-
if Launchy.dry_run? then
-
$stdout.puts dry_run( cmd, *args )
-
else
-
wet_run( cmd, *args )
-
end
-
end
-
-
-
#---------------------------------------
-
# The list of known runners
-
#---------------------------------------
-
-
1
class Windows < Runner
-
-
1
def all_args( cmd, *args )
-
args = [ 'cmd', '/c', *shell_commands( cmd, *args ) ]
-
Launchy.log "Windows: all_args => #{args.inspect}"
-
return args
-
end
-
-
1
def dry_run( cmd, *args )
-
all_args( cmd, *args ).join(" ")
-
end
-
-
# escape the reserved shell characters in windows command shell
-
# http://technet.microsoft.com/en-us/library/cc723564.aspx
-
#
-
# Also make sure that the item after 'start' is guaranteed to be quoted.
-
# https://github.com/copiousfreetime/launchy/issues/62
-
1
def shell_commands( cmd, *args )
-
parts = cmd.shellsplit
-
-
if start_idx = parts.index('start') then
-
title_idx = start_idx + 1
-
title = parts[title_idx]
-
title = title.sub(/^/,'"') unless title[0] == '"'
-
title = title.sub(/$/,'"') unless title[-1] == '"'
-
parts[title_idx] = title
-
end
-
-
cmdline = [ parts ]
-
cmdline << args.flatten.collect { |a| a.to_s.gsub(/([&|()<>^])/, "^\\1") }
-
return commandline_normalize( cmdline )
-
end
-
-
1
def wet_run( cmd, *args )
-
system( *all_args( cmd, *args ) )
-
end
-
end
-
-
1
class Jruby < Runner
-
1
def wet_run( cmd, *args )
-
require 'spoon'
-
Spoon.spawnp( *shell_commands( cmd, *args ) )
-
end
-
end
-
-
1
class Forkable < Runner
-
1
attr_reader :child_pid
-
-
1
def wet_run( cmd, *args )
-
@child_pid = fork do
-
close_file_descriptors unless Launchy.debug?
-
Launchy.log("wet_run: before exec in child process")
-
exec_or_raise( cmd, *args )
-
exit!
-
end
-
Process.detach( @child_pid )
-
end
-
-
1
private
-
-
# attaching to a StringIO instead of reopening so we don't loose the
-
# STDERR, needed for exec_or_raise.
-
1
def close_file_descriptors
-
$stdin.reopen( "/dev/null")
-
-
@saved_stdout = $stdout
-
@saved_stderr = $stderr
-
-
$stdout = StringIO.new
-
$stderr = StringIO.new
-
end
-
-
1
def exec_or_raise( cmd, *args )
-
exec( *shell_commands( cmd, *args ))
-
rescue Exception => e
-
$stderr = @saved_stderr
-
$stdout = @saved_stdout
-
raise e
-
end
-
end
-
end
-
end
-
1
module Launchy
-
1
class Error < ::StandardError; end
-
1
class ApplicationNotFoundError < Error; end
-
1
class CommandNotFoundError < Error; end
-
1
class ArgumentError < Error; end
-
end
-
1
module Launchy
-
1
VERSION = "2.4.3"
-
-
1
module Version
-
-
1
MAJOR = Integer(VERSION.split('.')[0])
-
1
MINOR = Integer(VERSION.split('.')[1])
-
1
PATCH = Integer(VERSION.split('.')[2])
-
-
1
def self.to_a
-
[MAJOR, MINOR, PATCH]
-
end
-
-
1
def self.to_s
-
VERSION
-
end
-
end
-
end
-
1
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__))) unless $LOAD_PATH.include?(File.expand_path(File.dirname(__FILE__)))
-
-
1
require 'nokogiri'
-
-
1
require 'loofah/metahelpers'
-
1
require 'loofah/elements'
-
-
1
require 'loofah/html5/whitelist'
-
1
require 'loofah/html5/scrub'
-
-
1
require 'loofah/scrubber'
-
1
require 'loofah/scrubbers'
-
-
1
require 'loofah/instance_methods'
-
1
require 'loofah/xml/document'
-
1
require 'loofah/xml/document_fragment'
-
1
require 'loofah/html/document'
-
1
require 'loofah/html/document_fragment'
-
-
# == Strings and IO Objects as Input
-
#
-
# Loofah.document and Loofah.fragment accept any IO object in addition
-
# to accepting a string. That IO object could be a file, or a socket,
-
# or a StringIO, or anything that responds to +read+ and
-
# +close+. Which makes it particularly easy to sanitize mass
-
# quantities of docs.
-
#
-
1
module Loofah
-
# The version of Loofah you are using
-
1
VERSION = '2.0.3'
-
-
1
class << self
-
# Shortcut for Loofah::HTML::Document.parse
-
# This method accepts the same parameters as Nokogiri::HTML::Document.parse
-
1
def document(*args, &block)
-
Loofah::HTML::Document.parse(*args, &block)
-
end
-
-
# Shortcut for Loofah::HTML::DocumentFragment.parse
-
# This method accepts the same parameters as Nokogiri::HTML::DocumentFragment.parse
-
1
def fragment(*args, &block)
-
Loofah::HTML::DocumentFragment.parse(*args, &block)
-
end
-
-
# Shortcut for Loofah.fragment(string_or_io).scrub!(method)
-
1
def scrub_fragment(string_or_io, method)
-
Loofah.fragment(string_or_io).scrub!(method)
-
end
-
-
# Shortcut for Loofah.document(string_or_io).scrub!(method)
-
1
def scrub_document(string_or_io, method)
-
Loofah.document(string_or_io).scrub!(method)
-
end
-
-
# Shortcut for Loofah::XML::Document.parse
-
# This method accepts the same parameters as Nokogiri::XML::Document.parse
-
1
def xml_document(*args, &block)
-
Loofah::XML::Document.parse(*args, &block)
-
end
-
-
# Shortcut for Loofah::XML::DocumentFragment.parse
-
# This method accepts the same parameters as Nokogiri::XML::DocumentFragment.parse
-
1
def xml_fragment(*args, &block)
-
Loofah::XML::DocumentFragment.parse(*args, &block)
-
end
-
-
# Shortcut for Loofah.xml_fragment(string_or_io).scrub!(method)
-
1
def scrub_xml_fragment(string_or_io, method)
-
Loofah.xml_fragment(string_or_io).scrub!(method)
-
end
-
-
# Shortcut for Loofah.xml_document(string_or_io).scrub!(method)
-
1
def scrub_xml_document(string_or_io, method)
-
Loofah.xml_document(string_or_io).scrub!(method)
-
end
-
-
# A helper to remove extraneous whitespace from text-ified HTML
-
1
def remove_extraneous_whitespace(string)
-
string.gsub(/\n\s*\n\s*\n/,"\n\n")
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Loofah
-
1
module Elements
-
# Block elements in HTML4
-
1
STRICT_BLOCK_LEVEL = Set.new %w[address blockquote center dir div dl
-
fieldset form h1 h2 h3 h4 h5 h6 hr isindex menu noframes
-
noscript ol p pre table ul]
-
-
# The following elements may also be considered block-level elements since they may contain block-level elements
-
1
LOOSE_BLOCK_LEVEL = Set.new %w[dd dt frameset li tbody td tfoot th thead tr]
-
-
1
BLOCK_LEVEL = STRICT_BLOCK_LEVEL + LOOSE_BLOCK_LEVEL
-
end
-
-
1
::Loofah::MetaHelpers.add_downcased_set_members_to_all_set_constants ::Loofah::Elements
-
end
-
1
module Loofah
-
1
module HTML # :nodoc:
-
#
-
# Subclass of Nokogiri::HTML::Document.
-
#
-
# See Loofah::ScrubBehavior and Loofah::TextBehavior for additional methods.
-
#
-
1
class Document < Nokogiri::HTML::Document
-
1
include Loofah::ScrubBehavior::Node
-
1
include Loofah::DocumentDecorator
-
1
include Loofah::TextBehavior
-
-
1
def serialize_root
-
at_xpath("/html/body")
-
end
-
end
-
end
-
end
-
1
module Loofah
-
1
module HTML # :nodoc:
-
#
-
# Subclass of Nokogiri::HTML::DocumentFragment.
-
#
-
# See Loofah::ScrubBehavior and Loofah::TextBehavior for additional methods.
-
#
-
1
class DocumentFragment < Nokogiri::HTML::DocumentFragment
-
1
include Loofah::TextBehavior
-
-
1
class << self
-
#
-
# Overridden Nokogiri::HTML::DocumentFragment
-
# constructor. Applications should use Loofah.fragment to
-
# parse a fragment.
-
#
-
1
def parse tags, encoding = nil
-
doc = Loofah::HTML::Document.new
-
-
encoding ||= tags.respond_to?(:encoding) ? tags.encoding.name : 'UTF-8'
-
doc.encoding = encoding
-
-
new(doc, tags)
-
end
-
end
-
-
#
-
# Returns the HTML markup contained by the fragment
-
#
-
1
def to_s
-
serialize_root.children.to_s
-
end
-
1
alias :serialize :to_s
-
-
1
def serialize_root
-
at_xpath("./body") || self
-
end
-
end
-
end
-
end
-
#encoding: US-ASCII
-
-
1
require 'cgi'
-
-
1
module Loofah
-
1
module HTML5 # :nodoc:
-
1
module Scrub
-
-
1
CONTROL_CHARACTERS = /[`\u0000-\u0020\u007f\u0080-\u0101]/
-
-
1
class << self
-
-
1
def allowed_element? element_name
-
::Loofah::HTML5::WhiteList::ALLOWED_ELEMENTS_WITH_LIBXML2.include? element_name
-
end
-
-
# alternative implementation of the html5lib attribute scrubbing algorithm
-
1
def scrub_attributes node
-
node.attribute_nodes.each do |attr_node|
-
attr_name = if attr_node.namespace
-
"#{attr_node.namespace.prefix}:#{attr_node.node_name}"
-
else
-
attr_node.node_name
-
end
-
-
if attr_name =~ /\Adata-[\w-]+\z/
-
next
-
end
-
-
unless WhiteList::ALLOWED_ATTRIBUTES.include?(attr_name)
-
attr_node.remove
-
next
-
end
-
-
if WhiteList::ATTR_VAL_IS_URI.include?(attr_name)
-
# this block lifted nearly verbatim from HTML5 sanitization
-
val_unescaped = CGI.unescapeHTML(attr_node.value).gsub(CONTROL_CHARACTERS,'').downcase
-
if val_unescaped =~ /^[a-z0-9][-+.a-z0-9]*:/ && ! WhiteList::ALLOWED_PROTOCOLS.include?(val_unescaped.split(WhiteList::PROTOCOL_SEPARATOR)[0])
-
attr_node.remove
-
next
-
end
-
end
-
if WhiteList::SVG_ATTR_VAL_ALLOWS_REF.include?(attr_name)
-
attr_node.value = attr_node.value.gsub(/url\s*\(\s*[^#\s][^)]+?\)/m, ' ') if attr_node.value
-
end
-
if WhiteList::SVG_ALLOW_LOCAL_HREF.include?(node.name) && attr_name == 'xlink:href' && attr_node.value =~ /^\s*[^#\s].*/m
-
attr_node.remove
-
next
-
end
-
end
-
-
scrub_css_attribute node
-
-
node.attribute_nodes.each do |attr_node|
-
node.remove_attribute(attr_node.name) if attr_node.value !~ /[^[:space:]]/
-
end
-
end
-
-
1
def scrub_css_attribute node
-
style = node.attributes['style']
-
style.value = scrub_css(style.value) if style
-
end
-
-
# lifted nearly verbatim from html5lib
-
1
def scrub_css style
-
# disallow urls
-
style = style.to_s.gsub(/url\s*\(\s*[^\s)]+?\s*\)\s*/, ' ')
-
-
# gauntlet
-
return '' unless style =~ /\A([:,;#%.\sa-zA-Z0-9!]|\w-\w|\'[\s\w]+\'|\"[\s\w]+\"|\([\d,\s]+\))*\z/
-
return '' unless style =~ /\A\s*([-\w]+\s*:[^:;]*(;\s*|$))*\z/
-
-
clean = []
-
style.scan(/([-\w]+)\s*:\s*([^:;]*)/) do |prop, val|
-
next if val.empty?
-
prop.downcase!
-
if WhiteList::ALLOWED_CSS_PROPERTIES.include?(prop)
-
clean << "#{prop}: #{val};"
-
elsif WhiteList::SHORTHAND_CSS_PROPERTIES.include?(prop.split('-')[0])
-
clean << "#{prop}: #{val};" unless val.split().any? do |keyword|
-
!WhiteList::ALLOWED_CSS_KEYWORDS.include?(keyword) &&
-
keyword !~ /\A(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|-?\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)\z/
-
end
-
elsif WhiteList::ALLOWED_SVG_PROPERTIES.include?(prop)
-
clean << "#{prop}: #{val};"
-
end
-
end
-
-
style = clean.join(' ')
-
end
-
-
end
-
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Loofah
-
1
module HTML5 # :nodoc:
-
#
-
# HTML whitelist lifted from HTML5lib sanitizer code:
-
#
-
# http://code.google.com/p/html5lib/
-
#
-
# <html5_license>
-
#
-
# Copyright (c) 2006-2008 The Authors
-
#
-
# Contributors:
-
# James Graham - jg307@cam.ac.uk
-
# Anne van Kesteren - annevankesteren@gmail.com
-
# Lachlan Hunt - lachlan.hunt@lachy.id.au
-
# Matt McDonald - kanashii@kanashii.ca
-
# Sam Ruby - rubys@intertwingly.net
-
# Ian Hickson (Google) - ian@hixie.ch
-
# Thomas Broyer - t.broyer@ltgt.net
-
# Jacques Distler - distler@golem.ph.utexas.edu
-
# Henri Sivonen - hsivonen@iki.fi
-
# The Mozilla Foundation (contributions from Henri Sivonen since 2008)
-
#
-
# Permission is hereby granted, free of charge, to any person
-
# obtaining a copy of this software and associated documentation
-
# files (the "Software"), to deal in the Software without
-
# restriction, including without limitation the rights to use, copy,
-
# modify, merge, publish, distribute, sublicense, and/or sell copies
-
# of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-
# DEALINGS IN THE SOFTWARE.
-
#
-
# </html5_license>
-
1
module WhiteList
-
-
1
ACCEPTABLE_ELEMENTS = Set.new %w[a abbr acronym address area
-
article aside audio b bdi bdo big blockquote br button canvas
-
caption center cite code col colgroup command datalist dd del
-
details dfn dir div dl dt em fieldset figcaption figure footer
-
font form h1 h2 h3 h4 h5 h6 header hr i img input ins kbd label
-
legend li map mark menu meter nav ol output optgroup option p
-
pre q s samp section select small span strike strong sub summary
-
sup table tbody td textarea tfoot th thead time tr tt u ul var
-
video]
-
-
1
MATHML_ELEMENTS = Set.new %w[annotation annotation-xml maction math merror mfrac
-
mfenced mi mmultiscripts mn mo mover mpadded mphantom mprescripts mroot mrow
-
mspace msqrt mstyle msub msubsup msup mtable mtd mtext mtr munder
-
munderover none semantics]
-
-
1
SVG_ELEMENTS = Set.new %w[a animate animateColor animateMotion animateTransform
-
circle clipPath defs desc ellipse feGaussianBlur filter font-face
-
font-face-name font-face-src foreignObject
-
g glyph hkern linearGradient line marker mask metadata missing-glyph
-
mpath path polygon polyline radialGradient rect set stop svg switch
-
text textPath title tspan use]
-
-
1
ACCEPTABLE_ATTRIBUTES = Set.new %w[abbr accept accept-charset accesskey action
-
align alt axis border cellpadding cellspacing char charoff charset
-
checked cite class clear cols colspan color compact coords datetime
-
dir disabled enctype for frame headers height href hreflang hspace id
-
ismap label lang longdesc loop loopcount loopend loopstart
-
maxlength media method multiple name nohref
-
noshade nowrap poster preload prompt readonly rel rev rows rowspan rules scope
-
selected shape size span src start style summary tabindex target title
-
type usemap valign value vspace width xml:lang]
-
-
1
MATHML_ATTRIBUTES = Set.new %w[actiontype align close
-
columnalign columnlines columnspacing columnspan depth display
-
displaystyle encoding equalcolumns equalrows fence fontstyle fontweight
-
frame height linethickness lspace mathbackground mathcolor mathvariant
-
maxsize minsize open other rowalign rowlines
-
rowspacing rowspan rspace scriptlevel selection separator separators
-
stretchy width xlink:href xlink:show xlink:type xmlns xmlns:xlink]
-
-
1
SVG_ATTRIBUTES = Set.new %w[accent-height accumulate additive alphabetic
-
arabic-form ascent attributeName attributeType baseProfile bbox begin
-
by calcMode cap-height class clip-path clip-rule color
-
color-interpolation-filters color-rendering content cx cy d dx
-
dy descent display dur end fill fill-opacity fill-rule
-
filterRes filterUnits font-family
-
font-size font-stretch font-style font-variant font-weight from fx fy g1
-
g2 glyph-name gradientUnits hanging height horiz-adv-x horiz-origin-x id
-
ideographic k keyPoints keySplines keyTimes lang marker-end
-
marker-mid marker-start markerHeight markerUnits markerWidth
-
maskContentUnits maskUnits mathematical max method min name offset opacity orient origin
-
overline-position overline-thickness panose-1 path pathLength
-
patternContentUnits patternTransform patternUnits points
-
preserveAspectRatio primitiveUnits r refX refY repeatCount repeatDur
-
requiredExtensions requiredFeatures restart rotate rx ry slope spacing
-
startOffset stdDeviation stemh
-
stemv stop-color stop-opacity strikethrough-position
-
strikethrough-thickness stroke stroke-dasharray stroke-dashoffset
-
stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity
-
stroke-width systemLanguage target text-anchor to transform type u1
-
u2 underline-position underline-thickness unicode unicode-range
-
units-per-em values version viewBox visibility width widths x
-
x-height x1 x2 xlink:actuate xlink:arcrole xlink:href xlink:role
-
xlink:show xlink:title xlink:type xml:base xml:lang xml:space xmlns
-
xmlns:xlink y y1 y2 zoomAndPan]
-
-
1
ATTR_VAL_IS_URI = Set.new %w[href src cite action longdesc xlink:href xml:base poster preload]
-
-
1
SVG_ATTR_VAL_ALLOWS_REF = Set.new %w[clip-path color-profile cursor fill
-
filter marker marker-start marker-mid marker-end mask stroke]
-
-
1
SVG_ALLOW_LOCAL_HREF = Set.new %w[altGlyph animate animateColor animateMotion
-
animateTransform cursor feImage filter linearGradient pattern
-
radialGradient textpath tref set use]
-
-
1
ACCEPTABLE_CSS_PROPERTIES = Set.new %w[azimuth background-color
-
border-bottom-color border-collapse border-color border-left-color
-
border-right-color border-top-color clear color cursor direction
-
display elevation float font font-family font-size font-style
-
font-variant font-weight height letter-spacing line-height overflow
-
pause pause-after pause-before pitch pitch-range richness speak
-
speak-header speak-numeral speak-punctuation speech-rate stress
-
text-align text-decoration text-indent unicode-bidi vertical-align
-
voice-family volume white-space width]
-
-
1
ACCEPTABLE_CSS_KEYWORDS = Set.new %w[auto aqua black block blue bold both bottom
-
brown center collapse dashed dotted fuchsia gray green !important
-
italic left lime maroon medium none navy normal nowrap olive pointer
-
purple red right solid silver teal top transparent underline white
-
yellow]
-
-
1
SHORTHAND_CSS_PROPERTIES = Set.new %w[background border margin padding]
-
-
1
ACCEPTABLE_SVG_PROPERTIES = Set.new %w[fill fill-opacity fill-rule stroke
-
stroke-width stroke-linecap stroke-linejoin stroke-opacity]
-
-
1
PROTOCOL_SEPARATOR = /:|(�*58)|(p)|(�*3a)|(%|%)3A/i
-
-
1
ACCEPTABLE_PROTOCOLS = Set.new %w[ed2k ftp http https irc mailto news gopher nntp
-
telnet webcal xmpp callto feed urn aim rsync tag ssh sftp rtsp afs]
-
-
# subclasses may define their own versions of these constants
-
1
ALLOWED_ELEMENTS = ACCEPTABLE_ELEMENTS + MATHML_ELEMENTS + SVG_ELEMENTS
-
1
ALLOWED_ATTRIBUTES = ACCEPTABLE_ATTRIBUTES + MATHML_ATTRIBUTES + SVG_ATTRIBUTES
-
1
ALLOWED_CSS_PROPERTIES = ACCEPTABLE_CSS_PROPERTIES
-
1
ALLOWED_CSS_KEYWORDS = ACCEPTABLE_CSS_KEYWORDS
-
1
ALLOWED_SVG_PROPERTIES = ACCEPTABLE_SVG_PROPERTIES
-
1
ALLOWED_PROTOCOLS = ACCEPTABLE_PROTOCOLS
-
-
1
VOID_ELEMENTS = Set.new %w[
-
base
-
link
-
meta
-
hr
-
br
-
img
-
embed
-
param
-
area
-
col
-
input
-
]
-
-
# additional tags we should consider safe since we have libxml2 fixing up our documents.
-
1
TAGS_SAFE_WITH_LIBXML2 = Set.new %w[html head body]
-
1
ALLOWED_ELEMENTS_WITH_LIBXML2 = ALLOWED_ELEMENTS + TAGS_SAFE_WITH_LIBXML2
-
end
-
-
1
::Loofah::MetaHelpers.add_downcased_set_members_to_all_set_constants ::Loofah::HTML5::WhiteList
-
end
-
end
-
1
module Loofah
-
#
-
# Mixes +scrub!+ into Document, DocumentFragment, Node and NodeSet.
-
#
-
# Traverse the document or fragment, invoking the +scrubber+ on
-
# each node.
-
#
-
# +scrubber+ must either be one of the symbols representing the
-
# built-in scrubbers (see Scrubbers), or a Scrubber instance.
-
#
-
# span2div = Loofah::Scrubber.new do |node|
-
# node.name = "div" if node.name == "span"
-
# end
-
# Loofah.fragment("<span>foo</span><p>bar</p>").scrub!(span2div).to_s
-
# # => "<div>foo</div><p>bar</p>"
-
#
-
# or
-
#
-
# unsafe_html = "ohai! <div>div is safe</div> <script>but script is not</script>"
-
# Loofah.fragment(unsafe_html).scrub!(:strip).to_s
-
# # => "ohai! <div>div is safe</div> "
-
#
-
# Note that this method is called implicitly from
-
# Loofah.scrub_fragment and Loofah.scrub_document.
-
#
-
# Please see Scrubber for more information on implementation and traversal, and
-
# README.rdoc for more example usage.
-
#
-
1
module ScrubBehavior
-
1
module Node # :nodoc:
-
1
def scrub!(scrubber)
-
#
-
# yes. this should be three separate methods. but nokogiri
-
# decorates (or not) based on whether the module name has
-
# already been included. and since documents get decorated
-
# just like their constituent nodes, we need to jam all the
-
# logic into a single module.
-
#
-
scrubber = ScrubBehavior.resolve_scrubber(scrubber)
-
case self
-
when Nokogiri::XML::Document
-
scrubber.traverse(root) if root
-
when Nokogiri::XML::DocumentFragment
-
children.scrub! scrubber
-
else
-
scrubber.traverse(self)
-
end
-
self
-
end
-
end
-
-
1
module NodeSet # :nodoc:
-
1
def scrub!(scrubber)
-
each { |node| node.scrub!(scrubber) }
-
self
-
end
-
end
-
-
1
def ScrubBehavior.resolve_scrubber(scrubber) # :nodoc:
-
scrubber = Scrubbers::MAP[scrubber].new if Scrubbers::MAP[scrubber]
-
unless scrubber.is_a?(Loofah::Scrubber)
-
raise Loofah::ScrubberNotFound, "not a Scrubber or a scrubber name: #{scrubber.inspect}"
-
end
-
scrubber
-
end
-
end
-
-
#
-
# Overrides +text+ in HTML::Document and HTML::DocumentFragment,
-
# and mixes in +to_text+.
-
#
-
1
module TextBehavior
-
#
-
# Returns a plain-text version of the markup contained by the document,
-
# with HTML entities encoded.
-
#
-
# This method is significantly faster than #to_text, but isn't
-
# clever about whitespace around block elements.
-
#
-
# Loofah.document("<h1>Title</h1><div>Content</div>").text
-
# # => "TitleContent"
-
#
-
# By default, the returned text will have HTML entities
-
# escaped. If you want unescaped entities, and you understand
-
# that the result is unsafe to render in a browser, then you
-
# can pass an argument as shown:
-
#
-
# frag = Loofah.fragment("<script>alert('EVIL');</script>")
-
# # ok for browser:
-
# frag.text # => "<script>alert('EVIL');</script>"
-
# # decidedly not ok for browser:
-
# frag.text(:encode_special_chars => false) # => "<script>alert('EVIL');</script>"
-
#
-
1
def text(options={})
-
result = serialize_root.children.inner_text rescue ""
-
if options[:encode_special_chars] == false
-
result # possibly dangerous if rendered in a browser
-
else
-
encode_special_chars result
-
end
-
end
-
1
alias :inner_text :text
-
1
alias :to_str :text
-
-
#
-
# Returns a plain-text version of the markup contained by the
-
# fragment, with HTML entities encoded.
-
#
-
# This method is slower than #to_text, but is clever about
-
# whitespace around block elements.
-
#
-
# Loofah.document("<h1>Title</h1><div>Content</div>").to_text
-
# # => "\nTitle\n\nContent\n"
-
#
-
1
def to_text(options={})
-
Loofah.remove_extraneous_whitespace self.dup.scrub!(:newline_block_elements).text(options)
-
end
-
end
-
-
1
module DocumentDecorator # :nodoc:
-
1
def initialize(*args, &block)
-
super
-
self.decorators(Nokogiri::XML::Node) << ScrubBehavior::Node
-
self.decorators(Nokogiri::XML::NodeSet) << ScrubBehavior::NodeSet
-
end
-
end
-
end
-
1
module Loofah
-
1
module MetaHelpers # :nodoc:
-
1
def self.add_downcased_set_members_to_all_set_constants mojule
-
2
mojule.constants.each do |constant_sym|
-
27
constant = mojule.const_get constant_sym
-
27
next unless Set === constant
-
26
constant.dup.each do |member|
-
1373
constant.add member.downcase
-
end
-
end
-
end
-
end
-
end
-
1
module Loofah
-
#
-
# A RuntimeError raised when Loofah could not find an appropriate scrubber.
-
#
-
1
class ScrubberNotFound < RuntimeError ; end
-
-
#
-
# A Scrubber wraps up a block (or method) that is run on an HTML node (element):
-
#
-
# # change all <span> tags to <div> tags
-
# span2div = Loofah::Scrubber.new do |node|
-
# node.name = "div" if node.name == "span"
-
# end
-
#
-
# Alternatively, this scrubber could have been implemented as:
-
#
-
# class Span2Div < Loofah::Scrubber
-
# def scrub(node)
-
# node.name = "div" if node.name == "span"
-
# end
-
# end
-
# span2div = Span2Div.new
-
#
-
# This can then be run on a document:
-
#
-
# Loofah.fragment("<span>foo</span><p>bar</p>").scrub!(span2div).to_s
-
# # => "<div>foo</div><p>bar</p>"
-
#
-
# Scrubbers can be run on a document in either a top-down traversal (the
-
# default) or bottom-up. Top-down scrubbers can optionally return
-
# Scrubber::STOP to terminate the traversal of a subtree.
-
#
-
1
class Scrubber
-
-
# Top-down Scrubbers may return CONTINUE to indicate that the subtree should be traversed.
-
1
CONTINUE = Object.new.freeze
-
-
# Top-down Scrubbers may return STOP to indicate that the subtree should not be traversed.
-
1
STOP = Object.new.freeze
-
-
# When a scrubber is initialized, the :direction may be specified
-
# as :top_down (the default) or :bottom_up.
-
1
attr_reader :direction
-
-
# When a scrubber is initialized, the optional block is saved as
-
# :block. Note that, if no block is passed, then the +scrub+
-
# method is assumed to have been implemented.
-
1
attr_reader :block
-
-
#
-
# Options may include
-
# :direction => :top_down (the default)
-
# or
-
# :direction => :bottom_up
-
#
-
# For top_down traversals, if the block returns
-
# Loofah::Scrubber::STOP, then the traversal will be terminated
-
# for the current node's subtree.
-
#
-
# Alternatively, a Scrubber may inherit from Loofah::Scrubber,
-
# and implement +scrub+, which is slightly faster than using a
-
# block.
-
#
-
1
def initialize(options = {}, &block)
-
direction = options[:direction] || :top_down
-
unless [:top_down, :bottom_up].include?(direction)
-
raise ArgumentError, "direction #{direction} must be one of :top_down or :bottom_up"
-
end
-
@direction, @block = direction, block
-
end
-
-
#
-
# Calling +traverse+ will cause the document to be traversed by
-
# either the lambda passed to the initializer or the +scrub+
-
# method, in the direction specified at +new+ time.
-
#
-
1
def traverse(node)
-
direction == :bottom_up ? traverse_conditionally_bottom_up(node) : traverse_conditionally_top_down(node)
-
end
-
-
#
-
# When +new+ is not passed a block, the class may implement
-
# +scrub+, which will be called for each document node.
-
#
-
1
def scrub(node)
-
raise ScrubberNotFound, "No scrub method has been defined on #{self.class.to_s}"
-
end
-
-
1
private
-
-
1
def html5lib_sanitize(node)
-
case node.type
-
when Nokogiri::XML::Node::ELEMENT_NODE
-
if HTML5::Scrub.allowed_element? node.name
-
HTML5::Scrub.scrub_attributes node
-
return Scrubber::CONTINUE
-
end
-
when Nokogiri::XML::Node::TEXT_NODE, Nokogiri::XML::Node::CDATA_SECTION_NODE
-
return Scrubber::CONTINUE
-
end
-
Scrubber::STOP
-
end
-
-
1
def traverse_conditionally_top_down(node)
-
if block
-
return if block.call(node) == STOP
-
else
-
return if scrub(node) == STOP
-
end
-
node.children.each {|j| traverse_conditionally_top_down(j)}
-
end
-
-
1
def traverse_conditionally_bottom_up(node)
-
node.children.each {|j| traverse_conditionally_bottom_up(j)}
-
if block
-
block.call(node)
-
else
-
scrub(node)
-
end
-
end
-
end
-
end
-
1
module Loofah
-
#
-
# Loofah provides some built-in scrubbers for sanitizing with
-
# HTML5lib's whitelist and for accomplishing some common
-
# transformation tasks.
-
#
-
#
-
# === Loofah::Scrubbers::Strip / scrub!(:strip)
-
#
-
# +:strip+ removes unknown/unsafe tags, but leaves behind the pristine contents:
-
#
-
# unsafe_html = "ohai! <div>div is safe</div> <foo>but foo is <b>not</b></foo>"
-
# Loofah.fragment(unsafe_html).scrub!(:strip)
-
# => "ohai! <div>div is safe</div> but foo is <b>not</b>"
-
#
-
#
-
# === Loofah::Scrubbers::Prune / scrub!(:prune)
-
#
-
# +:prune+ removes unknown/unsafe tags and their contents (including their subtrees):
-
#
-
# unsafe_html = "ohai! <div>div is safe</div> <foo>but foo is <b>not</b></foo>"
-
# Loofah.fragment(unsafe_html).scrub!(:prune)
-
# => "ohai! <div>div is safe</div> "
-
#
-
#
-
# === Loofah::Scrubbers::Escape / scrub!(:escape)
-
#
-
# +:escape+ performs HTML entity escaping on the unknown/unsafe tags:
-
#
-
# unsafe_html = "ohai! <div>div is safe</div> <foo>but foo is <b>not</b></foo>"
-
# Loofah.fragment(unsafe_html).scrub!(:escape)
-
# => "ohai! <div>div is safe</div> <foo>but foo is <b>not</b></foo>"
-
#
-
#
-
# === Loofah::Scrubbers::Whitewash / scrub!(:whitewash)
-
#
-
# +:whitewash+ removes all comments, styling and attributes in
-
# addition to doing markup-fixer-uppery and pruning unsafe tags. I
-
# like to call this "whitewashing", since it's like putting a new
-
# layer of paint on top of the HTML input to make it look nice.
-
#
-
# messy_markup = "ohai! <div id='foo' class='bar' style='margin: 10px'>div with attributes</div>"
-
# Loofah.fragment(messy_markup).scrub!(:whitewash)
-
# => "ohai! <div>div with attributes</div>"
-
#
-
# One use case for this scrubber is to clean up HTML that was
-
# cut-and-pasted from Microsoft Word into a WYSIWYG editor or a
-
# rich text editor. Microsoft's software is famous for injecting
-
# all kinds of cruft into its HTML output. Who needs that crap?
-
# Certainly not me.
-
#
-
#
-
# === Loofah::Scrubbers::NoFollow / scrub!(:nofollow)
-
#
-
# +:nofollow+ adds a rel="nofollow" attribute to all links
-
#
-
# link_farmers_markup = "ohai! <a href='http://www.myswarmysite.com/'>I like your blog post</a>"
-
# Loofah.fragment(link_farmers_markup).scrub!(:nofollow)
-
# => "ohai! <a href='http://www.myswarmysite.com/' rel="nofollow">I like your blog post</a>"
-
#
-
#
-
# === Loofah::Scrubbers::Unprintable / scrub!(:unprintable)
-
#
-
# +:unprintable+ removes unprintable Unicode characters.
-
#
-
# markup = "<p>Some text with an unprintable character at the end\u2028</p>"
-
# Loofah.fragment(markup).scrub!(:unprintable)
-
# => "<p>Some text with an unprintable character at the end</p>"
-
#
-
# You may not be able to see the unprintable character in the above example, but there is a
-
# U+2028 character right before the closing </p> tag. These characters can cause issues if
-
# the content is ever parsed by JavaScript - more information here:
-
#
-
# http://timelessrepo.com/json-isnt-a-javascript-subset
-
#
-
1
module Scrubbers
-
#
-
# === scrub!(:strip)
-
#
-
# +:strip+ removes unknown/unsafe tags, but leaves behind the pristine contents:
-
#
-
# unsafe_html = "ohai! <div>div is safe</div> <foo>but foo is <b>not</b></foo>"
-
# Loofah.fragment(unsafe_html).scrub!(:strip)
-
# => "ohai! <div>div is safe</div> but foo is <b>not</b>"
-
#
-
1
class Strip < Scrubber
-
1
def initialize
-
@direction = :bottom_up
-
end
-
-
1
def scrub(node)
-
return CONTINUE if html5lib_sanitize(node) == CONTINUE
-
node.before node.children
-
node.remove
-
end
-
end
-
-
#
-
# === scrub!(:prune)
-
#
-
# +:prune+ removes unknown/unsafe tags and their contents (including their subtrees):
-
#
-
# unsafe_html = "ohai! <div>div is safe</div> <foo>but foo is <b>not</b></foo>"
-
# Loofah.fragment(unsafe_html).scrub!(:prune)
-
# => "ohai! <div>div is safe</div> "
-
#
-
1
class Prune < Scrubber
-
1
def initialize
-
@direction = :top_down
-
end
-
-
1
def scrub(node)
-
return CONTINUE if html5lib_sanitize(node) == CONTINUE
-
node.remove
-
return STOP
-
end
-
end
-
-
#
-
# === scrub!(:escape)
-
#
-
# +:escape+ performs HTML entity escaping on the unknown/unsafe tags:
-
#
-
# unsafe_html = "ohai! <div>div is safe</div> <foo>but foo is <b>not</b></foo>"
-
# Loofah.fragment(unsafe_html).scrub!(:escape)
-
# => "ohai! <div>div is safe</div> <foo>but foo is <b>not</b></foo>"
-
#
-
1
class Escape < Scrubber
-
1
def initialize
-
@direction = :top_down
-
end
-
-
1
def scrub(node)
-
return CONTINUE if html5lib_sanitize(node) == CONTINUE
-
node.add_next_sibling Nokogiri::XML::Text.new(node.to_s, node.document)
-
node.remove
-
return STOP
-
end
-
end
-
-
#
-
# === scrub!(:whitewash)
-
#
-
# +:whitewash+ removes all comments, styling and attributes in
-
# addition to doing markup-fixer-uppery and pruning unsafe tags. I
-
# like to call this "whitewashing", since it's like putting a new
-
# layer of paint on top of the HTML input to make it look nice.
-
#
-
# messy_markup = "ohai! <div id='foo' class='bar' style='margin: 10px'>div with attributes</div>"
-
# Loofah.fragment(messy_markup).scrub!(:whitewash)
-
# => "ohai! <div>div with attributes</div>"
-
#
-
# One use case for this scrubber is to clean up HTML that was
-
# cut-and-pasted from Microsoft Word into a WYSIWYG editor or a
-
# rich text editor. Microsoft's software is famous for injecting
-
# all kinds of cruft into its HTML output. Who needs that crap?
-
# Certainly not me.
-
#
-
1
class Whitewash < Scrubber
-
1
def initialize
-
@direction = :top_down
-
end
-
-
1
def scrub(node)
-
case node.type
-
when Nokogiri::XML::Node::ELEMENT_NODE
-
if HTML5::Scrub.allowed_element? node.name
-
node.attributes.each { |attr| node.remove_attribute(attr.first) }
-
return CONTINUE if node.namespaces.empty?
-
end
-
when Nokogiri::XML::Node::TEXT_NODE, Nokogiri::XML::Node::CDATA_SECTION_NODE
-
return CONTINUE
-
end
-
node.remove
-
STOP
-
end
-
end
-
-
#
-
# === scrub!(:nofollow)
-
#
-
# +:nofollow+ adds a rel="nofollow" attribute to all links
-
#
-
# link_farmers_markup = "ohai! <a href='http://www.myswarmysite.com/'>I like your blog post</a>"
-
# Loofah.fragment(link_farmers_markup).scrub!(:nofollow)
-
# => "ohai! <a href='http://www.myswarmysite.com/' rel="nofollow">I like your blog post</a>"
-
#
-
1
class NoFollow < Scrubber
-
1
def initialize
-
@direction = :top_down
-
end
-
-
1
def scrub(node)
-
return CONTINUE unless (node.type == Nokogiri::XML::Node::ELEMENT_NODE) && (node.name == 'a')
-
node.set_attribute('rel', 'nofollow')
-
return STOP
-
end
-
end
-
-
# This class probably isn't useful publicly, but is used for #to_text's current implemention
-
1
class NewlineBlockElements < Scrubber # :nodoc:
-
1
def initialize
-
@direction = :bottom_up
-
end
-
-
1
def scrub(node)
-
return CONTINUE unless Loofah::Elements::BLOCK_LEVEL.include?(node.name)
-
node.add_next_sibling Nokogiri::XML::Text.new("\n#{node.content}\n", node.document)
-
node.remove
-
end
-
end
-
-
#
-
# === scrub!(:unprintable)
-
#
-
# +:unprintable+ removes unprintable Unicode characters.
-
#
-
# markup = "<p>Some text with an unprintable character at the end\u2028</p>"
-
# Loofah.fragment(markup).scrub!(:unprintable)
-
# => "<p>Some text with an unprintable character at the end</p>"
-
#
-
# You may not be able to see the unprintable character in the above example, but there is a
-
# U+2028 character right before the closing </p> tag. These characters can cause issues if
-
# the content is ever parsed by JavaScript - more information here:
-
#
-
# http://timelessrepo.com/json-isnt-a-javascript-subset
-
#
-
1
class Unprintable < Scrubber
-
1
def initialize
-
@direction = :top_down
-
end
-
-
1
def scrub(node)
-
if node.type == Nokogiri::XML::Node::TEXT_NODE
-
node.content = node.content.gsub(/\u2028|\u2029/, '')
-
end
-
CONTINUE
-
end
-
end
-
-
#
-
# A hash that maps a symbol (like +:prune+) to the appropriate Scrubber (Loofah::Scrubbers::Prune).
-
#
-
1
MAP = {
-
:escape => Escape,
-
:prune => Prune,
-
:whitewash => Whitewash,
-
:strip => Strip,
-
:nofollow => NoFollow,
-
:newline_block_elements => NewlineBlockElements,
-
:unprintable => Unprintable
-
}
-
-
#
-
# Returns an array of symbols representing the built-in scrubbers
-
#
-
1
def self.scrubber_symbols
-
MAP.keys
-
end
-
end
-
end
-
1
module Loofah
-
1
module XML # :nodoc:
-
#
-
# Subclass of Nokogiri::XML::Document.
-
#
-
# See Loofah::ScrubBehavior and Loofah::DocumentDecorator for additional methods.
-
#
-
1
class Document < Nokogiri::XML::Document
-
1
include Loofah::ScrubBehavior::Node
-
1
include Loofah::DocumentDecorator
-
end
-
end
-
end
-
1
module Loofah
-
1
module XML # :nodoc:
-
#
-
# Subclass of Nokogiri::XML::DocumentFragment.
-
#
-
# See Loofah::ScrubBehavior for additional methods.
-
#
-
1
class DocumentFragment < Nokogiri::XML::DocumentFragment
-
1
class << self
-
#
-
# Overridden Nokogiri::XML::DocumentFragment
-
# constructor. Applications should use Loofah.fragment to
-
# parse a fragment.
-
#
-
1
def parse tags
-
doc = Loofah::XML::Document.new
-
doc.encoding = tags.encoding.name if tags.respond_to?(:encoding)
-
self.new(doc, tags)
-
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail # :doc:
-
-
1
require 'date'
-
1
require 'shellwords'
-
-
1
require 'uri'
-
1
require 'net/smtp'
-
-
1
begin
-
# Use mime/types/columnar if available, for reduced memory usage
-
1
require 'mime/types/columnar'
-
rescue LoadError
-
require 'mime/types'
-
end
-
-
1
if RUBY_VERSION <= '1.8.6'
-
begin
-
require 'tlsmail'
-
rescue LoadError
-
raise "You need to install tlsmail if you are using ruby <= 1.8.6"
-
end
-
end
-
-
1
if RUBY_VERSION >= "1.9.0"
-
1
require 'mail/version_specific/ruby_1_9'
-
1
RubyVer = Ruby19
-
else
-
require 'mail/version_specific/ruby_1_8'
-
RubyVer = Ruby18
-
end
-
-
1
require 'mail/version'
-
-
1
require 'mail/core_extensions/string'
-
1
require 'mail/core_extensions/smtp' if RUBY_VERSION < '1.9.3'
-
1
require 'mail/indifferent_hash'
-
-
# Only load our multibyte extensions if AS is not already loaded
-
1
if defined?(ActiveSupport)
-
1
require 'active_support/inflector'
-
else
-
require 'mail/core_extensions/string/access'
-
require 'mail/core_extensions/string/multibyte'
-
require 'mail/multibyte'
-
end
-
-
1
require 'mail/constants'
-
1
require 'mail/utilities'
-
1
require 'mail/configuration'
-
-
1
@@autoloads = {}
-
1
def self.register_autoload(name, path)
-
54
@@autoloads[name] = path
-
54
autoload(name, path)
-
end
-
-
# This runs through the autoload list and explictly requires them for you.
-
# Useful when running mail in a threaded process.
-
#
-
# Usage:
-
#
-
# require 'mail'
-
# Mail.eager_autoload!
-
1
def self.eager_autoload!
-
@@autoloads.each { |_,path| require(path) }
-
end
-
-
# Autoload mail send and receive classes.
-
1
require 'mail/network'
-
-
1
require 'mail/message'
-
1
require 'mail/part'
-
1
require 'mail/header'
-
1
require 'mail/parts_list'
-
1
require 'mail/attachments_list'
-
1
require 'mail/body'
-
1
require 'mail/field'
-
1
require 'mail/field_list'
-
-
1
require 'mail/envelope'
-
-
1
register_autoload :Parsers, "mail/parsers"
-
-
# Autoload header field elements and transfer encodings.
-
1
require 'mail/elements'
-
1
require 'mail/encodings'
-
1
require 'mail/encodings/base64'
-
1
require 'mail/encodings/quoted_printable'
-
1
require 'mail/encodings/unix_to_unix'
-
-
1
require 'mail/matchers/has_sent_mail'
-
1
require 'mail/matchers/attachment_matchers.rb'
-
-
# Finally... require all the Mail.methods
-
1
require 'mail/mail'
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
-
# = Body
-
#
-
# The body is where the text of the email is stored. Mail treats the body
-
# as a single object. The body itself has no information about boundaries
-
# used in the MIME standard, it just looks at its content as either a single
-
# block of text, or (if it is a multipart message) as an array of blocks of text.
-
#
-
# A body has to be told to split itself up into a multipart message by calling
-
# #split with the correct boundary. This is because the body object has no way
-
# of knowing what the correct boundary is for itself (there could be many
-
# boundaries in a body in the case of a nested MIME text).
-
#
-
# Once split is called, Mail::Body will slice itself up on this boundary,
-
# assigning anything that appears before the first part to the preamble, and
-
# anything that appears after the closing boundary to the epilogue, then
-
# each part gets initialized into a Mail::Part object.
-
#
-
# The boundary that is used to split up the Body is also stored in the Body
-
# object for use on encoding itself back out to a string. You can
-
# overwrite this if it needs to be changed.
-
#
-
# On encoding, the body will return the preamble, then each part joined by
-
# the boundary, followed by a closing boundary string and then the epilogue.
-
1
class Body
-
-
1
def initialize(string = '')
-
@boundary = nil
-
@preamble = nil
-
@epilogue = nil
-
@charset = nil
-
@part_sort_order = [ "text/plain", "text/enriched", "text/html" ]
-
@parts = Mail::PartsList.new
-
if Utilities.blank?(string)
-
@raw_source = ''
-
else
-
# Do join first incase we have been given an Array in Ruby 1.9
-
if string.respond_to?(:join)
-
@raw_source = string.join('')
-
elsif string.respond_to?(:to_s)
-
@raw_source = string.to_s
-
else
-
raise "You can only assign a string or an object that responds_to? :join or :to_s to a body."
-
end
-
end
-
@encoding = (only_us_ascii? ? '7bit' : '8bit')
-
set_charset
-
end
-
-
# Matches this body with another body. Also matches the decoded value of this
-
# body with a string.
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body == body #=> true
-
#
-
# body = Mail::Body.new('The body')
-
# body == 'The body' #=> true
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body == "The body" #=> true
-
1
def ==(other)
-
if other.class == String
-
self.decoded == other
-
else
-
super
-
end
-
end
-
-
# Accepts a string and performs a regular expression against the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body =~ /The/ #=> 0
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body =~ /The/ #=> 0
-
1
def =~(regexp)
-
self.decoded =~ regexp
-
end
-
-
# Accepts a string and performs a regular expression against the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body.match(/The/) #=> #<MatchData "The">
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body.match(/The/) #=> #<MatchData "The">
-
1
def match(regexp)
-
self.decoded.match(regexp)
-
end
-
-
# Accepts anything that responds to #to_s and checks if it's a substring of the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body.include?('The') #=> true
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body.include?('The') #=> true
-
1
def include?(other)
-
self.decoded.include?(other.to_s)
-
end
-
-
# Allows you to set the sort order of the parts, overriding the default sort order.
-
# Defaults to 'text/plain', then 'text/enriched', then 'text/html' with any other content
-
# type coming after.
-
1
def set_sort_order(order)
-
@part_sort_order = order
-
end
-
-
# Allows you to sort the parts according to the default sort order, or the sort order you
-
# set with :set_sort_order.
-
#
-
# sort_parts! is also called from :encode, so there is no need for you to call this explicitly
-
1
def sort_parts!
-
@parts.each do |p|
-
p.body.set_sort_order(@part_sort_order)
-
p.body.sort_parts!
-
end
-
@parts.sort!(@part_sort_order)
-
end
-
-
# Returns the raw source that the body was initialized with, without
-
# any tampering
-
1
def raw_source
-
@raw_source
-
end
-
-
1
def get_best_encoding(target)
-
target_encoding = Mail::Encodings.get_encoding(target)
-
target_encoding.get_best_compatible(encoding, raw_source)
-
end
-
-
# Returns a body encoded using transfer_encoding. Multipart always uses an
-
# identiy encoding (i.e. no encoding).
-
# Calling this directly is not a good idea, but supported for compatibility
-
# TODO: Validate that preamble and epilogue are valid for requested encoding
-
1
def encoded(transfer_encoding = '8bit')
-
if multipart?
-
self.sort_parts!
-
encoded_parts = parts.map { |p| p.encoded }
-
([preamble] + encoded_parts).join(crlf_boundary) + end_boundary + epilogue.to_s
-
else
-
be = get_best_encoding(transfer_encoding)
-
dec = Mail::Encodings::get_encoding(encoding)
-
enc = Mail::Encodings::get_encoding(be)
-
if dec.nil?
-
# Cannot decode, so skip normalization
-
raw_source
-
else
-
# Decode then encode to normalize and allow transforming
-
# from base64 to Q-P and vice versa
-
decoded = dec.decode(raw_source)
-
if defined?(Encoding) && charset && charset != "US-ASCII"
-
decoded.encode!(charset)
-
decoded.force_encoding('BINARY') unless Encoding.find(charset).ascii_compatible?
-
end
-
enc.encode(decoded)
-
end
-
end
-
end
-
-
1
def decoded
-
if !Encodings.defined?(encoding)
-
raise UnknownEncodingType, "Don't know how to decode #{encoding}, please call #encoded and decode it yourself."
-
else
-
Encodings.get_encoding(encoding).decode(raw_source)
-
end
-
end
-
-
1
def to_s
-
decoded
-
end
-
-
1
def charset
-
@charset
-
end
-
-
1
def charset=( val )
-
@charset = val
-
end
-
-
1
def encoding(val = nil)
-
if val
-
self.encoding = val
-
else
-
@encoding
-
end
-
end
-
-
1
def encoding=( val )
-
@encoding = if val == "text" || Utilities.blank?(val)
-
(only_us_ascii? ? '7bit' : '8bit')
-
else
-
val
-
end
-
end
-
-
# Returns the preamble (any text that is before the first MIME boundary)
-
1
def preamble
-
@preamble
-
end
-
-
# Sets the preamble to a string (adds text before the first MIME boundary)
-
1
def preamble=( val )
-
@preamble = val
-
end
-
-
# Returns the epilogue (any text that is after the last MIME boundary)
-
1
def epilogue
-
@epilogue
-
end
-
-
# Sets the epilogue to a string (adds text after the last MIME boundary)
-
1
def epilogue=( val )
-
@epilogue = val
-
end
-
-
# Returns true if there are parts defined in the body
-
1
def multipart?
-
true unless parts.empty?
-
end
-
-
# Returns the boundary used by the body
-
1
def boundary
-
@boundary
-
end
-
-
# Allows you to change the boundary of this Body object
-
1
def boundary=( val )
-
@boundary = val
-
end
-
-
1
def parts
-
@parts
-
end
-
-
1
def <<( val )
-
if @parts
-
@parts << val
-
else
-
@parts = Mail::PartsList.new[val]
-
end
-
end
-
-
1
def split!(boundary)
-
self.boundary = boundary
-
parts = extract_parts
-
-
# Make the preamble equal to the preamble (if any)
-
self.preamble = parts[0].to_s.strip
-
# Make the epilogue equal to the epilogue (if any)
-
self.epilogue = parts[-1].to_s.strip
-
parts[1...-1].to_a.each { |part| @parts << Mail::Part.new(part) }
-
self
-
end
-
-
1
def only_us_ascii?
-
!(raw_source =~ /[^\x01-\x7f]/)
-
end
-
-
1
def empty?
-
!!raw_source.to_s.empty?
-
end
-
-
1
private
-
-
# split parts by boundary, ignore first part if empty, append final part when closing boundary was missing
-
1
def extract_parts
-
parts_regex = /
-
(?: # non-capturing group
-
\A | # start of string OR
-
\r\n # line break
-
)
-
(
-
--#{Regexp.escape(boundary || "")} # boundary delimiter
-
(?:--)? # with non-capturing optional closing
-
)
-
(?=\s*$) # lookahead matching zero or more spaces followed by line-ending
-
/x
-
parts = raw_source.split(parts_regex).each_slice(2).to_a
-
parts.each_with_index { |(part, _), index| parts.delete_at(index) if index > 0 && Utilities.blank?(part) }
-
-
if parts.size > 1
-
final_separator = parts[-2][1]
-
parts << [""] if final_separator != "--#{boundary}--"
-
end
-
parts.map(&:first)
-
end
-
-
1
def crlf_boundary
-
"\r\n--#{boundary}\r\n"
-
end
-
-
1
def end_boundary
-
"\r\n--#{boundary}--\r\n"
-
end
-
-
1
def set_charset
-
only_us_ascii? ? @charset = 'US-ASCII' : @charset = nil
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module Mail
-
1
module CheckDeliveryParams #:nodoc:
-
1
class << self
-
1
def check(mail)
-
[ check_from(mail.smtp_envelope_from),
-
check_to(mail.smtp_envelope_to),
-
check_message(mail) ]
-
end
-
-
1
def check_from(addr)
-
if Utilities.blank?(addr)
-
raise ArgumentError, "SMTP From address may not be blank: #{addr.inspect}"
-
end
-
-
check_addr 'From', addr
-
end
-
-
1
def check_to(addrs)
-
if Utilities.blank?(addrs)
-
raise ArgumentError, "SMTP To address may not be blank: #{addrs.inspect}"
-
end
-
-
Array(addrs).map do |addr|
-
check_addr 'To', addr
-
end
-
end
-
-
1
def check_addr(addr_name, addr)
-
validate_smtp_addr addr do |error_message|
-
raise ArgumentError, "SMTP #{addr_name} address #{error_message}: #{addr.inspect}"
-
end
-
end
-
-
1
def validate_smtp_addr(addr)
-
if addr.bytesize > 2048
-
yield 'may not exceed 2kB'
-
end
-
-
if /[\r\n]/ =~ addr
-
yield 'may not contain CR or LF line breaks'
-
end
-
-
addr
-
end
-
-
1
def check_message(message)
-
message = message.encoded if message.respond_to?(:encoded)
-
-
if Utilities.blank?(message)
-
raise ArgumentError, 'An encoded message is required to send an email'
-
end
-
-
message
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# Thanks to Nicolas Fouché for this wrapper
-
#
-
1
require 'singleton'
-
-
1
module Mail
-
-
# The Configuration class is a Singleton used to hold the default
-
# configuration for all Mail objects.
-
#
-
# Each new mail object gets a copy of these values at initialization
-
# which can be overwritten on a per mail object basis.
-
1
class Configuration
-
1
include Singleton
-
-
1
def initialize
-
@delivery_method = nil
-
@retriever_method = nil
-
super
-
end
-
-
1
def delivery_method(method = nil, settings = {})
-
return @delivery_method if @delivery_method && method.nil?
-
@delivery_method = lookup_delivery_method(method).new(settings)
-
end
-
-
1
def lookup_delivery_method(method)
-
case method.is_a?(String) ? method.to_sym : method
-
when nil
-
Mail::SMTP
-
when :smtp
-
Mail::SMTP
-
when :sendmail
-
Mail::Sendmail
-
when :exim
-
Mail::Exim
-
when :file
-
Mail::FileDelivery
-
when :smtp_connection
-
Mail::SMTPConnection
-
when :test
-
Mail::TestMailer
-
else
-
method
-
end
-
end
-
-
1
def retriever_method(method = nil, settings = {})
-
return @retriever_method if @retriever_method && method.nil?
-
@retriever_method = lookup_retriever_method(method).new(settings)
-
end
-
-
1
def lookup_retriever_method(method)
-
case method
-
when nil
-
Mail::POP3
-
when :pop3
-
Mail::POP3
-
when :imap
-
Mail::IMAP
-
when :test
-
Mail::TestRetriever
-
else
-
method
-
end
-
end
-
-
1
def param_encode_language(value = nil)
-
value ? @encode_language = value : @encode_language ||= 'en'
-
end
-
-
end
-
-
end
-
# encoding: us-ascii
-
# frozen_string_literal: true
-
1
module Mail
-
1
module Constants
-
1
white_space = %Q|\x9\x20|
-
1
text = %Q|\x1-\x8\xB\xC\xE-\x7f|
-
1
field_name = %Q|\x21-\x39\x3b-\x7e|
-
1
qp_safe = %Q|\x20-\x3c\x3e-\x7e|
-
-
1
aspecial = %Q|()<>[]:;@\\,."| # RFC5322
-
1
tspecial = %Q|()<>@,;:\\"/[]?=| # RFC2045
-
1
sp = %Q| |
-
1
control = %Q|\x00-\x1f\x7f-\xff|
-
-
1
if control.respond_to?(:force_encoding)
-
1
control = control.dup.force_encoding(Encoding::BINARY)
-
end
-
-
1
CRLF = /\r\n/
-
1
WSP = /[#{white_space}]/
-
1
FWS = /#{CRLF}#{WSP}*/
-
1
TEXT = /[#{text}]/ # + obs-text
-
1
FIELD_NAME = /[#{field_name}]+/
-
1
FIELD_PREFIX = /\A(#{FIELD_NAME})/
-
1
FIELD_BODY = /.+/m
-
1
FIELD_LINE = /^[#{field_name}]+:\s*.+$/
-
1
FIELD_SPLIT = /^(#{FIELD_NAME})\s*:\s*(#{FIELD_BODY})?$/
-
1
HEADER_LINE = /^([#{field_name}]+:\s*.+)$/
-
1
HEADER_SPLIT = /#{CRLF}(?!#{WSP})/
-
-
1
QP_UNSAFE = /[^#{qp_safe}]/
-
1
QP_SAFE = /[#{qp_safe}]/
-
1
CONTROL_CHAR = /[#{control}]/n
-
1
ATOM_UNSAFE = /[#{Regexp.quote aspecial}#{control}#{sp}]/n
-
1
PHRASE_UNSAFE = /[#{Regexp.quote aspecial}#{control}]/n
-
1
TOKEN_UNSAFE = /[#{Regexp.quote tspecial}#{control}#{sp}]/n
-
1
ENCODED_VALUE = /\=\?([^?]+)\?([QB])\?[^?]*?\?\=/mi
-
1
FULL_ENCODED_VALUE = /(\=\?[^?]+\?[QB]\?[^?]*?\?\=)/mi
-
-
1
EMPTY = ''
-
1
SPACE = ' '
-
1
UNDERSCORE = '_'
-
1
HYPHEN = '-'
-
1
COLON = ':'
-
1
ASTERISK = '*'
-
1
CR = "\r"
-
1
LF = "\n"
-
1
CR_ENCODED = "=0D"
-
1
LF_ENCODED = "=0A"
-
1
CAPITAL_M = 'M'
-
1
EQUAL_LF = "=\n"
-
1
NULL_SENDER = '<>'
-
-
1
Q_VALUES = ['Q','q']
-
1
B_VALUES = ['B','b']
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
class String #:nodoc:
-
-
1
unless method_defined?(:ascii_only?)
-
# Backport from Ruby 1.9 checks for non-us-ascii characters.
-
def ascii_only?
-
self !~ MATCH_NON_US_ASCII
-
end
-
-
MATCH_NON_US_ASCII = /[^\x00-\x7f]/
-
end
-
-
1
def not_ascii_only?
-
!ascii_only?
-
end
-
-
1
unless method_defined?(:bytesize)
-
alias :bytesize :length
-
end
-
end
-
# frozen_string_literal: true
-
1
module Mail
-
1
register_autoload :Address, 'mail/elements/address'
-
1
register_autoload :AddressList, 'mail/elements/address_list'
-
1
register_autoload :ContentDispositionElement, 'mail/elements/content_disposition_element'
-
1
register_autoload :ContentLocationElement, 'mail/elements/content_location_element'
-
1
register_autoload :ContentTransferEncodingElement, 'mail/elements/content_transfer_encoding_element'
-
1
register_autoload :ContentTypeElement, 'mail/elements/content_type_element'
-
1
register_autoload :DateTimeElement, 'mail/elements/date_time_element'
-
1
register_autoload :EnvelopeFromElement, 'mail/elements/envelope_from_element'
-
1
register_autoload :MessageIdsElement, 'mail/elements/message_ids_element'
-
1
register_autoload :MimeVersionElement, 'mail/elements/mime_version_element'
-
1
register_autoload :PhraseList, 'mail/elements/phrase_list'
-
1
register_autoload :ReceivedElement, 'mail/elements/received_element'
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
-
1
module Mail
-
# Raised when attempting to decode an unknown encoding type
-
1
class UnknownEncodingType < StandardError #:nodoc:
-
end
-
-
1
module Encodings
-
-
1
include Mail::Constants
-
1
extend Mail::Utilities
-
-
1
@transfer_encodings = {}
-
-
# Register transfer encoding
-
#
-
# Example
-
#
-
# Encodings.register "base64", Mail::Encodings::Base64
-
1
def Encodings.register(name, cls)
-
6
@transfer_encodings[get_name(name)] = cls
-
end
-
-
# Is the encoding we want defined?
-
#
-
# Example:
-
#
-
# Encodings.defined?(:base64) #=> true
-
1
def Encodings.defined?( str )
-
@transfer_encodings.include? get_name(str)
-
end
-
-
# Gets a defined encoding type, QuotedPrintable or Base64 for now.
-
#
-
# Each encoding needs to be defined as a Mail::Encodings::ClassName for
-
# this to work, allows us to add other encodings in the future.
-
#
-
# Example:
-
#
-
# Encodings.get_encoding(:base64) #=> Mail::Encodings::Base64
-
1
def Encodings.get_encoding( str )
-
@transfer_encodings[get_name(str)]
-
end
-
-
1
def Encodings.get_all
-
@transfer_encodings.values
-
end
-
-
1
def Encodings.get_name(enc)
-
6
underscoreize(enc).downcase
-
end
-
-
1
def Encodings.transcode_charset(str, from_charset, to_charset = 'UTF-8')
-
if from_charset
-
RubyVer.transcode_charset str, from_charset, to_charset
-
else
-
str
-
end
-
end
-
-
# Encodes a parameter value using URI Escaping, note the language field 'en' can
-
# be set using Mail::Configuration, like so:
-
#
-
# Mail.defaults do
-
# param_encode_language 'jp'
-
# end
-
#
-
# The character set used for encoding will either be the value of $KCODE for
-
# Ruby < 1.9 or the encoding on the string passed in.
-
#
-
# Example:
-
#
-
# Mail::Encodings.param_encode("This is fun") #=> "us-ascii'en'This%20is%20fun"
-
1
def Encodings.param_encode(str)
-
case
-
when str.ascii_only? && str =~ TOKEN_UNSAFE
-
%Q{"#{str}"}
-
when str.ascii_only?
-
str
-
else
-
RubyVer.param_encode(str)
-
end
-
end
-
-
# Decodes a parameter value using URI Escaping.
-
#
-
# Example:
-
#
-
# Mail::Encodings.param_decode("This%20is%20fun", 'us-ascii') #=> "This is fun"
-
#
-
# str = Mail::Encodings.param_decode("This%20is%20fun", 'iso-8559-1')
-
# str.encoding #=> 'ISO-8859-1' ## Only on Ruby 1.9
-
# str #=> "This is fun"
-
1
def Encodings.param_decode(str, encoding)
-
RubyVer.param_decode(str, encoding)
-
end
-
-
# Decodes or encodes a string as needed for either Base64 or QP encoding types in
-
# the =?<encoding>?[QB]?<string>?=" format.
-
#
-
# The output type needs to be :decode to decode the input string or :encode to
-
# encode the input string. The character set used for encoding will either be
-
# the value of $KCODE for Ruby < 1.9 or the encoding on the string passed in.
-
#
-
# On encoding, will only send out Base64 encoded strings.
-
1
def Encodings.decode_encode(str, output_type)
-
case
-
when output_type == :decode
-
Encodings.value_decode(str)
-
else
-
if str.ascii_only?
-
str
-
else
-
Encodings.b_value_encode(str, find_encoding(str))
-
end
-
end
-
end
-
-
# Decodes a given string as Base64 or Quoted Printable, depending on what
-
# type it is.
-
#
-
# String has to be of the format =?<encoding>?[QB]?<string>?=
-
1
def Encodings.value_decode(str)
-
# Optimization: If there's no encoded-words in the string, just return it
-
return str unless str =~ ENCODED_VALUE
-
-
lines = collapse_adjacent_encodings(str)
-
-
# Split on white-space boundaries with capture, so we capture the white-space as well
-
lines.each do |line|
-
line.gsub!(ENCODED_VALUE) do |string|
-
case $2
-
when *B_VALUES then b_value_decode(string)
-
when *Q_VALUES then q_value_decode(string)
-
end
-
end
-
end.join("")
-
end
-
-
# Takes an encoded string of the format =?<encoding>?[QB]?<string>?=
-
1
def Encodings.unquote_and_convert_to(str, to_encoding)
-
output = value_decode( str ).to_s # output is already converted to UTF-8
-
-
if 'utf8' == to_encoding.to_s.downcase.gsub("-", "")
-
output
-
elsif to_encoding
-
begin
-
if RUBY_VERSION >= '1.9'
-
output.encode(to_encoding)
-
else
-
require 'iconv'
-
Iconv.iconv(to_encoding, 'UTF-8', output).first
-
end
-
rescue Iconv::IllegalSequence, Iconv::InvalidEncoding, Errno::EINVAL
-
# the 'from' parameter specifies a charset other than what the text
-
# actually is...not much we can do in this case but just return the
-
# unconverted text.
-
#
-
# Ditto if either parameter represents an unknown charset, like
-
# X-UNKNOWN.
-
output
-
end
-
else
-
output
-
end
-
end
-
-
1
def Encodings.address_encode(address, charset = 'utf-8')
-
if address.is_a?(Array)
-
# loop back through for each element
-
address.compact.map { |a| Encodings.address_encode(a, charset) }.join(", ")
-
else
-
# find any word boundary that is not ascii and encode it
-
encode_non_usascii(address, charset) if address
-
end
-
end
-
-
1
def Encodings.encode_non_usascii(address, charset)
-
return address if address.ascii_only? or charset.nil?
-
us_ascii = %Q{\x00-\x7f}
-
# Encode any non usascii strings embedded inside of quotes
-
address = address.gsub(/(".*?[^#{us_ascii}].*?")/) { |s| Encodings.b_value_encode(unquote(s), charset) }
-
# Then loop through all remaining items and encode as needed
-
tokens = address.split(/\s/)
-
map_with_index(tokens) do |word, i|
-
if word.ascii_only?
-
word
-
else
-
previous_non_ascii = i>0 && tokens[i-1] && !tokens[i-1].ascii_only?
-
if previous_non_ascii #why are we adding an extra space here?
-
word = " #{word}"
-
end
-
Encodings.b_value_encode(word, charset)
-
end
-
end.join(' ')
-
end
-
-
# Encode a string with Base64 Encoding and returns it ready to be inserted
-
# as a value for a field, that is, in the =?<charset>?B?<string>?= format
-
#
-
# Example:
-
#
-
# Encodings.b_value_encode('This is あ string', 'UTF-8')
-
# #=> "=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?="
-
1
def Encodings.b_value_encode(encoded_str, encoding = nil)
-
return encoded_str if encoded_str.to_s.ascii_only?
-
string, encoding = RubyVer.b_value_encode(encoded_str, encoding)
-
map_lines(string) do |str|
-
"=?#{encoding}?B?#{str.chomp}?="
-
end.join(" ")
-
end
-
-
# Encode a string with Quoted-Printable Encoding and returns it ready to be inserted
-
# as a value for a field, that is, in the =?<charset>?Q?<string>?= format
-
#
-
# Example:
-
#
-
# Encodings.q_value_encode('This is あ string', 'UTF-8')
-
# #=> "=?UTF-8?Q?This_is_=E3=81=82_string?="
-
1
def Encodings.q_value_encode(encoded_str, encoding = nil)
-
return encoded_str if encoded_str.to_s.ascii_only?
-
string, encoding = RubyVer.q_value_encode(encoded_str, encoding)
-
string.gsub!("=\r\n", '') # We already have limited the string to the length we want
-
map_lines(string) do |str|
-
"=?#{encoding}?Q?#{str.chomp.gsub(/ /, '_')}?="
-
end.join(" ")
-
end
-
-
1
private
-
-
# Decodes a Base64 string from the "=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?=" format
-
#
-
# Example:
-
#
-
# Encodings.b_value_decode("=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?=")
-
# #=> 'This is あ string'
-
1
def Encodings.b_value_decode(str)
-
RubyVer.b_value_decode(str)
-
end
-
-
# Decodes a Quoted-Printable string from the "=?UTF-8?Q?This_is_=E3=81=82_string?=" format
-
#
-
# Example:
-
#
-
# Encodings.q_value_decode("=?UTF-8?Q?This_is_=E3=81=82_string?=")
-
# #=> 'This is あ string'
-
1
def Encodings.q_value_decode(str)
-
RubyVer.q_value_decode(str)
-
end
-
-
1
def Encodings.find_encoding(str)
-
RUBY_VERSION >= '1.9' ? str.encoding : $KCODE
-
end
-
-
# Gets the encoding type (Q or B) from the string.
-
1
def Encodings.value_encoding_from_string(str)
-
str[ENCODED_VALUE, 1]
-
end
-
-
# When the encoded string consists of multiple lines, lines with the same
-
# encoding (Q or B) can be joined together.
-
#
-
# String has to be of the format =?<encoding>?[QB]?<string>?=
-
1
def Encodings.collapse_adjacent_encodings(str)
-
results = []
-
previous_encoding = nil
-
lines = str.split(FULL_ENCODED_VALUE)
-
lines.each_slice(2) do |unencoded, encoded|
-
if encoded
-
encoding = value_encoding_from_string(encoded)
-
if encoding == previous_encoding && Utilities.blank?(unencoded)
-
results.last << encoded
-
else
-
results << unencoded unless unencoded == EMPTY
-
results << encoded
-
end
-
previous_encoding = encoding
-
else
-
results << unencoded
-
end
-
end
-
-
results
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require 'mail/encodings/8bit'
-
-
1
module Mail
-
1
module Encodings
-
1
class SevenBit < EightBit
-
1
NAME = '7bit'
-
-
1
PRIORITY = 1
-
-
# 7bit and 8bit operate the same
-
-
# Decode the string
-
1
def self.decode(str)
-
super
-
end
-
-
# Encode the string
-
1
def self.encode(str)
-
super
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
1
def self.cost(str)
-
super
-
end
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require 'mail/encodings/binary'
-
-
1
module Mail
-
1
module Encodings
-
1
class EightBit < Binary
-
1
NAME = '8bit'
-
-
1
PRIORITY = 4
-
-
# 8bit is an identiy encoding, meaning nothing to do
-
-
# Decode the string
-
1
def self.decode(str)
-
::Mail::Utilities.to_lf str
-
end
-
-
# Encode the string
-
1
def self.encode(str)
-
::Mail::Utilities.to_crlf str
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
1
def self.cost(str)
-
1.0
-
end
-
-
# Per RFC 2821 4.5.3.1, SMTP lines may not be longer than 1000 octets including the <CRLF>.
-
1
def self.compatible_input?(str)
-
!str.lines.find { |line| line.length > 998 }
-
end
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require 'mail/encodings/7bit'
-
-
1
module Mail
-
1
module Encodings
-
1
class Base64 < SevenBit
-
1
NAME = 'base64'
-
-
1
PRIORITY = 3
-
-
1
def self.can_encode?(enc)
-
true
-
end
-
-
# Decode the string from Base64
-
1
def self.decode(str)
-
RubyVer.decode_base64( str )
-
end
-
-
# Encode the string to Base64
-
1
def self.encode(str)
-
::Mail::Utilities.to_crlf(RubyVer.encode_base64( str ))
-
end
-
-
# Base64 has a fixed cost, 4 bytes out per 3 bytes in
-
1
def self.cost(str)
-
4.0/3
-
end
-
-
# Base64 inserts newlines automatically and cannot violate the SMTP spec.
-
1
def self.compatible_input?(str)
-
true
-
end
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require 'mail/encodings/transfer_encoding'
-
-
1
module Mail
-
1
module Encodings
-
1
class Binary < TransferEncoding
-
1
NAME = 'binary'
-
-
1
PRIORITY = 5
-
-
# Binary is an identiy encoding, meaning nothing to do
-
-
# Decode the string
-
1
def self.decode(str)
-
str
-
end
-
-
# Encode the string
-
1
def self.encode(str)
-
str
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
1
def self.cost(str)
-
1.0
-
end
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require 'mail/encodings/7bit'
-
-
1
module Mail
-
1
module Encodings
-
1
class QuotedPrintable < SevenBit
-
1
NAME='quoted-printable'
-
-
1
PRIORITY = 2
-
-
1
def self.can_encode?(str)
-
EightBit.can_encode? str
-
end
-
-
# Decode the string from Quoted-Printable. Cope with hard line breaks
-
# that were incorrectly encoded as hex instead of literal CRLF.
-
1
def self.decode(str)
-
::Mail::Utilities.to_lf str.gsub(/(?:=0D=0A|=0D|=0A)\r\n/, "\r\n").unpack("M*").first
-
end
-
-
1
def self.encode(str)
-
::Mail::Utilities.to_crlf([::Mail::Utilities.to_lf(str)].pack("M"))
-
end
-
-
1
def self.cost(str)
-
# These bytes probably do not need encoding
-
c = str.count("\x9\xA\xD\x20-\x3C\x3E-\x7E")
-
# Everything else turns into =XX where XX is a
-
# two digit hex number (taking 3 bytes)
-
total = (str.bytesize - c)*3 + c
-
total.to_f/str.bytesize
-
end
-
-
# QP inserts newlines automatically and cannot violate the SMTP spec.
-
1
def self.compatible_input?(str)
-
true
-
end
-
-
1
private
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
1
module Encodings
-
1
class TransferEncoding
-
1
NAME = ''
-
-
1
PRIORITY = -1
-
-
1
def self.can_transport?(enc)
-
enc = Encodings.get_name(enc)
-
if Encodings.defined? enc
-
Encodings.get_encoding(enc).new.is_a? self
-
else
-
false
-
end
-
end
-
-
1
def self.can_encode?(enc)
-
can_transport? enc
-
end
-
-
1
def self.cost(str)
-
raise "Unimplemented"
-
end
-
-
1
def self.compatible_input?(str)
-
true
-
end
-
-
1
def self.to_s
-
self::NAME
-
end
-
-
1
def self.get_best_compatible(source_encoding, str)
-
if self.can_transport?(source_encoding) && self.compatible_input?(str)
-
source_encoding
-
else
-
choices = Encodings.get_all.select do |enc|
-
self.can_transport?(enc) && enc.can_encode?(source_encoding)
-
end
-
-
best = nil
-
best_cost = nil
-
-
choices.each do |enc|
-
# If the current choice cannot be transported safely,
-
# give priority to other choices but allow it to be used as a fallback.
-
this_cost = enc.cost(str) if enc.compatible_input?(str)
-
-
if !best_cost || (this_cost && this_cost < best_cost)
-
best_cost = this_cost
-
best = enc
-
elsif this_cost == best_cost
-
best = enc if enc::PRIORITY < best::PRIORITY
-
end
-
end
-
-
best
-
end
-
end
-
-
1
def to_s
-
self.class.to_s
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module Mail
-
1
module Encodings
-
1
module UnixToUnix
-
1
NAME = "x-uuencode"
-
-
1
def self.decode(str)
-
str.sub(/\Abegin \d+ [^\n]*\n/, '').unpack('u').first
-
end
-
-
1
def self.encode(str)
-
[str].pack("u")
-
end
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Mail Envelope
-
#
-
# The Envelope class provides a field for the first line in an
-
# mbox file, that looks like "From mikel@test.lindsaar.net DATETIME"
-
#
-
# This envelope class reads that line, and turns it into an
-
# Envelope.from and Envelope.date for your use.
-
1
module Mail
-
1
class Envelope < StructuredField
-
-
1
def initialize(*args)
-
super(FIELD_NAME, strip_field(FIELD_NAME, args.last))
-
end
-
-
1
def element
-
@element ||= Mail::EnvelopeFromElement.new(value)
-
end
-
-
1
def date
-
::DateTime.parse("#{element.date_time}")
-
end
-
-
1
def from
-
element.address
-
end
-
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'mail/fields'
-
-
# encoding: utf-8
-
1
module Mail
-
# Provides a single class to call to create a new structured or unstructured
-
# field. Works out per RFC what field of field it is being given and returns
-
# the correct field of class back on new.
-
#
-
# ===Per RFC 2822
-
#
-
# 2.2. Header Fields
-
#
-
# Header fields are lines composed of a field name, followed by a colon
-
# (":"), followed by a field body, and terminated by CRLF. A field
-
# name MUST be composed of printable US-ASCII characters (i.e.,
-
# characters that have values between 33 and 126, inclusive), except
-
# colon. A field body may be composed of any US-ASCII characters,
-
# except for CR and LF. However, a field body may contain CRLF when
-
# used in header "folding" and "unfolding" as described in section
-
# 2.2.3. All field bodies MUST conform to the syntax described in
-
# sections 3 and 4 of this standard.
-
#
-
1
class Field
-
-
1
include Utilities
-
1
include Comparable
-
-
1
STRUCTURED_FIELDS = %w[ bcc cc content-description content-disposition
-
content-id content-location content-transfer-encoding
-
content-type date from in-reply-to keywords message-id
-
mime-version received references reply-to
-
resent-bcc resent-cc resent-date resent-from
-
resent-message-id resent-sender resent-to
-
return-path sender to ]
-
-
1
KNOWN_FIELDS = STRUCTURED_FIELDS + ['comments', 'subject']
-
-
1
FIELDS_MAP = {
-
"to" => ToField,
-
"cc" => CcField,
-
"bcc" => BccField,
-
"message-id" => MessageIdField,
-
"in-reply-to" => InReplyToField,
-
"references" => ReferencesField,
-
"subject" => SubjectField,
-
"comments" => CommentsField,
-
"keywords" => KeywordsField,
-
"date" => DateField,
-
"from" => FromField,
-
"sender" => SenderField,
-
"reply-to" => ReplyToField,
-
"resent-date" => ResentDateField,
-
"resent-from" => ResentFromField,
-
"resent-sender" => ResentSenderField,
-
"resent-to" => ResentToField,
-
"resent-cc" => ResentCcField,
-
"resent-bcc" => ResentBccField,
-
"resent-message-id" => ResentMessageIdField,
-
"return-path" => ReturnPathField,
-
"received" => ReceivedField,
-
"mime-version" => MimeVersionField,
-
"content-transfer-encoding" => ContentTransferEncodingField,
-
"content-description" => ContentDescriptionField,
-
"content-disposition" => ContentDispositionField,
-
"content-type" => ContentTypeField,
-
"content-id" => ContentIdField,
-
"content-location" => ContentLocationField,
-
}
-
-
1
FIELD_NAME_MAP = FIELDS_MAP.inject({}) do |map, (field, field_klass)|
-
29
map.update(field => field_klass::CAPITALIZED_FIELD)
-
end
-
-
# Generic Field Exception
-
1
class FieldError < StandardError
-
end
-
-
# Raised when a parsing error has occurred (ie, a StructuredField has tried
-
# to parse a field that is invalid or improperly written)
-
1
class ParseError < FieldError #:nodoc:
-
1
attr_accessor :element, :value, :reason
-
-
1
def initialize(element, value, reason)
-
@element = element
-
@value = value
-
@reason = reason
-
super("#{element} can not parse |#{value}|\nReason was: #{reason}")
-
end
-
end
-
-
# Raised when attempting to set a structured field's contents to an invalid syntax
-
1
class SyntaxError < FieldError #:nodoc:
-
end
-
-
# Accepts a string:
-
#
-
# Field.new("field-name: field data")
-
#
-
# Or name, value pair:
-
#
-
# Field.new("field-name", "value")
-
#
-
# Or a name by itself:
-
#
-
# Field.new("field-name")
-
#
-
# Note, does not want a terminating carriage return. Returns
-
# self appropriately parsed. If value is not a string, then
-
# it will be passed through as is, for example, content-type
-
# field can accept an array with the type and a hash of
-
# parameters:
-
#
-
# Field.new('content-type', ['text', 'plain', {:charset => 'UTF-8'}])
-
1
def initialize(name, value = nil, charset = 'utf-8')
-
case
-
when name.index(COLON) # Field.new("field-name: field data")
-
@charset = Utilities.blank?(value) ? charset : value
-
@name = name[FIELD_PREFIX]
-
@raw_value = name
-
@value = nil
-
when Utilities.blank?(value) # Field.new("field-name")
-
@name = name
-
@value = nil
-
@raw_value = nil
-
@charset = charset
-
else # Field.new("field-name", "value")
-
@name = name
-
@value = value
-
@raw_value = nil
-
@charset = charset
-
end
-
@name = FIELD_NAME_MAP[@name.to_s.downcase] || @name
-
end
-
-
1
def field=(value)
-
@field = value
-
end
-
-
1
def field
-
_, @value = split(@raw_value) if @raw_value && !@value
-
@field ||= create_field(@name, @value, @charset)
-
end
-
-
1
def name
-
@name
-
end
-
-
1
def value
-
field.value
-
end
-
-
1
def value=(val)
-
@field = create_field(name, val, @charset)
-
end
-
-
1
def to_s
-
field.to_s
-
end
-
-
1
def inspect
-
"#<#{self.class.name} 0x#{(object_id * 2).to_s(16)} #{instance_variables.map do |ivar|
-
"#{ivar}=#{instance_variable_get(ivar).inspect}"
-
end.join(" ")}>"
-
end
-
-
1
def update(name, value)
-
@field = create_field(name, value, @charset)
-
end
-
-
1
def same( other )
-
return false unless other.kind_of?(self.class)
-
match_to_s(other.name, self.name)
-
end
-
-
1
def ==( other )
-
return false unless other.kind_of?(self.class)
-
match_to_s(other.name, self.name) && match_to_s(other.value, self.value)
-
end
-
-
1
def responsible_for?( val )
-
name.to_s.casecmp(val.to_s) == 0
-
end
-
-
1
def <=>( other )
-
self.field_order_id <=> other.field_order_id
-
end
-
-
1
def field_order_id
-
@field_order_id ||= (FIELD_ORDER_LOOKUP[self.name.to_s.downcase] || 100)
-
end
-
-
1
def method_missing(name, *args, &block)
-
field.send(name, *args, &block)
-
end
-
-
1
if RUBY_VERSION >= '1.9.2'
-
1
def respond_to_missing?(method_name, include_private)
-
field.respond_to?(method_name, include_private) || super
-
end
-
else
-
def respond_to?(method_name, include_private = false)
-
field.respond_to?(method_name, include_private) || super
-
end
-
end
-
-
1
FIELD_ORDER = %w[ return-path received
-
resent-date resent-from resent-sender resent-to
-
resent-cc resent-bcc resent-message-id
-
date from sender reply-to to cc bcc
-
message-id in-reply-to references
-
subject comments keywords
-
mime-version content-type content-transfer-encoding
-
content-location content-disposition content-description ]
-
-
1
FIELD_ORDER_LOOKUP = Hash[FIELD_ORDER.each_with_index.to_a]
-
-
1
private
-
-
1
def split(raw_field)
-
match_data = raw_field.mb_chars.match(FIELD_SPLIT)
-
[match_data[1].to_s.mb_chars.strip, match_data[2].to_s.mb_chars.strip.to_s]
-
rescue
-
STDERR.puts "WARNING: Could not parse (and so ignoring) '#{raw_field}'"
-
end
-
-
# 2.2.3. Long Header Fields
-
#
-
# The process of moving from this folded multiple-line representation
-
# of a header field to its single line representation is called
-
# "unfolding". Unfolding is accomplished by simply removing any CRLF
-
# that is immediately followed by WSP. Each header field should be
-
# treated in its unfolded form for further syntactic and semantic
-
# evaluation.
-
1
def unfold(string)
-
string.gsub(/[\r\n \t]+/m, ' ')
-
end
-
-
1
def create_field(name, value, charset)
-
value = unfold(value) if value.is_a?(String)
-
-
begin
-
new_field(name, value, charset)
-
rescue Mail::Field::ParseError => e
-
field = Mail::UnstructuredField.new(name, value)
-
field.errors << [name, value, e]
-
field
-
end
-
end
-
-
1
def new_field(name, value, charset)
-
lower_case_name = name.to_s.downcase
-
if field_klass = FIELDS_MAP[lower_case_name]
-
field_klass.new(value, charset)
-
else
-
OptionalField.new(name, value, charset)
-
end
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
-
# Field List class provides an enhanced array that keeps a list of
-
# email fields in order. And allows you to insert new fields without
-
# having to worry about the order they will appear in.
-
1
class FieldList < Array
-
-
1
include Enumerable
-
-
# Insert the field in sorted order.
-
#
-
# Heavily based on bisect.insort from Python, which is:
-
# Copyright (C) 2001-2013 Python Software Foundation.
-
# Licensed under <http://docs.python.org/license.html>
-
# From <http://hg.python.org/cpython/file/2.7/Lib/bisect.py>
-
1
def <<( new_field )
-
lo = 0
-
hi = size
-
-
while lo < hi
-
mid = (lo + hi).div(2)
-
if new_field < self[mid]
-
hi = mid
-
else
-
lo = mid + 1
-
end
-
end
-
-
insert(lo, new_field)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
module Mail
-
1
register_autoload :UnstructuredField, 'mail/fields/unstructured_field'
-
1
register_autoload :StructuredField, 'mail/fields/structured_field'
-
1
register_autoload :OptionalField, 'mail/fields/optional_field'
-
-
1
register_autoload :BccField, 'mail/fields/bcc_field'
-
1
register_autoload :CcField, 'mail/fields/cc_field'
-
1
register_autoload :CommentsField, 'mail/fields/comments_field'
-
1
register_autoload :ContentDescriptionField, 'mail/fields/content_description_field'
-
1
register_autoload :ContentDispositionField, 'mail/fields/content_disposition_field'
-
1
register_autoload :ContentIdField, 'mail/fields/content_id_field'
-
1
register_autoload :ContentLocationField, 'mail/fields/content_location_field'
-
1
register_autoload :ContentTransferEncodingField, 'mail/fields/content_transfer_encoding_field'
-
1
register_autoload :ContentTypeField, 'mail/fields/content_type_field'
-
1
register_autoload :DateField, 'mail/fields/date_field'
-
1
register_autoload :FromField, 'mail/fields/from_field'
-
1
register_autoload :InReplyToField, 'mail/fields/in_reply_to_field'
-
1
register_autoload :KeywordsField, 'mail/fields/keywords_field'
-
1
register_autoload :MessageIdField, 'mail/fields/message_id_field'
-
1
register_autoload :MimeVersionField, 'mail/fields/mime_version_field'
-
1
register_autoload :ReceivedField, 'mail/fields/received_field'
-
1
register_autoload :ReferencesField, 'mail/fields/references_field'
-
1
register_autoload :ReplyToField, 'mail/fields/reply_to_field'
-
1
register_autoload :ResentBccField, 'mail/fields/resent_bcc_field'
-
1
register_autoload :ResentCcField, 'mail/fields/resent_cc_field'
-
1
register_autoload :ResentDateField, 'mail/fields/resent_date_field'
-
1
register_autoload :ResentFromField, 'mail/fields/resent_from_field'
-
1
register_autoload :ResentMessageIdField, 'mail/fields/resent_message_id_field'
-
1
register_autoload :ResentSenderField, 'mail/fields/resent_sender_field'
-
1
register_autoload :ResentToField, 'mail/fields/resent_to_field'
-
1
register_autoload :ReturnPathField, 'mail/fields/return_path_field'
-
1
register_autoload :SenderField, 'mail/fields/sender_field'
-
1
register_autoload :SubjectField, 'mail/fields/subject_field'
-
1
register_autoload :ToField, 'mail/fields/to_field'
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Blind Carbon Copy Field
-
#
-
# The Bcc field inherits from StructuredField and handles the Bcc: header
-
# field in the email.
-
#
-
# Sending bcc to a mail message will instantiate a Mail::Field object that
-
# has a BccField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Bcc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.bcc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:bcc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
# mail['bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
# mail['Bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
#
-
# mail[:bcc].encoded #=> '' # Bcc field does not get output into an email
-
# mail[:bcc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:bcc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:bcc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class BccField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'bcc'
-
1
CAPITALIZED_FIELD = 'Bcc'
-
-
1
def initialize(value = '', charset = 'utf-8')
-
@charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def include_in_headers=(include_in_headers)
-
@include_in_headers = include_in_headers
-
end
-
-
1
def include_in_headers
-
defined?(@include_in_headers) ? @include_in_headers : self.include_in_headers = false
-
end
-
-
# Bcc field should not be :encoded by default
-
1
def encoded
-
if include_in_headers
-
do_encode(CAPITALIZED_FIELD)
-
else
-
''
-
end
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Carbon Copy Field
-
#
-
# The Cc field inherits from StructuredField and handles the Cc: header
-
# field in the email.
-
#
-
# Sending cc to a mail message will instantiate a Mail::Field object that
-
# has a CcField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Cc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.cc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:cc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
# mail['cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
# mail['Cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
#
-
# mail[:cc].encoded #=> 'Cc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:cc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:cc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:cc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class CcField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'cc'
-
1
CAPITALIZED_FIELD = 'Cc'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Comments Field
-
#
-
# The Comments field inherits from UnstructuredField and handles the Comments:
-
# header field in the email.
-
#
-
# Sending comments to a mail message will instantiate a Mail::Field object that
-
# has a CommentsField as its field type.
-
#
-
# An email header can have as many comments fields as it wants. There is no upper
-
# limit, the comments field is also optional (that is, no comment is needed)
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.comments = 'This is a comment'
-
# mail.comments #=> 'This is a comment'
-
# mail[:comments] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
# mail['comments'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
# mail['comments'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
#
-
# mail.comments = "This is another comment"
-
# mail[:comments].map { |c| c.to_s }
-
# #=> ['This is a comment', "This is another comment"]
-
#
-
1
module Mail
-
1
class CommentsField < UnstructuredField
-
-
1
FIELD_NAME = 'comments'
-
1
CAPITALIZED_FIELD = 'Comments'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
@charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value))
-
self.parse
-
self
-
end
-
-
end
-
end
-
# frozen_string_literal: true
-
1
module Mail
-
-
1
class AddressContainer < Array
-
-
1
def initialize(field, list = [])
-
@field = field
-
super(list)
-
end
-
-
1
def <<(address)
-
@field << address
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require 'mail/fields/common/address_container'
-
-
1
module Mail
-
1
module CommonAddress # :nodoc:
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
@address_list = AddressList.new(encode_if_needed(val))
-
else
-
nil
-
end
-
end
-
-
1
def charset
-
@charset
-
end
-
-
1
def encode_if_needed(val)
-
Encodings.address_encode(val, charset)
-
end
-
-
# Allows you to iterate through each address object in the address_list
-
1
def each
-
address_list.addresses.each do |address|
-
yield(address)
-
end
-
end
-
-
# Returns the address string of all the addresses in the address list
-
1
def addresses
-
list = address_list.addresses.map { |a| a.address }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the formatted string of all the addresses in the address list
-
1
def formatted
-
list = address_list.addresses.map { |a| a.format }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the display name of all the addresses in the address list
-
1
def display_names
-
list = address_list.addresses.map { |a| a.display_name }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the actual address objects in the address list
-
1
def addrs
-
list = address_list.addresses
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns a hash of group name => address strings for the address list
-
1
def groups
-
address_list.addresses_grouped_by_group
-
end
-
-
# Returns the addresses that are part of groups
-
1
def group_addresses
-
decoded_group_addresses
-
end
-
-
# Returns a list of decoded group addresses
-
1
def decoded_group_addresses
-
groups.map { |k,v| v.map { |a| a.decoded } }.flatten
-
end
-
-
# Returns a list of encoded group addresses
-
1
def encoded_group_addresses
-
groups.map { |k,v| v.map { |a| a.encoded } }.flatten
-
end
-
-
# Returns the name of all the groups in a string
-
1
def group_names # :nodoc:
-
address_list.group_names
-
end
-
-
1
def default
-
addresses
-
end
-
-
1
def <<(val)
-
case
-
when val.nil?
-
raise ArgumentError, "Need to pass an address to <<"
-
when Utilities.blank?(val)
-
parse(encoded)
-
else
-
self.value = [self.value, val].reject {|a| Utilities.blank?(a) }.join(", ")
-
end
-
end
-
-
1
def value=(val)
-
super
-
parse(self.value)
-
end
-
-
1
private
-
-
1
def do_encode(field_name)
-
return '' if Utilities.blank?(value)
-
address_array = address_list.addresses.reject { |a| encoded_group_addresses.include?(a.encoded) }.compact.map { |a| a.encoded }
-
address_text = address_array.join(", \r\n\s")
-
group_array = groups.map { |k,v| "#{k}: #{v.map { |a| a.encoded }.join(", \r\n\s")};" }
-
group_text = group_array.join(" \r\n\s")
-
return_array = [address_text, group_text].reject { |a| Utilities.blank?(a) }
-
"#{field_name}: #{return_array.join(", \r\n\s")}\r\n"
-
end
-
-
1
def do_decode
-
return nil if Utilities.blank?(value)
-
address_array = address_list.addresses.reject { |a| decoded_group_addresses.include?(a.decoded) }.map { |a| a.decoded }
-
address_text = address_array.join(", ")
-
group_array = groups.map { |k,v| "#{k}: #{v.map { |a| a.decoded }.join(", ")};" }
-
group_text = group_array.join(" ")
-
return_array = [address_text, group_text].reject { |a| Utilities.blank?(a) }
-
return_array.join(", ")
-
end
-
-
1
def address_list # :nodoc:
-
@address_list ||= AddressList.new(value)
-
end
-
-
1
def get_group_addresses(group_list)
-
if group_list.respond_to?(:addresses)
-
group_list.addresses.map do |address|
-
Mail::Address.new(address)
-
end
-
else
-
[]
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
1
module CommonDate # :nodoc:
-
# Returns a date time object of the parsed date
-
1
def date_time
-
::DateTime.parse("#{element.date_string} #{element.time_string}")
-
end
-
-
1
def default
-
date_time
-
end
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
@element = Mail::DateTimeElement.new(val)
-
else
-
nil
-
end
-
end
-
-
1
private
-
-
1
def do_encode(field_name)
-
"#{field_name}: #{value}\r\n"
-
end
-
-
1
def do_decode
-
"#{value}"
-
end
-
-
1
def element
-
@element ||= Mail::DateTimeElement.new(value)
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
1
module CommonField # :nodoc:
-
1
include Mail::Constants
-
-
1
def name=(value)
-
@name = value
-
end
-
-
1
def name
-
@name ||= nil
-
end
-
-
1
def value=(value)
-
@length = nil
-
@tree = nil
-
@element = nil
-
@value = value
-
end
-
-
1
def value
-
@value
-
end
-
-
1
def to_s
-
decoded.to_s
-
end
-
-
1
def default
-
decoded
-
end
-
-
1
def field_length
-
@length ||= "#{name}: #{encode(decoded)}".length
-
end
-
-
1
def responsible_for?( val )
-
name.to_s.casecmp(val.to_s) == 0
-
end
-
-
1
private
-
-
1
def strip_field(field_name, value)
-
if value.is_a?(Array)
-
value
-
else
-
value.to_s.sub(/\A#{field_name}:\s+/i, EMPTY)
-
end
-
end
-
-
1
FILENAME_RE = /\b(filename|name)=([^;"\r\n]+\s[^;"\r\n]+)/
-
1
def ensure_filename_quoted(value)
-
if value.is_a?(String)
-
value.sub FILENAME_RE, '\1="\2"'
-
else
-
value
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
1
module CommonMessageId # :nodoc:
-
1
def element
-
@element ||= Mail::MessageIdsElement.new(value) unless Utilities.blank?(value)
-
end
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
@element = Mail::MessageIdsElement.new(val)
-
else
-
nil
-
end
-
end
-
-
1
def message_id
-
element.message_id if element
-
end
-
-
1
def message_ids
-
element.message_ids if element
-
end
-
-
1
def default
-
return nil unless message_ids
-
if message_ids.length == 1
-
message_ids[0]
-
else
-
message_ids
-
end
-
end
-
-
1
private
-
-
1
def do_encode(field_name)
-
%Q{#{field_name}: #{formated_message_ids("\r\n ")}\r\n}
-
end
-
-
1
def do_decode
-
formated_message_ids(' ')
-
end
-
-
1
def formated_message_ids(join)
-
message_ids.map{ |m| "<#{m}>" }.join(join) if message_ids
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
-
# ParameterHash is an intelligent Hash that allows you to add
-
# parameter values including the MIME extension paramaters that
-
# have the name*0="blah", name*1="bleh" keys, and will just return
-
# a single key called name="blahbleh" and do any required un-encoding
-
# to make that happen
-
# Parameters are defined in RFC2045, split keys are in RFC2231
-
-
1
class ParameterHash < IndifferentHash
-
-
1
include Mail::Utilities
-
-
1
def [](key_name)
-
key_pattern = Regexp.escape(key_name.to_s)
-
pairs = []
-
exact = nil
-
each do |k,v|
-
if k =~ /^#{key_pattern}(\*|$)/i
-
if $1 == ASTERISK
-
pairs << [k, v]
-
else
-
exact = k
-
end
-
end
-
end
-
if pairs.empty? # Just dealing with a single value pair
-
super(exact || key_name)
-
else # Dealing with a multiple value pair or a single encoded value pair
-
string = pairs.sort { |a,b| a.first.to_s <=> b.first.to_s }.map { |v| v.last }.join('')
-
if mt = string.match(/([\w\-]+)'(\w\w)'(.*)/)
-
string = mt[3]
-
encoding = mt[1]
-
else
-
encoding = nil
-
end
-
Mail::Encodings.param_decode(string, encoding)
-
end
-
end
-
-
1
def encoded
-
map.sort_by { |a| a.first.to_s }.map! do |key_name, value|
-
unless value.ascii_only?
-
value = Mail::Encodings.param_encode(value)
-
key_name = "#{key_name}*"
-
end
-
%Q{#{key_name}=#{quote_token(value)}}
-
end.join(";\r\n\s")
-
end
-
-
1
def decoded
-
map.sort_by { |a| a.first.to_s }.map! do |key_name, value|
-
%Q{#{key_name}=#{quote_token(value)}}
-
end.join("; ")
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
#
-
#
-
1
module Mail
-
1
class ContentDescriptionField < UnstructuredField
-
-
1
FIELD_NAME = 'content-description'
-
1
CAPITALIZED_FIELD = 'Content-Description'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require 'mail/fields/common/parameter_hash'
-
-
1
module Mail
-
1
class ContentDispositionField < StructuredField
-
-
1
FIELD_NAME = 'content-disposition'
-
1
CAPITALIZED_FIELD = 'Content-Disposition'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = ensure_filename_quoted(value)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
@element = Mail::ContentDispositionElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::ContentDispositionElement.new(value)
-
end
-
-
1
def disposition_type
-
element.disposition_type
-
end
-
-
1
def parameters
-
@parameters = ParameterHash.new
-
element.parameters.each { |p| @parameters.merge!(p) } unless element.parameters.nil?
-
@parameters
-
end
-
-
1
def filename
-
case
-
when !Utilities.blank?(parameters['filename'])
-
@filename = parameters['filename']
-
when !Utilities.blank?(parameters['name'])
-
@filename = parameters['name']
-
else
-
@filename = nil
-
end
-
@filename
-
end
-
-
# TODO: Fix this up
-
1
def encoded
-
if parameters.length > 0
-
p = ";\r\n\s#{parameters.encoded}\r\n"
-
else
-
p = "\r\n"
-
end
-
"#{CAPITALIZED_FIELD}: #{disposition_type}" + p
-
end
-
-
1
def decoded
-
if parameters.length > 0
-
p = "; #{parameters.decoded}"
-
else
-
p = ""
-
end
-
"#{disposition_type}" + p
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
#
-
#
-
1
module Mail
-
1
class ContentIdField < StructuredField
-
-
1
FIELD_NAME = 'content-id'
-
1
CAPITALIZED_FIELD = "Content-ID"
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
@uniq = 1
-
if Utilities.blank?(value)
-
value = generate_content_id
-
else
-
value = strip_field(FIELD_NAME, value)
-
end
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
@element = Mail::MessageIdsElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::MessageIdsElement.new(value)
-
end
-
-
1
def name
-
'Content-ID'
-
end
-
-
1
def content_id
-
element.message_id
-
end
-
-
1
def to_s
-
"<#{content_id}>"
-
end
-
-
# TODO: Fix this up
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: #{to_s}\r\n"
-
end
-
-
1
def decoded
-
"#{to_s}"
-
end
-
-
1
private
-
-
1
def generate_content_id
-
"<#{Mail.random_tag}@#{::Socket.gethostname}.mail>"
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
#
-
#
-
1
module Mail
-
1
class ContentLocationField < StructuredField
-
-
1
FIELD_NAME = 'content-location'
-
1
CAPITALIZED_FIELD = 'Content-Location'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
@element = Mail::ContentLocationElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::ContentLocationElement.new(value)
-
end
-
-
1
def location
-
element.location
-
end
-
-
# TODO: Fix this up
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: #{location}\r\n"
-
end
-
-
1
def decoded
-
location
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
#
-
#
-
1
module Mail
-
1
class ContentTransferEncodingField < StructuredField
-
-
1
FIELD_NAME = 'content-transfer-encoding'
-
1
CAPITALIZED_FIELD = 'Content-Transfer-Encoding'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = '7bit' if value.to_s =~ /7-?bits?/i
-
value = '8bit' if value.to_s =~ /8-?bits?/i
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
@element = Mail::ContentTransferEncodingElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::ContentTransferEncodingElement.new(value)
-
end
-
-
1
def encoding
-
element.encoding
-
end
-
-
# TODO: Fix this up
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: #{encoding}\r\n"
-
end
-
-
1
def decoded
-
encoding
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require 'mail/fields/common/parameter_hash'
-
-
1
module Mail
-
1
class ContentTypeField < StructuredField
-
-
1
FIELD_NAME = 'content-type'
-
1
CAPITALIZED_FIELD = 'Content-Type'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if value.class == Array
-
@main_type = value[0]
-
@sub_type = value[1]
-
@parameters = ParameterHash.new.merge!(value.last)
-
else
-
@main_type = nil
-
@sub_type = nil
-
@parameters = nil
-
value = strip_field(FIELD_NAME, value)
-
end
-
value = ensure_filename_quoted(value)
-
super(CAPITALIZED_FIELD, value, charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
self.value = val
-
@element = nil
-
element
-
end
-
end
-
-
1
def element
-
begin
-
@element ||= Mail::ContentTypeElement.new(value)
-
rescue
-
attempt_to_clean
-
end
-
end
-
-
1
def attempt_to_clean
-
# Sanitize the value, handle special cases
-
@element ||= Mail::ContentTypeElement.new(sanatize(value))
-
rescue
-
# All else fails, just get the MIME media type
-
@element ||= Mail::ContentTypeElement.new(get_mime_type(value))
-
end
-
-
1
def main_type
-
@main_type ||= element.main_type
-
end
-
-
1
def sub_type
-
@sub_type ||= element.sub_type
-
end
-
-
1
def string
-
"#{main_type}/#{sub_type}"
-
end
-
-
1
def default
-
decoded
-
end
-
-
1
alias :content_type :string
-
-
1
def parameters
-
unless @parameters
-
@parameters = ParameterHash.new
-
element.parameters.each { |p| @parameters.merge!(p) }
-
end
-
@parameters
-
end
-
-
1
def ContentTypeField.with_boundary(type)
-
new("#{type}; boundary=#{generate_boundary}")
-
end
-
-
1
def ContentTypeField.generate_boundary
-
"--==_mimepart_#{Mail.random_tag}"
-
end
-
-
1
def value
-
if @value.class == Array
-
"#{@main_type}/#{@sub_type}; #{stringify(parameters)}"
-
else
-
@value
-
end
-
end
-
-
1
def stringify(params)
-
params.map { |k,v| "#{k}=#{Encodings.param_encode(v)}" }.join("; ")
-
end
-
-
1
def filename
-
case
-
when parameters['filename']
-
@filename = parameters['filename']
-
when parameters['name']
-
@filename = parameters['name']
-
else
-
@filename = nil
-
end
-
@filename
-
end
-
-
# TODO: Fix this up
-
1
def encoded
-
if parameters.length > 0
-
p = ";\r\n\s#{parameters.encoded}"
-
else
-
p = ""
-
end
-
"#{CAPITALIZED_FIELD}: #{content_type}#{p}\r\n"
-
end
-
-
1
def decoded
-
if parameters.length > 0
-
p = "; #{parameters.decoded}"
-
else
-
p = ""
-
end
-
"#{content_type}" + p
-
end
-
-
1
private
-
-
1
def method_missing(name, *args, &block)
-
if name.to_s =~ /(\w+)=/
-
self.parameters[$1] = args.first
-
@value = "#{content_type}; #{stringify(parameters)}"
-
else
-
super
-
end
-
end
-
-
# Various special cases from random emails found that I am not going to change
-
# the parser for
-
1
def sanatize( val )
-
-
# TODO: check if there are cases where whitespace is not a separator
-
val = val.
-
gsub(/\s*=\s*/,'='). # remove whitespaces around equal sign
-
tr(' ',';').
-
squeeze(';').
-
gsub(';', '; '). #use '; ' as a separator (or EOL)
-
gsub(/;\s*$/,'') #remove trailing to keep examples below
-
-
if val =~ /(boundary=(\S*))/i
-
val = "#{$`.downcase}boundary=#{$2}#{$'.downcase}"
-
else
-
val.downcase!
-
end
-
-
case
-
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;;+(.*)$/i
-
# Handles 'text/plain;; format="flowed"' (double semi colon)
-
"#{$1}/#{$2}; #{$3}"
-
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;\s?(ISO[\w\-]+)$/i
-
# Microsoft helper:
-
# Handles 'type/subtype;ISO-8559-1'
-
"#{$1}/#{$2}; charset=#{quote_atom($3)}"
-
when val.chomp =~ /^text;?$/i
-
# Handles 'text;' and 'text'
-
"text/plain;"
-
when val.chomp =~ /^(\w+);\s(.*)$/i
-
# Handles 'text; <parameters>'
-
"text/plain; #{$2}"
-
when val =~ /([\w\-]+\/[\w\-]+);\scharset="charset="(\w+)""/i
-
# Handles text/html; charset="charset="GB2312""
-
"#{$1}; charset=#{quote_atom($2)}"
-
when val =~ /([\w\-]+\/[\w\-]+);\s+(.*)/i
-
type = $1
-
# Handles misquoted param values
-
# e.g: application/octet-stream; name=archiveshelp1[1].htm
-
# and: audio/x-midi;\r\n\sname=Part .exe
-
params = $2.to_s.split(/\s+/)
-
params = params.map { |i| i.to_s.chomp.strip }
-
params = params.map { |i| i.split(/\s*\=\s*/) }
-
params = params.map { |i| "#{i[0]}=#{dquote(i[1].to_s.gsub(/;$/,""))}" }.join('; ')
-
"#{type}; #{params}"
-
when val =~ /^\s*$/
-
'text/plain'
-
else
-
''
-
end
-
end
-
-
1
def get_mime_type( val )
-
case
-
when val =~ /^([\w\-]+)\/([\w\-]+);.+$/i
-
"#{$1}/#{$2}"
-
else
-
'text/plain'
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Date Field
-
#
-
# The Date field inherits from StructuredField and handles the Date: header
-
# field in the email.
-
#
-
# Sending date to a mail message will instantiate a Mail::Field object that
-
# has a DateField as its field type. This includes all Mail::CommonAddress
-
# module instance methods.
-
#
-
# There must be excatly one Date field in an RFC2822 email.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.date = 'Mon, 24 Nov 1997 14:22:01 -0800'
-
# mail.date #=> #<DateTime: 211747170121/86400,-1/3,2299161>
-
# mail.date.to_s #=> 'Mon, 24 Nov 1997 14:22:01 -0800'
-
# mail[:date] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
# mail['date'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
# mail['Date'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
#
-
1
require 'mail/fields/common/common_date'
-
-
1
module Mail
-
1
class DateField < StructuredField
-
-
1
include Mail::CommonDate
-
-
1
FIELD_NAME = 'date'
-
1
CAPITALIZED_FIELD = "Date"
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if Utilities.blank?(value)
-
value = ::DateTime.now.strftime('%a, %d %b %Y %H:%M:%S %z')
-
else
-
value = strip_field(FIELD_NAME, value)
-
value.to_s.gsub!(/\(.*?\)/, '')
-
value = ::DateTime.parse(value.to_s.squeeze(" ")).strftime('%a, %d %b %Y %H:%M:%S %z')
-
end
-
super(CAPITALIZED_FIELD, value, charset)
-
rescue ArgumentError => e
-
raise e unless "invalid date"==e.message
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = From Field
-
#
-
# The From field inherits from StructuredField and handles the From: header
-
# field in the email.
-
#
-
# Sending from to a mail message will instantiate a Mail::Field object that
-
# has a FromField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one From field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.from = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:from] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
# mail['from'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
# mail['From'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
#
-
# mail[:from].encoded #=> 'from: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:from].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:from].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:from].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class FromField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'from'
-
1
CAPITALIZED_FIELD = 'From'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = In-Reply-To Field
-
#
-
# The In-Reply-To field inherits from StructuredField and handles the
-
# In-Reply-To: header field in the email.
-
#
-
# Sending in_reply_to to a mail message will instantiate a Mail::Field object that
-
# has a InReplyToField as its field type. This includes all Mail::CommonMessageId
-
# module instance metods.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# Only one InReplyTo field can appear in a header, though it can have multiple
-
# Message IDs.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.in_reply_to = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.in_reply_to #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:in_reply_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
# mail['in_reply_to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
# mail['In-Reply-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
#
-
# mail[:in_reply_to].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
1
require 'mail/fields/common/common_message_id'
-
-
1
module Mail
-
1
class InReplyToField < StructuredField
-
-
1
include Mail::CommonMessageId
-
-
1
FIELD_NAME = 'in-reply-to'
-
1
CAPITALIZED_FIELD = 'In-Reply-To'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = value.join("\r\n\s") if value.is_a?(Array)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# keywords = "Keywords:" phrase *("," phrase) CRLF
-
1
module Mail
-
1
class KeywordsField < StructuredField
-
-
1
FIELD_NAME = 'keywords'
-
1
CAPITALIZED_FIELD = 'Keywords'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
@phrase_list ||= PhraseList.new(value)
-
end
-
end
-
-
1
def phrase_list
-
@phrase_list ||= PhraseList.new(value)
-
end
-
-
1
def keywords
-
phrase_list.phrases
-
end
-
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: #{keywords.join(",\r\n ")}\r\n"
-
end
-
-
1
def decoded
-
keywords.join(', ')
-
end
-
-
1
def default
-
keywords
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Message-ID Field
-
#
-
# The Message-ID field inherits from StructuredField and handles the
-
# Message-ID: header field in the email.
-
#
-
# Sending message_id to a mail message will instantiate a Mail::Field object that
-
# has a MessageIdField as its field type. This includes all Mail::CommonMessageId
-
# module instance metods.
-
#
-
# Only one MessageId field can appear in a header, and syntactically it can only have
-
# one Message ID. The message_ids method call has been left in however as it will only
-
# return the one message id, ie, an array of length 1.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.message_id = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.message_id #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:message_id] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
# mail['message_id'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
# mail['Message-ID'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
#
-
# mail[:message_id].message_id #=> 'F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom'
-
# mail[:message_id].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
1
require 'mail/fields/common/common_message_id'
-
-
1
module Mail
-
1
class MessageIdField < StructuredField
-
-
1
include Mail::CommonMessageId
-
-
1
FIELD_NAME = 'message-id'
-
1
CAPITALIZED_FIELD = 'Message-ID'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
@uniq = 1
-
if Utilities.blank?(value)
-
self.name = CAPITALIZED_FIELD
-
self.value = generate_message_id
-
else
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
end
-
self.parse
-
self
-
-
end
-
-
1
def name
-
'Message-ID'
-
end
-
-
1
def message_ids
-
[message_id]
-
end
-
-
1
def to_s
-
"<#{message_id}>"
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
1
private
-
-
1
def generate_message_id
-
"<#{Mail.random_tag}@#{::Socket.gethostname}.mail>"
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
#
-
#
-
1
module Mail
-
1
class MimeVersionField < StructuredField
-
-
1
FIELD_NAME = 'mime-version'
-
1
CAPITALIZED_FIELD = 'Mime-Version'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if Utilities.blank?(value)
-
value = '1.0'
-
end
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
-
end
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
@element = Mail::MimeVersionElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::MimeVersionElement.new(value)
-
end
-
-
1
def version
-
"#{element.major}.#{element.minor}"
-
end
-
-
1
def major
-
element.major.to_i
-
end
-
-
1
def minor
-
element.minor.to_i
-
end
-
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: #{version}\r\n"
-
end
-
-
1
def decoded
-
version
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# trace = [return]
-
# 1*received
-
#
-
# return = "Return-Path:" path CRLF
-
#
-
# path = ([CFWS] "<" ([CFWS] / addr-spec) ">" [CFWS]) /
-
# obs-path
-
#
-
# received = "Received:" name-val-list ";" date-time CRLF
-
#
-
# name-val-list = [CFWS] [name-val-pair *(CFWS name-val-pair)]
-
#
-
# name-val-pair = item-name CFWS item-value
-
#
-
# item-name = ALPHA *(["-"] (ALPHA / DIGIT))
-
#
-
# item-value = 1*angle-addr / addr-spec /
-
# atom / domain / msg-id
-
#
-
1
module Mail
-
1
class ReceivedField < StructuredField
-
-
1
FIELD_NAME = 'received'
-
1
CAPITALIZED_FIELD = 'Received'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
-
end
-
-
1
def parse(val = value)
-
unless Utilities.blank?(val)
-
@element = Mail::ReceivedElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::ReceivedElement.new(value)
-
end
-
-
1
def date_time
-
@datetime ||= ::DateTime.parse("#{element.date_time}")
-
end
-
-
1
def info
-
element.info
-
end
-
-
1
def formatted_date
-
date_time.strftime("%a, %d %b %Y %H:%M:%S ") + date_time.zone.delete(':')
-
end
-
-
1
def encoded
-
if Utilities.blank?(value)
-
"#{CAPITALIZED_FIELD}: \r\n"
-
else
-
"#{CAPITALIZED_FIELD}: #{info}; #{formatted_date}\r\n"
-
end
-
end
-
-
1
def decoded
-
if Utilities.blank?(value)
-
""
-
else
-
"#{info}; #{formatted_date}"
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = References Field
-
#
-
# The References field inherits references StructuredField and handles the References: header
-
# field in the email.
-
#
-
# Sending references to a mail message will instantiate a Mail::Field object that
-
# has a ReferencesField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# Only one References field can appear in a header, though it can have multiple
-
# Message IDs.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.references = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.references #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:references] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
# mail['references'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
# mail['References'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
#
-
# mail[:references].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
1
require 'mail/fields/common/common_message_id'
-
-
1
module Mail
-
1
class ReferencesField < StructuredField
-
-
1
include CommonMessageId
-
-
1
FIELD_NAME = 'references'
-
1
CAPITALIZED_FIELD = 'References'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = value.join("\r\n\s") if value.is_a?(Array)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Reply-To Field
-
#
-
# The Reply-To field inherits reply-to StructuredField and handles the Reply-To: header
-
# field in the email.
-
#
-
# Sending reply_to to a mail message will instantiate a Mail::Field object that
-
# has a ReplyToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Reply-To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.reply_to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:reply_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
# mail['reply-to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
# mail['Reply-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
#
-
# mail[:reply_to].encoded #=> 'Reply-To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:reply_to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:reply_to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:reply_to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ReplyToField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'reply-to'
-
1
CAPITALIZED_FIELD = 'Reply-To'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Resent-Bcc Field
-
#
-
# The Resent-Bcc field inherits resent-bcc StructuredField and handles the
-
# Resent-Bcc: header field in the email.
-
#
-
# Sending resent_bcc to a mail message will instantiate a Mail::Field object that
-
# has a ResentBccField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Bcc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_bcc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_bcc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
# mail['resent-bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
# mail['Resent-Bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
#
-
# mail[:resent_bcc].encoded #=> 'Resent-Bcc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_bcc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_bcc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_bcc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ResentBccField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'resent-bcc'
-
1
CAPITALIZED_FIELD = 'Resent-Bcc'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Resent-Cc Field
-
#
-
# The Resent-Cc field inherits resent-cc StructuredField and handles the Resent-Cc: header
-
# field in the email.
-
#
-
# Sending resent_cc to a mail message will instantiate a Mail::Field object that
-
# has a ResentCcField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Cc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_cc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_cc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
# mail['resent-cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
# mail['Resent-Cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
#
-
# mail[:resent_cc].encoded #=> 'Resent-Cc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_cc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_cc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_cc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ResentCcField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'resent-cc'
-
1
CAPITALIZED_FIELD = 'Resent-Cc'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# resent-date = "Resent-Date:" date-time CRLF
-
1
require 'mail/fields/common/common_date'
-
-
1
module Mail
-
1
class ResentDateField < StructuredField
-
-
1
include Mail::CommonDate
-
-
1
FIELD_NAME = 'resent-date'
-
1
CAPITALIZED_FIELD = 'Resent-Date'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if Utilities.blank?(value)
-
value = ::DateTime.now.strftime('%a, %d %b %Y %H:%M:%S %z')
-
else
-
value = strip_field(FIELD_NAME, value)
-
value = ::DateTime.parse(value.to_s).strftime('%a, %d %b %Y %H:%M:%S %z')
-
end
-
super(CAPITALIZED_FIELD, value, charset)
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Resent-From Field
-
#
-
# The Resent-From field inherits resent-from StructuredField and handles the Resent-From: header
-
# field in the email.
-
#
-
# Sending resent_from to a mail message will instantiate a Mail::Field object that
-
# has a ResentFromField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-From field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_from = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_from] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
# mail['resent-from'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
# mail['Resent-From'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
#
-
# mail[:resent_from].encoded #=> 'Resent-From: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_from].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_from].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_from].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ResentFromField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'resent-from'
-
1
CAPITALIZED_FIELD = 'Resent-From'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# resent-msg-id = "Resent-Message-ID:" msg-id CRLF
-
1
require 'mail/fields/common/common_message_id'
-
-
1
module Mail
-
1
class ResentMessageIdField < StructuredField
-
-
1
include CommonMessageId
-
-
1
FIELD_NAME = 'resent-message-id'
-
1
CAPITALIZED_FIELD = 'Resent-Message-ID'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def name
-
'Resent-Message-ID'
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Resent-Sender Field
-
#
-
# The Resent-Sender field inherits resent-sender StructuredField and handles the Resent-Sender: header
-
# field in the email.
-
#
-
# Sending resent_sender to a mail message will instantiate a Mail::Field object that
-
# has a ResentSenderField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Sender field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_sender = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_sender #=> ['mikel@test.lindsaar.net']
-
# mail[:resent_sender] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
# mail['resent-sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
# mail['Resent-Sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
#
-
# mail.resent_sender.to_s #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_sender.addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail.resent_sender.formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ResentSenderField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'resent-sender'
-
1
CAPITALIZED_FIELD = 'Resent-Sender'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def addresses
-
[address.address]
-
end
-
-
1
def address
-
address_list.addresses.first
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Resent-To Field
-
#
-
# The Resent-To field inherits resent-to StructuredField and handles the Resent-To: header
-
# field in the email.
-
#
-
# Sending resent_to to a mail message will instantiate a Mail::Field object that
-
# has a ResentToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
# mail['resent-to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
# mail['Resent-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
#
-
# mail[:resent_to].encoded #=> 'Resent-To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ResentToField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'resent-to'
-
1
CAPITALIZED_FIELD = 'Resent-To'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# 4.4.3. REPLY-TO / RESENT-REPLY-TO
-
#
-
# Note: The "Return-Path" field is added by the mail transport
-
# service, at the time of final deliver. It is intended
-
# to identify a path back to the orginator of the mes-
-
# sage. The "Reply-To" field is added by the message
-
# originator and is intended to direct replies.
-
#
-
# trace = [return]
-
# 1*received
-
#
-
# return = "Return-Path:" path CRLF
-
#
-
# path = ([CFWS] "<" ([CFWS] / addr-spec) ">" [CFWS]) /
-
# obs-path
-
#
-
# received = "Received:" name-val-list ";" date-time CRLF
-
#
-
# name-val-list = [CFWS] [name-val-pair *(CFWS name-val-pair)]
-
#
-
# name-val-pair = item-name CFWS item-value
-
#
-
# item-name = ALPHA *(["-"] (ALPHA / DIGIT))
-
#
-
# item-value = 1*angle-addr / addr-spec /
-
# atom / domain / msg-id
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ReturnPathField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'return-path'
-
1
CAPITALIZED_FIELD = 'Return-Path'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
value = nil if value == '<>'
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: <#{address}>\r\n"
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
1
def address
-
addresses.first
-
end
-
-
1
def default
-
address
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = Sender Field
-
#
-
# The Sender field inherits sender StructuredField and handles the Sender: header
-
# field in the email.
-
#
-
# Sending sender to a mail message will instantiate a Mail::Field object that
-
# has a SenderField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Sender field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.sender = 'Mikel Lindsaar <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
# mail[:sender] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
# mail['sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
# mail['Sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
#
-
# mail[:sender].encoded #=> "Sender: Mikel Lindsaar <mikel@test.lindsaar.net>\r\n"
-
# mail[:sender].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>'
-
# mail[:sender].addresses #=> ['mikel@test.lindsaar.net']
-
# mail[:sender].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class SenderField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'sender'
-
1
CAPITALIZED_FIELD = 'Sender'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def addresses
-
[address.address]
-
end
-
-
1
def address
-
address_list.addresses.first
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
1
def default
-
address.address
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require 'mail/fields/common/common_field'
-
-
1
module Mail
-
# Provides access to a structured header field
-
#
-
# ===Per RFC 2822:
-
# 2.2.2. Structured Header Field Bodies
-
#
-
# Some field bodies in this standard have specific syntactical
-
# structure more restrictive than the unstructured field bodies
-
# described above. These are referred to as "structured" field bodies.
-
# Structured field bodies are sequences of specific lexical tokens as
-
# described in sections 3 and 4 of this standard. Many of these tokens
-
# are allowed (according to their syntax) to be introduced or end with
-
# comments (as described in section 3.2.3) as well as the space (SP,
-
# ASCII value 32) and horizontal tab (HTAB, ASCII value 9) characters
-
# (together known as the white space characters, WSP), and those WSP
-
# characters are subject to header "folding" and "unfolding" as
-
# described in section 2.2.3. Semantic analysis of structured field
-
# bodies is given along with their syntax.
-
1
class StructuredField
-
-
1
include Mail::CommonField
-
1
include Mail::Utilities
-
-
1
def initialize(name = nil, value = nil, charset = nil)
-
self.name = name
-
self.value = value
-
self.charset = charset
-
self
-
end
-
-
1
def charset
-
@charset
-
end
-
-
1
def charset=(val)
-
@charset = val
-
end
-
-
1
def default
-
decoded
-
end
-
-
1
def errors
-
[]
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# subject = "Subject:" unstructured CRLF
-
1
module Mail
-
1
class SubjectField < UnstructuredField
-
-
1
FIELD_NAME = 'subject'
-
1
CAPITALIZED_FIELD = "Subject"
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
#
-
# = To Field
-
#
-
# The To field inherits to StructuredField and handles the To: header
-
# field in the email.
-
#
-
# Sending to to a mail message will instantiate a Mail::Field object that
-
# has a ToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
# mail['to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
# mail['To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
#
-
# mail[:to].encoded #=> 'To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ToField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'to'
-
1
CAPITALIZED_FIELD = 'To'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require 'mail/fields/common/common_field'
-
-
1
module Mail
-
# Provides access to an unstructured header field
-
#
-
# ===Per RFC 2822:
-
# 2.2.1. Unstructured Header Field Bodies
-
#
-
# Some field bodies in this standard are defined simply as
-
# "unstructured" (which is specified below as any US-ASCII characters,
-
# except for CR and LF) with no further restrictions. These are
-
# referred to as unstructured field bodies. Semantically, unstructured
-
# field bodies are simply to be treated as a single line of characters
-
# with no further processing (except for header "folding" and
-
# "unfolding" as described in section 2.2.3).
-
1
class UnstructuredField
-
-
1
include Mail::CommonField
-
1
include Mail::Utilities
-
-
1
attr_accessor :charset
-
1
attr_reader :errors
-
-
1
def initialize(name, value, charset = nil)
-
@errors = []
-
-
if value.is_a?(Array)
-
# Probably has arrived here from a failed parse of an AddressList Field
-
value = value.join(', ')
-
else
-
# Ensure we are dealing with a string
-
value = value.to_s
-
end
-
-
if charset
-
self.charset = charset
-
else
-
if value.respond_to?(:encoding)
-
self.charset = value.encoding
-
else
-
self.charset = $KCODE
-
end
-
end
-
self.name = name
-
self.value = value
-
self
-
end
-
-
1
def encoded
-
do_encode
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
1
def default
-
decoded
-
end
-
-
1
def parse # An unstructured field does not parse
-
self
-
end
-
-
1
private
-
-
1
def do_encode
-
value.nil? ? '' : "#{wrapped_value}\r\n"
-
end
-
-
1
def do_decode
-
Utilities.blank?(value) ? nil : Encodings.decode_encode(value, :decode)
-
end
-
-
# 2.2.3. Long Header Fields
-
#
-
# Each header field is logically a single line of characters comprising
-
# the field name, the colon, and the field body. For convenience
-
# however, and to deal with the 998/78 character limitations per line,
-
# the field body portion of a header field can be split into a multiple
-
# line representation; this is called "folding". The general rule is
-
# that wherever this standard allows for folding white space (not
-
# simply WSP characters), a CRLF may be inserted before any WSP. For
-
# example, the header field:
-
#
-
# Subject: This is a test
-
#
-
# can be represented as:
-
#
-
# Subject: This
-
# is a test
-
#
-
# Note: Though structured field bodies are defined in such a way that
-
# folding can take place between many of the lexical tokens (and even
-
# within some of the lexical tokens), folding SHOULD be limited to
-
# placing the CRLF at higher-level syntactic breaks. For instance, if
-
# a field body is defined as comma-separated values, it is recommended
-
# that folding occur after the comma separating the structured items in
-
# preference to other places where the field could be folded, even if
-
# it is allowed elsewhere.
-
1
def wrapped_value # :nodoc:
-
wrap_lines(name, fold("#{name}: ".length))
-
end
-
-
# 6.2. Display of 'encoded-word's
-
#
-
# When displaying a particular header field that contains multiple
-
# 'encoded-word's, any 'linear-white-space' that separates a pair of
-
# adjacent 'encoded-word's is ignored. (This is to allow the use of
-
# multiple 'encoded-word's to represent long strings of unencoded text,
-
# without having to separate 'encoded-word's where spaces occur in the
-
# unencoded text.)
-
1
def wrap_lines(name, folded_lines)
-
result = ["#{name}: #{folded_lines.shift}"]
-
result.concat(folded_lines)
-
result.join("\r\n\s")
-
end
-
-
1
def fold(prepend = 0) # :nodoc:
-
encoding = normalized_encoding
-
decoded_string = decoded.to_s
-
should_encode = decoded_string.not_ascii_only?
-
if should_encode
-
first = true
-
words = decoded_string.split(/[ \t]/).map do |word|
-
if first
-
first = !first
-
else
-
word = " #{word}"
-
end
-
if word.not_ascii_only?
-
word
-
else
-
word.scan(/.{7}|.+$/)
-
end
-
end.flatten
-
else
-
words = decoded_string.split(/[ \t]/)
-
end
-
-
folded_lines = []
-
while !words.empty?
-
limit = 78 - prepend
-
limit = limit - 7 - encoding.length if should_encode
-
line = String.new
-
first_word = true
-
while !words.empty?
-
break unless word = words.first.dup
-
word.encode!(charset) if charset && word.respond_to?(:encode!)
-
word = encode(word) if should_encode
-
word = encode_crlf(word)
-
# Skip to next line if we're going to go past the limit
-
# Unless this is the first word, in which case we're going to add it anyway
-
# Note: This means that a word that's longer than 998 characters is going to break the spec. Please fix if this is a problem for you.
-
# (The fix, it seems, would be to use encoded-word encoding on it, because that way you can break it across multiple lines and
-
# the linebreak will be ignored)
-
break if !line.empty? && (line.length + word.length + 1 > limit)
-
# Remove the word from the queue ...
-
words.shift
-
# Add word separator
-
if first_word
-
first_word = false
-
else
-
line << " " if !should_encode
-
end
-
-
# ... add it in encoded form to the current line
-
line << word
-
end
-
# Encode the line if necessary
-
line = "=?#{encoding}?Q?#{line}?=" if should_encode
-
# Add the line to the output and reset the prepend
-
folded_lines << line
-
prepend = 0
-
end
-
folded_lines
-
end
-
-
1
def encode(value)
-
value = [value].pack(CAPITAL_M).gsub(EQUAL_LF, EMPTY)
-
value.gsub!(/"/, '=22')
-
value.gsub!(/\(/, '=28')
-
value.gsub!(/\)/, '=29')
-
value.gsub!(/\?/, '=3F')
-
value.gsub!(/_/, '=5F')
-
value.gsub!(/ /, '_')
-
value
-
end
-
-
1
def encode_crlf(value)
-
value.gsub!(CR, CR_ENCODED)
-
value.gsub!(LF, LF_ENCODED)
-
value
-
end
-
-
1
def normalized_encoding
-
encoding = charset.to_s.upcase.gsub('_', '-')
-
encoding = 'UTF-8' if encoding == 'UTF8' # Ruby 1.8.x and $KCODE == 'u'
-
encoding
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
-
# Provides access to a header object.
-
#
-
# ===Per RFC2822
-
#
-
# 2.2. Header Fields
-
#
-
# Header fields are lines composed of a field name, followed by a colon
-
# (":"), followed by a field body, and terminated by CRLF. A field
-
# name MUST be composed of printable US-ASCII characters (i.e.,
-
# characters that have values between 33 and 126, inclusive), except
-
# colon. A field body may be composed of any US-ASCII characters,
-
# except for CR and LF. However, a field body may contain CRLF when
-
# used in header "folding" and "unfolding" as described in section
-
# 2.2.3. All field bodies MUST conform to the syntax described in
-
# sections 3 and 4 of this standard.
-
1
class Header
-
1
include Constants
-
1
include Utilities
-
1
include Enumerable
-
-
1
@@maximum_amount = 1000
-
-
# Large amount of headers in Email might create extra high CPU load
-
# Use this parameter to limit number of headers that will be parsed by
-
# mail library.
-
# Default: 1000
-
1
def self.maximum_amount
-
@@maximum_amount
-
end
-
-
1
def self.maximum_amount=(value)
-
@@maximum_amount = value
-
end
-
-
# Creates a new header object.
-
#
-
# Accepts raw text or nothing. If given raw text will attempt to parse
-
# it and split it into the various fields, instantiating each field as
-
# it goes.
-
#
-
# If it finds a field that should be a structured field (such as content
-
# type), but it fails to parse it, it will simply make it an unstructured
-
# field and leave it alone. This will mean that the data is preserved but
-
# no automatic processing of that field will happen. If you find one of
-
# these cases, please make a patch and send it in, or at the least, send
-
# me the example so we can fix it.
-
1
def initialize(header_text = nil, charset = nil)
-
@charset = charset
-
self.raw_source = ::Mail::Utilities.to_crlf(header_text).lstrip
-
split_header if header_text
-
end
-
-
1
def initialize_copy(original)
-
super
-
@fields = @fields.dup
-
end
-
-
# The preserved raw source of the header as you passed it in, untouched
-
# for your Regexing glory.
-
1
def raw_source
-
@raw_source
-
end
-
-
# Returns an array of all the fields in the header in order that they
-
# were read in.
-
1
def fields
-
@fields ||= FieldList.new
-
end
-
-
# 3.6. Field definitions
-
#
-
# It is important to note that the header fields are not guaranteed to
-
# be in a particular order. They may appear in any order, and they
-
# have been known to be reordered occasionally when transported over
-
# the Internet. However, for the purposes of this standard, header
-
# fields SHOULD NOT be reordered when a message is transported or
-
# transformed. More importantly, the trace header fields and resent
-
# header fields MUST NOT be reordered, and SHOULD be kept in blocks
-
# prepended to the message. See sections 3.6.6 and 3.6.7 for more
-
# information.
-
#
-
# Populates the fields container with Field objects in the order it
-
# receives them in.
-
#
-
# Acceps an array of field string values, for example:
-
#
-
# h = Header.new
-
# h.fields = ['From: mikel@me.com', 'To: bob@you.com']
-
1
def fields=(unfolded_fields)
-
@fields = Mail::FieldList.new
-
warn "Warning: more than #{self.class.maximum_amount} header fields only using the first #{self.class.maximum_amount}" if unfolded_fields.length > self.class.maximum_amount
-
unfolded_fields[0..(self.class.maximum_amount-1)].each do |field|
-
-
field = Field.new(field, nil, charset)
-
if limited_field?(field.name) && (selected = select_field_for(field.name)) && selected.any?
-
selected.first.update(field.name, field.value)
-
else
-
@fields << field
-
end
-
end
-
-
end
-
-
1
def errors
-
@fields.map(&:errors).flatten(1)
-
end
-
-
# 3.6. Field definitions
-
#
-
# The following table indicates limits on the number of times each
-
# field may occur in a message header as well as any special
-
# limitations on the use of those fields. An asterisk next to a value
-
# in the minimum or maximum column indicates that a special restriction
-
# appears in the Notes column.
-
#
-
# <snip table from 3.6>
-
#
-
# As per RFC, many fields can appear more than once, we will return a string
-
# of the value if there is only one header, or if there is more than one
-
# matching header, will return an array of values in order that they appear
-
# in the header ordered from top to bottom.
-
#
-
# Example:
-
#
-
# h = Header.new
-
# h.fields = ['To: mikel@me.com', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
-
# h['To'] #=> 'mikel@me.com'
-
# h['X-Mail-SPAM'] #=> ['15', '20']
-
1
def [](name)
-
name = dasherize(name)
-
name.downcase!
-
selected = select_field_for(name)
-
case
-
when selected.length > 1
-
selected.map { |f| f }
-
when !Utilities.blank?(selected)
-
selected.first
-
else
-
nil
-
end
-
end
-
-
# Sets the FIRST matching field in the header to passed value, or deletes
-
# the FIRST field matched from the header if passed nil
-
#
-
# Example:
-
#
-
# h = Header.new
-
# h.fields = ['To: mikel@me.com', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
-
# h['To'] = 'bob@you.com'
-
# h['To'] #=> 'bob@you.com'
-
# h['X-Mail-SPAM'] = '10000'
-
# h['X-Mail-SPAM'] # => ['15', '20', '10000']
-
# h['X-Mail-SPAM'] = nil
-
# h['X-Mail-SPAM'] # => nil
-
1
def []=(name, value)
-
name = dasherize(name)
-
if name.include?(':')
-
raise ArgumentError, "Header names may not contain a colon: #{name.inspect}"
-
end
-
fn = name.downcase
-
selected = select_field_for(fn)
-
-
case
-
# User wants to delete the field
-
when !Utilities.blank?(selected) && value == nil
-
fields.delete_if { |f| selected.include?(f) }
-
-
# User wants to change the field
-
when !Utilities.blank?(selected) && limited_field?(fn)
-
selected.first.update(fn, value)
-
-
# User wants to create the field
-
else
-
# Need to insert in correct order for trace fields
-
self.fields << Field.new(name.to_s, value, charset)
-
end
-
if dasherize(fn) == "content-type"
-
# Update charset if specified in Content-Type
-
params = self[:content_type].parameters rescue nil
-
@charset = params[:charset] if params && params[:charset]
-
end
-
end
-
-
1
def charset
-
@charset
-
end
-
-
1
def charset=(val)
-
params = self[:content_type].parameters rescue nil
-
if params
-
params[:charset] = val
-
end
-
@charset = val
-
end
-
-
1
LIMITED_FIELDS = %w[ date from sender reply-to to cc bcc
-
message-id in-reply-to references subject
-
return-path content-type mime-version
-
content-transfer-encoding content-description
-
content-id content-disposition content-location]
-
-
1
def encoded
-
buffer = String.new
-
buffer.force_encoding('us-ascii') if buffer.respond_to?(:force_encoding)
-
fields.each do |field|
-
buffer << field.encoded
-
end
-
buffer
-
end
-
-
1
def to_s
-
encoded
-
end
-
-
1
def decoded
-
raise NoMethodError, 'Can not decode an entire header as there could be character set conflicts, try calling #decoded on the various fields.'
-
end
-
-
1
def field_summary
-
fields.map { |f| "<#{f.name}: #{f.value}>" }.join(", ")
-
end
-
-
# Returns true if the header has a Message-ID defined (empty or not)
-
1
def has_message_id?
-
!fields.select { |f| f.responsible_for?('Message-ID') }.empty?
-
end
-
-
# Returns true if the header has a Content-ID defined (empty or not)
-
1
def has_content_id?
-
!fields.select { |f| f.responsible_for?('Content-ID') }.empty?
-
end
-
-
# Returns true if the header has a Date defined (empty or not)
-
1
def has_date?
-
!fields.select { |f| f.responsible_for?('Date') }.empty?
-
end
-
-
# Returns true if the header has a MIME version defined (empty or not)
-
1
def has_mime_version?
-
!fields.select { |f| f.responsible_for?('Mime-Version') }.empty?
-
end
-
-
1
private
-
-
1
def raw_source=(val)
-
@raw_source = val
-
end
-
-
# Splits an unfolded and line break cleaned header into individual field
-
# strings.
-
1
def split_header
-
self.fields = raw_source.split(HEADER_SPLIT)
-
end
-
-
1
def select_field_for(name)
-
fields.select { |f| f.responsible_for?(name) }
-
end
-
-
1
def limited_field?(name)
-
LIMITED_FIELDS.include?(name.to_s.downcase)
-
end
-
-
# Enumerable support; yield each field in order to the block if there is one,
-
# or return an Enumerator for them if there isn't.
-
1
def each( &block )
-
return self.fields.each( &block ) if block
-
self.fields.each
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
-
# This is an almost cut and paste from ActiveSupport v3.0.6, copied in here so that Mail
-
# itself does not depend on ActiveSupport to avoid versioning conflicts
-
-
1
module Mail
-
1
class IndifferentHash < Hash
-
-
1
def initialize(constructor = {})
-
if constructor.is_a?(Hash)
-
super()
-
update(constructor)
-
else
-
super(constructor)
-
end
-
end
-
-
1
def default(key = nil)
-
if key.is_a?(Symbol) && include?(key = key.to_s)
-
self[key]
-
else
-
super
-
end
-
end
-
-
1
def self.new_from_hash_copying_default(hash)
-
IndifferentHash.new(hash).tap do |new_hash|
-
new_hash.default = hash.default
-
end
-
end
-
-
1
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
-
1
alias_method :regular_update, :update unless method_defined?(:regular_update)
-
-
# Assigns a new value to the hash:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash[:key] = "value"
-
#
-
1
def []=(key, value)
-
regular_writer(convert_key(key), convert_value(value))
-
end
-
-
1
alias_method :store, :[]=
-
-
# Updates the instantized hash with values from the second:
-
#
-
# hash_1 = HashWithIndifferentAccess.new
-
# hash_1[:key] = "value"
-
#
-
# hash_2 = HashWithIndifferentAccess.new
-
# hash_2[:key] = "New Value!"
-
#
-
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
-
#
-
1
def update(other_hash)
-
other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) }
-
self
-
end
-
-
1
alias_method :merge!, :update
-
-
# Checks the hash for a key matching the argument passed in:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash["key"] = "value"
-
# hash.key? :key # => true
-
# hash.key? "key" # => true
-
#
-
1
def key?(key)
-
super(convert_key(key))
-
end
-
-
1
alias_method :include?, :key?
-
1
alias_method :has_key?, :key?
-
1
alias_method :member?, :key?
-
-
# Fetches the value for the specified key, same as doing hash[key]
-
1
def fetch(key, *extras)
-
super(convert_key(key), *extras)
-
end
-
-
# Returns an array of the values at the specified indices:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash[:a] = "x"
-
# hash[:b] = "y"
-
# hash.values_at("a", "b") # => ["x", "y"]
-
#
-
1
def values_at(*indices)
-
indices.collect {|key| self[convert_key(key)]}
-
end
-
-
# Returns an exact copy of the hash.
-
1
def dup
-
IndifferentHash.new(self)
-
end
-
-
# Merges the instantized and the specified hashes together, giving precedence to the values from the second hash
-
# Does not overwrite the existing hash.
-
1
def merge(hash)
-
self.dup.update(hash)
-
end
-
-
# Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second.
-
# This overloaded definition prevents returning a regular hash, if reverse_merge is called on a HashWithDifferentAccess.
-
1
def reverse_merge(other_hash)
-
super self.class.new_from_hash_copying_default(other_hash)
-
end
-
-
1
def reverse_merge!(other_hash)
-
replace(reverse_merge( other_hash ))
-
end
-
-
# Removes a specified key from the hash.
-
1
def delete(key)
-
super(convert_key(key))
-
end
-
-
1
def stringify_keys!; self end
-
1
def stringify_keys; dup end
-
1
def symbolize_keys; to_hash.symbolize_keys end
-
1
def to_options!; self end
-
-
1
def to_hash
-
Hash.new(default).merge!(self)
-
end
-
-
1
protected
-
-
1
def convert_key(key)
-
key.kind_of?(Symbol) ? key.to_s : key
-
end
-
-
1
def convert_value(value)
-
if value.class == Hash
-
self.class.new_from_hash_copying_default(value)
-
elsif value.is_a?(Array)
-
value.dup.replace(value.map { |e| convert_value(e) })
-
else
-
value
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
-
# Allows you to create a new Mail::Message object.
-
#
-
# You can make an email via passing a string or passing a block.
-
#
-
# For example, the following two examples will create the same email
-
# message:
-
#
-
# Creating via a string:
-
#
-
# string = "To: mikel@test.lindsaar.net\r\n"
-
# string << "From: bob@test.lindsaar.net\r\n"
-
# string << "Subject: This is an email\r\n"
-
# string << "\r\n"
-
# string << "This is the body"
-
# Mail.new(string)
-
#
-
# Or creating via a block:
-
#
-
# message = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'bob@test.lindsaar.net'
-
# subject 'This is an email'
-
# body 'This is the body'
-
# end
-
#
-
# Or creating via a hash (or hash like object):
-
#
-
# message = Mail.new({:to => 'mikel@test.lindsaar.net',
-
# 'from' => 'bob@test.lindsaar.net',
-
# :subject => 'This is an email',
-
# :body => 'This is the body' })
-
#
-
# Note, the hash keys can be strings or symbols, the passed in object
-
# does not need to be a hash, it just needs to respond to :each_pair
-
# and yield each key value pair.
-
#
-
# As a side note, you can also create a new email through creating
-
# a Mail::Message object directly and then passing in values via string,
-
# symbol or direct method calls. See Mail::Message for more information.
-
#
-
# mail = Mail.new
-
# mail.to = 'mikel@test.lindsaar.net'
-
# mail[:from] = 'bob@test.lindsaar.net'
-
# mail['subject'] = 'This is an email'
-
# mail.body = 'This is the body'
-
1
def self.new(*args, &block)
-
Message.new(args, &block)
-
end
-
-
# Sets the default delivery method and retriever method for all new Mail objects.
-
# The delivery_method and retriever_method default to :smtp and :pop3, with defaults
-
# set.
-
#
-
# So sending a new email, if you have an SMTP server running on localhost is
-
# as easy as:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'bob@test.lindsaar.net'
-
# subject 'hi there!'
-
# body 'this is a body'
-
# end
-
#
-
# If you do not specify anything, you will get the following equivalent code set in
-
# every new mail object:
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "localhost",
-
# :port => 25,
-
# :domain => 'localhost.localdomain',
-
# :user_name => nil,
-
# :password => nil,
-
# :authentication => nil,
-
# :enable_starttls_auto => true }
-
#
-
# retriever_method :pop3, { :address => "localhost",
-
# :port => 995,
-
# :user_name => nil,
-
# :password => nil,
-
# :enable_ssl => true }
-
# end
-
#
-
# Mail.delivery_method.new #=> Mail::SMTP instance
-
# Mail.retriever_method.new #=> Mail::POP3 instance
-
#
-
# Each mail object inherits the default set in Mail.delivery_method, however, on
-
# a per email basis, you can override the method:
-
#
-
# mail.delivery_method :sendmail
-
#
-
# Or you can override the method and pass in settings:
-
#
-
# mail.delivery_method :sendmail, { :address => 'some.host' }
-
#
-
# You can also just modify the settings:
-
#
-
# mail.delivery_settings = { :address => 'some.host' }
-
#
-
# The passed in hash is just merged against the defaults with +merge!+ and the result
-
# assigned the mail object. So the above example will change only the :address value
-
# of the global smtp_settings to be 'some.host', keeping all other values
-
1
def self.defaults(&block)
-
Configuration.instance.instance_eval(&block)
-
end
-
-
# Returns the delivery method selected, defaults to an instance of Mail::SMTP
-
1
def self.delivery_method
-
Configuration.instance.delivery_method
-
end
-
-
# Returns the retriever method selected, defaults to an instance of Mail::POP3
-
1
def self.retriever_method
-
Configuration.instance.retriever_method
-
end
-
-
# Send an email using the default configuration. You do need to set a default
-
# configuration first before you use self.deliver, if you don't, an appropriate
-
# error will be raised telling you to.
-
#
-
# If you do not specify a delivery type, SMTP will be used.
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'This is a test email'
-
# body 'Not much to say here'
-
# end
-
#
-
# You can also do:
-
#
-
# mail = Mail.read('email.eml')
-
# mail.deliver!
-
#
-
# And your email object will be created and sent.
-
1
def self.deliver(*args, &block)
-
mail = self.new(args, &block)
-
mail.deliver
-
mail
-
end
-
-
# Find emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.find(*args, &block)
-
retriever_method.find(*args, &block)
-
end
-
-
# Finds and then deletes retrieved emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.find_and_delete(*args, &block)
-
retriever_method.find_and_delete(*args, &block)
-
end
-
-
# Receive the first email(s) from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.first(*args, &block)
-
retriever_method.first(*args, &block)
-
end
-
-
# Receive the first email(s) from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.last(*args, &block)
-
retriever_method.last(*args, &block)
-
end
-
-
# Receive all emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.all(*args, &block)
-
retriever_method.all(*args, &block)
-
end
-
-
# Reads in an email message from a path and instantiates it as a new Mail::Message
-
1
def self.read(filename)
-
self.new(File.open(filename, 'rb') { |f| f.read })
-
end
-
-
# Delete all emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.delete_all(*args, &block)
-
retriever_method.delete_all(*args, &block)
-
end
-
-
# Instantiates a new Mail::Message using a string
-
1
def Mail.read_from_string(mail_as_string)
-
Mail.new(mail_as_string)
-
end
-
-
1
def Mail.connection(&block)
-
retriever_method.connection(&block)
-
end
-
-
# Initialize the observers and interceptors arrays
-
1
@@delivery_notification_observers = []
-
1
@@delivery_interceptors = []
-
-
# You can register an object to be informed of every email that is sent through
-
# this method.
-
#
-
# Your object needs to respond to a single method #delivered_email(mail)
-
# which receives the email that is sent.
-
1
def self.register_observer(observer)
-
unless @@delivery_notification_observers.include?(observer)
-
@@delivery_notification_observers << observer
-
end
-
end
-
-
# Unregister the given observer, allowing mail to resume operations
-
# without it.
-
1
def self.unregister_observer(observer)
-
@@delivery_notification_observers.delete(observer)
-
end
-
-
# You can register an object to be given every mail object that will be sent,
-
# before it is sent. So if you want to add special headers or modify any
-
# email that gets sent through the Mail library, you can do so.
-
#
-
# Your object needs to respond to a single method #delivering_email(mail)
-
# which receives the email that is about to be sent. Make your modifications
-
# directly to this object.
-
1
def self.register_interceptor(interceptor)
-
unless @@delivery_interceptors.include?(interceptor)
-
@@delivery_interceptors << interceptor
-
end
-
end
-
-
# Unregister the given interceptor, allowing mail to resume operations
-
# without it.
-
1
def self.unregister_interceptor(interceptor)
-
@@delivery_interceptors.delete(interceptor)
-
end
-
-
1
def self.inform_observers(mail)
-
@@delivery_notification_observers.each do |observer|
-
observer.delivered_email(mail)
-
end
-
end
-
-
1
def self.inform_interceptors(mail)
-
@@delivery_interceptors.each do |interceptor|
-
interceptor.delivering_email(mail)
-
end
-
end
-
-
1
protected
-
-
1
RANDOM_TAG='%x%x_%x%x%d%x'
-
-
1
def self.random_tag
-
t = Time.now
-
sprintf(RANDOM_TAG,
-
t.to_i, t.tv_usec,
-
$$, Thread.current.object_id.abs, self.uniq, rand(255))
-
end
-
-
1
private
-
-
1
def self.something_random
-
1
(Thread.current.object_id * rand(255) / Time.now.to_f).to_s.slice(-3..-1).to_i
-
end
-
-
1
def self.uniq
-
@@uniq += 1
-
end
-
-
1
@@uniq = self.something_random
-
-
end
-
# frozen_string_literal: true
-
1
module Mail
-
1
module Matchers
-
1
def any_attachment
-
AnyAttachmentMatcher.new
-
end
-
-
1
def an_attachment_with_filename(filename)
-
AttachmentFilenameMatcher.new(filename)
-
end
-
-
1
class AnyAttachmentMatcher
-
1
def ===(other)
-
other.attachment?
-
end
-
end
-
-
1
class AttachmentFilenameMatcher
-
1
attr_reader :filename
-
1
def initialize(filename)
-
@filename = filename
-
end
-
-
1
def ===(other)
-
other.attachment? && other.filename == filename
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
require "yaml"
-
-
1
module Mail
-
# The Message class provides a single point of access to all things to do with an
-
# email message.
-
#
-
# You create a new email message by calling the Mail::Message.new method, or just
-
# Mail.new
-
#
-
# A Message object by default has the following objects inside it:
-
#
-
# * A Header object which contains all information and settings of the header of the email
-
# * Body object which contains all parts of the email that are not part of the header, this
-
# includes any attachments, body text, MIME parts etc.
-
#
-
# ==Per RFC2822
-
#
-
# 2.1. General Description
-
#
-
# At the most basic level, a message is a series of characters. A
-
# message that is conformant with this standard is comprised of
-
# characters with values in the range 1 through 127 and interpreted as
-
# US-ASCII characters [ASCII]. For brevity, this document sometimes
-
# refers to this range of characters as simply "US-ASCII characters".
-
#
-
# Note: This standard specifies that messages are made up of characters
-
# in the US-ASCII range of 1 through 127. There are other documents,
-
# specifically the MIME document series [RFC2045, RFC2046, RFC2047,
-
# RFC2048, RFC2049], that extend this standard to allow for values
-
# outside of that range. Discussion of those mechanisms is not within
-
# the scope of this standard.
-
#
-
# Messages are divided into lines of characters. A line is a series of
-
# characters that is delimited with the two characters carriage-return
-
# and line-feed; that is, the carriage return (CR) character (ASCII
-
# value 13) followed immediately by the line feed (LF) character (ASCII
-
# value 10). (The carriage-return/line-feed pair is usually written in
-
# this document as "CRLF".)
-
#
-
# A message consists of header fields (collectively called "the header
-
# of the message") followed, optionally, by a body. The header is a
-
# sequence of lines of characters with special syntax as defined in
-
# this standard. The body is simply a sequence of characters that
-
# follows the header and is separated from the header by an empty line
-
# (i.e., a line with nothing preceding the CRLF).
-
1
class Message
-
-
1
include Constants
-
1
include Utilities
-
-
# ==Making an email
-
#
-
# You can make an new mail object via a block, passing a string, file or direct assignment.
-
#
-
# ===Making an email via a block
-
#
-
# mail = Mail.new do
-
# from 'mikel@test.lindsaar.net'
-
# to 'you@test.lindsaar.net'
-
# subject 'This is a test email'
-
# body File.read('body.txt')
-
# end
-
#
-
# mail.to_s #=> "From: mikel@test.lindsaar.net\r\nTo: you@...
-
#
-
# ===Making an email via passing a string
-
#
-
# mail = Mail.new("To: mikel@test.lindsaar.net\r\nSubject: Hello\r\n\r\nHi there!")
-
# mail.body.to_s #=> 'Hi there!'
-
# mail.subject #=> 'Hello'
-
# mail.to #=> 'mikel@test.lindsaar.net'
-
#
-
# ===Making an email from a file
-
#
-
# mail = Mail.read('path/to/file.eml')
-
# mail.body.to_s #=> 'Hi there!'
-
# mail.subject #=> 'Hello'
-
# mail.to #=> 'mikel@test.lindsaar.net'
-
#
-
# ===Making an email via assignment
-
#
-
# You can assign values to a mail object via four approaches:
-
#
-
# * Message#field_name=(value)
-
# * Message#field_name(value)
-
# * Message#['field_name']=(value)
-
# * Message#[:field_name]=(value)
-
#
-
# Examples:
-
#
-
# mail = Mail.new
-
# mail['from'] = 'mikel@test.lindsaar.net'
-
# mail[:to] = 'you@test.lindsaar.net'
-
# mail.subject 'This is a test email'
-
# mail.body = 'This is a body'
-
#
-
# mail.to_s #=> "From: mikel@test.lindsaar.net\r\nTo: you@...
-
#
-
1
def initialize(*args, &block)
-
@body = nil
-
@body_raw = nil
-
@separate_parts = false
-
@text_part = nil
-
@html_part = nil
-
@errors = nil
-
@header = nil
-
@charset = self.class.default_charset
-
@defaulted_charset = true
-
-
@smtp_envelope_from = nil
-
@smtp_envelope_to = nil
-
-
@perform_deliveries = true
-
@raise_delivery_errors = true
-
-
@delivery_handler = nil
-
-
@delivery_method = Mail.delivery_method.dup
-
-
@transport_encoding = Mail::Encodings.get_encoding('7bit')
-
-
@mark_for_delete = false
-
-
if args.flatten.first.respond_to?(:each_pair)
-
init_with_hash(args.flatten.first)
-
else
-
init_with_string(args.flatten[0].to_s)
-
end
-
-
if block_given?
-
instance_eval(&block)
-
end
-
-
self
-
end
-
-
# If you assign a delivery handler, mail will call :deliver_mail on the
-
# object you assign to delivery_handler, it will pass itself as the
-
# single argument.
-
#
-
# If you define a delivery_handler, then you are responsible for the
-
# following actions in the delivery cycle:
-
#
-
# * Appending the mail object to Mail.deliveries as you see fit.
-
# * Checking the mail.perform_deliveries flag to decide if you should
-
# actually call :deliver! the mail object or not.
-
# * Checking the mail.raise_delivery_errors flag to decide if you
-
# should raise delivery errors if they occur.
-
# * Actually calling :deliver! (with the bang) on the mail object to
-
# get it to deliver itself.
-
#
-
# A simplest implementation of a delivery_handler would be
-
#
-
# class MyObject
-
#
-
# def initialize
-
# @mail = Mail.new('To: mikel@test.lindsaar.net')
-
# @mail.delivery_handler = self
-
# end
-
#
-
# attr_accessor :mail
-
#
-
# def deliver_mail(mail)
-
# yield
-
# end
-
# end
-
#
-
# Then doing:
-
#
-
# obj = MyObject.new
-
# obj.mail.deliver
-
#
-
# Would cause Mail to call obj.deliver_mail passing itself as a parameter,
-
# which then can just yield and let Mail do its own private do_delivery
-
# method.
-
1
attr_accessor :delivery_handler
-
-
# If set to false, mail will go through the motions of doing a delivery,
-
# but not actually call the delivery method or append the mail object to
-
# the Mail.deliveries collection. Useful for testing.
-
#
-
# Mail.deliveries.size #=> 0
-
# mail.delivery_method :smtp
-
# mail.perform_deliveries = false
-
# mail.deliver # Mail::SMTP not called here
-
# Mail.deliveries.size #=> 0
-
#
-
# If you want to test and query the Mail.deliveries collection to see what
-
# mail you sent, you should set perform_deliveries to true and use
-
# the :test mail delivery_method:
-
#
-
# Mail.deliveries.size #=> 0
-
# mail.delivery_method :test
-
# mail.perform_deliveries = true
-
# mail.deliver
-
# Mail.deliveries.size #=> 1
-
#
-
# This setting is ignored by mail (though still available as a flag) if you
-
# define a delivery_handler
-
1
attr_accessor :perform_deliveries
-
-
# If set to false, mail will silently catch and ignore any exceptions
-
# raised through attempting to deliver an email.
-
#
-
# This setting is ignored by mail (though still available as a flag) if you
-
# define a delivery_handler
-
1
attr_accessor :raise_delivery_errors
-
-
1
def self.default_charset; @@default_charset; end
-
2
def self.default_charset=(charset); @@default_charset = charset; end
-
1
self.default_charset = 'UTF-8'
-
-
1
def register_for_delivery_notification(observer)
-
STDERR.puts("Message#register_for_delivery_notification is deprecated, please call Mail.register_observer instead")
-
Mail.register_observer(observer)
-
end
-
-
1
def inform_observers
-
Mail.inform_observers(self)
-
end
-
-
1
def inform_interceptors
-
Mail.inform_interceptors(self)
-
end
-
-
# Delivers an mail object.
-
#
-
# Examples:
-
#
-
# mail = Mail.read('file.eml')
-
# mail.deliver
-
1
def deliver
-
inform_interceptors
-
if delivery_handler
-
delivery_handler.deliver_mail(self) { do_delivery }
-
else
-
do_delivery
-
end
-
inform_observers
-
self
-
end
-
-
# This method bypasses checking perform_deliveries and raise_delivery_errors,
-
# so use with caution.
-
#
-
# It still however fires off the interceptors and calls the observers callbacks if they are defined.
-
#
-
# Returns self
-
1
def deliver!
-
inform_interceptors
-
response = delivery_method.deliver!(self)
-
inform_observers
-
delivery_method.settings[:return_response] ? response : self
-
end
-
-
1
def delivery_method(method = nil, settings = {})
-
unless method
-
@delivery_method
-
else
-
@delivery_method = Configuration.instance.lookup_delivery_method(method).new(settings)
-
end
-
end
-
-
1
def reply(*args, &block)
-
self.class.new.tap do |reply|
-
if message_id
-
bracketed_message_id = "<#{message_id}>"
-
reply.in_reply_to = bracketed_message_id
-
if !references.nil?
-
refs = [references].flatten.map { |r| "<#{r}>" }
-
refs << bracketed_message_id
-
reply.references = refs.join(' ')
-
elsif !in_reply_to.nil? && !in_reply_to.kind_of?(Array)
-
reply.references = "<#{in_reply_to}> #{bracketed_message_id}"
-
end
-
reply.references ||= bracketed_message_id
-
end
-
if subject
-
reply.subject = subject =~ /^Re:/i ? subject : "RE: #{subject}"
-
end
-
if reply_to || from
-
reply.to = self[reply_to ? :reply_to : :from].to_s
-
end
-
if to
-
reply.from = self[:to].formatted.first.to_s
-
end
-
-
unless args.empty?
-
if args.flatten.first.respond_to?(:each_pair)
-
reply.send(:init_with_hash, args.flatten.first)
-
else
-
reply.send(:init_with_string, args.flatten[0].to_s.strip)
-
end
-
end
-
-
if block_given?
-
reply.instance_eval(&block)
-
end
-
end
-
end
-
-
# Provides the operator needed for sort et al.
-
#
-
# Compares this mail object with another mail object, this is done by date, so an
-
# email that is older than another will appear first.
-
#
-
# Example:
-
#
-
# mail1 = Mail.new do
-
# date(Time.now)
-
# end
-
# mail2 = Mail.new do
-
# date(Time.now - 86400) # 1 day older
-
# end
-
# [mail2, mail1].sort #=> [mail2, mail1]
-
1
def <=>(other)
-
if other.nil?
-
1
-
else
-
self.date <=> other.date
-
end
-
end
-
-
# Two emails are the same if they have the same fields and body contents. One
-
# gotcha here is that Mail will insert Message-IDs when calling encoded, so doing
-
# mail1.encoded == mail2.encoded is most probably not going to return what you think
-
# as the assigned Message-IDs by Mail (if not already defined as the same) will ensure
-
# that the two objects are unique, and this comparison will ALWAYS return false.
-
#
-
# So the == operator has been defined like so: Two messages are the same if they have
-
# the same content, ignoring the Message-ID field, unless BOTH emails have a defined and
-
# different Message-ID value, then they are false.
-
#
-
# So, in practice the == operator works like this:
-
#
-
# m1 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <DIFFERENT@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> false
-
1
def ==(other)
-
return false unless other.respond_to?(:encoded)
-
-
if self.message_id && other.message_id
-
self.encoded == other.encoded
-
else
-
self_message_id, other_message_id = self.message_id, other.message_id
-
begin
-
self.message_id, other.message_id = '<temp@test>', '<temp@test>'
-
self.encoded == other.encoded
-
ensure
-
self.message_id, other.message_id = self_message_id, other_message_id
-
end
-
end
-
end
-
-
1
def initialize_copy(original)
-
super
-
@header = @header.dup
-
end
-
-
# Provides access to the raw source of the message as it was when it
-
# was instantiated. This is set at initialization and so is untouched
-
# by the parsers or decoder / encoders
-
#
-
# Example:
-
#
-
# mail = Mail.new('This is an invalid email message')
-
# mail.raw_source #=> "This is an invalid email message"
-
1
def raw_source
-
@raw_source
-
end
-
-
# Sets the envelope from for the email
-
1
def set_envelope( val )
-
@raw_envelope = val
-
@envelope = Mail::Envelope.new( val )
-
end
-
-
# The raw_envelope is the From mikel@test.lindsaar.net Mon May 2 16:07:05 2009
-
# type field that you can see at the top of any email that has come
-
# from a mailbox
-
1
def raw_envelope
-
@raw_envelope
-
end
-
-
1
def envelope_from
-
@envelope ? @envelope.from : nil
-
end
-
-
1
def envelope_date
-
@envelope ? @envelope.date : nil
-
end
-
-
# Sets the header of the message object.
-
#
-
# Example:
-
#
-
# mail.header = 'To: mikel@test.lindsaar.net\r\nFrom: Bob@bob.com'
-
# mail.header #=> <#Mail::Header
-
1
def header=(value)
-
@header = Mail::Header.new(value, charset)
-
end
-
-
# Returns the header object of the message object. Or, if passed
-
# a parameter sets the value.
-
#
-
# Example:
-
#
-
# mail = Mail::Message.new('To: mikel\r\nFrom: you')
-
# mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...
-
#
-
# mail.header #=> nil
-
# mail.header 'To: mikel\r\nFrom: you'
-
# mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...
-
1
def header(value = nil)
-
value ? self.header = value : @header
-
end
-
-
# Provides a way to set custom headers, by passing in a hash
-
1
def headers(hash = {})
-
hash.each_pair do |k,v|
-
header[k] = v
-
end
-
end
-
-
# Returns a list of parser errors on the header, each field that had an error
-
# will be reparsed as an unstructured field to preserve the data inside, but
-
# will not be used for further processing.
-
#
-
# It returns a nested array of [field_name, value, original_error_message]
-
# per error found.
-
#
-
# Example:
-
#
-
# message = Mail.new("Content-Transfer-Encoding: weirdo\r\n")
-
# message.errors.size #=> 1
-
# message.errors.first[0] #=> "Content-Transfer-Encoding"
-
# message.errors.first[1] #=> "weirdo"
-
# message.errors.first[3] #=> <The original error message exception>
-
#
-
# This is a good first defence on detecting spam by the way. Some spammers send
-
# invalid emails to try and get email parsers to give up parsing them.
-
1
def errors
-
header.errors
-
end
-
-
# Returns the Bcc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc << 'ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def bcc( val = nil )
-
default :bcc, val
-
end
-
-
# Sets the Bcc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def bcc=( val )
-
header[:bcc] = val
-
end
-
-
# Returns the Cc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc << 'ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def cc( val = nil )
-
default :cc, val
-
end
-
-
# Sets the Cc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def cc=( val )
-
header[:cc] = val
-
end
-
-
1
def comments( val = nil )
-
default :comments, val
-
end
-
-
1
def comments=( val )
-
header[:comments] = val
-
end
-
-
1
def content_description( val = nil )
-
default :content_description, val
-
end
-
-
1
def content_description=( val )
-
header[:content_description] = val
-
end
-
-
1
def content_disposition( val = nil )
-
default :content_disposition, val
-
end
-
-
1
def content_disposition=( val )
-
header[:content_disposition] = val
-
end
-
-
1
def content_id( val = nil )
-
default :content_id, val
-
end
-
-
1
def content_id=( val )
-
header[:content_id] = val
-
end
-
-
1
def content_location( val = nil )
-
default :content_location, val
-
end
-
-
1
def content_location=( val )
-
header[:content_location] = val
-
end
-
-
1
def content_transfer_encoding( val = nil )
-
default :content_transfer_encoding, val
-
end
-
-
1
def content_transfer_encoding=( val )
-
header[:content_transfer_encoding] = val
-
end
-
-
1
def content_type( val = nil )
-
default :content_type, val
-
end
-
-
1
def content_type=( val )
-
header[:content_type] = val
-
end
-
-
1
def date( val = nil )
-
default :date, val
-
end
-
-
1
def date=( val )
-
header[:date] = val
-
end
-
-
1
def transport_encoding( val = nil)
-
if val
-
self.transport_encoding = val
-
else
-
@transport_encoding
-
end
-
end
-
-
1
def transport_encoding=( val )
-
@transport_encoding = Mail::Encodings.get_encoding(val)
-
end
-
-
# Returns the From value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from << 'ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def from( val = nil )
-
default :from, val
-
end
-
-
# Sets the From value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def from=( val )
-
header[:from] = val
-
end
-
-
1
def in_reply_to( val = nil )
-
default :in_reply_to, val
-
end
-
-
1
def in_reply_to=( val )
-
header[:in_reply_to] = val
-
end
-
-
1
def keywords( val = nil )
-
default :keywords, val
-
end
-
-
1
def keywords=( val )
-
header[:keywords] = val
-
end
-
-
# Returns the Message-ID of the mail object. Note, per RFC 2822 the Message ID
-
# consists of what is INSIDE the < > usually seen in the mail header, so this method
-
# will return only what is inside.
-
#
-
# Example:
-
#
-
# mail.message_id = '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
#
-
# Also allows you to set the Message-ID by passing a string as a parameter
-
#
-
# mail.message_id '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
1
def message_id( val = nil )
-
default :message_id, val
-
end
-
-
# Sets the Message-ID. Note, per RFC 2822 the Message ID consists of what is INSIDE
-
# the < > usually seen in the mail header, so this method will return only what is inside.
-
#
-
# mail.message_id = '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
1
def message_id=( val )
-
header[:message_id] = val
-
end
-
-
# Returns the MIME version of the email as a string
-
#
-
# Example:
-
#
-
# mail.mime_version = '1.0'
-
# mail.mime_version #=> '1.0'
-
#
-
# Also allows you to set the MIME version by passing a string as a parameter.
-
#
-
# Example:
-
#
-
# mail.mime_version '1.0'
-
# mail.mime_version #=> '1.0'
-
1
def mime_version( val = nil )
-
default :mime_version, val
-
end
-
-
# Sets the MIME version of the email by accepting a string
-
#
-
# Example:
-
#
-
# mail.mime_version = '1.0'
-
# mail.mime_version #=> '1.0'
-
1
def mime_version=( val )
-
header[:mime_version] = val
-
end
-
-
1
def received( val = nil )
-
if val
-
header[:received] = val
-
else
-
header[:received]
-
end
-
end
-
-
1
def received=( val )
-
header[:received] = val
-
end
-
-
1
def references( val = nil )
-
default :references, val
-
end
-
-
1
def references=( val )
-
header[:references] = val
-
end
-
-
# Returns the Reply-To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.reply_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.reply_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to << 'ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def reply_to( val = nil )
-
default :reply_to, val
-
end
-
-
# Sets the Reply-To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def reply_to=( val )
-
header[:reply_to] = val
-
end
-
-
# Returns the Resent-Bcc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc << 'ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_bcc( val = nil )
-
default :resent_bcc, val
-
end
-
-
# Sets the Resent-Bcc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_bcc=( val )
-
header[:resent_bcc] = val
-
end
-
-
# Returns the Resent-Cc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc << 'ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_cc( val = nil )
-
default :resent_cc, val
-
end
-
-
# Sets the Resent-Cc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_cc=( val )
-
header[:resent_cc] = val
-
end
-
-
1
def resent_date( val = nil )
-
default :resent_date, val
-
end
-
-
1
def resent_date=( val )
-
header[:resent_date] = val
-
end
-
-
# Returns the Resent-From value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net']
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_from ['Mikel <mikel@test.lindsaar.net>']
-
# mail.resent_from #=> 'mikel@test.lindsaar.net'
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from << 'ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_from( val = nil )
-
default :resent_from, val
-
end
-
-
# Sets the Resent-From value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net']
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_from=( val )
-
header[:resent_from] = val
-
end
-
-
1
def resent_message_id( val = nil )
-
default :resent_message_id, val
-
end
-
-
1
def resent_message_id=( val )
-
header[:resent_message_id] = val
-
end
-
-
# Returns the Resent-Sender value of the mail object, as a single string of an address
-
# spec. A sender per RFC 2822 must be a single address, so you can not append to
-
# this address.
-
#
-
# Example:
-
#
-
# mail.resent_sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_sender 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
1
def resent_sender( val = nil )
-
default :resent_sender, val
-
end
-
-
# Sets the Resent-Sender value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
1
def resent_sender=( val )
-
header[:resent_sender] = val
-
end
-
-
# Returns the Resent-To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to << 'ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_to( val = nil )
-
default :resent_to, val
-
end
-
-
# Sets the Resent-To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_to=( val )
-
header[:resent_to] = val
-
end
-
-
# Returns the return path of the mail object, or sets it if you pass a string
-
1
def return_path( val = nil )
-
default :return_path, val
-
end
-
-
# Sets the return path of the object
-
1
def return_path=( val )
-
header[:return_path] = val
-
end
-
-
# Returns the Sender value of the mail object, as a single string of an address
-
# spec. A sender per RFC 2822 must be a single address.
-
#
-
# Example:
-
#
-
# mail.sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.sender 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
1
def sender( val = nil )
-
default :sender, val
-
end
-
-
# Sets the Sender value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
1
def sender=( val )
-
header[:sender] = val
-
end
-
-
# Returns the SMTP Envelope From value of the mail object, as a single
-
# string of an address spec.
-
#
-
# Defaults to Return-Path, Sender, or the first From address.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
1
def smtp_envelope_from( val = nil )
-
if val
-
self.smtp_envelope_from = val
-
else
-
@smtp_envelope_from || return_path || sender || from_addrs.first
-
end
-
end
-
-
# Sets the From address on the SMTP Envelope.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
1
def smtp_envelope_from=( val )
-
@smtp_envelope_from = val
-
end
-
-
# Returns the SMTP Envelope To value of the mail object.
-
#
-
# Defaults to #destinations: To, Cc, and Bcc addresses.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_to #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to ['Mikel <mikel@test.lindsaar.net>', 'Lindsaar <lindsaar@test.lindsaar.net>']
-
# mail.smtp_envelope_to #=> ['mikel@test.lindsaar.net', 'lindsaar@test.lindsaar.net']
-
1
def smtp_envelope_to( val = nil )
-
if val
-
self.smtp_envelope_to = val
-
else
-
@smtp_envelope_to || destinations
-
end
-
end
-
-
# Sets the To addresses on the SMTP Envelope.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_to #=> 'mikel@test.lindsaar.net'
-
#
-
# mail.smtp_envelope_to = ['Mikel <mikel@test.lindsaar.net>', 'Lindsaar <lindsaar@test.lindsaar.net>']
-
# mail.smtp_envelope_to #=> ['mikel@test.lindsaar.net', 'lindsaar@test.lindsaar.net']
-
1
def smtp_envelope_to=( val )
-
@smtp_envelope_to =
-
case val
-
when Array, NilClass
-
val
-
else
-
[val]
-
end
-
end
-
-
# Returns the decoded value of the subject field, as a single string.
-
#
-
# Example:
-
#
-
# mail.subject = "G'Day mate"
-
# mail.subject #=> "G'Day mate"
-
# mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
-
# mail.subject #=> "This is あ string"
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.subject "G'Day mate"
-
# mail.subject #=> "G'Day mate"
-
1
def subject( val = nil )
-
default :subject, val
-
end
-
-
# Sets the Subject value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
-
# mail.subject #=> "This is あ string"
-
1
def subject=( val )
-
header[:subject] = val
-
end
-
-
# Returns the To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to << 'ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def to( val = nil )
-
default :to, val
-
end
-
-
# Sets the To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def to=( val )
-
header[:to] = val
-
end
-
-
# Returns the default value of the field requested as a symbol.
-
#
-
# Each header field has a :default method which returns the most common use case for
-
# that field, for example, the date field types will return a DateTime object when
-
# sent :default, the subject, or unstructured fields will return a decoded string of
-
# their value, the address field types will return a single addr_spec or an array of
-
# addr_specs if there is more than one.
-
1
def default( sym, val = nil )
-
if val
-
header[sym] = val
-
else
-
header[sym].default if header[sym]
-
end
-
end
-
-
# Sets the body object of the message object.
-
#
-
# Example:
-
#
-
# mail.body = 'This is the body'
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...
-
#
-
# You can also reset the body of an Message object by setting body to nil
-
#
-
# Example:
-
#
-
# mail.body = 'this is the body'
-
# mail.body.encoded #=> 'this is the body'
-
# mail.body = nil
-
# mail.body.encoded #=> ''
-
#
-
# If you try and set the body of an email that is a multipart email, then instead
-
# of deleting all the parts of your email, mail will add a text/plain part to
-
# your email:
-
#
-
# mail.add_file 'somefilename.png'
-
# mail.parts.length #=> 1
-
# mail.body = "This is a body"
-
# mail.parts.length #=> 2
-
# mail.parts.last.content_type.content_type #=> 'This is a body'
-
1
def body=(value)
-
body_lazy(value)
-
end
-
-
# Returns the body of the message object. Or, if passed
-
# a parameter sets the value.
-
#
-
# Example:
-
#
-
# mail = Mail::Message.new('To: mikel\r\n\r\nThis is the body')
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...
-
#
-
# mail.body 'This is another body'
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is anothe...
-
1
def body(value = nil)
-
if value
-
self.body = value
-
# add_encoding_to_body
-
else
-
process_body_raw if @body_raw
-
@body
-
end
-
end
-
-
1
def body_encoding(value)
-
if value.nil?
-
body.encoding
-
else
-
body.encoding = value
-
end
-
end
-
-
1
def body_encoding=(value)
-
body.encoding = value
-
end
-
-
# Returns the list of addresses this message should be sent to by
-
# collecting the addresses off the to, cc and bcc fields.
-
#
-
# Example:
-
#
-
# mail.to = 'mikel@test.lindsaar.net'
-
# mail.cc = 'sam@test.lindsaar.net'
-
# mail.bcc = 'bob@test.lindsaar.net'
-
# mail.destinations.length #=> 3
-
# mail.destinations.first #=> 'mikel@test.lindsaar.net'
-
1
def destinations
-
[to_addrs, cc_addrs, bcc_addrs].compact.flatten
-
end
-
-
# Returns an array of addresses (the encoded value) in the From field,
-
# if no From field, returns an empty array
-
1
def from_addrs
-
from ? [from].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the To field,
-
# if no To field, returns an empty array
-
1
def to_addrs
-
to ? [to].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the Cc field,
-
# if no Cc field, returns an empty array
-
1
def cc_addrs
-
cc ? [cc].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the Bcc field,
-
# if no Bcc field, returns an empty array
-
1
def bcc_addrs
-
bcc ? [bcc].flatten : []
-
end
-
-
# Allows you to add an arbitrary header
-
#
-
# Example:
-
#
-
# mail['foo'] = '1234'
-
# mail['foo'].to_s #=> '1234'
-
1
def []=(name, value)
-
if name.to_s == 'body'
-
self.body = value
-
elsif name.to_s =~ /content[-_]type/i
-
header[name] = value
-
elsif name.to_s == 'charset'
-
self.charset = value
-
else
-
header[name] = value
-
end
-
end
-
-
# Allows you to read an arbitrary header
-
#
-
# Example:
-
#
-
# mail['foo'] = '1234'
-
# mail['foo'].to_s #=> '1234'
-
1
def [](name)
-
header[underscoreize(name)]
-
end
-
-
# Method Missing in this implementation allows you to set any of the
-
# standard fields directly as you would the "to", "subject" etc.
-
#
-
# Those fields used most often (to, subject et al) are given their
-
# own method for ease of documentation and also to avoid the hook
-
# call to method missing.
-
#
-
# This will only catch the known fields listed in:
-
#
-
# Mail::Field::KNOWN_FIELDS
-
#
-
# as per RFC 2822, any ruby string or method name could pretty much
-
# be a field name, so we don't want to just catch ANYTHING sent to
-
# a message object and interpret it as a header.
-
#
-
# This method provides all three types of header call to set, read
-
# and explicitly set with the = operator
-
#
-
# Examples:
-
#
-
# mail.comments = 'These are some comments'
-
# mail.comments #=> 'These are some comments'
-
#
-
# mail.comments 'These are other comments'
-
# mail.comments #=> 'These are other comments'
-
#
-
#
-
# mail.date = 'Tue, 1 Jul 2003 10:52:37 +0200'
-
# mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
-
#
-
# mail.date 'Tue, 1 Jul 2003 10:52:37 +0200'
-
# mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
-
#
-
#
-
# mail.resent_msg_id = '<1234@resent_msg_id.lindsaar.net>'
-
# mail.resent_msg_id #=> '<1234@resent_msg_id.lindsaar.net>'
-
#
-
# mail.resent_msg_id '<4567@resent_msg_id.lindsaar.net>'
-
# mail.resent_msg_id #=> '<4567@resent_msg_id.lindsaar.net>'
-
1
def method_missing(name, *args, &block)
-
#:nodoc:
-
# Only take the structured fields, as we could take _anything_ really
-
# as it could become an optional field... "but therin lies the dark side"
-
field_name = underscoreize(name).chomp("=")
-
if Mail::Field::KNOWN_FIELDS.include?(field_name)
-
if args.empty?
-
header[field_name]
-
else
-
header[field_name] = args.first
-
end
-
else
-
super # otherwise pass it on
-
end
-
#:startdoc:
-
end
-
-
# Returns an FieldList of all the fields in the header in the order that
-
# they appear in the header
-
1
def header_fields
-
header.fields
-
end
-
-
# Returns true if the message has a message ID field, the field may or may
-
# not have a value, but the field exists or not.
-
1
def has_message_id?
-
header.has_message_id?
-
end
-
-
# Returns true if the message has a Date field, the field may or may
-
# not have a value, but the field exists or not.
-
1
def has_date?
-
header.has_date?
-
end
-
-
# Returns true if the message has a Mime-Version field, the field may or may
-
# not have a value, but the field exists or not.
-
1
def has_mime_version?
-
header.has_mime_version?
-
end
-
-
1
def has_content_type?
-
tmp = header[:content_type].main_type rescue nil
-
!!tmp
-
end
-
-
1
def has_charset?
-
tmp = header[:content_type].parameters rescue nil
-
!!(has_content_type? && tmp && tmp['charset'])
-
end
-
-
1
def has_content_transfer_encoding?
-
header[:content_transfer_encoding] && Utilities.blank?(header[:content_transfer_encoding].errors)
-
end
-
-
1
def has_transfer_encoding? # :nodoc:
-
STDERR.puts(":has_transfer_encoding? is deprecated in Mail 1.4.3. Please use has_content_transfer_encoding?\n#{caller}")
-
has_content_transfer_encoding?
-
end
-
-
# Creates a new empty Message-ID field and inserts it in the correct order
-
# into the Header. The MessageIdField object will automatically generate
-
# a unique message ID if you try and encode it or output it to_s without
-
# specifying a message id.
-
#
-
# It will preserve the message ID you specify if you do.
-
1
def add_message_id(msg_id_val = '')
-
header['message-id'] = msg_id_val
-
end
-
-
# Creates a new empty Date field and inserts it in the correct order
-
# into the Header. The DateField object will automatically generate
-
# DateTime.now's date if you try and encode it or output it to_s without
-
# specifying a date yourself.
-
#
-
# It will preserve any date you specify if you do.
-
1
def add_date(date_val = '')
-
header['date'] = date_val
-
end
-
-
# Creates a new empty Mime Version field and inserts it in the correct order
-
# into the Header. The MimeVersion object will automatically generate
-
# set itself to '1.0' if you try and encode it or output it to_s without
-
# specifying a version yourself.
-
#
-
# It will preserve any date you specify if you do.
-
1
def add_mime_version(ver_val = '')
-
header['mime-version'] = ver_val
-
end
-
-
# Adds a content type and charset if the body is US-ASCII
-
#
-
# Otherwise raises a warning
-
1
def add_content_type
-
header[:content_type] = 'text/plain'
-
end
-
-
# Adds a content type and charset if the body is US-ASCII
-
#
-
# Otherwise raises a warning
-
1
def add_charset
-
if !body.empty?
-
# Only give a warning if this isn't an attachment, has non US-ASCII and the user
-
# has not specified an encoding explicitly.
-
if @defaulted_charset && body.raw_source.not_ascii_only? && !self.attachment?
-
warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n"
-
STDERR.puts(warning)
-
end
-
header[:content_type].parameters['charset'] = @charset
-
end
-
end
-
-
# Adds a content transfer encoding
-
#
-
# Otherwise raises a warning
-
1
def add_content_transfer_encoding
-
if body.only_us_ascii?
-
header[:content_transfer_encoding] = '7bit'
-
else
-
warning = "Non US-ASCII detected and no content-transfer-encoding defined.\nDefaulting to 8bit, set your own if this is incorrect.\n"
-
STDERR.puts(warning)
-
header[:content_transfer_encoding] = '8bit'
-
end
-
end
-
-
1
def add_transfer_encoding # :nodoc:
-
STDERR.puts(":add_transfer_encoding is deprecated in Mail 1.4.3. Please use add_content_transfer_encoding\n#{caller}")
-
add_content_transfer_encoding
-
end
-
-
1
def transfer_encoding # :nodoc:
-
STDERR.puts(":transfer_encoding is deprecated in Mail 1.4.3. Please use content_transfer_encoding\n#{caller}")
-
content_transfer_encoding
-
end
-
-
# Returns the MIME media type of part we are on, this is taken from the content-type header
-
1
def mime_type
-
has_content_type? ? header[:content_type].string : nil rescue nil
-
end
-
-
1
def message_content_type
-
STDERR.puts(":message_content_type is deprecated in Mail 1.4.3. Please use mime_type\n#{caller}")
-
mime_type
-
end
-
-
# Returns the character set defined in the content type field
-
1
def charset
-
if @header
-
has_content_type? ? content_type_parameters['charset'] : @charset
-
else
-
@charset
-
end
-
end
-
-
# Sets the charset to the supplied value.
-
1
def charset=(value)
-
@defaulted_charset = false
-
@charset = value
-
@header.charset = value
-
end
-
-
# Returns the main content type
-
1
def main_type
-
has_content_type? ? header[:content_type].main_type : nil rescue nil
-
end
-
-
# Returns the sub content type
-
1
def sub_type
-
has_content_type? ? header[:content_type].sub_type : nil rescue nil
-
end
-
-
# Returns the content type parameters
-
1
def mime_parameters
-
STDERR.puts(':mime_parameters is deprecated in Mail 1.4.3, please use :content_type_parameters instead')
-
content_type_parameters
-
end
-
-
# Returns the content type parameters
-
1
def content_type_parameters
-
has_content_type? ? header[:content_type].parameters : nil rescue nil
-
end
-
-
# Returns true if the message is multipart
-
1
def multipart?
-
has_content_type? ? !!(main_type =~ /^multipart$/i) : false
-
end
-
-
# Returns true if the message is a multipart/report
-
1
def multipart_report?
-
multipart? && sub_type =~ /^report$/i
-
end
-
-
# Returns true if the message is a multipart/report; report-type=delivery-status;
-
1
def delivery_status_report?
-
multipart_report? && content_type_parameters['report-type'] =~ /^delivery-status$/i
-
end
-
-
# returns the part in a multipart/report email that has the content-type delivery-status
-
1
def delivery_status_part
-
@delivery_stats_part ||= parts.select { |p| p.delivery_status_report_part? }.first
-
end
-
-
1
def bounced?
-
delivery_status_part and delivery_status_part.bounced?
-
end
-
-
1
def action
-
delivery_status_part and delivery_status_part.action
-
end
-
-
1
def final_recipient
-
delivery_status_part and delivery_status_part.final_recipient
-
end
-
-
1
def error_status
-
delivery_status_part and delivery_status_part.error_status
-
end
-
-
1
def diagnostic_code
-
delivery_status_part and delivery_status_part.diagnostic_code
-
end
-
-
1
def remote_mta
-
delivery_status_part and delivery_status_part.remote_mta
-
end
-
-
1
def retryable?
-
delivery_status_part and delivery_status_part.retryable?
-
end
-
-
# Returns the current boundary for this message part
-
1
def boundary
-
content_type_parameters ? content_type_parameters['boundary'] : nil
-
end
-
-
# Returns a parts list object of all the parts in the message
-
1
def parts
-
body.parts
-
end
-
-
# Returns an AttachmentsList object, which holds all of the attachments in
-
# the receiver object (either the entire email or a part within) and all
-
# of its descendants.
-
#
-
# It also allows you to add attachments to the mail object directly, like so:
-
#
-
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
-
#
-
# If you do this, then Mail will take the file name and work out the MIME media type
-
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
-
# base64 encode the contents of the attachment all for you.
-
#
-
# You can also specify overrides if you want by passing a hash instead of a string:
-
#
-
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
-
# :content => File.read('/path/to/filename.jpg')}
-
#
-
# If you want to use a different encoding than Base64, you can pass an encoding in,
-
# but then it is up to you to pass in the content pre-encoded, and don't expect
-
# Mail to know how to decode this data:
-
#
-
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
-
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
-
# :encoding => 'SpecialEncoding',
-
# :content => file_content }
-
#
-
# You can also search for specific attachments:
-
#
-
# # By Filename
-
# mail.attachments['filename.jpg'] #=> Mail::Part object or nil
-
#
-
# # or by index
-
# mail.attachments[0] #=> Mail::Part (first attachment)
-
#
-
1
def attachments
-
parts.attachments
-
end
-
-
1
def has_attachments?
-
!attachments.empty?
-
end
-
-
# Accessor for html_part
-
1
def html_part(&block)
-
if block_given?
-
self.html_part = Mail::Part.new(:content_type => 'text/html', &block)
-
else
-
@html_part || find_first_mime_type('text/html')
-
end
-
end
-
-
# Accessor for text_part
-
1
def text_part(&block)
-
if block_given?
-
self.text_part = Mail::Part.new(:content_type => 'text/plain', &block)
-
else
-
@text_part || find_first_mime_type('text/plain')
-
end
-
end
-
-
# Helper to add a html part to a multipart/alternative email. If this and
-
# text_part are both defined in a message, then it will be a multipart/alternative
-
# message and set itself that way.
-
1
def html_part=(msg)
-
# Assign the html part and set multipart/alternative if there's a text part.
-
if msg
-
msg = Mail::Part.new(:body => msg) unless msg.kind_of?(Mail::Message)
-
-
@html_part = msg
-
@html_part.content_type = 'text/html' unless @html_part.has_content_type?
-
add_multipart_alternate_header if text_part
-
add_part @html_part
-
-
# If nil, delete the html part and back out of multipart/alternative.
-
elsif @html_part
-
parts.delete_if { |p| p.object_id == @html_part.object_id }
-
@html_part = nil
-
if text_part
-
self.content_type = nil
-
body.boundary = nil
-
end
-
end
-
end
-
-
# Helper to add a text part to a multipart/alternative email. If this and
-
# html_part are both defined in a message, then it will be a multipart/alternative
-
# message and set itself that way.
-
1
def text_part=(msg)
-
# Assign the text part and set multipart/alternative if there's an html part.
-
if msg
-
msg = Mail::Part.new(:body => msg) unless msg.kind_of?(Mail::Message)
-
-
@text_part = msg
-
@text_part.content_type = 'text/plain' unless @text_part.has_content_type?
-
add_multipart_alternate_header if html_part
-
add_part @text_part
-
-
# If nil, delete the text part and back out of multipart/alternative.
-
elsif @text_part
-
parts.delete_if { |p| p.object_id == @text_part.object_id }
-
@text_part = nil
-
if html_part
-
self.content_type = nil
-
body.boundary = nil
-
end
-
end
-
end
-
-
# Adds a part to the parts list or creates the part list
-
1
def add_part(part)
-
if !body.multipart? && !Utilities.blank?(self.body.decoded)
-
@text_part = Mail::Part.new('Content-Type: text/plain;')
-
@text_part.body = body.decoded
-
self.body << @text_part
-
add_multipart_alternate_header
-
end
-
add_boundary
-
self.body << part
-
end
-
-
# Allows you to add a part in block form to an existing mail message object
-
#
-
# Example:
-
#
-
# mail = Mail.new do
-
# part :content_type => "multipart/alternative", :content_disposition => "inline" do |p|
-
# p.part :content_type => "text/plain", :body => "test text\nline #2"
-
# p.part :content_type => "text/html", :body => "<b>test</b> HTML<br/>\nline #2"
-
# end
-
# end
-
1
def part(params = {})
-
new_part = Part.new(params)
-
yield new_part if block_given?
-
add_part(new_part)
-
end
-
-
# Adds a file to the message. You have two options with this method, you can
-
# just pass in the absolute path to the file you want and Mail will read the file,
-
# get the filename from the path you pass in and guess the MIME media type, or you
-
# can pass in the filename as a string, and pass in the file content as a blob.
-
#
-
# Example:
-
#
-
# m = Mail.new
-
# m.add_file('/path/to/filename.png')
-
#
-
# m = Mail.new
-
# m.add_file(:filename => 'filename.png', :content => File.read('/path/to/file.jpg'))
-
#
-
# Note also that if you add a file to an existing message, Mail will convert that message
-
# to a MIME multipart email, moving whatever plain text body you had into its own text
-
# plain part.
-
#
-
# Example:
-
#
-
# m = Mail.new do
-
# body 'this is some text'
-
# end
-
# m.multipart? #=> false
-
# m.add_file('/path/to/filename.png')
-
# m.multipart? #=> true
-
# m.parts.first.content_type.content_type #=> 'text/plain'
-
# m.parts.last.content_type.content_type #=> 'image/png'
-
#
-
# See also #attachments
-
1
def add_file(values)
-
convert_to_multipart unless self.multipart? || Utilities.blank?(self.body.decoded)
-
add_multipart_mixed_header
-
if values.is_a?(String)
-
basename = File.basename(values)
-
filedata = File.open(values, 'rb') { |f| f.read }
-
else
-
basename = values[:filename]
-
filedata = values
-
unless filedata[:content]
-
filedata = values.merge(:content=>File.open(values[:filename], 'rb') { |f| f.read })
-
end
-
end
-
self.attachments[basename] = filedata
-
end
-
-
1
def convert_to_multipart
-
text = body.decoded
-
self.body = ''
-
text_part = Mail::Part.new({:content_type => 'text/plain;',
-
:body => text})
-
text_part.charset = charset unless @defaulted_charset
-
self.body << text_part
-
end
-
-
# Encodes the message, calls encode on all its parts, gets an email message
-
# ready to send
-
1
def ready_to_send!
-
identify_and_set_transfer_encoding
-
parts.sort!([ "text/plain", "text/enriched", "text/html", "multipart/alternative" ])
-
parts.each do |part|
-
part.transport_encoding = transport_encoding
-
part.ready_to_send!
-
end
-
add_required_fields
-
end
-
-
1
def encode!
-
STDERR.puts("Deprecated in 1.1.0 in favour of :ready_to_send! as it is less confusing with encoding and decoding.")
-
ready_to_send!
-
end
-
-
# Outputs an encoded string representation of the mail message including
-
# all headers, attachments, etc. This is an encoded email in US-ASCII,
-
# so it is able to be directly sent to an email server.
-
1
def encoded
-
ready_to_send!
-
buffer = header.encoded
-
buffer << "\r\n"
-
buffer << body.encoded(content_transfer_encoding)
-
buffer
-
end
-
-
1
def without_attachments!
-
return self unless has_attachments?
-
-
parts.delete_if { |p| p.attachment? }
-
body_raw = if parts.empty?
-
''
-
else
-
body.encoded
-
end
-
-
@body = Mail::Body.new(body_raw)
-
-
self
-
end
-
-
1
def to_yaml(opts = {})
-
hash = {}
-
hash['headers'] = {}
-
header.fields.each do |field|
-
hash['headers'][field.name] = field.value
-
end
-
hash['delivery_handler'] = delivery_handler.to_s if delivery_handler
-
hash['transport_encoding'] = transport_encoding.to_s
-
special_variables = [:@header, :@delivery_handler, :@transport_encoding]
-
if multipart?
-
hash['multipart_body'] = []
-
body.parts.map { |part| hash['multipart_body'] << part.to_yaml }
-
special_variables.push(:@body, :@text_part, :@html_part)
-
end
-
(instance_variables.map(&:to_sym) - special_variables).each do |var|
-
hash[var.to_s] = instance_variable_get(var)
-
end
-
hash.to_yaml(opts)
-
end
-
-
1
def self.from_yaml(str)
-
hash = YAML.load(str)
-
m = self.new(:headers => hash['headers'])
-
hash.delete('headers')
-
hash.each do |k,v|
-
case
-
when k == 'delivery_handler'
-
begin
-
m.delivery_handler = Object.const_get(v) unless Utilities.blank?(v)
-
rescue NameError
-
end
-
when k == 'transport_encoding'
-
m.transport_encoding(v)
-
when k == 'multipart_body'
-
v.map {|part| m.add_part Mail::Part.from_yaml(part) }
-
when k =~ /^@/
-
m.instance_variable_set(k.to_sym, v)
-
end
-
end
-
m
-
end
-
-
1
def self.from_hash(hash)
-
Mail::Message.new(hash)
-
end
-
-
1
def to_s
-
encoded
-
end
-
-
1
def inspect
-
"#<#{self.class}:#{self.object_id}, Multipart: #{multipart?}, Headers: #{header.field_summary}>"
-
end
-
-
1
def decoded
-
case
-
when self.text?
-
decode_body_as_text
-
when self.attachment?
-
decode_body
-
when !self.multipart?
-
body.decoded
-
else
-
raise NoMethodError, 'Can not decode an entire message, try calling #decoded on the various fields and body or parts if it is a multipart message.'
-
end
-
end
-
-
1
def read
-
if self.attachment?
-
decode_body
-
else
-
raise NoMethodError, 'Can not call read on a part unless it is an attachment.'
-
end
-
end
-
-
1
def decode_body
-
body.decoded
-
end
-
-
# Returns true if this part is an attachment,
-
# false otherwise.
-
1
def attachment?
-
!!find_attachment
-
end
-
-
# Returns the attachment data if there is any
-
1
def attachment
-
@attachment
-
end
-
-
# Returns the filename of the attachment
-
1
def filename
-
find_attachment
-
end
-
-
1
def all_parts
-
parts.map { |p| [p, p.all_parts] }.flatten
-
end
-
-
1
def find_first_mime_type(mt)
-
all_parts.detect { |p| p.mime_type == mt && !p.attachment? }
-
end
-
-
# Skips the deletion of this message. All other messages
-
# flagged for delete still will be deleted at session close (i.e. when
-
# #find exits). Only has an effect if you're using #find_and_delete
-
# or #find with :delete_after_find set to true.
-
1
def skip_deletion
-
@mark_for_delete = false
-
end
-
-
# Sets whether this message should be deleted at session close (i.e.
-
# after #find). Message will only be deleted if messages are retrieved
-
# using the #find_and_delete method, or by calling #find with
-
# :delete_after_find set to true.
-
1
def mark_for_delete=(value = true)
-
@mark_for_delete = value
-
end
-
-
# Returns whether message will be marked for deletion.
-
# If so, the message will be deleted at session close (i.e. after #find
-
# exits), but only if also using the #find_and_delete method, or by
-
# calling #find with :delete_after_find set to true.
-
#
-
# Side-note: Just to be clear, this method will return true even if
-
# the message hasn't yet been marked for delete on the mail server.
-
# However, if this method returns true, it *will be* marked on the
-
# server after each block yields back to #find or #find_and_delete.
-
1
def is_marked_for_delete?
-
return @mark_for_delete
-
end
-
-
1
def text?
-
has_content_type? ? !!(main_type =~ /^text$/i) : false
-
end
-
-
1
private
-
-
1
HEADER_SEPARATOR = /#{CRLF}#{CRLF}|#{CRLF}#{WSP}*#{CRLF}(?!#{WSP})/m
-
-
# 2.1. General Description
-
# A message consists of header fields (collectively called "the header
-
# of the message") followed, optionally, by a body. The header is a
-
# sequence of lines of characters with special syntax as defined in
-
# this standard. The body is simply a sequence of characters that
-
# follows the header and is separated from the header by an empty line
-
# (i.e., a line with nothing preceding the CRLF).
-
#
-
# Additionally, I allow for the case where someone might have put whitespace
-
# on the "gap line"
-
1
def parse_message
-
header_part, body_part = raw_source.lstrip.split(HEADER_SEPARATOR, 2)
-
self.header = header_part
-
self.body = body_part
-
end
-
-
1
def raw_source=(value)
-
value = value.dup.force_encoding(Encoding::BINARY) if RUBY_VERSION >= "1.9.1"
-
@raw_source = ::Mail::Utilities.to_crlf(value)
-
end
-
-
# see comments to body=. We take data and process it lazily
-
1
def body_lazy(value)
-
process_body_raw if @body_raw && value
-
case
-
when value == nil || value.length<=0
-
@body = Mail::Body.new('')
-
@body_raw = nil
-
add_encoding_to_body
-
when @body && @body.multipart?
-
@body << Mail::Part.new(value)
-
add_encoding_to_body
-
else
-
@body_raw = value
-
# process_body_raw
-
end
-
end
-
-
-
1
def process_body_raw
-
@body = Mail::Body.new(@body_raw)
-
@body_raw = nil
-
separate_parts if @separate_parts
-
-
add_encoding_to_body
-
end
-
-
1
def set_envelope_header
-
raw_string = raw_source.to_s
-
if match_data = raw_source.to_s.match(/\AFrom\s(#{TEXT}+)#{CRLF}/m)
-
set_envelope(match_data[1])
-
self.raw_source = raw_string.sub(match_data[0], "")
-
end
-
end
-
-
1
def separate_parts
-
body.split!(boundary)
-
end
-
-
1
def add_encoding_to_body
-
if has_content_transfer_encoding?
-
@body.encoding = content_transfer_encoding
-
end
-
end
-
-
1
def identify_and_set_transfer_encoding
-
if body && body.multipart?
-
self.content_transfer_encoding = @transport_encoding
-
else
-
self.content_transfer_encoding = body.get_best_encoding(@transport_encoding)
-
end
-
end
-
-
1
def add_required_fields
-
add_required_message_fields
-
add_multipart_mixed_header if body.multipart?
-
add_content_type unless has_content_type?
-
add_charset if text? && !has_charset?
-
add_content_transfer_encoding unless has_content_transfer_encoding?
-
end
-
-
1
def add_required_message_fields
-
add_date unless has_date?
-
add_mime_version unless has_mime_version?
-
add_message_id unless has_message_id?
-
end
-
-
1
def add_multipart_alternate_header
-
header['content-type'] = ContentTypeField.with_boundary('multipart/alternative').value
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
-
1
def add_boundary
-
unless body.boundary && boundary
-
header['content-type'] = 'multipart/mixed' unless header['content-type']
-
header['content-type'].parameters[:boundary] = ContentTypeField.generate_boundary
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
end
-
-
1
def add_multipart_mixed_header
-
unless header['content-type']
-
header['content-type'] = ContentTypeField.with_boundary('multipart/mixed').value
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
end
-
-
1
def init_with_hash(hash)
-
passed_in_options = IndifferentHash.new(hash)
-
self.raw_source = ''
-
-
@header = Mail::Header.new
-
@body = Mail::Body.new
-
@body_raw = nil
-
-
# We need to store the body until last, as we need all headers added first
-
body_content = nil
-
-
passed_in_options.each_pair do |k,v|
-
k = underscoreize(k).to_sym if k.class == String
-
if k == :headers
-
self.headers(v)
-
elsif k == :body
-
body_content = v
-
else
-
self[k] = v
-
end
-
end
-
-
if body_content
-
self.body = body_content
-
if has_content_transfer_encoding?
-
body.encoding = content_transfer_encoding
-
end
-
end
-
end
-
-
1
def init_with_string(string)
-
self.raw_source = string
-
set_envelope_header
-
parse_message
-
@separate_parts = multipart?
-
end
-
-
# Returns the filename of the attachment (if it exists) or returns nil
-
1
def find_attachment
-
content_type_name = header[:content_type].filename rescue nil
-
content_disp_name = header[:content_disposition].filename rescue nil
-
content_loc_name = header[:content_location].location rescue nil
-
case
-
when content_type && content_type_name
-
filename = content_type_name
-
when content_disposition && content_disp_name
-
filename = content_disp_name
-
when content_location && content_loc_name
-
filename = content_loc_name
-
else
-
filename = nil
-
end
-
filename = Mail::Encodings.decode_encode(filename, :decode) if filename rescue filename
-
filename
-
end
-
-
1
def do_delivery
-
begin
-
if perform_deliveries
-
delivery_method.deliver!(self)
-
end
-
rescue => e # Net::SMTP errors or sendmail pipe errors
-
raise e if raise_delivery_errors
-
end
-
end
-
-
1
def decode_body_as_text
-
Encodings.transcode_charset decode_body, charset, 'UTF-8'
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'mail/network/retriever_methods/base'
-
-
1
module Mail
-
1
register_autoload :SMTP, 'mail/network/delivery_methods/smtp'
-
1
register_autoload :FileDelivery, 'mail/network/delivery_methods/file_delivery'
-
1
register_autoload :Sendmail, 'mail/network/delivery_methods/sendmail'
-
1
register_autoload :Exim, 'mail/network/delivery_methods/exim'
-
1
register_autoload :SMTPConnection, 'mail/network/delivery_methods/smtp_connection'
-
1
register_autoload :TestMailer, 'mail/network/delivery_methods/test_mailer'
-
-
1
register_autoload :POP3, 'mail/network/retriever_methods/pop3'
-
1
register_autoload :IMAP, 'mail/network/retriever_methods/imap'
-
1
register_autoload :TestRetriever, 'mail/network/retriever_methods/test_retriever'
-
end
-
# frozen_string_literal: true
-
1
require 'mail/check_delivery_params'
-
-
1
module Mail
-
# FileDelivery class delivers emails into multiple files based on the destination
-
# address. Each file is appended to if it already exists.
-
#
-
# So if you have an email going to fred@test, bob@test, joe@anothertest, and you
-
# set your location path to /path/to/mails then FileDelivery will create the directory
-
# if it does not exist, and put one copy of the email in three files, called
-
# by their message id
-
#
-
# Make sure the path you specify with :location is writable by the Ruby process
-
# running Mail.
-
1
class FileDelivery
-
1
if RUBY_VERSION >= '1.9.1'
-
1
require 'fileutils'
-
else
-
require 'ftools'
-
end
-
-
1
attr_accessor :settings
-
-
1
def initialize(values)
-
self.settings = { :location => './mails' }.merge!(values)
-
end
-
-
1
def deliver!(mail)
-
Mail::CheckDeliveryParams.check(mail)
-
-
if ::File.respond_to?(:makedirs)
-
::File.makedirs settings[:location]
-
else
-
::FileUtils.mkdir_p settings[:location]
-
end
-
-
mail.destinations.uniq.each do |to|
-
::File.open(::File.join(settings[:location], File.basename(to.to_s)), 'a') { |f| "#{f.write(mail.encoded)}\r\n\r\n" }
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'mail/check_delivery_params'
-
-
1
module Mail
-
# A delivery method implementation which sends via sendmail.
-
#
-
# To use this, first find out where the sendmail binary is on your computer,
-
# if you are on a mac or unix box, it is usually in /usr/sbin/sendmail, this will
-
# be your sendmail location.
-
#
-
# Mail.defaults do
-
# delivery_method :sendmail
-
# end
-
#
-
# Or if your sendmail binary is not at '/usr/sbin/sendmail'
-
#
-
# Mail.defaults do
-
# delivery_method :sendmail, :location => '/absolute/path/to/your/sendmail'
-
# end
-
#
-
# Then just deliver the email as normal:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# Or by calling deliver on a Mail message
-
#
-
# mail = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# mail.deliver!
-
1
class Sendmail
-
1
DEFAULTS = {
-
:location => '/usr/sbin/sendmail',
-
:arguments => '-i'
-
}
-
-
1
attr_accessor :settings
-
-
1
def initialize(values)
-
self.settings = self.class::DEFAULTS.merge(values)
-
end
-
-
1
def deliver!(mail)
-
smtp_from, smtp_to, message = Mail::CheckDeliveryParams.check(mail)
-
-
from = "-f #{self.class.shellquote(smtp_from)}"
-
to = smtp_to.map { |_to| self.class.shellquote(_to) }.join(' ')
-
-
arguments = "#{settings[:arguments]} #{from} --"
-
self.class.call(settings[:location], arguments, to, message)
-
end
-
-
1
def self.call(path, arguments, destinations, encoded_message)
-
popen "#{path} #{arguments} #{destinations}" do |io|
-
io.puts ::Mail::Utilities.to_lf(encoded_message)
-
io.flush
-
end
-
end
-
-
1
if RUBY_VERSION < '1.9.0'
-
def self.popen(command, &block)
-
IO.popen "#{command} 2>&1", 'w+', &block
-
end
-
else
-
1
def self.popen(command, &block)
-
IO.popen command, 'w+', :err => :out, &block
-
end
-
end
-
-
# The following is an adaptation of ruby 1.9.2's shellwords.rb file,
-
# it is modified to include '+' in the allowed list to allow for
-
# sendmail to accept email addresses as the sender with a + in them.
-
1
def self.shellquote(address)
-
# Process as a single byte sequence because not all shell
-
# implementations are multibyte aware.
-
#
-
# A LF cannot be escaped with a backslash because a backslash + LF
-
# combo is regarded as line continuation and simply ignored. Strip it.
-
escaped = address.gsub(/([^A-Za-z0-9_\s\+\-.,:\/@])/n, "\\\\\\1").gsub("\n", '')
-
%("#{escaped}")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'mail/check_delivery_params'
-
-
1
module Mail
-
# == Sending Email with SMTP
-
#
-
# Mail allows you to send emails using SMTP. This is done by wrapping Net::SMTP in
-
# an easy to use manner.
-
#
-
# === Sending via SMTP server on Localhost
-
#
-
# Sending locally (to a postfix or sendmail server running on localhost) requires
-
# no special setup. Just to Mail.deliver &block or message.deliver! and it will
-
# be sent in this method.
-
#
-
# === Sending via MobileMe
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "smtp.me.com",
-
# :port => 587,
-
# :domain => 'your.host.name',
-
# :user_name => '<username>',
-
# :password => '<password>',
-
# :authentication => 'plain',
-
# :enable_starttls_auto => true }
-
# end
-
#
-
# === Sending via GMail
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "smtp.gmail.com",
-
# :port => 587,
-
# :domain => 'your.host.name',
-
# :user_name => '<username>',
-
# :password => '<password>',
-
# :authentication => 'plain',
-
# :enable_starttls_auto => true }
-
# end
-
#
-
# === Certificate verification
-
#
-
# When using TLS, some mail servers provide certificates that are self-signed
-
# or whose names do not exactly match the hostname given in the address.
-
# OpenSSL will reject these by default. The best remedy is to use the correct
-
# hostname or update the certificate authorities trusted by your ruby. If
-
# that isn't possible, you can control this behavior with
-
# an :openssl_verify_mode setting. Its value may be either an OpenSSL
-
# verify mode constant (OpenSSL::SSL::VERIFY_NONE), or a string containing
-
# the name of an OpenSSL verify mode (none, peer, client_once,
-
# fail_if_no_peer_cert).
-
#
-
# === Others
-
#
-
# Feel free to send me other examples that were tricky
-
#
-
# === Delivering the email
-
#
-
# Once you have the settings right, sending the email is done by:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# Or by calling deliver on a Mail message
-
#
-
# mail = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# mail.deliver!
-
1
class SMTP
-
1
attr_accessor :settings
-
-
1
def initialize(values)
-
self.settings = { :address => "localhost",
-
:port => 25,
-
:domain => 'localhost.localdomain',
-
:user_name => nil,
-
:password => nil,
-
:authentication => nil,
-
:enable_starttls_auto => true,
-
:openssl_verify_mode => nil,
-
:ssl => nil,
-
:tls => nil
-
}.merge!(values)
-
end
-
-
# Send the message via SMTP.
-
# The from and to attributes are optional. If not set, they are retrieve from the Message.
-
1
def deliver!(mail)
-
smtp_from, smtp_to, message = Mail::CheckDeliveryParams.check(mail)
-
-
smtp = Net::SMTP.new(settings[:address], settings[:port])
-
if settings[:tls] || settings[:ssl]
-
if smtp.respond_to?(:enable_tls)
-
smtp.enable_tls(ssl_context)
-
end
-
elsif settings[:enable_starttls_auto]
-
if smtp.respond_to?(:enable_starttls_auto)
-
smtp.enable_starttls_auto(ssl_context)
-
end
-
end
-
-
response = nil
-
smtp.start(settings[:domain], settings[:user_name], settings[:password], settings[:authentication]) do |smtp_obj|
-
response = smtp_obj.sendmail(message, smtp_from, smtp_to)
-
end
-
-
if settings[:return_response]
-
response
-
else
-
self
-
end
-
end
-
-
1
private
-
-
# Allow SSL context to be configured via settings, for Ruby >= 1.9
-
# Just returns openssl verify mode for Ruby 1.8.x
-
1
def ssl_context
-
openssl_verify_mode = settings[:openssl_verify_mode]
-
-
if openssl_verify_mode.kind_of?(String)
-
openssl_verify_mode = "OpenSSL::SSL::VERIFY_#{openssl_verify_mode.upcase}".constantize
-
end
-
-
context = Net::SMTP.default_ssl_context
-
context.verify_mode = openssl_verify_mode
-
context.ca_path = settings[:ca_path] if settings[:ca_path]
-
context.ca_file = settings[:ca_file] if settings[:ca_file]
-
context
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'mail/check_delivery_params'
-
-
1
module Mail
-
# The TestMailer is a bare bones mailer that does nothing. It is useful
-
# when you are testing.
-
#
-
# It also provides a template of the minimum methods you require to implement
-
# if you want to make a custom mailer for Mail
-
1
class TestMailer
-
# Provides a store of all the emails sent with the TestMailer so you can check them.
-
1
def self.deliveries
-
@@deliveries ||= []
-
end
-
-
# Allows you to over write the default deliveries store from an array to some
-
# other object. If you just want to clear the store,
-
# call TestMailer.deliveries.clear.
-
#
-
# If you place another object here, please make sure it responds to:
-
#
-
# * << (message)
-
# * clear
-
# * length
-
# * size
-
# * and other common Array methods
-
1
def self.deliveries=(val)
-
18
@@deliveries = val
-
end
-
-
1
attr_accessor :settings
-
-
1
def initialize(values)
-
@settings = values.dup
-
end
-
-
1
def deliver!(mail)
-
Mail::CheckDeliveryParams.check(mail)
-
Mail::TestMailer.deliveries << mail
-
end
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
-
1
module Mail
-
-
1
class Retriever
-
-
# Get the oldest received email(s)
-
#
-
# Possible options:
-
# count: number of emails to retrieve. The default value is 1.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
1
def first(options = {}, &block)
-
options ||= {}
-
options[:what] = :first
-
options[:count] ||= 1
-
find(options, &block)
-
end
-
-
# Get the most recent received email(s)
-
#
-
# Possible options:
-
# count: number of emails to retrieve. The default value is 1.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
1
def last(options = {}, &block)
-
options ||= {}
-
options[:what] = :last
-
options[:count] ||= 1
-
find(options, &block)
-
end
-
-
# Get all emails.
-
#
-
# Possible options:
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
1
def all(options = {}, &block)
-
options ||= {}
-
options[:count] = :all
-
find(options, &block)
-
end
-
-
# Find emails in the mailbox, and then deletes them. Without any options, the
-
# five last received emails are returned.
-
#
-
# Possible options:
-
# what: last or first emails. The default is :first.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
# count: number of emails to retrieve. The default value is 10. A value of 1 returns an
-
# instance of Message, not an array of Message instances.
-
# delete_after_find: flag for whether to delete each retreived email after find. Default
-
# is true. Call #find if you would like this to default to false.
-
#
-
1
def find_and_delete(options = {}, &block)
-
options ||= {}
-
options[:delete_after_find] ||= true
-
find(options, &block)
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
1
class Part < Message
-
-
# Creates a new empty Content-ID field and inserts it in the correct order
-
# into the Header. The ContentIdField object will automatically generate
-
# a unique content ID if you try and encode it or output it to_s without
-
# specifying a content id.
-
#
-
# It will preserve the content ID you specify if you do.
-
1
def add_content_id(content_id_val = '')
-
header['content-id'] = content_id_val
-
end
-
-
# Returns true if the part has a content ID field, the field may or may
-
# not have a value, but the field exists or not.
-
1
def has_content_id?
-
header.has_content_id?
-
end
-
-
1
def inline_content_id
-
# TODO: Deprecated in 2.2.2 - Remove in 2.3
-
STDERR.puts("Part#inline_content_id is deprecated, please call Part#cid instead")
-
cid
-
end
-
-
1
def cid
-
add_content_id unless has_content_id?
-
uri_escape(unbracket(content_id))
-
end
-
-
1
def url
-
"cid:#{cid}"
-
end
-
-
1
def inline?
-
header[:content_disposition].disposition_type == 'inline' if header[:content_disposition].respond_to?(:disposition_type)
-
end
-
-
1
def add_required_fields
-
super
-
add_content_id if !has_content_id? && inline?
-
end
-
-
1
def add_required_message_fields
-
# Override so we don't add Date, MIME-Version, or Message-ID.
-
end
-
-
1
def delivery_status_report_part?
-
(main_type =~ /message/i && sub_type =~ /delivery-status/i) && body =~ /Status:/
-
end
-
-
1
def delivery_status_data
-
delivery_status_report_part? ? parse_delivery_status_report : {}
-
end
-
-
1
def bounced?
-
if action.is_a?(Array)
-
!!(action.first =~ /failed/i)
-
else
-
!!(action =~ /failed/i)
-
end
-
end
-
-
-
# Either returns the action if the message has just a single report, or an
-
# array of all the actions, one for each report
-
1
def action
-
get_return_values('action')
-
end
-
-
1
def final_recipient
-
get_return_values('final-recipient')
-
end
-
-
1
def error_status
-
get_return_values('status')
-
end
-
-
1
def diagnostic_code
-
get_return_values('diagnostic-code')
-
end
-
-
1
def remote_mta
-
get_return_values('remote-mta')
-
end
-
-
1
def retryable?
-
!(error_status =~ /^5/)
-
end
-
-
1
private
-
-
1
def get_return_values(key)
-
if delivery_status_data[key].is_a?(Array)
-
delivery_status_data[key].map { |a| a.value }
-
elsif !delivery_status_data[key].nil?
-
delivery_status_data[key].value
-
else
-
nil
-
end
-
end
-
-
# A part may not have a header.... so, just init a body if no header
-
1
def parse_message
-
header_part, body_part = raw_source.split(/#{CRLF}#{WSP}*#{CRLF}/m, 2)
-
if header_part =~ HEADER_LINE
-
self.header = header_part
-
self.body = body_part
-
else
-
self.header = "Content-Type: text/plain\r\n"
-
self.body = raw_source
-
end
-
end
-
-
1
def parse_delivery_status_report
-
@delivery_status_data ||= Header.new(body.to_s.gsub("\r\n\r\n", "\r\n"))
-
end
-
-
end
-
-
end
-
# frozen_string_literal: true
-
1
require 'delegate'
-
-
1
module Mail
-
1
class PartsList < DelegateClass(Array)
-
1
attr_reader :parts
-
-
1
def initialize(*args)
-
@parts = Array.new(*args)
-
super @parts
-
end
-
-
# The #encode_with and #to_yaml methods are just implemented
-
# for the sake of backward compatibility ; the delegator does
-
# not correctly delegate these calls to the delegated object
-
1
def encode_with(coder) # :nodoc:
-
coder.represent_object(nil, @parts)
-
end
-
-
1
def to_yaml(options = {}) # :nodoc:
-
@parts.to_yaml(options)
-
end
-
-
1
def attachments
-
Mail::AttachmentsList.new(@parts)
-
end
-
-
1
def collect
-
if block_given?
-
ary = PartsList.new
-
each { |o| ary << yield(o) }
-
ary
-
else
-
to_a
-
end
-
end
-
1
alias_method :map, :collect
-
-
1
def map!
-
raise NoMethodError, "#map! is not defined, please call #collect and create a new PartsList"
-
end
-
-
1
def collect!
-
raise NoMethodError, "#collect! is not defined, please call #collect and create a new PartsList"
-
end
-
-
1
def sort
-
self.class.new(@parts.sort)
-
end
-
-
1
def sort!(order)
-
# stable sort should be used to maintain the relative order as the parts are added
-
i = 0;
-
sorted = @parts.sort_by do |a|
-
# OK, 10000 is arbitrary... if anyone actually wants to explicitly sort 10000 parts of a
-
# single email message... please show me a use case and I'll put more work into this method,
-
# in the meantime, it works :)
-
[get_order_value(a, order), i += 1]
-
end
-
@parts.clear
-
sorted.each { |p| @parts << p }
-
end
-
-
1
private
-
-
1
def get_order_value(part, order)
-
if part.respond_to?(:content_type) && !part[:content_type].nil?
-
order.index(part[:content_type].string.downcase) || 10000
-
else
-
10000
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
1
module Mail
-
1
module Utilities
-
-
1
LF = "\n"
-
1
CRLF = "\r\n"
-
-
1
include Constants
-
-
# Returns true if the string supplied is free from characters not allowed as an ATOM
-
1
def atom_safe?( str )
-
not ATOM_UNSAFE === str
-
end
-
-
# If the string supplied has ATOM unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
1
def quote_atom( str )
-
atom_safe?( str ) ? str : dquote(str)
-
end
-
-
# If the string supplied has PHRASE unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
1
def quote_phrase( str )
-
if RUBY_VERSION >= '1.9'
-
original_encoding = str.encoding
-
ascii_str = str.dup.force_encoding('ASCII-8BIT')
-
if (PHRASE_UNSAFE === ascii_str)
-
dquote(ascii_str).force_encoding(original_encoding)
-
else
-
str
-
end
-
else
-
(PHRASE_UNSAFE === str) ? dquote(str) : str
-
end
-
end
-
-
# Returns true if the string supplied is free from characters not allowed as a TOKEN
-
1
def token_safe?( str )
-
not TOKEN_UNSAFE === str
-
end
-
-
# If the string supplied has TOKEN unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
1
def quote_token( str )
-
token_safe?( str ) ? str : dquote(str)
-
end
-
-
# Wraps supplied string in double quotes and applies \-escaping as necessary,
-
# unless it is already wrapped.
-
#
-
# Example:
-
#
-
# string = 'This is a string'
-
# dquote(string) #=> '"This is a string"'
-
#
-
# string = 'This is "a string"'
-
# dquote(string #=> '"This is \"a string\"'
-
1
def dquote( str )
-
'"' + unquote(str).gsub(/[\\"]/n) {|s| '\\' + s } + '"'
-
end
-
-
# Unwraps supplied string from inside double quotes and
-
# removes any \-escaping.
-
#
-
# Example:
-
#
-
# string = '"This is a string"'
-
# unquote(string) #=> 'This is a string'
-
#
-
# string = '"This is \"a string\""'
-
# unqoute(string) #=> 'This is "a string"'
-
1
def unquote( str )
-
if str =~ /^"(.*?)"$/
-
unescape($1)
-
else
-
str
-
end
-
end
-
-
# Removes any \-escaping.
-
#
-
# Example:
-
#
-
# string = 'This is \"a string\"'
-
# unescape(string) #=> 'This is "a string"'
-
#
-
# string = '"This is \"a string\""'
-
# unescape(string) #=> '"This is "a string""'
-
1
def unescape( str )
-
str.gsub(/\\(.)/, '\1')
-
end
-
1
module_function :unescape
-
-
# Wraps a string in parenthesis and escapes any that are in the string itself.
-
#
-
# Example:
-
#
-
# paren( 'This is a string' ) #=> '(This is a string)'
-
1
def paren( str )
-
RubyVer.paren( str )
-
end
-
-
# Unwraps a string from being wrapped in parenthesis
-
#
-
# Example:
-
#
-
# str = '(This is a string)'
-
# unparen( str ) #=> 'This is a string'
-
1
def unparen( str )
-
match = str.match(/^\((.*?)\)$/)
-
match ? match[1] : str
-
end
-
-
# Wraps a string in angle brackets and escapes any that are in the string itself
-
#
-
# Example:
-
#
-
# bracket( 'This is a string' ) #=> '<This is a string>'
-
1
def bracket( str )
-
RubyVer.bracket( str )
-
end
-
-
# Unwraps a string from being wrapped in parenthesis
-
#
-
# Example:
-
#
-
# str = '<This is a string>'
-
# unbracket( str ) #=> 'This is a string'
-
1
def unbracket( str )
-
match = str.match(/^\<(.*?)\>$/)
-
match ? match[1] : str
-
end
-
-
# Escape parenthesies in a string
-
#
-
# Example:
-
#
-
# str = 'This is (a) string'
-
# escape_paren( str ) #=> 'This is \(a\) string'
-
1
def escape_paren( str )
-
RubyVer.escape_paren( str )
-
end
-
-
1
def uri_escape( str )
-
uri_parser.escape(str)
-
end
-
-
1
def uri_unescape( str )
-
uri_parser.unescape(str)
-
end
-
-
1
def uri_parser
-
@uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI
-
end
-
-
# Matches two objects with their to_s values case insensitively
-
#
-
# Example:
-
#
-
# obj2 = "This_is_An_object"
-
# obj1 = :this_IS_an_object
-
# match_to_s( obj1, obj2 ) #=> true
-
1
def match_to_s( obj1, obj2 )
-
obj1.to_s.casecmp(obj2.to_s) == 0
-
end
-
-
# Capitalizes a string that is joined by hyphens correctly.
-
#
-
# Example:
-
#
-
# string = 'resent-from-field'
-
# capitalize_field( string ) #=> 'Resent-From-Field'
-
1
def capitalize_field( str )
-
str.to_s.split("-").map { |v| v.capitalize }.join("-")
-
end
-
-
# Takes an underscored word and turns it into a class name
-
#
-
# Example:
-
#
-
# constantize("hello") #=> "Hello"
-
# constantize("hello-there") #=> "HelloThere"
-
# constantize("hello-there-mate") #=> "HelloThereMate"
-
1
def constantize( str )
-
str.to_s.split(/[-_]/).map { |v| v.capitalize }.to_s
-
end
-
-
# Swaps out all underscores (_) for hyphens (-) good for stringing from symbols
-
# a field name.
-
#
-
# Example:
-
#
-
# string = :resent_from_field
-
# dasherize ( string ) #=> 'resent_from_field'
-
1
def dasherize( str )
-
str.to_s.tr(UNDERSCORE, HYPHEN)
-
end
-
-
# Swaps out all hyphens (-) for underscores (_) good for stringing to symbols
-
# a field name.
-
#
-
# Example:
-
#
-
# string = :resent_from_field
-
# underscoreize ( string ) #=> 'resent_from_field'
-
1
def underscoreize( str )
-
6
str.to_s.downcase.tr(HYPHEN, UNDERSCORE)
-
end
-
-
1
if RUBY_VERSION <= '1.8.6'
-
-
def map_lines( str, &block )
-
results = []
-
str.each_line do |line|
-
results << yield(line)
-
end
-
results
-
end
-
-
def map_with_index( enum, &block )
-
results = []
-
enum.each_with_index do |token, i|
-
results[i] = yield(token, i)
-
end
-
results
-
end
-
-
else
-
-
1
def map_lines( str, &block )
-
str.each_line.map(&block)
-
end
-
-
1
def map_with_index( enum, &block )
-
enum.each_with_index.map(&block)
-
end
-
-
end
-
-
# Test String#encode works correctly with line endings.
-
# Some versions of Ruby (e.g. MRI <1.9, JRuby, Rubinius) line ending
-
# normalization does not work correctly or did not have #encode.
-
1
if ("\r".encode(:universal_newline => true) rescue nil) == LF &&
-
2
(LF.encode(:crlf_newline => true) rescue nil) == CRLF
-
# Using String#encode is better performing than Regexp
-
-
1
def self.to_lf(input)
-
input.kind_of?(String) ? input.to_str.encode(input.encoding, :universal_newline => true) : ''
-
end
-
-
1
def self.to_crlf(input)
-
input.kind_of?(String) ? input.to_str.encode(input.encoding, :universal_newline => true).encode!(input.encoding, :crlf_newline => true) : ''
-
end
-
-
else
-
-
def self.to_lf(input)
-
input.kind_of?(String) ? input.to_str.gsub(/\r\n|\r/, LF) : ''
-
end
-
-
if RUBY_VERSION >= '1.9'
-
# This 1.9 only regex can save a reasonable amount of time (~20%)
-
# by not matching "\r\n" so the string is returned unchanged in
-
# the common case.
-
CRLF_REGEX = Regexp.new("(?<!\r)\n|\r(?!\n)")
-
else
-
CRLF_REGEX = /\n|\r\n|\r/
-
end
-
-
def self.to_crlf(input)
-
input.kind_of?(String) ? input.to_str.gsub(CRLF_REGEX, CRLF) : ''
-
end
-
-
end
-
-
# Returns true if the object is considered blank.
-
# A blank includes things like '', ' ', nil,
-
# and arrays and hashes that have nothing in them.
-
#
-
# This logic is mostly shared with ActiveSupport's blank?
-
1
def self.blank?(value)
-
if value.kind_of?(NilClass)
-
true
-
elsif value.kind_of?(String)
-
value !~ /\S/
-
else
-
value.respond_to?(:empty?) ? value.empty? : !value
-
end
-
end
-
-
end
-
end
-
# frozen_string_literal: true
-
1
module Mail
-
1
module VERSION
-
-
1
MAJOR = 2
-
1
MINOR = 6
-
1
PATCH = 6
-
1
BUILD = nil
-
-
1
STRING = [MAJOR, MINOR, PATCH, BUILD].compact.join('.')
-
-
1
def self.version
-
STRING
-
end
-
-
end
-
end
-
# encoding: utf-8
-
# frozen_string_literal: true
-
-
1
module Mail
-
1
class Ruby19
-
1
class StrictCharsetEncoder
-
1
def encode(string, charset)
-
string.force_encoding(Mail::Ruby19.pick_encoding(charset))
-
end
-
end
-
-
1
class BestEffortCharsetEncoder
-
1
def encode(string, charset)
-
string.force_encoding(pick_encoding(charset))
-
end
-
-
1
private
-
-
1
def pick_encoding(charset)
-
charset = case charset
-
when /ansi_x3.110-1983/
-
'ISO-8859-1'
-
when /Windows-?1258/i # Windows-1258 is similar to 1252
-
"Windows-1252"
-
else
-
charset
-
end
-
Mail::Ruby19.pick_encoding(charset)
-
end
-
end
-
-
1
class << self
-
1
attr_accessor :charset_encoder
-
end
-
1
self.charset_encoder = StrictCharsetEncoder.new
-
-
# Escapes any parenthesis in a string that are unescaped this uses
-
# a Ruby 1.9.1 regexp feature of negative look behind
-
1
def Ruby19.escape_paren( str )
-
re = /(?<!\\)([\(\)])/ # Only match unescaped parens
-
str.gsub(re) { |s| '\\' + s }
-
end
-
-
1
def Ruby19.paren( str )
-
str = $1 if str =~ /^\((.*)?\)$/
-
str = escape_paren( str )
-
'(' + str + ')'
-
end
-
-
1
def Ruby19.escape_bracket( str )
-
re = /(?<!\\)([\<\>])/ # Only match unescaped brackets
-
str.gsub(re) { |s| '\\' + s }
-
end
-
-
1
def Ruby19.bracket( str )
-
str = $1 if str =~ /^\<(.*)?\>$/
-
str = escape_bracket( str )
-
'<' + str + '>'
-
end
-
-
1
def Ruby19.decode_base64(str)
-
if !str.end_with?("=") && str.length % 4 != 0
-
str = str.ljust((str.length + 3) & ~3, "=")
-
end
-
str.unpack( 'm' ).first
-
end
-
-
1
def Ruby19.encode_base64(str)
-
[str].pack( 'm' )
-
end
-
-
1
def Ruby19.has_constant?(klass, string)
-
klass.const_defined?( string, false )
-
end
-
-
1
def Ruby19.get_constant(klass, string)
-
klass.const_get( string )
-
end
-
-
1
def Ruby19.transcode_charset(str, from_encoding, to_encoding = Encoding::UTF_8)
-
charset_encoder.encode(str.dup, from_encoding).encode(to_encoding, :undef => :replace, :invalid => :replace, :replace => '')
-
end
-
-
1
def Ruby19.b_value_encode(str, encoding = nil)
-
encoding = str.encoding.to_s
-
[Ruby19.encode_base64(str), encoding]
-
end
-
-
1
def Ruby19.b_value_decode(str)
-
match = str.match(/\=\?(.+)?\?[Bb]\?(.*)\?\=/m)
-
if match
-
charset = match[1]
-
str = Ruby19.decode_base64(match[2])
-
str = charset_encoder.encode(str, charset)
-
end
-
decoded = str.encode(Encoding::UTF_8, :invalid => :replace, :replace => "")
-
decoded.valid_encoding? ? decoded : decoded.encode(Encoding::UTF_16LE, :invalid => :replace, :replace => "").encode(Encoding::UTF_8)
-
rescue Encoding::UndefinedConversionError, ArgumentError, Encoding::ConverterNotFoundError
-
warn "Encoding conversion failed #{$!}"
-
str.dup.force_encoding(Encoding::UTF_8)
-
end
-
-
1
def Ruby19.q_value_encode(str, encoding = nil)
-
encoding = str.encoding.to_s
-
[Encodings::QuotedPrintable.encode(str), encoding]
-
end
-
-
1
def Ruby19.q_value_decode(str)
-
match = str.match(/\=\?(.+)?\?[Qq]\?(.*)\?\=/m)
-
if match
-
charset = match[1]
-
string = match[2].gsub(/_/, '=20')
-
# Remove trailing = if it exists in a Q encoding
-
string = string.sub(/\=$/, '')
-
str = Encodings::QuotedPrintable.decode(string)
-
str = charset_encoder.encode(str, charset)
-
# We assume that binary strings hold utf-8 directly to work around
-
# jruby/jruby#829 which subtly changes String#encode semantics.
-
str.force_encoding(Encoding::UTF_8) if str.encoding == Encoding::ASCII_8BIT
-
end
-
decoded = str.encode(Encoding::UTF_8, :invalid => :replace, :replace => "")
-
decoded.valid_encoding? ? decoded : decoded.encode(Encoding::UTF_16LE, :invalid => :replace, :replace => "").encode(Encoding::UTF_8)
-
rescue Encoding::UndefinedConversionError, ArgumentError, Encoding::ConverterNotFoundError
-
warn "Encoding conversion failed #{$!}"
-
str.dup.force_encoding(Encoding::UTF_8)
-
end
-
-
1
def Ruby19.param_decode(str, encoding)
-
str = uri_parser.unescape(str)
-
str = charset_encoder.encode(str, encoding) if encoding
-
str
-
end
-
-
1
def Ruby19.param_encode(str)
-
encoding = str.encoding.to_s.downcase
-
language = Configuration.instance.param_encode_language
-
"#{encoding}'#{language}'#{uri_parser.escape(str)}"
-
end
-
-
1
def Ruby19.uri_parser
-
@uri_parser ||= URI::Parser.new
-
end
-
-
# Pick a Ruby encoding corresponding to the message charset. Most
-
# charsets have a Ruby encoding, but some need manual aliasing here.
-
#
-
# TODO: add this as a test somewhere:
-
# Encoding.list.map { |e| [e.to_s.upcase == pick_encoding(e.to_s.downcase.gsub("-", "")), e.to_s] }.select {|a,b| !b}
-
# Encoding.list.map { |e| [e.to_s == pick_encoding(e.to_s), e.to_s] }.select {|a,b| !b}
-
1
def Ruby19.pick_encoding(charset)
-
charset = charset.to_s
-
encoding = case charset.downcase
-
-
# ISO-8859-8-I etc. http://en.wikipedia.org/wiki/ISO-8859-8-I
-
when /^iso[-_]?8859-(\d+)(-i)?$/
-
"ISO-8859-#{$1}"
-
-
# ISO-8859-15, ISO-2022-JP and alike
-
when /^iso[-_]?(\d{4})-?(\w{1,2})$/
-
"ISO-#{$1}-#{$2}"
-
-
# "ISO-2022-JP-KDDI" and alike
-
when /^iso[-_]?(\d{4})-?(\w{1,2})-?(\w*)$/
-
"ISO-#{$1}-#{$2}-#{$3}"
-
-
# UTF-8, UTF-32BE and alike
-
when /^utf[\-_]?(\d{1,2})?(\w{1,2})$/
-
"UTF-#{$1}#{$2}".gsub(/\A(UTF-(?:16|32))\z/, '\\1BE')
-
-
# Windows-1252 and alike
-
when /^windows-?(.*)$/
-
"Windows-#{$1}"
-
-
when '8bit'
-
Encoding::ASCII_8BIT
-
-
# alternatives/misspellings of us-ascii seen in the wild
-
when /^iso[-_]?646(-us)?$/, 'us=ascii'
-
Encoding::ASCII
-
-
# Microsoft-specific alias for MACROMAN
-
when 'macintosh'
-
Encoding::MACROMAN
-
-
# Microsoft-specific alias for CP949 (Korean)
-
when 'ks_c_5601-1987'
-
Encoding::CP949
-
-
# Wrongly written Shift_JIS (Japanese)
-
when 'shift-jis'
-
Encoding::Shift_JIS
-
-
# GB2312 (Chinese charset) is a subset of GB18030 (its replacement)
-
when 'gb2312'
-
Encoding::GB18030
-
-
when 'cp-850'
-
Encoding::CP850
-
-
when 'latin2'
-
Encoding::ISO_8859_2
-
-
else
-
charset
-
end
-
-
convert_to_encoding(encoding)
-
end
-
-
1
class << self
-
1
private
-
-
1
def convert_to_encoding(encoding)
-
if encoding.is_a?(Encoding)
-
encoding
-
else
-
begin
-
Encoding.find(encoding)
-
rescue ArgumentError
-
Encoding::BINARY
-
end
-
end
-
end
-
end
-
end
-
end
-
##
-
1
module MIME
-
end
-
-
# The definition of one MIME content-type.
-
#
-
# == Usage
-
# require 'mime/types'
-
#
-
# plaintext = MIME::Types['text/plain'].first
-
# # returns [text/plain, text/plain]
-
# text = plaintext.first
-
# print text.media_type # => 'text'
-
# print text.sub_type # => 'plain'
-
#
-
# puts text.extensions.join(" ") # => 'asc txt c cc h hh cpp'
-
#
-
# puts text.encoding # => 8bit
-
# puts text.binary? # => false
-
# puts text.ascii? # => true
-
# puts text == 'text/plain' # => true
-
# puts MIME::Type.simplified('x-appl/x-zip') # => 'appl/zip'
-
#
-
# puts MIME::Types.any? { |type|
-
# type.content_type == 'text/plain'
-
# } # => true
-
# puts MIME::Types.all?(&:registered?)
-
# # => false
-
1
class MIME::Type
-
# Reflects a MIME content-type specification that is not correctly
-
# formatted (it isn't +type+/+subtype+).
-
1
class InvalidContentType < ArgumentError
-
# :stopdoc:
-
1
def initialize(type_string)
-
@type_string = type_string
-
end
-
-
1
def to_s
-
"Invalid Content-Type #{@type_string.inspect}"
-
end
-
# :startdoc:
-
end
-
-
# Reflects an unsupported MIME encoding.
-
1
class InvalidEncoding < ArgumentError
-
# :stopdoc:
-
1
def initialize(encoding)
-
@encoding = encoding
-
end
-
-
1
def to_s
-
"Invalid Encoding #{@encoding.inspect}"
-
end
-
# :startdoc:
-
end
-
-
# The released version of the mime-types library.
-
1
VERSION = '3.1'
-
-
1
include Comparable
-
-
# :stopdoc:
-
# TODO verify mime-type character restrictions; I am pretty sure that this is
-
# too wide open.
-
1
MEDIA_TYPE_RE = %r{([-\w.+]+)/([-\w.+]*)}
-
1
I18N_RE = %r{[^[:alnum:]]}
-
1
BINARY_ENCODINGS = %w(base64 8bit)
-
1
ASCII_ENCODINGS = %w(7bit quoted-printable)
-
# :startdoc:
-
-
1
private_constant :MEDIA_TYPE_RE, :I18N_RE, :BINARY_ENCODINGS,
-
:ASCII_ENCODINGS
-
-
# Builds a MIME::Type object from the +content_type+, a MIME Content Type
-
# value (e.g., 'text/plain' or 'applicaton/x-eruby'). The constructed object
-
# is yielded to an optional block for additional configuration, such as
-
# associating extensions and encoding information.
-
#
-
# * When provided a Hash or a MIME::Type, the MIME::Type will be
-
# constructed with #init_with.
-
# * When provided an Array, the MIME::Type will be constructed using
-
# the first element as the content type and the remaining flattened
-
# elements as extensions.
-
# * Otherwise, the content_type will be used as a string.
-
#
-
# Yields the newly constructed +self+ object.
-
1
def initialize(content_type) # :yields self:
-
@friendly = {}
-
@obsolete = @registered = false
-
@preferred_extension = @docs = @use_instead = nil
-
self.extensions = []
-
-
case content_type
-
when Hash
-
init_with(content_type)
-
when Array
-
self.content_type = content_type.shift
-
self.extensions = content_type.flatten
-
when MIME::Type
-
init_with(content_type.to_h)
-
else
-
self.content_type = content_type
-
end
-
-
self.encoding ||= :default
-
self.xrefs ||= {}
-
-
yield self if block_given?
-
end
-
-
# Indicates that a MIME type is like another type. This differs from
-
# <tt>==</tt> because <tt>x-</tt> prefixes are removed for this comparison.
-
1
def like?(other)
-
other = if other.respond_to?(:simplified)
-
MIME::Type.simplified(other.simplified, remove_x_prefix: true)
-
else
-
MIME::Type.simplified(other.to_s, remove_x_prefix: true)
-
end
-
MIME::Type.simplified(simplified, remove_x_prefix: true) == other
-
end
-
-
# Compares the +other+ MIME::Type against the exact content type or the
-
# simplified type (the simplified type will be used if comparing against
-
# something that can be treated as a String with #to_s). In comparisons, this
-
# is done against the lowercase version of the MIME::Type.
-
1
def <=>(other)
-
3928
if other.nil?
-
-1
-
3928
elsif other.respond_to?(:simplified)
-
simplified <=> other.simplified
-
else
-
3928
simplified <=> MIME::Type.simplified(other.to_s)
-
end
-
end
-
-
# Compares the +other+ MIME::Type based on how reliable it is before doing a
-
# normal <=> comparison. Used by MIME::Types#[] to sort types. The
-
# comparisons involved are:
-
#
-
# 1. self.simplified <=> other.simplified (ensures that we
-
# don't try to compare different types)
-
# 2. IANA-registered definitions < other definitions.
-
# 3. Complete definitions < incomplete definitions.
-
# 4. Current definitions < obsolete definitions.
-
# 5. Obselete with use-instead names < obsolete without.
-
# 6. Obsolete use-instead definitions are compared.
-
#
-
# While this method is public, its use is strongly discouraged by consumers
-
# of mime-types. In mime-types 3, this method is likely to see substantial
-
# revision and simplification to ensure current registered content types sort
-
# before unregistered or obsolete content types.
-
1
def priority_compare(other)
-
pc = simplified <=> other.simplified
-
if pc.zero?
-
pc = if (reg = registered?) != other.registered?
-
reg ? -1 : 1 # registered < unregistered
-
elsif (comp = complete?) != other.complete?
-
comp ? -1 : 1 # complete < incomplete
-
elsif (obs = obsolete?) != other.obsolete?
-
obs ? 1 : -1 # current < obsolete
-
elsif obs and ((ui = use_instead) != (oui = other.use_instead))
-
if ui.nil?
-
1
-
elsif oui.nil?
-
-1
-
else
-
ui <=> oui
-
end
-
else
-
0
-
end
-
end
-
-
pc
-
end
-
-
# Returns +true+ if the +other+ object is a MIME::Type and the content types
-
# match.
-
1
def eql?(other)
-
other.kind_of?(MIME::Type) and self == other
-
end
-
-
# Returns the whole MIME content-type string.
-
#
-
# The content type is a presentation value from the MIME type registry and
-
# should not be used for comparison. The case of the content type is
-
# preserved, and extension markers (<tt>x-</tt>) are kept.
-
#
-
# text/plain => text/plain
-
# x-chemical/x-pdb => x-chemical/x-pdb
-
# audio/QCELP => audio/QCELP
-
1
attr_reader :content_type
-
# A simplified form of the MIME content-type string, suitable for
-
# case-insensitive comparison, with any extension markers (<tt>x-</tt)
-
# removed and converted to lowercase.
-
#
-
# text/plain => text/plain
-
# x-chemical/x-pdb => x-chemical/x-pdb
-
# audio/QCELP => audio/qcelp
-
1
attr_reader :simplified
-
# Returns the media type of the simplified MIME::Type.
-
#
-
# text/plain => text
-
# x-chemical/x-pdb => x-chemical
-
# audio/QCELP => audio
-
1
attr_reader :media_type
-
# Returns the media type of the unmodified MIME::Type.
-
#
-
# text/plain => text
-
# x-chemical/x-pdb => x-chemical
-
# audio/QCELP => audio
-
1
attr_reader :raw_media_type
-
# Returns the sub-type of the simplified MIME::Type.
-
#
-
# text/plain => plain
-
# x-chemical/x-pdb => pdb
-
# audio/QCELP => QCELP
-
1
attr_reader :sub_type
-
# Returns the media type of the unmodified MIME::Type.
-
#
-
# text/plain => plain
-
# x-chemical/x-pdb => x-pdb
-
# audio/QCELP => qcelp
-
1
attr_reader :raw_sub_type
-
-
##
-
# The list of extensions which are known to be used for this MIME::Type.
-
# Non-array values will be coerced into an array with #to_a. Array values
-
# will be flattened, +nil+ values removed, and made unique.
-
#
-
# :attr_accessor: extensions
-
1
def extensions
-
1964
@extensions.to_a
-
end
-
-
##
-
1
def extensions=(value) # :nodoc:
-
1964
@extensions = Set[*Array(value).flatten.compact].freeze
-
1964
MIME::Types.send(:reindex_extensions, self)
-
end
-
-
# Merge the +extensions+ provided into this MIME::Type. The extensions added
-
# will be merged uniquely.
-
1
def add_extensions(*extensions)
-
self.extensions += extensions
-
end
-
-
##
-
# The preferred extension for this MIME type. If one is not set and there are
-
# exceptions defined, the first extension will be used.
-
#
-
# When setting #preferred_extensions, if #extensions does not contain this
-
# extension, this will be added to #xtensions.
-
#
-
# :attr_accessor: preferred_extension
-
-
##
-
1
def preferred_extension
-
@preferred_extension || extensions.first
-
end
-
-
##
-
1
def preferred_extension=(value) # :nodoc:
-
add_extensions(value) if value
-
@preferred_extension = value
-
end
-
-
##
-
# The encoding (+7bit+, +8bit+, <tt>quoted-printable</tt>, or +base64+)
-
# required to transport the data of this content type safely across a
-
# network, which roughly corresponds to Content-Transfer-Encoding. A value of
-
# +nil+ or <tt>:default</tt> will reset the #encoding to the
-
# #default_encoding for the MIME::Type. Raises ArgumentError if the encoding
-
# provided is invalid.
-
#
-
# If the encoding is not provided on construction, this will be either
-
# 'quoted-printable' (for text/* media types) and 'base64' for eveything
-
# else.
-
#
-
# :attr_accessor: encoding
-
-
##
-
1
attr_reader :encoding
-
-
##
-
1
def encoding=(enc) # :nodoc:
-
if enc.nil? or enc == :default
-
@encoding = default_encoding
-
elsif BINARY_ENCODINGS.include?(enc) or ASCII_ENCODINGS.include?(enc)
-
@encoding = enc
-
else
-
fail InvalidEncoding, enc
-
end
-
end
-
-
# Returns the default encoding for the MIME::Type based on the media type.
-
1
def default_encoding
-
(@media_type == 'text') ? 'quoted-printable' : 'base64'
-
end
-
-
##
-
# Returns the media type or types that should be used instead of this media
-
# type, if it is obsolete. If there is no replacement media type, or it is
-
# not obsolete, +nil+ will be returned.
-
#
-
# :attr_accessor: use_instead
-
-
##
-
1
def use_instead
-
obsolete? ? @use_instead : nil
-
end
-
-
##
-
1
attr_writer :use_instead
-
-
# Returns +true+ if the media type is obsolete.
-
1
attr_accessor :obsolete
-
1
alias_method :obsolete?, :obsolete
-
-
# The documentation for this MIME::Type.
-
1
attr_accessor :docs
-
-
# A friendly short description for this MIME::Type.
-
#
-
# call-seq:
-
# text_plain.friendly # => "Text File"
-
# text_plain.friendly('en') # => "Text File"
-
1
def friendly(lang = 'en'.freeze)
-
@friendly ||= {}
-
-
case lang
-
when String, Symbol
-
@friendly[lang.to_s]
-
when Array
-
@friendly.update(Hash[*lang])
-
when Hash
-
@friendly.update(lang)
-
else
-
fail ArgumentError,
-
"Expected a language or translation set, not #{lang.inspect}"
-
end
-
end
-
-
# A key suitable for use as a lookup key for translations, such as with
-
# the I18n library.
-
#
-
# call-seq:
-
# text_plain.i18n_key # => "text.plain"
-
# 3gpp_xml.i18n_key # => "application.vnd-3gpp-bsf-xml"
-
# # from application/vnd.3gpp.bsf+xml
-
# x_msword.i18n_key # => "application.word"
-
# # from application/x-msword
-
1
attr_reader :i18n_key
-
-
##
-
# The cross-references list for this MIME::Type.
-
#
-
# :attr_accessor: xrefs
-
-
##
-
1
attr_reader :xrefs
-
-
##
-
1
def xrefs=(x) # :nodoc:
-
MIME::Types::Container.new.merge(x).tap do |xr|
-
xr.each do |k, v|
-
xr[k] = Set[*v] unless v.kind_of? Set
-
end
-
-
@xrefs = xr
-
end
-
end
-
-
# The decoded cross-reference URL list for this MIME::Type.
-
1
def xref_urls
-
xrefs.flat_map { |type, values|
-
name = :"xref_url_for_#{type.tr('-', '_')}"
-
respond_to?(name, true) and xref_map(values, name) or values.to_a
-
}
-
end
-
-
# Indicates whether the MIME type has been registered with IANA.
-
1
attr_accessor :registered
-
1
alias_method :registered?, :registered
-
-
# MIME types can be specified to be sent across a network in particular
-
# formats. This method returns +true+ when the MIME::Type encoding is set
-
# to <tt>base64</tt>.
-
1
def binary?
-
BINARY_ENCODINGS.include?(encoding)
-
end
-
-
# MIME types can be specified to be sent across a network in particular
-
# formats. This method returns +false+ when the MIME::Type encoding is
-
# set to <tt>base64</tt>.
-
1
def ascii?
-
ASCII_ENCODINGS.include?(encoding)
-
end
-
-
# Indicateswhether the MIME type is declared as a signature type.
-
1
attr_accessor :signature
-
1
alias_method :signature?, :signature
-
-
# Returns +true+ if the MIME::Type specifies an extension list,
-
# indicating that it is a complete MIME::Type.
-
1
def complete?
-
!@extensions.empty?
-
end
-
-
# Returns the MIME::Type as a string.
-
1
def to_s
-
content_type
-
end
-
-
# Returns the MIME::Type as a string for implicit conversions. This allows
-
# MIME::Type objects to appear on either side of a comparison.
-
#
-
# 'text/plain' == MIME::Type.new('text/plain')
-
1
def to_str
-
content_type
-
end
-
-
# Converts the MIME::Type to a JSON string.
-
1
def to_json(*args)
-
require 'json'
-
to_h.to_json(*args)
-
end
-
-
# Converts the MIME::Type to a hash. The output of this method can also be
-
# used to initialize a MIME::Type.
-
1
def to_h
-
encode_with({})
-
end
-
-
# Populates the +coder+ with attributes about this record for
-
# serialization. The structure of +coder+ should match the structure used
-
# with #init_with.
-
#
-
# This method should be considered a private implementation detail.
-
1
def encode_with(coder)
-
coder['content-type'] = @content_type
-
coder['docs'] = @docs unless @docs.nil? or @docs.empty?
-
unless @friendly.nil? or @friendly.empty?
-
coder['friendly'] = @friendly
-
end
-
coder['encoding'] = @encoding
-
coder['extensions'] = @extensions.to_a unless @extensions.empty?
-
coder['preferred-extension'] = @preferred_extension if @preferred_extension
-
if obsolete?
-
coder['obsolete'] = obsolete?
-
coder['use-instead'] = use_instead if use_instead
-
end
-
unless xrefs.empty?
-
{}.tap do |hash|
-
xrefs.each do |k, v|
-
hash[k] = v.sort.to_a
-
end
-
coder['xrefs'] = hash
-
end
-
end
-
coder['registered'] = registered?
-
coder['signature'] = signature? if signature?
-
coder
-
end
-
-
# Initialize an empty object from +coder+, which must contain the
-
# attributes necessary for initializing an empty object.
-
#
-
# This method should be considered a private implementation detail.
-
1
def init_with(coder)
-
self.content_type = coder['content-type']
-
self.docs = coder['docs'] || ''
-
self.encoding = coder['encoding']
-
self.extensions = coder['extensions'] || []
-
self.preferred_extension = coder['preferred-extension']
-
self.obsolete = coder['obsolete'] || false
-
self.registered = coder['registered'] || false
-
self.signature = coder['signature']
-
self.xrefs = coder['xrefs'] || {}
-
self.use_instead = coder['use-instead']
-
-
friendly(coder['friendly'] || {})
-
end
-
-
1
def inspect # :nodoc:
-
# We are intentionally lying here because MIME::Type::Columnar is an
-
# implementation detail.
-
"#<MIME::Type: #{self}>"
-
end
-
-
1
class << self
-
# MIME media types are case-insensitive, but are typically presented in a
-
# case-preserving format in the type registry. This method converts
-
# +content_type+ to lowercase.
-
#
-
# In previous versions of mime-types, this would also remove any extension
-
# prefix (<tt>x-</tt>). This is no longer default behaviour, but may be
-
# provided by providing a truth value to +remove_x_prefix+.
-
1
def simplified(content_type, remove_x_prefix: false)
-
5892
simplify_matchdata(match(content_type), remove_x_prefix)
-
end
-
-
# Converts a provided +content_type+ into a translation key suitable for
-
# use with the I18n library.
-
1
def i18n_key(content_type)
-
1964
simplify_matchdata(match(content_type), joiner: '.') { |e|
-
3928
e.gsub!(I18N_RE, '-'.freeze)
-
}
-
end
-
-
# Return a +MatchData+ object of the +content_type+ against pattern of
-
# media types.
-
1
def match(content_type)
-
7856
case content_type
-
when MatchData
-
3928
content_type
-
else
-
3928
MEDIA_TYPE_RE.match(content_type)
-
end
-
end
-
-
1
private
-
-
1
def simplify_matchdata(matchdata, remove_x = false, joiner: '/'.freeze)
-
7856
return nil unless matchdata
-
-
matchdata.captures.map { |e|
-
7856
e.downcase!
-
7856
e.sub!(%r{^x-}, ''.freeze) if remove_x
-
7856
yield e if block_given?
-
7856
e
-
3928
}.join(joiner)
-
end
-
end
-
-
1
private
-
-
1
def content_type=(type_string)
-
1964
match = MEDIA_TYPE_RE.match(type_string)
-
1964
fail InvalidContentType, type_string if match.nil?
-
-
1964
@content_type = type_string
-
1964
@raw_media_type, @raw_sub_type = match.captures
-
1964
@simplified = MIME::Type.simplified(match)
-
1964
@i18n_key = MIME::Type.i18n_key(match)
-
1964
@media_type, @sub_type = MEDIA_TYPE_RE.match(@simplified).captures
-
end
-
-
1
def xref_map(values, helper)
-
values.map { |value| send(helper, value) }
-
end
-
-
1
def xref_url_for_rfc(value)
-
'http://www.iana.org/go/%s'.freeze % value
-
end
-
-
1
def xref_url_for_draft(value)
-
'http://www.iana.org/go/%s'.freeze % value.sub(/\ARFC/, 'draft')
-
end
-
-
1
def xref_url_for_rfc_errata(value)
-
'http://www.rfc-editor.org/errata_search.php?eid=%s'.freeze % value
-
end
-
-
1
def xref_url_for_person(value)
-
'http://www.iana.org/assignments/media-types/media-types.xhtml#%s'.freeze %
-
value
-
end
-
-
1
def xref_url_for_template(value)
-
'http://www.iana.org/assignments/media-types/%s'.freeze % value
-
end
-
end
-
1
require 'mime/type'
-
-
# A version of MIME::Type that works hand-in-hand with a MIME::Types::Columnar
-
# container to load data by columns.
-
#
-
# When a field is has not yet been loaded, that data will be loaded for all
-
# types in the container before forwarding the message to MIME::Type.
-
#
-
# More information can be found in MIME::Types::Columnar.
-
#
-
# MIME::Type::Columnar is *not* intended to be created except by
-
# MIME::Types::Columnar containers.
-
1
class MIME::Type::Columnar < MIME::Type
-
1
def initialize(container, content_type, extensions) # :nodoc:
-
1964
@container = container
-
1964
self.content_type = content_type
-
1964
self.extensions = extensions
-
end
-
-
1
def self.column(*methods, file: nil) # :nodoc:
-
7
file = methods.first unless file
-
-
7
file_method = :"load_#{file}"
-
7
methods.each do |m|
-
21
define_method m do |*args|
-
@container.send(file_method)
-
super(*args)
-
end
-
end
-
end
-
-
1
column :friendly
-
1
column :encoding, :encoding=
-
1
column :docs, :docs=
-
1
column :preferred_extension, :preferred_extension=
-
1
column :obsolete, :obsolete=, :obsolete?, :registered, :registered=,
-
:registered?, :signature, :signature=, :signature?, file: 'flags'
-
1
column :xrefs, :xrefs=, :xref_urls
-
1
column :use_instead, :use_instead=
-
-
1
def encode_with(coder) # :nodoc:
-
@container.send(:load_friendly)
-
@container.send(:load_encoding)
-
@container.send(:load_docs)
-
@container.send(:load_flags)
-
@container.send(:load_use_instead)
-
@container.send(:load_xrefs)
-
@container.send(:load_preferred_extension)
-
super
-
end
-
-
1
class << self
-
1
undef column
-
end
-
end
-
##
-
1
module MIME
-
##
-
1
class Types
-
end
-
end
-
-
1
require 'mime/type'
-
-
# MIME::Types is a registry of MIME types. It is both a class (created with
-
# MIME::Types.new) and a default registry (loaded automatically or through
-
# interactions with MIME::Types.[] and MIME::Types.type_for).
-
#
-
# == The Default mime-types Registry
-
#
-
# The default mime-types registry is loaded automatically when the library
-
# is required (<tt>require 'mime/types'</tt>), but it may be lazily loaded
-
# (loaded on first use) with the use of the environment variable
-
# +RUBY_MIME_TYPES_LAZY_LOAD+ having any value other than +false+. The
-
# initial startup is about 14× faster (~10 ms vs ~140 ms), but the
-
# registry will be loaded at some point in the future.
-
#
-
# The default mime-types registry can also be loaded from a Marshal cache
-
# file specific to the version of MIME::Types being loaded. This will be
-
# handled automatically with the use of a file referred to in the
-
# environment variable +RUBY_MIME_TYPES_CACHE+. MIME::Types will attempt to
-
# load the registry from this cache file (MIME::Type::Cache.load); if it
-
# cannot be loaded (because the file does not exist, there is an error, or
-
# the data is for a different version of mime-types), the default registry
-
# will be loaded from the normal JSON version and then the cache file will
-
# be *written* to the location indicated by +RUBY_MIME_TYPES_CACHE+. Cache
-
# file loads just over 4½× faster (~30 ms vs ~140 ms).
-
# loads.
-
#
-
# Notes:
-
# * The loading of the default registry is *not* atomic; when using a
-
# multi-threaded environment, it is recommended that lazy loading is not
-
# used and mime-types is loaded as early as possible.
-
# * Cache files should be specified per application in a multiprocess
-
# environment and should be initialized during deployment or before
-
# forking to minimize the chance that the multiple processes will be
-
# trying to write to the same cache file at the same time, or that two
-
# applications that are on different versions of mime-types would be
-
# thrashing the cache.
-
# * Unless cache files are preinitialized, the application using the
-
# mime-types cache file must have read/write permission to the cache file.
-
#
-
# == Usage
-
# require 'mime/types'
-
#
-
# plaintext = MIME::Types['text/plain']
-
# print plaintext.media_type # => 'text'
-
# print plaintext.sub_type # => 'plain'
-
#
-
# puts plaintext.extensions.join(" ") # => 'asc txt c cc h hh cpp'
-
#
-
# puts plaintext.encoding # => 8bit
-
# puts plaintext.binary? # => false
-
# puts plaintext.ascii? # => true
-
# puts plaintext.obsolete? # => false
-
# puts plaintext.registered? # => true
-
# puts plaintext == 'text/plain' # => true
-
# puts MIME::Type.simplified('x-appl/x-zip') # => 'appl/zip'
-
#
-
1
class MIME::Types
-
# The release version of Ruby MIME::Types
-
1
VERSION = MIME::Type::VERSION
-
-
1
include Enumerable
-
-
# Creates a new MIME::Types registry.
-
1
def initialize
-
1
@type_variants = Container.new
-
1
@extension_index = Container.new
-
end
-
-
# Returns the number of known type variants.
-
1
def count
-
@type_variants.values.inject(0) { |a, e| a + e.size }
-
end
-
-
1
def inspect # :nodoc:
-
"#<#{self.class}: #{count} variants, #{@extension_index.count} extensions>"
-
end
-
-
# Iterates through the type variants.
-
1
def each
-
if block_given?
-
@type_variants.each_value { |tv| tv.each { |t| yield t } }
-
else
-
enum_for(:each)
-
end
-
end
-
-
1
@__types__ = nil
-
-
# Returns a list of MIME::Type objects, which may be empty. The optional
-
# flag parameters are <tt>:complete</tt> (finds only complete MIME::Type
-
# objects) and <tt>:registered</tt> (finds only MIME::Types that are
-
# registered). It is possible for multiple matches to be returned for
-
# either type (in the example below, 'text/plain' returns two values --
-
# one for the general case, and one for VMS systems).
-
#
-
# puts "\nMIME::Types['text/plain']"
-
# MIME::Types['text/plain'].each { |t| puts t.to_a.join(", ") }
-
#
-
# puts "\nMIME::Types[/^image/, complete: true]"
-
# MIME::Types[/^image/, :complete => true].each do |t|
-
# puts t.to_a.join(", ")
-
# end
-
#
-
# If multiple type definitions are returned, returns them sorted as
-
# follows:
-
# 1. Complete definitions sort before incomplete ones;
-
# 2. IANA-registered definitions sort before LTSW-recorded
-
# definitions.
-
# 3. Current definitions sort before obsolete ones;
-
# 4. Obsolete definitions with use-instead clauses sort before those
-
# without;
-
# 5. Obsolete definitions use-instead clauses are compared.
-
# 6. Sort on name.
-
1
def [](type_id, complete: false, registered: false)
-
matches = case type_id
-
when MIME::Type
-
@type_variants[type_id.simplified]
-
when Regexp
-
match(type_id)
-
else
-
@type_variants[MIME::Type.simplified(type_id)]
-
end
-
-
prune_matches(matches, complete, registered).sort { |a, b|
-
a.priority_compare(b)
-
}
-
end
-
-
# Return the list of MIME::Types which belongs to the file based on its
-
# filename extension. If there is no extension, the filename will be used
-
# as the matching criteria on its own.
-
#
-
# This will always return a merged, flatten, priority sorted, unique array.
-
#
-
# puts MIME::Types.type_for('citydesk.xml')
-
# => [application/xml, text/xml]
-
# puts MIME::Types.type_for('citydesk.gif')
-
# => [image/gif]
-
# puts MIME::Types.type_for(%w(citydesk.xml citydesk.gif))
-
# => [application/xml, image/gif, text/xml]
-
1
def type_for(filename)
-
Array(filename).flat_map { |fn|
-
@extension_index[fn.chomp.downcase[/\.?([^.]*?)$/, 1]]
-
}.compact.inject(:+).sort { |a, b|
-
a.priority_compare(b)
-
}
-
end
-
1
alias_method :of, :type_for
-
-
# Add one or more MIME::Type objects to the set of known types. If the
-
# type is already known, a warning will be displayed.
-
#
-
# The last parameter may be the value <tt>:silent</tt> or +true+ which
-
# will suppress duplicate MIME type warnings.
-
1
def add(*types)
-
1964
quiet = ((types.last == :silent) or (types.last == true))
-
-
1964
types.each do |mime_type|
-
1964
case mime_type
-
when true, false, nil, Symbol
-
nil
-
when MIME::Types
-
variants = mime_type.instance_variable_get(:@type_variants)
-
add(*variants.values.inject(:+).to_a, quiet)
-
when Array
-
add(*mime_type, quiet)
-
else
-
1964
add_type(mime_type, quiet)
-
end
-
end
-
end
-
-
# Add a single MIME::Type object to the set of known types. If the +type+ is
-
# already known, a warning will be displayed. The +quiet+ parameter may be a
-
# truthy value to suppress that warning.
-
1
def add_type(type, quiet = false)
-
1964
if !quiet and @type_variants[type.simplified].include?(type)
-
MIME::Types.logger.warn <<-warning
-
Type #{type} is already registered as a variant of #{type.simplified}.
-
warning
-
end
-
-
1964
add_type_variant!(type)
-
1964
index_extensions!(type)
-
end
-
-
1
private
-
-
1
def add_type_variant!(mime_type)
-
1964
@type_variants[mime_type.simplified] << mime_type
-
end
-
-
1
def reindex_extensions!(mime_type)
-
1964
return unless @type_variants[mime_type.simplified].include?(mime_type)
-
index_extensions!(mime_type)
-
end
-
-
1
def index_extensions!(mime_type)
-
3280
mime_type.extensions.each { |ext| @extension_index[ext] << mime_type }
-
end
-
-
1
def prune_matches(matches, complete, registered)
-
matches.delete_if { |e| !e.complete? } if complete
-
matches.delete_if { |e| !e.registered? } if registered
-
matches
-
end
-
-
1
def match(pattern)
-
@type_variants.select { |k, _|
-
k =~ pattern
-
}.values.inject(:+)
-
end
-
end
-
-
1
require 'mime/types/cache'
-
1
require 'mime/types/container'
-
1
require 'mime/types/loader'
-
1
require 'mime/types/logger'
-
1
require 'mime/types/_columnar'
-
1
require 'mime/types/registry'
-
1
require 'mime/type/columnar'
-
-
# MIME::Types::Columnar is used to extend a MIME::Types container to load data
-
# by columns instead of from JSON or YAML. Column loads of MIME types loaded
-
# through the columnar store are synchronized with a Mutex.
-
#
-
# MIME::Types::Columnar is not intended to be used directly, but will be added
-
# to an instance of MIME::Types when it is loaded with
-
# MIME::Types::Loader#load_columnar.
-
1
module MIME::Types::Columnar
-
1
LOAD_MUTEX = Mutex.new # :nodoc:
-
-
1
def self.extended(obj) # :nodoc:
-
1
super
-
1
obj.instance_variable_set(:@__mime_data__, [])
-
1
obj.instance_variable_set(:@__files__, Set.new)
-
end
-
-
# Load the first column data file (type and extensions).
-
1
def load_base_data(path) #:nodoc:
-
1
@__root__ = path
-
-
1
each_file_line('content_type', false) do |line|
-
1964
line = line.split
-
1964
content_type = line.shift
-
1964
extensions = line
-
# content_type, *extensions = line.split
-
-
1964
type = MIME::Type::Columnar.new(self, content_type, extensions)
-
1964
@__mime_data__ << type
-
1964
add(type)
-
end
-
-
1
self
-
end
-
-
1
private
-
-
1
def each_file_line(name, lookup = true)
-
1
LOAD_MUTEX.synchronize do
-
1
next if @__files__.include?(name)
-
-
1
i = -1
-
1
column = File.join(@__root__, "mime.#{name}.column")
-
-
1
IO.readlines(column, encoding: 'UTF-8'.freeze).each do |line|
-
1964
line.chomp!
-
-
1964
if lookup
-
type = @__mime_data__[i += 1] or next
-
yield type, line
-
else
-
1964
yield line
-
end
-
end
-
-
1
@__files__ << name
-
end
-
end
-
-
1
def load_encoding
-
each_file_line('encoding') do |type, line|
-
pool ||= {}
-
line.freeze
-
type.instance_variable_set(:@encoding, (pool[line] ||= line))
-
end
-
end
-
-
1
def load_docs
-
each_file_line('docs') do |type, line|
-
type.instance_variable_set(:@docs, opt(line))
-
end
-
end
-
-
1
def load_preferred_extension
-
each_file_line('pext') do |type, line|
-
type.instance_variable_set(:@preferred_extension, opt(line))
-
end
-
end
-
-
1
def load_flags
-
each_file_line('flags') do |type, line|
-
line = line.split
-
type.instance_variable_set(:@obsolete, flag(line.shift))
-
type.instance_variable_set(:@registered, flag(line.shift))
-
type.instance_variable_set(:@signature, flag(line.shift))
-
end
-
end
-
-
1
def load_xrefs
-
each_file_line('xrefs') { |type, line|
-
type.instance_variable_set(:@xrefs, dict(line, array: true))
-
}
-
end
-
-
1
def load_friendly
-
each_file_line('friendly') { |type, line|
-
type.instance_variable_set(:@friendly, dict(line))
-
}
-
end
-
-
1
def load_use_instead
-
each_file_line('use_instead') do |type, line|
-
type.instance_variable_set(:@use_instead, opt(line))
-
end
-
end
-
-
1
def dict(line, array: false)
-
if line == '-'.freeze
-
{}
-
else
-
line.split('|'.freeze).each_with_object({}) { |l, h|
-
k, v = l.split('^'.freeze)
-
v = nil if v.empty?
-
h[k] = array ? Array(v) : v
-
}
-
end
-
end
-
-
1
def arr(line)
-
if line == '-'.freeze
-
[]
-
else
-
line.split('|'.freeze).flatten.compact.uniq
-
end
-
end
-
-
1
def opt(line)
-
line unless line == '-'.freeze
-
end
-
-
1
def flag(line)
-
line == '1'.freeze ? true : false
-
end
-
end
-
1
MIME::Types::Cache = Struct.new(:version, :data) # :nodoc:
-
-
# Caching of MIME::Types registries is advisable if you will be loading
-
# the default registry relatively frequently. With the class methods on
-
# MIME::Types::Cache, any MIME::Types registry can be marshaled quickly
-
# and easily.
-
#
-
# The cache is invalidated on a per-data-version basis; a cache file for
-
# version 3.2015.1118 will not be reused with version 3.2015.1201.
-
1
class << MIME::Types::Cache
-
# Attempts to load the cache from the file provided as a parameter or in
-
# the environment variable +RUBY_MIME_TYPES_CACHE+. Returns +nil+ if the
-
# file does not exist, if the file cannot be loaded, or if the data in
-
# the cache version is different than this version.
-
1
def load(cache_file = nil)
-
1
cache_file ||= ENV['RUBY_MIME_TYPES_CACHE']
-
1
return nil unless cache_file and File.exist?(cache_file)
-
-
cache = Marshal.load(File.binread(cache_file))
-
if cache.version == MIME::Types::Data::VERSION
-
Marshal.load(cache.data)
-
else
-
MIME::Types.logger.warn <<-warning.chomp
-
Could not load MIME::Types cache: invalid version
-
warning
-
nil
-
end
-
rescue => e
-
MIME::Types.logger.warn <<-warning.chomp
-
Could not load MIME::Types cache: #{e}
-
warning
-
return nil
-
end
-
-
# Attempts to save the types provided to the cache file provided.
-
#
-
# If +types+ is not provided or is +nil+, the cache will contain the
-
# current MIME::Types default registry.
-
#
-
# If +cache_file+ is not provided or is +nil+, the cache will be written
-
# to the file specified in the environment variable
-
# +RUBY_MIME_TYPES_CACHE+. If there is no cache file specified either
-
# directly or through the environment, this method will return +nil+
-
1
def save(types = nil, cache_file = nil)
-
1
cache_file ||= ENV['RUBY_MIME_TYPES_CACHE']
-
1
return nil unless cache_file
-
-
types ||= MIME::Types.send(:__types__)
-
-
File.open(cache_file, 'wb') do |f|
-
f.write(
-
Marshal.dump(new(MIME::Types::Data::VERSION, Marshal.dump(types)))
-
)
-
end
-
end
-
end
-
1
require 'set'
-
-
# MIME::Types requires a container Hash with a default values for keys
-
# resulting in an empty array (<tt>[]</tt>), but this cannot be dumped through
-
# Marshal because of the presence of that default Proc. This class exists
-
# solely to satisfy that need.
-
1
class MIME::Types::Container < Hash # :nodoc:
-
1
def initialize
-
2
super
-
3128
self.default_proc = ->(h, k) { h[k] = Set.new }
-
end
-
-
1
def marshal_dump
-
{}.merge(self)
-
end
-
-
1
def marshal_load(hash)
-
self.default_proc = ->(h, k) { h[k] = Set.new }
-
merge!(hash)
-
end
-
-
1
def encode_with(coder)
-
each { |k, v| coder[k] = v.to_a }
-
end
-
-
1
def init_with(coder)
-
self.default_proc = ->(h, k) { h[k] = Set.new }
-
coder.map.each { |k, v| self[k] = Set[*v] }
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
##
-
1
module MIME; end
-
##
-
1
class MIME::Types; end
-
-
1
require 'mime/types/data'
-
-
# This class is responsible for initializing the MIME::Types registry from
-
# the data files supplied with the mime-types library.
-
#
-
# The Loader will use one of the following paths:
-
# 1. The +path+ provided in its constructor argument;
-
# 2. The value of ENV['RUBY_MIME_TYPES_DATA']; or
-
# 3. The value of MIME::Types::Data::PATH.
-
#
-
# When #load is called, the +path+ will be searched recursively for all YAML
-
# (.yml or .yaml) files. By convention, there is one file for each media
-
# type (application.yml, audio.yml, etc.), but this is not required.
-
1
class MIME::Types::Loader
-
# The path that will be read for the MIME::Types files.
-
1
attr_reader :path
-
# The MIME::Types container instance that will be loaded. If not provided
-
# at initialization, a new MIME::Types instance will be constructed.
-
1
attr_reader :container
-
-
# Creates a Loader object that can be used to load MIME::Types registries
-
# into memory, using YAML, JSON, or Columnar registry format loaders.
-
1
def initialize(path = nil, container = nil)
-
1
path = path || ENV['RUBY_MIME_TYPES_DATA'] || MIME::Types::Data::PATH
-
1
@container = container || MIME::Types.new
-
1
@path = File.expand_path(path)
-
# begin
-
# require 'mime/lazy_types'
-
# @container.extend(MIME::LazyTypes)
-
# end
-
end
-
-
# Loads a MIME::Types registry from YAML files (<tt>*.yml</tt> or
-
# <tt>*.yaml</tt>) recursively found in +path+.
-
#
-
# It is expected that the YAML objects contained within the registry array
-
# will be tagged as <tt>!ruby/object:MIME::Type</tt>.
-
#
-
# Note that the YAML format is about 2½ times *slower* than the JSON format.
-
#
-
# NOTE: The purpose of this format is purely for maintenance reasons.
-
1
def load_yaml
-
Dir[yaml_path].sort.each do |f|
-
container.add(*self.class.load_from_yaml(f), :silent)
-
end
-
container
-
end
-
-
# Loads a MIME::Types registry from JSON files (<tt>*.json</tt>)
-
# recursively found in +path+.
-
#
-
# It is expected that the JSON objects will be an array of hash objects.
-
# The JSON format is the registry format for the MIME types registry
-
# shipped with the mime-types library.
-
1
def load_json
-
Dir[json_path].sort.each do |f|
-
types = self.class.load_from_json(f)
-
container.add(*types, :silent)
-
end
-
container
-
end
-
-
# Loads a MIME::Types registry from columnar files recursively found in
-
# +path+.
-
1
def load_columnar
-
1
require 'mime/types/columnar' unless defined?(MIME::Types::Columnar)
-
1
container.extend(MIME::Types::Columnar)
-
1
container.load_base_data(path)
-
-
1
container
-
end
-
-
# Loads a MIME::Types registry. Loads from JSON files by default
-
# (#load_json).
-
#
-
# This will load from columnar files (#load_columnar) if <tt>columnar:
-
# true</tt> is provided in +options+ and there are columnar files in +path+.
-
1
def load(options = { columnar: false })
-
1
if options[:columnar] && !Dir[columnar_path].empty?
-
1
load_columnar
-
else
-
load_json
-
end
-
end
-
-
1
class << self
-
# Loads the default MIME::Type registry.
-
1
def load(options = { columnar: false })
-
1
new.load(options)
-
end
-
-
# Loads MIME::Types from a single YAML file.
-
#
-
# It is expected that the YAML objects contained within the registry
-
# array will be tagged as <tt>!ruby/object:MIME::Type</tt>.
-
#
-
# Note that the YAML format is about 2½ times *slower* than the JSON
-
# format.
-
#
-
# NOTE: The purpose of this format is purely for maintenance reasons.
-
1
def load_from_yaml(filename)
-
begin
-
require 'psych'
-
rescue LoadError
-
nil
-
end
-
require 'yaml'
-
YAML.load(read_file(filename))
-
end
-
-
# Loads MIME::Types from a single JSON file.
-
#
-
# It is expected that the JSON objects will be an array of hash objects.
-
# The JSON format is the registry format for the MIME types registry
-
# shipped with the mime-types library.
-
1
def load_from_json(filename)
-
require 'json'
-
JSON.parse(read_file(filename)).map { |type| MIME::Type.new(type) }
-
end
-
-
1
private
-
-
1
def read_file(filename)
-
File.open(filename, 'r:UTF-8:-', &:read)
-
end
-
end
-
-
1
private
-
-
1
def yaml_path
-
File.join(path, '*.y{,a}ml')
-
end
-
-
1
def json_path
-
File.join(path, '*.json')
-
end
-
-
1
def columnar_path
-
1
File.join(path, '*.column')
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
1
require 'logger'
-
-
##
-
1
module MIME
-
##
-
1
class Types
-
1
class << self
-
# Configure the MIME::Types logger. This defaults to an instance of a
-
# logger that passes messages (unformatted) through to Kernel#warn.
-
1
attr_accessor :logger
-
end
-
-
1
class WarnLogger < ::Logger #:nodoc:
-
1
class WarnLogDevice < ::Logger::LogDevice #:nodoc:
-
1
def initialize(*)
-
end
-
-
1
def write(m)
-
Kernel.warn(m)
-
end
-
-
1
def close
-
end
-
end
-
-
1
def initialize(_1, _2 = nil, _3 = nil)
-
1
super nil
-
1
@logdev = WarnLogDevice.new
-
1
@formatter = ->(_s, _d, _p, m) { m }
-
end
-
end
-
-
1
self.logger = WarnLogger.new(nil)
-
end
-
end
-
1
class << MIME::Types
-
1
include Enumerable
-
-
##
-
1
def new(*) # :nodoc:
-
1
super.tap do |types|
-
1
__instances__.add types
-
end
-
end
-
-
# MIME::Types#[] against the default MIME::Types registry.
-
1
def [](type_id, complete: false, registered: false)
-
__types__[type_id, complete: complete, registered: registered]
-
end
-
-
# MIME::Types#count against the default MIME::Types registry.
-
1
def count
-
__types__.count
-
end
-
-
# MIME::Types#each against the default MIME::Types registry.
-
1
def each
-
if block_given?
-
__types__.each { |t| yield t }
-
else
-
enum_for(:each)
-
end
-
end
-
-
# MIME::Types#type_for against the default MIME::Types registry.
-
1
def type_for(filename)
-
__types__.type_for(filename)
-
end
-
1
alias_method :of, :type_for
-
-
# MIME::Types#add against the default MIME::Types registry.
-
1
def add(*types)
-
__types__.add(*types)
-
end
-
-
1
private
-
-
1
def lazy_load?
-
1
(lazy = ENV['RUBY_MIME_TYPES_LAZY_LOAD']) && (lazy != 'false')
-
end
-
-
1
def __types__
-
(defined?(@__types__) and @__types__) or load_default_mime_types
-
end
-
-
1
unless private_method_defined?(:load_mode)
-
1
def load_mode
-
1
{ columnar: true }
-
end
-
end
-
-
1
def load_default_mime_types(mode = load_mode)
-
1
@__types__ = MIME::Types::Cache.load
-
1
unless @__types__
-
1
@__types__ = MIME::Types::Loader.load(mode)
-
1
MIME::Types::Cache.save(@__types__)
-
end
-
1
@__types__
-
end
-
-
1
def __instances__
-
1965
@__instances__ ||= Set.new
-
end
-
-
1
def reindex_extensions(type)
-
1964
__instances__.each do |instance|
-
1964
instance.send(:reindex_extensions!, type)
-
end
-
1964
true
-
end
-
end
-
-
##
-
1
class MIME::Types
-
1
load_default_mime_types(load_mode) unless lazy_load?
-
end
-
# frozen_string_literal: true
-
-
1
module MIME
-
1
class Types
-
1
module Data
-
1
VERSION = '3.2016.0521'
-
-
# The path that will be used for loading the MIME::Types data. The
-
# default location is __FILE__/../../../../data, which is where the data
-
# lives in the gem installation of the mime-types-data library.
-
#
-
# The MIME::Types::Loader will load all JSON or columnar files contained
-
# in this path.
-
#
-
# System maintainer note: this is the constant to change when packaging
-
# mime-types for your system. It is recommended that the path be
-
# something like /usr/share/ruby/mime-types/.
-
1
PATH = File.expand_path('../../../../data', __FILE__)
-
end
-
end
-
end
-
1
require "optparse"
-
1
require "thread"
-
1
require "mutex_m"
-
1
require "minitest/parallel"
-
1
require "stringio"
-
-
##
-
# :include: README.rdoc
-
-
1
module Minitest
-
1
VERSION = "5.10.2" # :nodoc:
-
1
ENCS = "".respond_to? :encoding # :nodoc:
-
-
1
@@installed_at_exit ||= false
-
1
@@after_run = []
-
1
@extensions = []
-
-
2
mc = (class << self; self; end)
-
-
##
-
# Parallel test executor
-
-
1
mc.send :attr_accessor, :parallel_executor
-
1
self.parallel_executor = Parallel::Executor.new((ENV["N"] || 2).to_i)
-
-
##
-
# Filter object for backtraces.
-
-
1
mc.send :attr_accessor, :backtrace_filter
-
-
##
-
# Reporter object to be used for all runs.
-
#
-
# NOTE: This accessor is only available during setup, not during runs.
-
-
1
mc.send :attr_accessor, :reporter
-
-
##
-
# Names of known extension plugins.
-
-
1
mc.send :attr_accessor, :extensions
-
-
##
-
# The signal to use for dumping information to STDERR. Defaults to "INFO".
-
-
1
mc.send :attr_accessor, :info_signal
-
1
self.info_signal = "INFO"
-
-
##
-
# Registers Minitest to run at process exit
-
-
1
def self.autorun
-
at_exit {
-
1
next if $! and not ($!.kind_of? SystemExit and $!.success?)
-
-
1
exit_code = nil
-
-
1
at_exit {
-
1
@@after_run.reverse_each(&:call)
-
1
exit exit_code || false
-
}
-
-
1
exit_code = Minitest.run ARGV
-
1
} unless @@installed_at_exit
-
1
@@installed_at_exit = true
-
end
-
-
##
-
# A simple hook allowing you to run a block of code after everything
-
# is done running. Eg:
-
#
-
# Minitest.after_run { p $debugging_info }
-
-
1
def self.after_run &block
-
@@after_run << block
-
end
-
-
1
def self.init_plugins options # :nodoc:
-
self.extensions.each do |name|
-
msg = "plugin_#{name}_init"
-
send msg, options if self.respond_to? msg
-
end
-
end
-
-
1
def self.load_plugins # :nodoc:
-
return unless self.extensions.empty?
-
-
seen = {}
-
-
require "rubygems" unless defined? Gem
-
-
Gem.find_files("minitest/*_plugin.rb").each do |plugin_path|
-
name = File.basename plugin_path, "_plugin.rb"
-
-
next if seen[name]
-
seen[name] = true
-
-
require plugin_path
-
self.extensions << name
-
end
-
end
-
-
##
-
# This is the top-level run method. Everything starts from here. It
-
# tells each Runnable sub-class to run, and each of those are
-
# responsible for doing whatever they do.
-
#
-
# The overall structure of a run looks like this:
-
#
-
# Minitest.autorun
-
# Minitest.run(args)
-
# Minitest.__run(reporter, options)
-
# Runnable.runnables.each
-
# runnable.run(reporter, options)
-
# self.runnable_methods.each
-
# self.run_one_method(self, runnable_method, reporter)
-
# Minitest.run_one_method(klass, runnable_method)
-
# klass.new(runnable_method).run
-
-
1
def self.run args = []
-
self.load_plugins
-
-
options = process_args args
-
-
reporter = CompositeReporter.new
-
reporter << SummaryReporter.new(options[:io], options)
-
reporter << ProgressReporter.new(options[:io], options)
-
-
self.reporter = reporter # this makes it available to plugins
-
self.init_plugins options
-
self.reporter = nil # runnables shouldn't depend on the reporter, ever
-
-
self.parallel_executor.start if parallel_executor.respond_to?(:start)
-
reporter.start
-
begin
-
__run reporter, options
-
rescue Interrupt
-
warn "Interrupted. Exiting..."
-
end
-
self.parallel_executor.shutdown
-
reporter.report
-
-
reporter.passed?
-
end
-
-
##
-
# Internal run method. Responsible for telling all Runnable
-
# sub-classes to run.
-
-
1
def self.__run reporter, options
-
suites = Runnable.runnables.reject { |s| s.runnable_methods.empty? }.shuffle
-
parallel, serial = suites.partition { |s| s.test_order == :parallel }
-
-
# If we run the parallel tests before the serial tests, the parallel tests
-
# could run in parallel with the serial tests. This would be bad because
-
# the serial tests won't lock around Reporter#record. Run the serial tests
-
# first, so that after they complete, the parallel tests will lock when
-
# recording results.
-
serial.map { |suite| suite.run reporter, options } +
-
parallel.map { |suite| suite.run reporter, options }
-
end
-
-
1
def self.process_args args = [] # :nodoc:
-
options = {
-
:io => $stdout,
-
}
-
orig_args = args.dup
-
-
OptionParser.new do |opts|
-
opts.banner = "minitest options:"
-
opts.version = Minitest::VERSION
-
-
opts.on "-h", "--help", "Display this help." do
-
puts opts
-
exit
-
end
-
-
desc = "Sets random seed. Also via env. Eg: SEED=n rake"
-
opts.on "-s", "--seed SEED", Integer, desc do |m|
-
options[:seed] = m.to_i
-
end
-
-
opts.on "-v", "--verbose", "Verbose. Show progress processing files." do
-
options[:verbose] = true
-
end
-
-
opts.on "-n", "--name PATTERN", "Filter run on /regexp/ or string." do |a|
-
options[:filter] = a
-
end
-
-
opts.on "-e", "--exclude PATTERN", "Exclude /regexp/ or string from run." do |a|
-
options[:exclude] = a
-
end
-
-
unless extensions.empty?
-
opts.separator ""
-
opts.separator "Known extensions: #{extensions.join(", ")}"
-
-
extensions.each do |meth|
-
msg = "plugin_#{meth}_options"
-
send msg, opts, options if self.respond_to?(msg)
-
end
-
end
-
-
begin
-
opts.parse! args
-
rescue OptionParser::InvalidOption => e
-
puts
-
puts e
-
puts
-
puts opts
-
exit 1
-
end
-
-
orig_args -= args
-
end
-
-
unless options[:seed] then
-
srand
-
options[:seed] = (ENV["SEED"] || srand).to_i % 0xFFFF
-
orig_args << "--seed" << options[:seed].to_s
-
end
-
-
srand options[:seed]
-
-
options[:args] = orig_args.map { |s|
-
s =~ /[\s|&<>$()]/ ? s.inspect : s
-
}.join " "
-
-
options
-
end
-
-
1
def self.filter_backtrace bt # :nodoc:
-
backtrace_filter.filter bt
-
end
-
-
##
-
# Represents anything "runnable", like Test, Spec, Benchmark, or
-
# whatever you can dream up.
-
#
-
# Subclasses of this are automatically registered and available in
-
# Runnable.runnables.
-
-
1
class Runnable
-
##
-
# Number of assertions executed in this run.
-
-
1
attr_accessor :assertions
-
-
##
-
# An assertion raised during the run, if any.
-
-
1
attr_accessor :failures
-
-
##
-
# Name of the run.
-
-
1
def name
-
@NAME
-
end
-
-
##
-
# Set the name of the run.
-
-
1
def name= o
-
@NAME = o
-
end
-
-
1
def self.inherited klass # :nodoc:
-
7
self.runnables << klass
-
7
super
-
end
-
-
##
-
# Returns all instance methods matching the pattern +re+.
-
-
1
def self.methods_matching re
-
public_instance_methods(true).grep(re).map(&:to_s)
-
end
-
-
1
def self.reset # :nodoc:
-
1
@@runnables = []
-
end
-
-
1
reset
-
-
##
-
# Responsible for running all runnable methods in a given class,
-
# each in its own instance. Each instance is passed to the
-
# reporter to record.
-
-
1
def self.run reporter, options = {}
-
filter = options[:filter] || "/./"
-
filter = Regexp.new $1 if filter =~ %r%/(.*)/%
-
-
filtered_methods = self.runnable_methods.find_all { |m|
-
filter === m || filter === "#{self}##{m}"
-
}
-
-
exclude = options[:exclude]
-
exclude = Regexp.new $1 if exclude =~ %r%/(.*)/%
-
-
filtered_methods.delete_if { |m|
-
exclude === m || exclude === "#{self}##{m}"
-
}
-
-
return if filtered_methods.empty?
-
-
with_info_handler reporter do
-
filtered_methods.each do |method_name|
-
run_one_method self, method_name, reporter
-
end
-
end
-
end
-
-
##
-
# Runs a single method and has the reporter record the result.
-
# This was considered internal API but is factored out of run so
-
# that subclasses can specialize the running of an individual
-
# test. See Minitest::ParallelTest::ClassMethods for an example.
-
-
1
def self.run_one_method klass, method_name, reporter
-
reporter.prerecord klass, method_name
-
reporter.record Minitest.run_one_method(klass, method_name)
-
end
-
-
1
def self.with_info_handler reporter, &block # :nodoc:
-
handler = lambda do
-
unless reporter.passed? then
-
warn "Current results:"
-
warn ""
-
warn reporter.reporters.first
-
warn ""
-
end
-
end
-
-
on_signal ::Minitest.info_signal, handler, &block
-
end
-
-
1
SIGNALS = Signal.list # :nodoc:
-
-
1
def self.on_signal name, action # :nodoc:
-
supported = SIGNALS[name]
-
-
old_trap = trap name do
-
old_trap.call if old_trap.respond_to? :call
-
action.call
-
end if supported
-
-
yield
-
ensure
-
trap name, old_trap if supported
-
end
-
-
##
-
# Each subclass of Runnable is responsible for overriding this
-
# method to return all runnable methods. See #methods_matching.
-
-
1
def self.runnable_methods
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Returns all subclasses of Runnable.
-
-
1
def self.runnables
-
7
@@runnables
-
end
-
-
1
def marshal_dump # :nodoc:
-
[self.name, self.failures, self.assertions]
-
end
-
-
1
def marshal_load ary # :nodoc:
-
self.name, self.failures, self.assertions = ary
-
end
-
-
1
def failure # :nodoc:
-
self.failures.first
-
end
-
-
1
def initialize name # :nodoc:
-
self.name = name
-
self.failures = []
-
self.assertions = 0
-
end
-
-
##
-
# Runs a single method. Needs to return self.
-
-
1
def run
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Did this run pass?
-
#
-
# Note: skipped runs are not considered passing, but they don't
-
# cause the process to exit non-zero.
-
-
1
def passed?
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Returns a single character string to print based on the result
-
# of the run. Eg ".", "F", or "E".
-
-
1
def result_code
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Was this run skipped? See #passed? for more information.
-
-
1
def skipped?
-
raise NotImplementedError, "subclass responsibility"
-
end
-
end
-
-
##
-
# Defines the API for Reporters. Subclass this and override whatever
-
# you want. Go nuts.
-
-
1
class AbstractReporter
-
1
include Mutex_m
-
-
##
-
# Starts reporting on the run.
-
-
1
def start
-
end
-
-
##
-
# About to start running a test. This allows a reporter to show
-
# that it is starting or that we are in the middle of a test run.
-
-
1
def prerecord klass, name
-
end
-
-
##
-
# Record a result and output the Runnable#result_code. Stores the
-
# result of the run if the run did not pass.
-
-
1
def record result
-
end
-
-
##
-
# Outputs the summary of the run.
-
-
1
def report
-
end
-
-
##
-
# Did this run pass?
-
-
1
def passed?
-
true
-
end
-
end
-
-
1
class Reporter < AbstractReporter # :nodoc:
-
##
-
# The IO used to report.
-
-
1
attr_accessor :io
-
-
##
-
# Command-line options for this run.
-
-
1
attr_accessor :options
-
-
1
def initialize io = $stdout, options = {} # :nodoc:
-
super()
-
self.io = io
-
self.options = options
-
end
-
end
-
-
##
-
# A very simple reporter that prints the "dots" during the run.
-
#
-
# This is added to the top-level CompositeReporter at the start of
-
# the run. If you want to change the output of minitest via a
-
# plugin, pull this out of the composite and replace it with your
-
# own.
-
-
1
class ProgressReporter < Reporter
-
1
def prerecord klass, name
-
if options[:verbose] then
-
io.print "%s#%s = " % [klass, name]
-
io.flush
-
end
-
end
-
-
1
def record result # :nodoc:
-
io.print "%.2f s = " % [result.time] if options[:verbose]
-
io.print result.result_code
-
io.puts if options[:verbose]
-
end
-
end
-
-
##
-
# A reporter that gathers statistics about a test run. Does not do
-
# any IO because meant to be used as a parent class for a reporter
-
# that does.
-
#
-
# If you want to create an entirely different type of output (eg,
-
# CI, HTML, etc), this is the place to start.
-
-
1
class StatisticsReporter < Reporter
-
# :stopdoc:
-
1
attr_accessor :assertions
-
1
attr_accessor :count
-
1
attr_accessor :results
-
1
attr_accessor :start_time
-
1
attr_accessor :total_time
-
1
attr_accessor :failures
-
1
attr_accessor :errors
-
1
attr_accessor :skips
-
# :startdoc:
-
-
1
def initialize io = $stdout, options = {} # :nodoc:
-
super
-
-
self.assertions = 0
-
self.count = 0
-
self.results = []
-
self.start_time = nil
-
self.total_time = nil
-
self.failures = nil
-
self.errors = nil
-
self.skips = nil
-
end
-
-
1
def passed? # :nodoc:
-
results.all?(&:skipped?)
-
end
-
-
1
def start # :nodoc:
-
self.start_time = Minitest.clock_time
-
end
-
-
1
def record result # :nodoc:
-
self.count += 1
-
self.assertions += result.assertions
-
-
results << result if not result.passed? or result.skipped?
-
end
-
-
1
def report # :nodoc:
-
aggregate = results.group_by { |r| r.failure.class }
-
aggregate.default = [] # dumb. group_by should provide this
-
-
self.total_time = Minitest.clock_time - start_time
-
self.failures = aggregate[Assertion].size
-
self.errors = aggregate[UnexpectedError].size
-
self.skips = aggregate[Skip].size
-
end
-
end
-
-
##
-
# A reporter that prints the header, summary, and failure details at
-
# the end of the run.
-
#
-
# This is added to the top-level CompositeReporter at the start of
-
# the run. If you want to change the output of minitest via a
-
# plugin, pull this out of the composite and replace it with your
-
# own.
-
-
1
class SummaryReporter < StatisticsReporter
-
# :stopdoc:
-
1
attr_accessor :sync
-
1
attr_accessor :old_sync
-
# :startdoc:
-
-
1
def start # :nodoc:
-
super
-
-
io.puts "Run options: #{options[:args]}"
-
io.puts
-
io.puts "# Running:"
-
io.puts
-
-
self.sync = io.respond_to? :"sync=" # stupid emacs
-
self.old_sync, io.sync = io.sync, true if self.sync
-
end
-
-
1
def report # :nodoc:
-
super
-
-
io.sync = self.old_sync
-
-
io.puts unless options[:verbose] # finish the dots
-
io.puts
-
io.puts statistics
-
aggregated_results io
-
io.puts summary
-
end
-
-
1
def statistics # :nodoc:
-
"Finished in %.6fs, %.4f runs/s, %.4f assertions/s." %
-
[total_time, count / total_time, assertions / total_time]
-
end
-
-
1
def aggregated_results io # :nodoc:
-
filtered_results = results.dup
-
filtered_results.reject!(&:skipped?) unless options[:verbose]
-
-
filtered_results.each_with_index { |result, i|
-
io.puts "\n%3d) %s" % [i+1, result]
-
}
-
io.puts
-
io
-
end
-
-
1
def to_s
-
aggregated_results(StringIO.new(binary_string)).string
-
end
-
-
1
def summary # :nodoc:
-
extra = ""
-
-
extra = "\n\nYou have skipped tests. Run with --verbose for details." if
-
results.any?(&:skipped?) unless options[:verbose] or ENV["MT_NO_SKIP_MSG"]
-
-
"%d runs, %d assertions, %d failures, %d errors, %d skips%s" %
-
[count, assertions, failures, errors, skips, extra]
-
end
-
-
1
private
-
-
1
if '<3'.respond_to? :b
-
1
def binary_string; ''.b; end
-
else
-
def binary_string; ''.force_encoding(Encoding::ASCII_8BIT); end
-
end
-
end
-
-
##
-
# Dispatch to multiple reporters as one.
-
-
1
class CompositeReporter < AbstractReporter
-
##
-
# The list of reporters to dispatch to.
-
-
1
attr_accessor :reporters
-
-
1
def initialize *reporters # :nodoc:
-
super()
-
self.reporters = reporters
-
end
-
-
1
def io # :nodoc:
-
reporters.first.io
-
end
-
-
##
-
# Add another reporter to the mix.
-
-
1
def << reporter
-
self.reporters << reporter
-
end
-
-
1
def passed? # :nodoc:
-
self.reporters.all?(&:passed?)
-
end
-
-
1
def start # :nodoc:
-
self.reporters.each(&:start)
-
end
-
-
1
def prerecord klass, name # :nodoc:
-
self.reporters.each do |reporter|
-
# TODO: remove conditional for minitest 6
-
reporter.prerecord klass, name if reporter.respond_to? :prerecord
-
end
-
end
-
-
1
def record result # :nodoc:
-
self.reporters.each do |reporter|
-
reporter.record result
-
end
-
end
-
-
1
def report # :nodoc:
-
self.reporters.each(&:report)
-
end
-
end
-
-
##
-
# Represents run failures.
-
-
1
class Assertion < Exception
-
1
def error # :nodoc:
-
self
-
end
-
-
##
-
# Where was this run before an assertion was raised?
-
-
1
def location
-
last_before_assertion = ""
-
self.backtrace.reverse_each do |s|
-
break if s =~ /in .(assert|refute|flunk|pass|fail|raise|must|wont)/
-
last_before_assertion = s
-
end
-
last_before_assertion.sub(/:in .*$/, "")
-
end
-
-
1
def result_code # :nodoc:
-
result_label[0, 1]
-
end
-
-
1
def result_label # :nodoc:
-
"Failure"
-
end
-
end
-
-
##
-
# Assertion raised when skipping a run.
-
-
1
class Skip < Assertion
-
1
def result_label # :nodoc:
-
"Skipped"
-
end
-
end
-
-
##
-
# Assertion wrapping an unexpected error that was raised during a run.
-
-
1
class UnexpectedError < Assertion
-
1
attr_accessor :exception # :nodoc:
-
-
1
def initialize exception # :nodoc:
-
super "Unexpected exception"
-
self.exception = exception
-
end
-
-
1
def backtrace # :nodoc:
-
self.exception.backtrace
-
end
-
-
1
def error # :nodoc:
-
self.exception
-
end
-
-
1
def message # :nodoc:
-
bt = Minitest.filter_backtrace(self.backtrace).join "\n "
-
"#{self.exception.class}: #{self.exception.message}\n #{bt}"
-
end
-
-
1
def result_label # :nodoc:
-
"Error"
-
end
-
end
-
-
##
-
# Provides a simple set of guards that you can use in your tests
-
# to skip execution if it is not applicable. These methods are
-
# mixed into Test as both instance and class methods so you
-
# can use them inside or outside of the test methods.
-
#
-
# def test_something_for_mri
-
# skip "bug 1234" if jruby?
-
# # ...
-
# end
-
#
-
# if windows? then
-
# # ... lots of test methods ...
-
# end
-
-
1
module Guard
-
-
##
-
# Is this running on jruby?
-
-
1
def jruby? platform = RUBY_PLATFORM
-
"java" == platform
-
end
-
-
##
-
# Is this running on maglev?
-
-
1
def maglev? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE
-
"maglev" == platform
-
end
-
-
##
-
# Is this running on mri?
-
-
1
def mri? platform = RUBY_DESCRIPTION
-
/^ruby/ =~ platform
-
end
-
-
##
-
# Is this running on rubinius?
-
-
1
def rubinius? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE
-
"rbx" == platform
-
end
-
-
##
-
# Is this running on windows?
-
-
1
def windows? platform = RUBY_PLATFORM
-
/mswin|mingw/ =~ platform
-
end
-
end
-
-
1
class BacktraceFilter # :nodoc:
-
1
def filter bt
-
return ["No backtrace"] unless bt
-
-
return bt.dup if $DEBUG
-
-
mt_re = %r%lib/minitest%
-
-
new_bt = bt.take_while { |line| line !~ mt_re }
-
new_bt = bt.select { |line| line !~ mt_re } if new_bt.empty?
-
new_bt = bt.dup if new_bt.empty?
-
-
new_bt
-
end
-
end
-
-
1
self.backtrace_filter = BacktraceFilter.new
-
-
1
def self.run_one_method klass, method_name # :nodoc:
-
result = klass.new(method_name).run
-
raise "#{klass}#run _must_ return self" unless klass === result
-
result
-
end
-
-
# :stopdoc:
-
-
1
if defined? Process::CLOCK_MONOTONIC # :nodoc:
-
1
def self.clock_time
-
Process.clock_gettime Process::CLOCK_MONOTONIC
-
end
-
else
-
def self.clock_time
-
Time.now
-
end
-
end
-
-
# :startdoc:
-
end
-
-
1
require "minitest/test"
-
# encoding: UTF-8
-
-
1
require "rbconfig"
-
1
require "tempfile"
-
1
require "stringio"
-
-
1
module Minitest
-
##
-
# Minitest Assertions. All assertion methods accept a +msg+ which is
-
# printed if the assertion fails.
-
#
-
# Protocol: Nearly everything here boils up to +assert+, which
-
# expects to be able to increment an instance accessor named
-
# +assertions+. This is not provided by Assertions and must be
-
# provided by the thing including Assertions. See Minitest::Runnable
-
# for an example.
-
-
1
module Assertions
-
1
UNDEFINED = Object.new # :nodoc:
-
-
1
def UNDEFINED.inspect # :nodoc:
-
"UNDEFINED" # again with the rdoc bugs... :(
-
end
-
-
##
-
# Returns the diff command to use in #diff. Tries to intelligently
-
# figure out what diff to use.
-
-
1
def self.diff
-
@diff = if (RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ &&
-
system("diff.exe", __FILE__, __FILE__)) then
-
"diff.exe -u"
-
elsif Minitest::Test.maglev? then
-
"diff -u"
-
elsif system("gdiff", __FILE__, __FILE__)
-
"gdiff -u" # solaris and kin suck
-
elsif system("diff", __FILE__, __FILE__)
-
"diff -u"
-
else
-
nil
-
end unless defined? @diff
-
-
@diff
-
end
-
-
##
-
# Set the diff command to use in #diff.
-
-
1
def self.diff= o
-
@diff = o
-
end
-
-
##
-
# Returns a diff between +exp+ and +act+. If there is no known
-
# diff command or if it doesn't make sense to diff the output
-
# (single line, short output), then it simply returns a basic
-
# comparison between the two.
-
-
1
def diff exp, act
-
expect = mu_pp_for_diff exp
-
butwas = mu_pp_for_diff act
-
result = nil
-
-
need_to_diff =
-
(expect.include?("\n") ||
-
butwas.include?("\n") ||
-
expect.size > 30 ||
-
butwas.size > 30 ||
-
expect == butwas) &&
-
Minitest::Assertions.diff
-
-
return "Expected: #{mu_pp exp}\n Actual: #{mu_pp act}" unless
-
need_to_diff
-
-
Tempfile.open("expect") do |a|
-
a.puts expect
-
a.flush
-
-
Tempfile.open("butwas") do |b|
-
b.puts butwas
-
b.flush
-
-
result = `#{Minitest::Assertions.diff} #{a.path} #{b.path}`
-
result.sub!(/^\-\-\- .+/, "--- expected")
-
result.sub!(/^\+\+\+ .+/, "+++ actual")
-
-
if result.empty? then
-
klass = exp.class
-
result = [
-
"No visible difference in the #{klass}#inspect output.\n",
-
"You should look at the implementation of #== on ",
-
"#{klass} or its members.\n",
-
expect,
-
].join
-
end
-
end
-
end
-
-
result
-
end
-
-
##
-
# This returns a human-readable version of +obj+. By default
-
# #inspect is called. You can override this to use #pretty_print
-
# if you want.
-
-
1
def mu_pp obj
-
s = obj.inspect
-
-
if defined? Encoding then
-
s = s.encode Encoding.default_external
-
-
if String === obj && obj.encoding != Encoding.default_external then
-
s = "# encoding: #{obj.encoding}\n#{s}"
-
end
-
end
-
-
s
-
end
-
-
##
-
# This returns a diff-able human-readable version of +obj+. This
-
# differs from the regular mu_pp because it expands escaped
-
# newlines and makes hex-values generic (like object_ids). This
-
# uses mu_pp to do the first pass and then cleans it up.
-
-
1
def mu_pp_for_diff obj
-
mu_pp(obj).gsub(/\\n/, "\n").gsub(/:0x[a-fA-F0-9]{4,}/m, ":0xXXXXXX")
-
end
-
-
##
-
# Fails unless +test+ is truthy.
-
-
1
def assert test, msg = nil
-
self.assertions += 1
-
unless test then
-
msg ||= "Expected #{mu_pp test} to be truthy."
-
msg = msg.call if Proc === msg
-
raise Minitest::Assertion, msg
-
end
-
true
-
end
-
-
1
def _synchronize # :nodoc:
-
yield
-
end
-
-
##
-
# Fails unless +obj+ is empty.
-
-
1
def assert_empty obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to be empty" }
-
assert_respond_to obj, :empty?
-
assert obj.empty?, msg
-
end
-
-
1
E = "" # :nodoc:
-
-
##
-
# Fails unless <tt>exp == act</tt> printing the difference between
-
# the two, if possible.
-
#
-
# If there is no visible difference but the assertion fails, you
-
# should suspect that your #== is buggy, or your inspect output is
-
# missing crucial details. For nicer structural diffing, set
-
# Minitest::Test.make_my_diffs_pretty!
-
#
-
# For floats use assert_in_delta.
-
#
-
# See also: Minitest::Assertions.diff
-
-
1
def assert_equal exp, act, msg = nil
-
msg = message(msg, E) { diff exp, act }
-
result = assert exp == act, msg
-
-
if exp.nil? then
-
if Minitest::VERSION =~ /^6/ then
-
refute_nil exp, "Use assert_nil if expecting nil."
-
else
-
where = Minitest.filter_backtrace(caller).first
-
where = where.split(/:in /, 2).first # clean up noise
-
-
warn "DEPRECATED: Use assert_nil if expecting nil from #{where}. This will fail in Minitest 6."
-
end
-
end
-
-
result
-
end
-
-
##
-
# For comparing Floats. Fails unless +exp+ and +act+ are within +delta+
-
# of each other.
-
#
-
# assert_in_delta Math::PI, (22.0 / 7.0), 0.01
-
-
1
def assert_in_delta exp, act, delta = 0.001, msg = nil
-
n = (exp - act).abs
-
msg = message(msg) {
-
"Expected |#{exp} - #{act}| (#{n}) to be <= #{delta}"
-
}
-
assert delta >= n, msg
-
end
-
-
##
-
# For comparing Floats. Fails unless +exp+ and +act+ have a relative
-
# error less than +epsilon+.
-
-
1
def assert_in_epsilon a, b, epsilon = 0.001, msg = nil
-
assert_in_delta a, b, [a.abs, b.abs].min * epsilon, msg
-
end
-
-
##
-
# Fails unless +collection+ includes +obj+.
-
-
1
def assert_includes collection, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(collection)} to include #{mu_pp(obj)}"
-
}
-
assert_respond_to collection, :include?
-
assert collection.include?(obj), msg
-
end
-
-
##
-
# Fails unless +obj+ is an instance of +cls+.
-
-
1
def assert_instance_of cls, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to be an instance of #{cls}, not #{obj.class}"
-
}
-
-
assert obj.instance_of?(cls), msg
-
end
-
-
##
-
# Fails unless +obj+ is a kind of +cls+.
-
-
1
def assert_kind_of cls, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to be a kind of #{cls}, not #{obj.class}" }
-
-
assert obj.kind_of?(cls), msg
-
end
-
-
##
-
# Fails unless +matcher+ <tt>=~</tt> +obj+.
-
-
1
def assert_match matcher, obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp matcher} to match #{mu_pp obj}" }
-
assert_respond_to matcher, :"=~"
-
matcher = Regexp.new Regexp.escape matcher if String === matcher
-
assert matcher =~ obj, msg
-
end
-
-
##
-
# Fails unless +obj+ is nil
-
-
1
def assert_nil obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to be nil" }
-
assert obj.nil?, msg
-
end
-
-
##
-
# For testing with binary operators. Eg:
-
#
-
# assert_operator 5, :<=, 4
-
-
1
def assert_operator o1, op, o2 = UNDEFINED, msg = nil
-
return assert_predicate o1, op, msg if UNDEFINED == o2
-
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op} #{mu_pp(o2)}" }
-
assert o1.__send__(op, o2), msg
-
end
-
-
##
-
# Fails if stdout or stderr do not output the expected results.
-
# Pass in nil if you don't care about that streams output. Pass in
-
# "" if you require it to be silent. Pass in a regexp if you want
-
# to pattern match.
-
#
-
# assert_output(/hey/) { method_with_output }
-
#
-
# NOTE: this uses #capture_io, not #capture_subprocess_io.
-
#
-
# See also: #assert_silent
-
-
1
def assert_output stdout = nil, stderr = nil
-
out, err = capture_io do
-
yield
-
end
-
-
err_msg = Regexp === stderr ? :assert_match : :assert_equal if stderr
-
out_msg = Regexp === stdout ? :assert_match : :assert_equal if stdout
-
-
y = send err_msg, stderr, err, "In stderr" if err_msg
-
x = send out_msg, stdout, out, "In stdout" if out_msg
-
-
(!stdout || x) && (!stderr || y)
-
end
-
-
##
-
# For testing with predicates. Eg:
-
#
-
# assert_predicate str, :empty?
-
#
-
# This is really meant for specs and is front-ended by assert_operator:
-
#
-
# str.must_be :empty?
-
-
1
def assert_predicate o1, op, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op}" }
-
assert o1.__send__(op), msg
-
end
-
-
##
-
# Fails unless the block raises one of +exp+. Returns the
-
# exception matched so you can check the message, attributes, etc.
-
#
-
# +exp+ takes an optional message on the end to help explain
-
# failures and defaults to StandardError if no exception class is
-
# passed.
-
-
1
def assert_raises *exp
-
msg = "#{exp.pop}.\n" if String === exp.last
-
exp << StandardError if exp.empty?
-
-
begin
-
yield
-
rescue *exp => e
-
pass # count assertion
-
return e
-
rescue Minitest::Skip, Minitest::Assertion
-
# don't count assertion
-
raise
-
rescue SignalException, SystemExit
-
raise
-
rescue Exception => e
-
flunk proc {
-
exception_details(e, "#{msg}#{mu_pp(exp)} exception expected, not")
-
}
-
end
-
-
exp = exp.first if exp.size == 1
-
-
flunk "#{msg}#{mu_pp(exp)} expected but nothing was raised."
-
end
-
-
##
-
# Fails unless +obj+ responds to +meth+.
-
-
1
def assert_respond_to obj, meth, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} (#{obj.class}) to respond to ##{meth}"
-
}
-
assert obj.respond_to?(meth), msg
-
end
-
-
##
-
# Fails unless +exp+ and +act+ are #equal?
-
-
1
def assert_same exp, act, msg = nil
-
msg = message(msg) {
-
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
-
"Expected %s (oid=%d) to be the same as %s (oid=%d)" % data
-
}
-
assert exp.equal?(act), msg
-
end
-
-
##
-
# +send_ary+ is a receiver, message and arguments.
-
#
-
# Fails unless the call returns a true value
-
-
1
def assert_send send_ary, m = nil
-
where = Minitest.filter_backtrace(caller).first
-
where = where.split(/:in /, 2).first # clean up noise
-
warn "DEPRECATED: assert_send. From #{where}"
-
-
recv, msg, *args = send_ary
-
m = message(m) {
-
"Expected #{mu_pp(recv)}.#{msg}(*#{mu_pp(args)}) to return true" }
-
assert recv.__send__(msg, *args), m
-
end
-
-
##
-
# Fails if the block outputs anything to stderr or stdout.
-
#
-
# See also: #assert_output
-
-
1
def assert_silent
-
assert_output "", "" do
-
yield
-
end
-
end
-
-
##
-
# Fails unless the block throws +sym+
-
-
1
def assert_throws sym, msg = nil
-
default = "Expected #{mu_pp(sym)} to have been thrown"
-
caught = true
-
catch(sym) do
-
begin
-
yield
-
rescue ThreadError => e # wtf?!? 1.8 + threads == suck
-
default += ", not \:#{e.message[/uncaught throw \`(\w+?)\'/, 1]}"
-
rescue ArgumentError => e # 1.9 exception
-
raise e unless e.message.include?("uncaught throw")
-
default += ", not #{e.message.split(/ /).last}"
-
rescue NameError => e # 1.8 exception
-
raise e unless e.name == sym
-
default += ", not #{e.name.inspect}"
-
end
-
caught = false
-
end
-
-
assert caught, message(msg) { default }
-
end
-
-
##
-
# Captures $stdout and $stderr into strings:
-
#
-
# out, err = capture_io do
-
# puts "Some info"
-
# warn "You did a bad thing"
-
# end
-
#
-
# assert_match %r%info%, out
-
# assert_match %r%bad%, err
-
#
-
# NOTE: For efficiency, this method uses StringIO and does not
-
# capture IO for subprocesses. Use #capture_subprocess_io for
-
# that.
-
-
1
def capture_io
-
_synchronize do
-
begin
-
captured_stdout, captured_stderr = StringIO.new, StringIO.new
-
-
orig_stdout, orig_stderr = $stdout, $stderr
-
$stdout, $stderr = captured_stdout, captured_stderr
-
-
yield
-
-
return captured_stdout.string, captured_stderr.string
-
ensure
-
$stdout = orig_stdout
-
$stderr = orig_stderr
-
end
-
end
-
end
-
-
##
-
# Captures $stdout and $stderr into strings, using Tempfile to
-
# ensure that subprocess IO is captured as well.
-
#
-
# out, err = capture_subprocess_io do
-
# system "echo Some info"
-
# system "echo You did a bad thing 1>&2"
-
# end
-
#
-
# assert_match %r%info%, out
-
# assert_match %r%bad%, err
-
#
-
# NOTE: This method is approximately 10x slower than #capture_io so
-
# only use it when you need to test the output of a subprocess.
-
-
1
def capture_subprocess_io
-
_synchronize do
-
begin
-
require "tempfile"
-
-
captured_stdout, captured_stderr = Tempfile.new("out"), Tempfile.new("err")
-
-
orig_stdout, orig_stderr = $stdout.dup, $stderr.dup
-
$stdout.reopen captured_stdout
-
$stderr.reopen captured_stderr
-
-
yield
-
-
$stdout.rewind
-
$stderr.rewind
-
-
return captured_stdout.read, captured_stderr.read
-
ensure
-
captured_stdout.unlink
-
captured_stderr.unlink
-
$stdout.reopen orig_stdout
-
$stderr.reopen orig_stderr
-
end
-
end
-
end
-
-
##
-
# Returns details for exception +e+
-
-
1
def exception_details e, msg
-
[
-
"#{msg}",
-
"Class: <#{e.class}>",
-
"Message: <#{e.message.inspect}>",
-
"---Backtrace---",
-
"#{Minitest.filter_backtrace(e.backtrace).join("\n")}",
-
"---------------",
-
].join "\n"
-
end
-
-
##
-
# Fails with +msg+
-
-
1
def flunk msg = nil
-
msg ||= "Epic Fail!"
-
assert false, msg
-
end
-
-
##
-
# Returns a proc that will output +msg+ along with the default message.
-
-
1
def message msg = nil, ending = nil, &default
-
proc {
-
msg = msg.call.chomp(".") if Proc === msg
-
custom_message = "#{msg}.\n" unless msg.nil? or msg.to_s.empty?
-
"#{custom_message}#{default.call}#{ending || "."}"
-
}
-
end
-
-
##
-
# used for counting assertions
-
-
1
def pass _msg = nil
-
assert true
-
end
-
-
##
-
# Fails if +test+ is truthy.
-
-
1
def refute test, msg = nil
-
msg ||= message { "Expected #{mu_pp(test)} to not be truthy" }
-
not assert !test, msg
-
end
-
-
##
-
# Fails if +obj+ is empty.
-
-
1
def refute_empty obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be empty" }
-
assert_respond_to obj, :empty?
-
refute obj.empty?, msg
-
end
-
-
##
-
# Fails if <tt>exp == act</tt>.
-
#
-
# For floats use refute_in_delta.
-
-
1
def refute_equal exp, act, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(act)} to not be equal to #{mu_pp(exp)}"
-
}
-
refute exp == act, msg
-
end
-
-
##
-
# For comparing Floats. Fails if +exp+ is within +delta+ of +act+.
-
#
-
# refute_in_delta Math::PI, (22.0 / 7.0)
-
-
1
def refute_in_delta exp, act, delta = 0.001, msg = nil
-
n = (exp - act).abs
-
msg = message(msg) {
-
"Expected |#{exp} - #{act}| (#{n}) to not be <= #{delta}"
-
}
-
refute delta >= n, msg
-
end
-
-
##
-
# For comparing Floats. Fails if +exp+ and +act+ have a relative error
-
# less than +epsilon+.
-
-
1
def refute_in_epsilon a, b, epsilon = 0.001, msg = nil
-
refute_in_delta a, b, a * epsilon, msg
-
end
-
-
##
-
# Fails if +collection+ includes +obj+.
-
-
1
def refute_includes collection, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(collection)} to not include #{mu_pp(obj)}"
-
}
-
assert_respond_to collection, :include?
-
refute collection.include?(obj), msg
-
end
-
-
##
-
# Fails if +obj+ is an instance of +cls+.
-
-
1
def refute_instance_of cls, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to not be an instance of #{cls}"
-
}
-
refute obj.instance_of?(cls), msg
-
end
-
-
##
-
# Fails if +obj+ is a kind of +cls+.
-
-
1
def refute_kind_of cls, obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be a kind of #{cls}" }
-
refute obj.kind_of?(cls), msg
-
end
-
-
##
-
# Fails if +matcher+ <tt>=~</tt> +obj+.
-
-
1
def refute_match matcher, obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp matcher} to not match #{mu_pp obj}" }
-
assert_respond_to matcher, :"=~"
-
matcher = Regexp.new Regexp.escape matcher if String === matcher
-
refute matcher =~ obj, msg
-
end
-
-
##
-
# Fails if +obj+ is nil.
-
-
1
def refute_nil obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be nil" }
-
refute obj.nil?, msg
-
end
-
-
##
-
# Fails if +o1+ is not +op+ +o2+. Eg:
-
#
-
# refute_operator 1, :>, 2 #=> pass
-
# refute_operator 1, :<, 2 #=> fail
-
-
1
def refute_operator o1, op, o2 = UNDEFINED, msg = nil
-
return refute_predicate o1, op, msg if UNDEFINED == o2
-
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op} #{mu_pp(o2)}" }
-
refute o1.__send__(op, o2), msg
-
end
-
-
##
-
# For testing with predicates.
-
#
-
# refute_predicate str, :empty?
-
#
-
# This is really meant for specs and is front-ended by refute_operator:
-
#
-
# str.wont_be :empty?
-
-
1
def refute_predicate o1, op, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op}" }
-
refute o1.__send__(op), msg
-
end
-
-
##
-
# Fails if +obj+ responds to the message +meth+.
-
-
1
def refute_respond_to obj, meth, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not respond to #{meth}" }
-
-
refute obj.respond_to?(meth), msg
-
end
-
-
##
-
# Fails if +exp+ is the same (by object identity) as +act+.
-
-
1
def refute_same exp, act, msg = nil
-
msg = message(msg) {
-
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
-
"Expected %s (oid=%d) to not be the same as %s (oid=%d)" % data
-
}
-
refute exp.equal?(act), msg
-
end
-
-
##
-
# Skips the current run. If run in verbose-mode, the skipped run
-
# gets listed at the end of the run but doesn't cause a failure
-
# exit code.
-
-
1
def skip msg = nil, bt = caller
-
msg ||= "Skipped, no message given"
-
@skip = true
-
raise Minitest::Skip, msg, bt
-
end
-
-
##
-
# Was this testcase skipped? Meant for #teardown.
-
-
1
def skipped?
-
defined?(@skip) and @skip
-
end
-
end
-
end
-
1
module Minitest
-
1
module Parallel #:nodoc:
-
-
##
-
# The engine used to run multiple tests in parallel.
-
-
1
class Executor
-
-
##
-
# The size of the pool of workers.
-
-
1
attr_reader :size
-
-
##
-
# Create a parallel test executor of with +size+ workers.
-
-
1
def initialize size
-
1
@size = size
-
1
@queue = Queue.new
-
1
@pool = nil
-
end
-
-
##
-
# Start the executor
-
-
1
def start
-
@pool = size.times.map {
-
Thread.new(@queue) do |queue|
-
Thread.current.abort_on_exception = true
-
while (job = queue.pop)
-
klass, method, reporter = job
-
result = Minitest.run_one_method klass, method
-
reporter.synchronize { reporter.record result }
-
end
-
end
-
}
-
end
-
-
##
-
# Add a job to the queue
-
-
1
def << work; @queue << work; end
-
-
##
-
# Shuts down the pool of workers by signalling them to quit and
-
# waiting for them all to finish what they're currently working
-
# on.
-
-
1
def shutdown
-
size.times { @queue << nil }
-
@pool.each(&:join)
-
end
-
end
-
-
1
module Test
-
1
def _synchronize; Minitest::Test.io_lock.synchronize { yield }; end # :nodoc:
-
-
1
module ClassMethods # :nodoc:
-
1
def run_one_method klass, method_name, reporter
-
Minitest.parallel_executor << [klass, method_name, reporter]
-
end
-
-
1
def test_order
-
:parallel
-
end
-
end
-
end
-
end
-
end
-
1
require "minitest" unless defined? Minitest::Runnable
-
-
1
module Minitest
-
##
-
# Subclass Test to create your own tests. Typically you'll want a
-
# Test subclass per implementation class.
-
#
-
# See Minitest::Assertions
-
-
1
class Test < Runnable
-
1
require "minitest/assertions"
-
1
include Minitest::Assertions
-
-
1
PASSTHROUGH_EXCEPTIONS = [NoMemoryError, SignalException, SystemExit] # :nodoc:
-
-
# :stopdoc:
-
2
class << self; attr_accessor :io_lock; end
-
1
self.io_lock = Mutex.new
-
# :startdoc:
-
-
##
-
# Call this at the top of your tests when you absolutely
-
# positively need to have ordered tests. In doing so, you're
-
# admitting that you suck and your tests are weak.
-
-
1
def self.i_suck_and_my_tests_are_order_dependent!
-
class << self
-
undef_method :test_order if method_defined? :test_order
-
define_method :test_order do :alpha end
-
end
-
end
-
-
##
-
# Make diffs for this Test use #pretty_inspect so that diff
-
# in assert_equal can have more details. NOTE: this is much slower
-
# than the regular inspect but much more usable for complex
-
# objects.
-
-
1
def self.make_my_diffs_pretty!
-
require "pp"
-
-
define_method :mu_pp, &:pretty_inspect
-
end
-
-
##
-
# Call this at the top of your tests when you want to run your
-
# tests in parallel. In doing so, you're admitting that you rule
-
# and your tests are awesome.
-
-
1
def self.parallelize_me!
-
include Minitest::Parallel::Test
-
extend Minitest::Parallel::Test::ClassMethods
-
end
-
-
##
-
# Returns all instance methods starting with "test_". Based on
-
# #test_order, the methods are either sorted, randomized
-
# (default), or run in parallel.
-
-
1
def self.runnable_methods
-
methods = methods_matching(/^test_/)
-
-
case self.test_order
-
when :random, :parallel then
-
max = methods.size
-
methods.sort.sort_by { rand max }
-
when :alpha, :sorted then
-
methods.sort
-
else
-
raise "Unknown test_order: #{self.test_order.inspect}"
-
end
-
end
-
-
##
-
# Defines the order to run tests (:random by default). Override
-
# this or use a convenience method to change it for your tests.
-
-
1
def self.test_order
-
:random
-
end
-
-
##
-
# The time it took to run this test.
-
-
1
attr_accessor :time
-
-
1
def marshal_dump # :nodoc:
-
super << self.time
-
end
-
-
1
def marshal_load ary # :nodoc:
-
self.time = ary.pop
-
super
-
end
-
-
1
TEARDOWN_METHODS = %w[ before_teardown teardown after_teardown ] # :nodoc:
-
-
##
-
# Runs a single test with setup/teardown hooks.
-
-
1
def run
-
with_info_handler do
-
time_it do
-
capture_exceptions do
-
before_setup; setup; after_setup
-
-
self.send self.name
-
end
-
-
TEARDOWN_METHODS.each do |hook|
-
capture_exceptions do
-
self.send hook
-
end
-
end
-
end
-
end
-
-
self # per contract
-
end
-
-
##
-
# Provides before/after hooks for setup and teardown. These are
-
# meant for library writers, NOT for regular test authors. See
-
# #before_setup for an example.
-
-
1
module LifecycleHooks
-
-
##
-
# Runs before every test, before setup. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# As a simplistic example:
-
#
-
# module MyMinitestPlugin
-
# def before_setup
-
# super
-
# # ... stuff to do before setup is run
-
# end
-
#
-
# def after_setup
-
# # ... stuff to do after setup is run
-
# super
-
# end
-
#
-
# def before_teardown
-
# super
-
# # ... stuff to do before teardown is run
-
# end
-
#
-
# def after_teardown
-
# # ... stuff to do after teardown is run
-
# super
-
# end
-
# end
-
#
-
# class MiniTest::Test
-
# include MyMinitestPlugin
-
# end
-
-
1
def before_setup; end
-
-
##
-
# Runs before every test. Use this to set up before each test
-
# run.
-
-
1
def setup; end
-
-
##
-
# Runs before every test, after setup. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
1
def after_setup; end
-
-
##
-
# Runs after every test, before teardown. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
1
def before_teardown; end
-
-
##
-
# Runs after every test. Use this to clean up after each test
-
# run.
-
-
1
def teardown; end
-
-
##
-
# Runs after every test, after teardown. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
1
def after_teardown; end
-
end # LifecycleHooks
-
-
1
def capture_exceptions # :nodoc:
-
yield
-
rescue *PASSTHROUGH_EXCEPTIONS
-
raise
-
rescue Assertion => e
-
self.failures << e
-
rescue Exception => e
-
self.failures << UnexpectedError.new(e)
-
end
-
-
##
-
# Did this run error?
-
-
1
def error?
-
self.failures.any? { |f| UnexpectedError === f }
-
end
-
-
##
-
# The location identifier of this test.
-
-
1
def location
-
loc = " [#{self.failure.location}]" unless passed? or error?
-
"#{self.class}##{self.name}#{loc}"
-
end
-
-
##
-
# Did this run pass?
-
#
-
# Note: skipped runs are not considered passing, but they don't
-
# cause the process to exit non-zero.
-
-
1
def passed?
-
not self.failure
-
end
-
-
##
-
# Returns ".", "F", or "E" based on the result of the run.
-
-
1
def result_code
-
self.failure and self.failure.result_code or "."
-
end
-
-
##
-
# Was this run skipped?
-
-
1
def skipped?
-
self.failure and Skip === self.failure
-
end
-
-
1
def time_it # :nodoc:
-
t0 = Minitest.clock_time
-
-
yield
-
ensure
-
self.time = Minitest.clock_time - t0
-
end
-
-
1
def to_s # :nodoc:
-
return location if passed? and not skipped?
-
-
failures.map { |failure|
-
"#{failure.result_label}:\n#{self.location}:\n#{failure.message}\n"
-
}.join "\n"
-
end
-
-
1
def with_info_handler &block # :nodoc:
-
t0 = Minitest.clock_time
-
-
handler = lambda do
-
warn "\nCurrent: %s#%s %.2fs" % [self.class, self.name, Minitest.clock_time - t0]
-
end
-
-
self.class.on_signal ::Minitest.info_signal, handler, &block
-
end
-
-
1
include LifecycleHooks
-
1
include Guard
-
1
extend Guard
-
end # Test
-
end
-
-
1
require "minitest/unit" unless defined?(MiniTest) # compatibility layer only
-
# :stopdoc:
-
-
1
unless defined?(Minitest) then
-
# all of this crap is just to avoid circular requires and is only
-
# needed if a user requires "minitest/unit" directly instead of
-
# "minitest/autorun", so we also warn
-
-
from = caller.reject { |s| s =~ /rubygems/ }.join("\n ")
-
warn "Warning: you should require 'minitest/autorun' instead."
-
warn %(Warning: or add 'gem "minitest"' before 'require "minitest/autorun"')
-
warn "From:\n #{from}"
-
-
module Minitest; end
-
MiniTest = Minitest # prevents minitest.rb from requiring back to us
-
require "minitest"
-
end
-
-
1
MiniTest = Minitest unless defined?(MiniTest)
-
-
1
module Minitest
-
1
class Unit
-
1
VERSION = Minitest::VERSION
-
1
class TestCase < Minitest::Test
-
1
def self.inherited klass # :nodoc:
-
from = caller.first
-
warn "MiniTest::Unit::TestCase is now Minitest::Test. From #{from}"
-
super
-
end
-
end
-
-
1
def self.autorun # :nodoc:
-
from = caller.first
-
warn "MiniTest::Unit.autorun is now Minitest.autorun. From #{from}"
-
Minitest.autorun
-
end
-
-
1
def self.after_tests &b # :nodoc:
-
from = caller.first
-
warn "MiniTest::Unit.after_tests is now Minitest.after_run. From #{from}"
-
Minitest.after_run(&b)
-
end
-
end
-
end
-
-
# :startdoc:
-
# -*- coding: utf-8 -*-
-
# Modify the PATH on windows so that the external DLLs will get loaded.
-
-
1
require 'rbconfig'
-
-
1
if defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
-
# The line below caused a problem on non-GAE rack environment.
-
# unless defined?(JRuby::Rack::VERSION) || defined?(AppEngine::ApiProxy)
-
#
-
# However, simply cutting defined?(JRuby::Rack::VERSION) off resulted in
-
# an unable-to-load-nokogiri problem. Thus, now, Nokogiri checks the presense
-
# of appengine-rack.jar in $LOAD_PATH. If Nokogiri is on GAE, Nokogiri
-
# should skip loading xml jars. This is because those are in WEB-INF/lib and
-
# already set in the classpath.
-
unless $LOAD_PATH.to_s.include?("appengine-rack")
-
require 'stringio'
-
require 'isorelax.jar'
-
require 'jing.jar'
-
require 'nekohtml.jar'
-
require 'nekodtd.jar'
-
require 'xercesImpl.jar'
-
require 'serializer.jar'
-
require 'xalan.jar'
-
require 'xml-apis.jar'
-
end
-
end
-
-
1
begin
-
1
RUBY_VERSION =~ /(\d+\.\d+)/
-
1
require "nokogiri/#{$1}/nokogiri"
-
rescue LoadError
-
1
require 'nokogiri/nokogiri'
-
end
-
1
require 'nokogiri/version'
-
1
require 'nokogiri/syntax_error'
-
1
require 'nokogiri/xml'
-
1
require 'nokogiri/xslt'
-
1
require 'nokogiri/html'
-
1
require 'nokogiri/decorators/slop'
-
1
require 'nokogiri/css'
-
1
require 'nokogiri/html/builder'
-
-
# Nokogiri parses and searches XML/HTML very quickly, and also has
-
# correctly implemented CSS3 selector support as well as XPath 1.0
-
# support.
-
#
-
# Parsing a document returns either a Nokogiri::XML::Document, or a
-
# Nokogiri::HTML::Document depending on the kind of document you parse.
-
#
-
# Here is an example:
-
#
-
# require 'nokogiri'
-
# require 'open-uri'
-
#
-
# # Get a Nokogiri::HTML:Document for the page we’re interested in...
-
#
-
# doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))
-
#
-
# # Do funky things with it using Nokogiri::XML::Node methods...
-
#
-
# ####
-
# # Search for nodes by css
-
# doc.css('h3.r a.l').each do |link|
-
# puts link.content
-
# end
-
#
-
# See Nokogiri::XML::Searchable#css for more information about CSS searching.
-
# See Nokogiri::XML::Searchable#xpath for more information about XPath searching.
-
1
module Nokogiri
-
1
class << self
-
###
-
# Parse an HTML or XML document. +string+ contains the document.
-
1
def parse string, url = nil, encoding = nil, options = nil
-
if string.respond_to?(:read) ||
-
/^\s*<(?:!DOCTYPE\s+)?html[\s>]/i === string[0, 512]
-
# Expect an HTML indicator to appear within the first 512
-
# characters of a document. (<?xml ?> + <?xml-stylesheet ?>
-
# shouldn't be that long)
-
Nokogiri.HTML(string, url, encoding,
-
options || XML::ParseOptions::DEFAULT_HTML)
-
else
-
Nokogiri.XML(string, url, encoding,
-
options || XML::ParseOptions::DEFAULT_XML)
-
end.tap { |doc|
-
yield doc if block_given?
-
}
-
end
-
-
###
-
# Create a new Nokogiri::XML::DocumentFragment
-
1
def make input = nil, opts = {}, &blk
-
if input
-
Nokogiri::HTML.fragment(input).children.first
-
else
-
Nokogiri(&blk)
-
end
-
end
-
-
###
-
# Parse a document and add the Slop decorator. The Slop decorator
-
# implements method_missing such that methods may be used instead of CSS
-
# or XPath. For example:
-
#
-
# doc = Nokogiri::Slop(<<-eohtml)
-
# <html>
-
# <body>
-
# <p>first</p>
-
# <p>second</p>
-
# </body>
-
# </html>
-
# eohtml
-
# assert_equal('second', doc.html.body.p[1].text)
-
#
-
1
def Slop(*args, &block)
-
Nokogiri(*args, &block).slop!
-
end
-
-
1
def install_default_aliases
-
# Make sure to support some popular encoding aliases not known by
-
# all iconv implementations.
-
{
-
'Windows-31J' => 'CP932', # Windows-31J is the IANA registered name of CP932.
-
1
}.each { |alias_name, name|
-
1
EncodingHandler.alias(name, alias_name) if EncodingHandler[alias_name].nil?
-
}
-
end
-
end
-
-
1
Nokogiri.install_default_aliases
-
end
-
-
###
-
# Parser a document contained in +args+. Nokogiri will try to guess what
-
# type of document you are attempting to parse. For more information, see
-
# Nokogiri.parse
-
#
-
# To specify the type of document, use Nokogiri.XML or Nokogiri.HTML.
-
1
def Nokogiri(*args, &block)
-
if block_given?
-
Nokogiri::HTML::Builder.new(&block).doc.root
-
else
-
Nokogiri.parse(*args)
-
end
-
end
-
1
require 'nokogiri/css/node'
-
1
require 'nokogiri/css/xpath_visitor'
-
1
x = $-w
-
1
$-w = false
-
1
require 'nokogiri/css/parser'
-
1
$-w = x
-
-
1
require 'nokogiri/css/tokenizer'
-
1
require 'nokogiri/css/syntax_error'
-
-
1
module Nokogiri
-
1
module CSS
-
1
class << self
-
###
-
# Parse this CSS selector in +selector+. Returns an AST.
-
1
def parse selector
-
Parser.new.parse selector
-
end
-
-
###
-
# Get the XPath for +selector+.
-
1
def xpath_for selector, options={}
-
15
Parser.new(options[:ns] || {}).xpath_for selector, options
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module CSS
-
1
class Node
-
1
ALLOW_COMBINATOR_ON_SELF = [:DIRECT_ADJACENT_SELECTOR, :FOLLOWING_SELECTOR, :CHILD_SELECTOR]
-
-
# Get the type of this node
-
1
attr_accessor :type
-
# Get the value of this node
-
1
attr_accessor :value
-
-
# Create a new Node with +type+ and +value+
-
1
def initialize type, value
-
2
@type = type
-
2
@value = value
-
end
-
-
# Accept +visitor+
-
1
def accept visitor
-
2
visitor.send(:"visit_#{type.to_s.downcase}", self)
-
end
-
-
###
-
# Convert this CSS node to xpath with +prefix+ using +visitor+
-
1
def to_xpath prefix = '//', visitor = XPathVisitor.new
-
2
prefix = '.' if ALLOW_COMBINATOR_ON_SELF.include?(type) && value.first.nil?
-
2
prefix + visitor.accept(self)
-
end
-
-
# Find a node by type using +types+
-
1
def find_by_type types
-
matches = []
-
matches << self if to_type == types
-
@value.each do |v|
-
matches += v.find_by_type(types) if v.respond_to?(:find_by_type)
-
end
-
matches
-
end
-
-
# Convert to_type
-
1
def to_type
-
[@type] + @value.map { |n|
-
n.to_type if n.respond_to?(:to_type)
-
}.compact
-
end
-
-
# Convert to array
-
1
def to_a
-
[@type] + @value.map { |n| n.respond_to?(:to_a) ? n.to_a : [n] }
-
end
-
end
-
end
-
end
-
#
-
# DO NOT MODIFY!!!!
-
# This file is automatically generated by Racc 1.4.12
-
# from Racc grammer file "".
-
#
-
-
1
require 'racc/parser.rb'
-
-
-
1
require 'nokogiri/css/parser_extras'
-
-
1
module Nokogiri
-
1
module CSS
-
1
class Parser < Racc::Parser
-
-
-
1
def unescape_css_identifier(identifier)
-
identifier.gsub(/\\(?:([^0-9a-fA-F])|([0-9a-fA-F]{1,6})\s?)/){ |m| $1 || [$2.hex].pack('U') }
-
end
-
##### State transition tables begin ###
-
-
1
racc_action_table = [
-
24, 93, 56, 57, 33, 55, 94, 23, 24, 22,
-
12, 93, 33, 27, 35, 52, 88, 22, -23, 25,
-
92, 98, 23, 33, 26, 18, 20, 25, 27, 86,
-
23, 24, 26, 18, 20, 33, 27, 11, 39, 24,
-
22, 23, 89, 33, 18, 101, 100, 27, 22, 12,
-
25, 24, 95, 23, 90, 26, 18, 20, 25, 27,
-
66, 23, 24, 26, 18, 20, 33, 27, 91, 90,
-
51, 22, 96, 85, 33, 26, 33, -23, 33, 56,
-
87, 25, 60, 99, 23, 74, 26, 18, 20, 39,
-
27, 39, 23, 39, 23, 18, 23, 18, 27, 18,
-
27, 33, 27, 33, 56, 87, 22, 60, 56, 87,
-
102, 60, 56, 87, 33, 60, 39, 24, 39, 23,
-
103, 23, 18, 20, 18, 27, 46, 27, 49, 39,
-
93, 44, 23, 105, 33, 18, 51, 45, 27, 33,
-
-23, 26, 108, 56, 58, 109, 60, nil, nil, 39,
-
nil, nil, 23, nil, 39, 18, nil, 23, 27, nil,
-
18, 20, nil, 27, 82, 83, nil, nil, nil, 82,
-
83, nil, nil, nil, nil, 78, 79, 80, nil, 81,
-
78, 79, 80, 77, 81, 4, 5, 10, 77, 4,
-
5, 43, nil, nil, nil, 6, nil, 8, 7, 6,
-
nil, 8, 7, 4, 5, 10, nil, nil, nil, nil,
-
nil, nil, nil, 6, nil, 8, 7 ]
-
-
1
racc_action_check = [
-
42, 58, 24, 24, 42, 24, 57, 15, 43, 42,
-
64, 57, 43, 15, 11, 24, 53, 43, 58, 42,
-
56, 64, 42, 14, 42, 42, 42, 43, 42, 50,
-
43, 3, 43, 43, 43, 3, 43, 1, 14, 9,
-
3, 14, 54, 9, 14, 76, 76, 14, 9, 1,
-
3, 27, 59, 3, 60, 3, 3, 3, 9, 3,
-
27, 9, 12, 9, 9, 9, 12, 9, 55, 55,
-
27, 12, 61, 49, 28, 27, 62, 46, 30, 92,
-
92, 12, 92, 75, 12, 45, 12, 12, 12, 28,
-
12, 62, 28, 30, 62, 28, 30, 62, 28, 30,
-
62, 39, 30, 32, 90, 90, 39, 90, 51, 51,
-
84, 51, 93, 93, 31, 93, 39, 23, 32, 39,
-
86, 32, 39, 39, 32, 39, 23, 32, 23, 31,
-
87, 18, 31, 91, 29, 31, 23, 21, 31, 25,
-
22, 23, 94, 25, 25, 105, 25, nil, nil, 29,
-
nil, nil, 29, nil, 25, 29, nil, 25, 29, nil,
-
25, 25, nil, 25, 48, 48, nil, nil, nil, 47,
-
47, nil, nil, nil, nil, 48, 48, 48, nil, 48,
-
47, 47, 47, 48, 47, 0, 0, 0, 47, 17,
-
17, 17, nil, nil, nil, 0, nil, 0, 0, 17,
-
nil, 17, 17, 26, 26, 26, nil, nil, nil, nil,
-
nil, nil, nil, 26, nil, 26, 26 ]
-
-
1
racc_action_pointer = [
-
178, 37, nil, 29, nil, nil, nil, nil, nil, 37,
-
nil, 14, 60, nil, 17, -17, nil, 182, 120, nil,
-
nil, 108, 111, 115, -8, 133, 196, 49, 68, 128,
-
72, 108, 97, nil, nil, nil, nil, nil, nil, 95,
-
nil, nil, -2, 6, nil, 74, 48, 166, 161, 48,
-
0, 98, nil, -7, 19, 57, 8, -1, -11, 29,
-
42, 49, 70, nil, -2, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, 58, 35, nil, nil, nil,
-
nil, nil, nil, nil, 85, nil, 109, 118, nil, nil,
-
94, 126, 69, 102, 129, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, 132, nil, nil, nil, nil ]
-
-
1
racc_action_default = [
-
-74, -75, -2, -24, -4, -5, -6, -7, -8, -24,
-
-73, -75, -24, -3, -47, -10, -13, -17, -75, -19,
-
-20, -75, -22, -24, -75, -24, -74, -75, -53, -54,
-
-55, -56, -57, -58, -14, 110, -1, -9, -46, -24,
-
-11, -12, -24, -24, -18, -75, -29, -61, -61, -75,
-
-75, -75, -30, -75, -75, -38, -39, -40, -22, -75,
-
-38, -75, -70, -72, -75, -44, -45, -48, -49, -50,
-
-51, -52, -15, -16, -21, -75, -75, -62, -63, -64,
-
-65, -66, -67, -68, -75, -27, -75, -40, -31, -32,
-
-75, -43, -75, -75, -75, -33, -69, -71, -34, -25,
-
-59, -60, -26, -28, -35, -75, -36, -37, -42, -41 ]
-
-
1
racc_goto_table = [
-
53, 38, 13, 1, 41, 48, 62, 40, 34, 65,
-
50, 36, 63, 75, 84, 67, 68, 69, 70, 71,
-
62, 47, 37, 42, 54, nil, 63, nil, nil, 64,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, 72, 73, nil, nil, nil, nil, nil, nil, 97,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, nil, 104, nil, 106, 107 ]
-
-
1
racc_goto_check = [
-
18, 12, 2, 1, 11, 9, 7, 10, 2, 9,
-
15, 2, 12, 17, 17, 12, 12, 12, 12, 12,
-
7, 16, 8, 5, 19, nil, 12, nil, nil, 1,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, 2, 2, nil, nil, nil, nil, nil, nil, 12,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, nil, 18, nil, 18, 18 ]
-
-
1
racc_goto_pointer = [
-
nil, 3, -1, nil, nil, 6, nil, -19, 8, -18,
-
-8, -11, -13, nil, nil, -13, -2, -34, -24, 0,
-
nil, nil, nil, nil ]
-
-
1
racc_goto_default = [
-
nil, nil, nil, 2, 3, 9, 17, 14, nil, 15,
-
31, 30, 16, 29, 19, 21, nil, nil, 59, nil,
-
28, 32, 76, 61 ]
-
-
1
racc_reduce_table = [
-
0, 0, :racc_error,
-
3, 32, :_reduce_1,
-
1, 32, :_reduce_2,
-
2, 32, :_reduce_3,
-
1, 36, :_reduce_4,
-
1, 36, :_reduce_5,
-
1, 36, :_reduce_6,
-
1, 36, :_reduce_7,
-
1, 36, :_reduce_8,
-
2, 37, :_reduce_9,
-
1, 37, :_reduce_none,
-
2, 37, :_reduce_11,
-
2, 37, :_reduce_12,
-
1, 37, :_reduce_13,
-
2, 34, :_reduce_14,
-
3, 33, :_reduce_15,
-
3, 33, :_reduce_16,
-
1, 33, :_reduce_none,
-
2, 44, :_reduce_18,
-
1, 38, :_reduce_none,
-
1, 38, :_reduce_20,
-
3, 45, :_reduce_21,
-
1, 45, :_reduce_22,
-
1, 46, :_reduce_23,
-
0, 46, :_reduce_none,
-
4, 42, :_reduce_25,
-
4, 42, :_reduce_26,
-
3, 42, :_reduce_27,
-
3, 47, :_reduce_28,
-
1, 47, :_reduce_29,
-
2, 40, :_reduce_30,
-
3, 40, :_reduce_31,
-
3, 40, :_reduce_32,
-
3, 40, :_reduce_33,
-
3, 40, :_reduce_34,
-
3, 49, :_reduce_35,
-
3, 49, :_reduce_36,
-
3, 49, :_reduce_37,
-
1, 49, :_reduce_none,
-
1, 49, :_reduce_none,
-
1, 49, :_reduce_40,
-
4, 50, :_reduce_41,
-
3, 50, :_reduce_42,
-
2, 50, :_reduce_43,
-
2, 41, :_reduce_44,
-
2, 41, :_reduce_45,
-
1, 39, :_reduce_none,
-
0, 39, :_reduce_none,
-
2, 43, :_reduce_48,
-
2, 43, :_reduce_49,
-
2, 43, :_reduce_50,
-
2, 43, :_reduce_51,
-
2, 43, :_reduce_52,
-
1, 43, :_reduce_none,
-
1, 43, :_reduce_none,
-
1, 43, :_reduce_none,
-
1, 43, :_reduce_none,
-
1, 43, :_reduce_none,
-
1, 51, :_reduce_58,
-
2, 48, :_reduce_59,
-
2, 48, :_reduce_60,
-
0, 48, :_reduce_none,
-
1, 53, :_reduce_62,
-
1, 53, :_reduce_63,
-
1, 53, :_reduce_64,
-
1, 53, :_reduce_65,
-
1, 53, :_reduce_66,
-
1, 53, :_reduce_67,
-
1, 53, :_reduce_68,
-
3, 52, :_reduce_69,
-
1, 54, :_reduce_none,
-
2, 54, :_reduce_none,
-
1, 54, :_reduce_none,
-
1, 35, :_reduce_none,
-
0, 35, :_reduce_none ]
-
-
1
racc_reduce_n = 75
-
-
1
racc_shift_n = 110
-
-
1
racc_token_table = {
-
false => 0,
-
:error => 1,
-
:FUNCTION => 2,
-
:INCLUDES => 3,
-
:DASHMATCH => 4,
-
:LBRACE => 5,
-
:HASH => 6,
-
:PLUS => 7,
-
:GREATER => 8,
-
:S => 9,
-
:STRING => 10,
-
:IDENT => 11,
-
:COMMA => 12,
-
:NUMBER => 13,
-
:PREFIXMATCH => 14,
-
:SUFFIXMATCH => 15,
-
:SUBSTRINGMATCH => 16,
-
:TILDE => 17,
-
:NOT_EQUAL => 18,
-
:SLASH => 19,
-
:DOUBLESLASH => 20,
-
:NOT => 21,
-
:EQUAL => 22,
-
:RPAREN => 23,
-
:LSQUARE => 24,
-
:RSQUARE => 25,
-
:HAS => 26,
-
"." => 27,
-
"*" => 28,
-
"|" => 29,
-
":" => 30 }
-
-
1
racc_nt_base = 31
-
-
1
racc_use_result_var = true
-
-
1
Racc_arg = [
-
racc_action_table,
-
racc_action_check,
-
racc_action_default,
-
racc_action_pointer,
-
racc_goto_table,
-
racc_goto_check,
-
racc_goto_default,
-
racc_goto_pointer,
-
racc_nt_base,
-
racc_reduce_table,
-
racc_token_table,
-
racc_shift_n,
-
racc_reduce_n,
-
racc_use_result_var ]
-
-
1
Racc_token_to_s_table = [
-
"$end",
-
"error",
-
"FUNCTION",
-
"INCLUDES",
-
"DASHMATCH",
-
"LBRACE",
-
"HASH",
-
"PLUS",
-
"GREATER",
-
"S",
-
"STRING",
-
"IDENT",
-
"COMMA",
-
"NUMBER",
-
"PREFIXMATCH",
-
"SUFFIXMATCH",
-
"SUBSTRINGMATCH",
-
"TILDE",
-
"NOT_EQUAL",
-
"SLASH",
-
"DOUBLESLASH",
-
"NOT",
-
"EQUAL",
-
"RPAREN",
-
"LSQUARE",
-
"RSQUARE",
-
"HAS",
-
"\".\"",
-
"\"*\"",
-
"\"|\"",
-
"\":\"",
-
"$start",
-
"selector",
-
"simple_selector_1toN",
-
"prefixless_combinator_selector",
-
"optional_S",
-
"combinator",
-
"simple_selector",
-
"element_name",
-
"hcap_0toN",
-
"function",
-
"pseudo",
-
"attrib",
-
"hcap_1toN",
-
"class",
-
"namespaced_ident",
-
"namespace",
-
"attrib_name",
-
"attrib_val_0or1",
-
"expr",
-
"nth",
-
"attribute_id",
-
"negation",
-
"eql_incl_dash",
-
"negation_arg" ]
-
-
1
Racc_debug_parser = false
-
-
##### State transition tables end #####
-
-
# reduce 0 omitted
-
-
1
def _reduce_1(val, _values, result)
-
result = [val.first, val.last].flatten
-
-
result
-
end
-
-
1
def _reduce_2(val, _values, result)
-
result = val.flatten
-
result
-
end
-
-
1
def _reduce_3(val, _values, result)
-
2
result = [val.last].flatten
-
2
result
-
end
-
-
1
def _reduce_4(val, _values, result)
-
result = :DIRECT_ADJACENT_SELECTOR
-
result
-
end
-
-
1
def _reduce_5(val, _values, result)
-
result = :CHILD_SELECTOR
-
result
-
end
-
-
1
def _reduce_6(val, _values, result)
-
result = :FOLLOWING_SELECTOR
-
result
-
end
-
-
1
def _reduce_7(val, _values, result)
-
result = :DESCENDANT_SELECTOR
-
result
-
end
-
-
1
def _reduce_8(val, _values, result)
-
result = :CHILD_SELECTOR
-
result
-
end
-
-
1
def _reduce_9(val, _values, result)
-
2
result = if val[1].nil?
-
2
val.first
-
else
-
Node.new(:CONDITIONAL_SELECTOR, [val.first, val[1]])
-
end
-
-
2
result
-
end
-
-
# reduce 10 omitted
-
-
1
def _reduce_11(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR, val)
-
-
result
-
end
-
-
1
def _reduce_12(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR, val)
-
-
result
-
end
-
-
1
def _reduce_13(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR,
-
[Node.new(:ELEMENT_NAME, ['*']), val.first]
-
)
-
-
result
-
end
-
-
1
def _reduce_14(val, _values, result)
-
result = Node.new(val.first, [nil, val.last])
-
-
result
-
end
-
-
1
def _reduce_15(val, _values, result)
-
result = Node.new(val[1], [val.first, val.last])
-
-
result
-
end
-
-
1
def _reduce_16(val, _values, result)
-
result = Node.new(:DESCENDANT_SELECTOR, [val.first, val.last])
-
-
result
-
end
-
-
# reduce 17 omitted
-
-
1
def _reduce_18(val, _values, result)
-
result = Node.new(:CLASS_CONDITION, [unescape_css_identifier(val[1])])
-
result
-
end
-
-
# reduce 19 omitted
-
-
1
def _reduce_20(val, _values, result)
-
result = Node.new(:ELEMENT_NAME, val)
-
result
-
end
-
-
1
def _reduce_21(val, _values, result)
-
result = Node.new(:ELEMENT_NAME,
-
[[val.first, val.last].compact.join(':')]
-
)
-
-
result
-
end
-
-
1
def _reduce_22(val, _values, result)
-
2
name = @namespaces.key?('xmlns') ? "xmlns:#{val.first}" : val.first
-
2
result = Node.new(:ELEMENT_NAME, [name])
-
-
2
result
-
end
-
-
1
def _reduce_23(val, _values, result)
-
result = val[0]
-
result
-
end
-
-
# reduce 24 omitted
-
-
1
def _reduce_25(val, _values, result)
-
result = Node.new(:ATTRIBUTE_CONDITION,
-
[val[1]] + (val[2] || [])
-
)
-
-
result
-
end
-
-
1
def _reduce_26(val, _values, result)
-
result = Node.new(:ATTRIBUTE_CONDITION,
-
[val[1]] + (val[2] || [])
-
)
-
-
result
-
end
-
-
1
def _reduce_27(val, _values, result)
-
# Non standard, but hpricot supports it.
-
result = Node.new(:PSEUDO_CLASS,
-
[Node.new(:FUNCTION, ['nth-child(', val[1]])]
-
)
-
-
result
-
end
-
-
1
def _reduce_28(val, _values, result)
-
result = Node.new(:ELEMENT_NAME,
-
[[val.first, val.last].compact.join(':')]
-
)
-
-
result
-
end
-
-
1
def _reduce_29(val, _values, result)
-
# Default namespace is not applied to attributes.
-
# So we don't add prefix "xmlns:" as in namespaced_ident.
-
result = Node.new(:ELEMENT_NAME, [val.first])
-
-
result
-
end
-
-
1
def _reduce_30(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip])
-
-
result
-
end
-
-
1
def _reduce_31(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
1
def _reduce_32(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
1
def _reduce_33(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
1
def _reduce_34(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
1
def _reduce_35(val, _values, result)
-
result = [val.first, val.last]
-
result
-
end
-
-
1
def _reduce_36(val, _values, result)
-
result = [val.first, val.last]
-
result
-
end
-
-
1
def _reduce_37(val, _values, result)
-
result = [val.first, val.last]
-
result
-
end
-
-
# reduce 38 omitted
-
-
# reduce 39 omitted
-
-
1
def _reduce_40(val, _values, result)
-
case val[0]
-
when 'even'
-
result = Node.new(:NTH, ['2','n','+','0'])
-
when 'odd'
-
result = Node.new(:NTH, ['2','n','+','1'])
-
when 'n'
-
result = Node.new(:NTH, ['1','n','+','0'])
-
else
-
# This is not CSS standard. It allows us to support this:
-
# assert_xpath("//a[foo(., @href)]", @parser.parse('a:foo(@href)'))
-
# assert_xpath("//a[foo(., @a, b)]", @parser.parse('a:foo(@a, b)'))
-
# assert_xpath("//a[foo(., a, 10)]", @parser.parse('a:foo(a, 10)'))
-
result = val
-
end
-
-
result
-
end
-
-
1
def _reduce_41(val, _values, result)
-
if val[1] == 'n'
-
result = Node.new(:NTH, val)
-
else
-
raise Racc::ParseError, "parse error on IDENT '#{val[1]}'"
-
end
-
-
result
-
end
-
-
1
def _reduce_42(val, _values, result)
-
# n+3, -n+3
-
if val[0] == 'n'
-
val.unshift("1")
-
result = Node.new(:NTH, val)
-
elsif val[0] == '-n'
-
val[0] = 'n'
-
val.unshift("-1")
-
result = Node.new(:NTH, val)
-
else
-
raise Racc::ParseError, "parse error on IDENT '#{val[1]}'"
-
end
-
-
result
-
end
-
-
1
def _reduce_43(val, _values, result)
-
# 5n, -5n, 10n-1
-
n = val[1]
-
if n[0, 2] == 'n-'
-
val[1] = 'n'
-
val << "-"
-
# b is contained in n as n is the string "n-b"
-
val << n[2, n.size]
-
result = Node.new(:NTH, val)
-
elsif n == 'n'
-
val << "+"
-
val << "0"
-
result = Node.new(:NTH, val)
-
else
-
raise Racc::ParseError, "parse error on IDENT '#{val[1]}'"
-
end
-
-
result
-
end
-
-
1
def _reduce_44(val, _values, result)
-
result = Node.new(:PSEUDO_CLASS, [val[1]])
-
-
result
-
end
-
-
1
def _reduce_45(val, _values, result)
-
result = Node.new(:PSEUDO_CLASS, [val[1]])
-
result
-
end
-
-
# reduce 46 omitted
-
-
# reduce 47 omitted
-
-
1
def _reduce_48(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
1
def _reduce_49(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
1
def _reduce_50(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
1
def _reduce_51(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
1
def _reduce_52(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
# reduce 53 omitted
-
-
# reduce 54 omitted
-
-
# reduce 55 omitted
-
-
# reduce 56 omitted
-
-
# reduce 57 omitted
-
-
1
def _reduce_58(val, _values, result)
-
result = Node.new(:ID, [unescape_css_identifier(val.first)])
-
result
-
end
-
-
1
def _reduce_59(val, _values, result)
-
result = [val.first, val[1]]
-
result
-
end
-
-
1
def _reduce_60(val, _values, result)
-
result = [val.first, val[1]]
-
result
-
end
-
-
# reduce 61 omitted
-
-
1
def _reduce_62(val, _values, result)
-
result = :equal
-
result
-
end
-
-
1
def _reduce_63(val, _values, result)
-
result = :prefix_match
-
result
-
end
-
-
1
def _reduce_64(val, _values, result)
-
result = :suffix_match
-
result
-
end
-
-
1
def _reduce_65(val, _values, result)
-
result = :substring_match
-
result
-
end
-
-
1
def _reduce_66(val, _values, result)
-
result = :not_equal
-
result
-
end
-
-
1
def _reduce_67(val, _values, result)
-
result = :includes
-
result
-
end
-
-
1
def _reduce_68(val, _values, result)
-
result = :dash_match
-
result
-
end
-
-
1
def _reduce_69(val, _values, result)
-
result = Node.new(:NOT, [val[1]])
-
-
result
-
end
-
-
# reduce 70 omitted
-
-
# reduce 71 omitted
-
-
# reduce 72 omitted
-
-
# reduce 73 omitted
-
-
# reduce 74 omitted
-
-
1
def _reduce_none(val, _values, result)
-
val[0]
-
end
-
-
end # class Parser
-
end # module CSS
-
end # module Nokogiri
-
1
require 'thread'
-
-
1
module Nokogiri
-
1
module CSS
-
1
class Parser < Racc::Parser
-
1
@cache_on = true
-
1
@cache = {}
-
1
@mutex = Mutex.new
-
-
1
class << self
-
# Turn on CSS parse caching
-
1
attr_accessor :cache_on
-
1
alias :cache_on? :cache_on
-
1
alias :set_cache :cache_on=
-
-
# Get the css selector in +string+ from the cache
-
1
def [] string
-
15
return unless @cache_on
-
30
@mutex.synchronize { @cache[string] }
-
end
-
-
# Set the css selector in +string+ in the cache to +value+
-
1
def []= string, value
-
2
return value unless @cache_on
-
4
@mutex.synchronize { @cache[string] = value }
-
end
-
-
# Clear the cache
-
1
def clear_cache
-
@mutex.synchronize { @cache = {} }
-
end
-
-
# Execute +block+ without cache
-
1
def without_cache &block
-
tmp = @cache_on
-
@cache_on = false
-
block.call
-
@cache_on = tmp
-
end
-
-
###
-
# Parse this CSS selector in +selector+. Returns an AST.
-
1
def parse selector
-
@warned ||= false
-
unless @warned
-
$stderr.puts('Nokogiri::CSS::Parser.parse is deprecated, call Nokogiri::CSS.parse(), this will be removed August 1st or version 1.4.0 (whichever is first)')
-
@warned = true
-
end
-
new.parse selector
-
end
-
end
-
-
# Create a new CSS parser with respect to +namespaces+
-
1
def initialize namespaces = {}
-
15
@tokenizer = Tokenizer.new
-
15
@namespaces = namespaces
-
15
super()
-
end
-
-
1
def parse string
-
2
@tokenizer.scan_setup string
-
2
do_parse
-
end
-
-
1
def next_token
-
4
@tokenizer.next_token
-
end
-
-
# Get the xpath for +string+ using +options+
-
1
def xpath_for string, options={}
-
15
key = "#{string}#{options[:ns]}#{options[:prefix]}"
-
15
v = self.class[key]
-
15
return v if v
-
-
2
args = [
-
options[:prefix] || '//',
-
options[:visitor] || XPathVisitor.new
-
]
-
2
self.class[key] = parse(string).map { |ast|
-
2
ast.to_xpath(*args)
-
}
-
end
-
-
# On CSS parser error, raise an exception
-
1
def on_error error_token_id, error_value, value_stack
-
after = value_stack.compact.last
-
raise SyntaxError.new("unexpected '#{error_value}' after '#{after}'")
-
end
-
end
-
end
-
end
-
1
require 'nokogiri/syntax_error'
-
1
module Nokogiri
-
1
module CSS
-
1
class SyntaxError < ::Nokogiri::SyntaxError
-
end
-
end
-
end
-
#--
-
# DO NOT MODIFY!!!!
-
# This file is automatically generated by rex 1.0.5
-
# from lexical definition file "lib/nokogiri/css/tokenizer.rex".
-
#++
-
-
1
module Nokogiri
-
1
module CSS
-
1
class Tokenizer # :nodoc:
-
1
require 'strscan'
-
-
1
class ScanError < StandardError ; end
-
-
1
attr_reader :lineno
-
1
attr_reader :filename
-
1
attr_accessor :state
-
-
1
def scan_setup(str)
-
2
@ss = StringScanner.new(str)
-
2
@lineno = 1
-
2
@state = nil
-
end
-
-
1
def action
-
2
yield
-
end
-
-
1
def scan_str(str)
-
scan_setup(str)
-
do_parse
-
end
-
1
alias :scan :scan_str
-
-
1
def load_file( filename )
-
@filename = filename
-
open(filename, "r") do |f|
-
scan_setup(f.read)
-
end
-
end
-
-
1
def scan_file( filename )
-
load_file(filename)
-
do_parse
-
end
-
-
-
1
def next_token
-
4
return if @ss.eos?
-
-
# skips empty actions
-
2
until token = _next_token or @ss.eos?; end
-
2
token
-
end
-
-
1
def _next_token
-
2
text = @ss.peek(1)
-
2
@lineno += 1 if text == "\n"
-
2
token = case @state
-
when nil
-
case
-
2
when (text = @ss.scan(/has\([\s]*/))
-
action { [:HAS, text] }
-
-
2
when (text = @ss.scan(/[-@]?([_A-Za-z]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*\([\s]*/))
-
action { [:FUNCTION, text] }
-
-
2
when (text = @ss.scan(/[-@]?([_A-Za-z]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*/))
-
4
action { [:IDENT, text] }
-
-
when (text = @ss.scan(/\#([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])+/))
-
action { [:HASH, text] }
-
-
when (text = @ss.scan(/[\s]*~=[\s]*/))
-
action { [:INCLUDES, text] }
-
-
when (text = @ss.scan(/[\s]*\|=[\s]*/))
-
action { [:DASHMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*\^=[\s]*/))
-
action { [:PREFIXMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*\$=[\s]*/))
-
action { [:SUFFIXMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*\*=[\s]*/))
-
action { [:SUBSTRINGMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*!=[\s]*/))
-
action { [:NOT_EQUAL, text] }
-
-
when (text = @ss.scan(/[\s]*=[\s]*/))
-
action { [:EQUAL, text] }
-
-
when (text = @ss.scan(/[\s]*\)/))
-
action { [:RPAREN, text] }
-
-
when (text = @ss.scan(/\[[\s]*/))
-
action { [:LSQUARE, text] }
-
-
when (text = @ss.scan(/[\s]*\]/))
-
action { [:RSQUARE, text] }
-
-
when (text = @ss.scan(/[\s]*\+[\s]*/))
-
action { [:PLUS, text] }
-
-
when (text = @ss.scan(/[\s]*>[\s]*/))
-
action { [:GREATER, text] }
-
-
when (text = @ss.scan(/[\s]*,[\s]*/))
-
action { [:COMMA, text] }
-
-
when (text = @ss.scan(/[\s]*~[\s]*/))
-
action { [:TILDE, text] }
-
-
when (text = @ss.scan(/\:not\([\s]*/))
-
action { [:NOT, text] }
-
-
when (text = @ss.scan(/-?([0-9]+|[0-9]*\.[0-9]+)/))
-
action { [:NUMBER, text] }
-
-
when (text = @ss.scan(/[\s]*\/\/[\s]*/))
-
action { [:DOUBLESLASH, text] }
-
-
when (text = @ss.scan(/[\s]*\/[\s]*/))
-
action { [:SLASH, text] }
-
-
when (text = @ss.scan(/U\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})?/))
-
action {[:UNICODE_RANGE, text] }
-
-
when (text = @ss.scan(/[\s]+/))
-
action { [:S, text] }
-
-
when (text = @ss.scan(/"([^\n\r\f"]|\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*"|'([^\n\r\f']|\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*'/))
-
action { [:STRING, text] }
-
-
when (text = @ss.scan(/./))
-
action { [text, text] }
-
-
else
-
text = @ss.string[@ss.pos .. -1]
-
raise ScanError, "can not match: '" + text + "'"
-
2
end # if
-
-
else
-
raise ScanError, "undefined state: '" + state.to_s + "'"
-
end # case state
-
2
token
-
end # def _next_token
-
-
end # class
-
end
-
end
-
1
module Nokogiri
-
1
module CSS
-
1
class XPathVisitor # :nodoc:
-
1
def visit_function node
-
-
msg = :"visit_function_#{node.value.first.gsub(/[(]/, '')}"
-
return self.send(msg, node) if self.respond_to?(msg)
-
-
case node.value.first
-
when /^text\(/
-
'child::text()'
-
when /^self\(/
-
"self::#{node.value[1]}"
-
when /^eq\(/
-
"position() = #{node.value[1]}"
-
when /^(nth|nth-of-type)\(/
-
if node.value[1].is_a?(Nokogiri::CSS::Node) and node.value[1].type == :NTH
-
nth(node.value[1])
-
else
-
"position() = #{node.value[1]}"
-
end
-
when /^nth-child\(/
-
if node.value[1].is_a?(Nokogiri::CSS::Node) and node.value[1].type == :NTH
-
nth(node.value[1], :child => true)
-
else
-
"count(preceding-sibling::*) = #{node.value[1].to_i-1}"
-
end
-
when /^nth-last-of-type\(/
-
if node.value[1].is_a?(Nokogiri::CSS::Node) and node.value[1].type == :NTH
-
nth(node.value[1], :last => true)
-
else
-
index = node.value[1].to_i - 1
-
index == 0 ? "position() = last()" : "position() = last() - #{index}"
-
end
-
when /^nth-last-child\(/
-
if node.value[1].is_a?(Nokogiri::CSS::Node) and node.value[1].type == :NTH
-
nth(node.value[1], :last => true, :child => true)
-
else
-
"count(following-sibling::*) = #{node.value[1].to_i-1}"
-
end
-
when /^(first|first-of-type)\(/
-
"position() = 1"
-
when /^(last|last-of-type)\(/
-
"position() = last()"
-
when /^contains\(/
-
"contains(., #{node.value[1]})"
-
when /^gt\(/
-
"position() > #{node.value[1]}"
-
when /^only-child\(/
-
"last() = 1"
-
when /^comment\(/
-
"comment()"
-
when /^has\(/
-
node.value[1].accept(self)
-
else
-
args = ['.'] + node.value[1..-1]
-
"#{node.value.first}#{args.join(', ')})"
-
end
-
end
-
-
1
def visit_not node
-
child = node.value.first
-
if :ELEMENT_NAME == child.type
-
"not(self::#{child.accept(self)})"
-
else
-
"not(#{child.accept(self)})"
-
end
-
end
-
-
1
def visit_id node
-
node.value.first =~ /^#(.*)$/
-
"@id = '#{$1}'"
-
end
-
-
1
def visit_attribute_condition node
-
attribute = if (node.value.first.type == :FUNCTION) or (node.value.first.value.first =~ /::/)
-
''
-
else
-
'@'
-
end
-
attribute += node.value.first.accept(self)
-
-
# Support non-standard css
-
attribute.gsub!(/^@@/, '@')
-
-
return attribute unless node.value.length == 3
-
-
value = node.value.last
-
value = "'#{value}'" if value !~ /^['"]/
-
-
case node.value[1]
-
when :equal
-
attribute + " = " + "#{value}"
-
when :not_equal
-
attribute + " != " + "#{value}"
-
when :substring_match
-
"contains(#{attribute}, #{value})"
-
when :prefix_match
-
"starts-with(#{attribute}, #{value})"
-
when :dash_match
-
"#{attribute} = #{value} or starts-with(#{attribute}, concat(#{value}, '-'))"
-
when :includes
-
"contains(concat(\" \", #{attribute}, \" \"),concat(\" \", #{value}, \" \"))"
-
when :suffix_match
-
"substring(#{attribute}, string-length(#{attribute}) - " +
-
"string-length(#{value}) + 1, string-length(#{value})) = #{value}"
-
else
-
attribute + " #{node.value[1]} " + "#{value}"
-
end
-
end
-
-
1
def visit_pseudo_class node
-
if node.value.first.is_a?(Nokogiri::CSS::Node) and node.value.first.type == :FUNCTION
-
node.value.first.accept(self)
-
else
-
msg = :"visit_pseudo_class_#{node.value.first.gsub(/[(]/, '')}"
-
return self.send(msg, node) if self.respond_to?(msg)
-
-
case node.value.first
-
when "first" then "position() = 1"
-
when "first-child" then "count(preceding-sibling::*) = 0"
-
when "last" then "position() = last()"
-
when "last-child" then "count(following-sibling::*) = 0"
-
when "first-of-type" then "position() = 1"
-
when "last-of-type" then "position() = last()"
-
when "only-child" then "count(preceding-sibling::*) = 0 and count(following-sibling::*) = 0"
-
when "only-of-type" then "last() = 1"
-
when "empty" then "not(node())"
-
when "parent" then "node()"
-
when "root" then "not(parent::*)"
-
else
-
node.value.first + "(.)"
-
end
-
end
-
end
-
-
1
def visit_class_condition node
-
"contains(concat(' ', normalize-space(@class), ' '), ' #{node.value.first} ')"
-
end
-
-
1
def visit_combinator node
-
if is_of_type_pseudo_class?(node.value.last)
-
"#{node.value.first.accept(self) if node.value.first}][#{node.value.last.accept(self)}"
-
else
-
"#{node.value.first.accept(self) if node.value.first} and #{node.value.last.accept(self)}"
-
end
-
end
-
-
{
-
'direct_adjacent_selector' => "/following-sibling::*[1]/self::",
-
'following_selector' => "/following-sibling::",
-
'descendant_selector' => '//',
-
'child_selector' => '/',
-
1
}.each do |k,v|
-
4
class_eval %{
-
def visit_#{k} node
-
"\#{node.value.first.accept(self) if node.value.first}#{v}\#{node.value.last.accept(self)}"
-
end
-
}
-
end
-
-
1
def visit_conditional_selector node
-
node.value.first.accept(self) + '[' +
-
node.value.last.accept(self) + ']'
-
end
-
-
1
def visit_element_name node
-
2
node.value.first
-
end
-
-
1
def accept node
-
2
node.accept(self)
-
end
-
-
1
private
-
1
def nth node, options={}
-
raise ArgumentError, "expected an+b node to contain 4 tokens, but is #{node.value.inspect}" unless node.value.size == 4
-
-
a, b = read_a_and_positive_b node.value
-
position = if options[:child]
-
options[:last] ? "(count(following-sibling::*) + 1)" : "(count(preceding-sibling::*) + 1)"
-
else
-
options[:last] ? "(last()-position()+1)" : "position()"
-
end
-
-
if b.zero?
-
"(#{position} mod #{a}) = 0"
-
else
-
compare = a < 0 ? "<=" : ">="
-
if a.abs == 1
-
"#{position} #{compare} #{b}"
-
else
-
"(#{position} #{compare} #{b}) and (((#{position}-#{b}) mod #{a.abs}) = 0)"
-
end
-
end
-
end
-
-
1
def read_a_and_positive_b values
-
op = values[2]
-
if op == "+"
-
a = values[0].to_i
-
b = values[3].to_i
-
elsif op == "-"
-
a = values[0].to_i
-
b = a - (values[3].to_i % a)
-
else
-
raise ArgumentError, "expected an+b node to have either + or - as the operator, but is #{op.inspect}"
-
end
-
[a, b]
-
end
-
-
1
def is_of_type_pseudo_class? node
-
if node.type==:PSEUDO_CLASS
-
if node.value[0].is_a?(Nokogiri::CSS::Node) and node.value[0].type == :FUNCTION
-
node.value[0].value[0]
-
else
-
node.value[0]
-
end =~ /(nth|first|last|only)-of-type(\()?/
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module Decorators
-
###
-
# The Slop decorator implements method missing such that a methods may be
-
# used instead of XPath or CSS. See Nokogiri.Slop
-
1
module Slop
-
# The default XPath search context for Slop
-
1
XPATH_PREFIX = "./"
-
-
###
-
# look for node with +name+. See Nokogiri.Slop
-
1
def method_missing name, *args, &block
-
if args.empty?
-
list = xpath("#{XPATH_PREFIX}#{name.to_s.sub(/^_/, '')}")
-
elsif args.first.is_a? Hash
-
hash = args.first
-
if hash[:css]
-
list = css("#{name}#{hash[:css]}")
-
elsif hash[:xpath]
-
conds = Array(hash[:xpath]).join(' and ')
-
list = xpath("#{XPATH_PREFIX}#{name}[#{conds}]")
-
end
-
else
-
CSS::Parser.without_cache do
-
list = xpath(
-
*CSS.xpath_for("#{name}#{args.first}", :prefix => XPATH_PREFIX)
-
)
-
end
-
end
-
-
super if list.empty?
-
list.length == 1 ? list.first : list
-
end
-
-
1
def respond_to_missing? name, include_private = false
-
list = xpath("#{XPATH_PREFIX}#{name.to_s.sub(/^_/, '')}")
-
-
!list.empty?
-
end
-
end
-
end
-
end
-
1
require 'nokogiri/html/entity_lookup'
-
1
require 'nokogiri/html/document'
-
1
require 'nokogiri/html/document_fragment'
-
1
require 'nokogiri/html/sax/parser_context'
-
1
require 'nokogiri/html/sax/parser'
-
1
require 'nokogiri/html/sax/push_parser'
-
1
require 'nokogiri/html/element_description'
-
1
require 'nokogiri/html/element_description_defaults'
-
-
1
module Nokogiri
-
1
class << self
-
###
-
# Parse HTML. Convenience method for Nokogiri::HTML::Document.parse
-
1
def HTML thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
-
69
Nokogiri::HTML::Document.parse(thing, url, encoding, options, &block)
-
end
-
end
-
-
1
module HTML
-
1
class << self
-
###
-
# Parse HTML. Convenience method for Nokogiri::HTML::Document.parse
-
1
def parse thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
-
Document.parse(thing, url, encoding, options, &block)
-
end
-
-
####
-
# Parse a fragment from +string+ in to a NodeSet.
-
1
def fragment string, encoding = nil
-
HTML::DocumentFragment.parse string, encoding
-
end
-
end
-
-
# Instance of Nokogiri::HTML::EntityLookup
-
1
NamedCharacters = EntityLookup.new
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
###
-
# Nokogiri HTML builder is used for building HTML documents. It is very
-
# similar to the Nokogiri::XML::Builder. In fact, you should go read the
-
# documentation for Nokogiri::XML::Builder before reading this
-
# documentation.
-
#
-
# == Synopsis:
-
#
-
# Create an HTML document with a body that has an onload attribute, and a
-
# span tag with a class of "bold" that has content of "Hello world".
-
#
-
# builder = Nokogiri::HTML::Builder.new do |doc|
-
# doc.html {
-
# doc.body(:onload => 'some_func();') {
-
# doc.span.bold {
-
# doc.text "Hello world"
-
# }
-
# }
-
# }
-
# end
-
# puts builder.to_html
-
#
-
# The HTML builder inherits from the XML builder, so make sure to read the
-
# Nokogiri::XML::Builder documentation.
-
1
class Builder < Nokogiri::XML::Builder
-
###
-
# Convert the builder to HTML
-
1
def to_html
-
@doc.to_html
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
class Document < Nokogiri::XML::Document
-
###
-
# Get the meta tag encoding for this document. If there is no meta tag,
-
# then nil is returned.
-
1
def meta_encoding
-
case
-
when meta = at('//meta[@charset]')
-
meta[:charset]
-
when meta = meta_content_type
-
meta['content'][/charset\s*=\s*([\w-]+)/i, 1]
-
end
-
end
-
-
###
-
# Set the meta tag encoding for this document.
-
#
-
# If an meta encoding tag is already present, its content is
-
# replaced with the given text.
-
#
-
# Otherwise, this method tries to create one at an appropriate
-
# place supplying head and/or html elements as necessary, which
-
# is inside a head element if any, and before any text node or
-
# content element (typically <body>) if any.
-
#
-
# The result when trying to set an encoding that is different
-
# from the document encoding is undefined.
-
#
-
# Beware in CRuby, that libxml2 automatically inserts a meta tag
-
# into a head element.
-
1
def meta_encoding= encoding
-
case
-
when meta = meta_content_type
-
meta['content'] = 'text/html; charset=%s' % encoding
-
encoding
-
when meta = at('//meta[@charset]')
-
meta['charset'] = encoding
-
else
-
meta = XML::Node.new('meta', self)
-
if dtd = internal_subset and dtd.html5_dtd?
-
meta['charset'] = encoding
-
else
-
meta['http-equiv'] = 'Content-Type'
-
meta['content'] = 'text/html; charset=%s' % encoding
-
end
-
-
case
-
when head = at('//head')
-
head.prepend_child(meta)
-
else
-
set_metadata_element(meta)
-
end
-
encoding
-
end
-
end
-
-
1
def meta_content_type
-
xpath('//meta[@http-equiv and boolean(@content)]').find { |node|
-
node['http-equiv'] =~ /\AContent-Type\z/i
-
}
-
end
-
1
private :meta_content_type
-
-
###
-
# Get the title string of this document. Return nil if there is
-
# no title tag.
-
1
def title
-
title = at('//title') and title.inner_text
-
end
-
-
###
-
# Set the title string of this document.
-
#
-
# If a title element is already present, its content is replaced
-
# with the given text.
-
#
-
# Otherwise, this method tries to create one at an appropriate
-
# place supplying head and/or html elements as necessary, which
-
# is inside a head element if any, right after a meta
-
# encoding/charset tag if any, and before any text node or
-
# content element (typically <body>) if any.
-
1
def title=(text)
-
tnode = XML::Text.new(text, self)
-
if title = at('//title')
-
title.children = tnode
-
return text
-
end
-
-
title = XML::Node.new('title', self) << tnode
-
case
-
when head = at('//head')
-
head << title
-
when meta = at('//meta[@charset]') || meta_content_type
-
# better put after charset declaration
-
meta.add_next_sibling(title)
-
else
-
set_metadata_element(title)
-
end
-
text
-
end
-
-
1
def set_metadata_element(element)
-
case
-
when head = at('//head')
-
head << element
-
when html = at('//html')
-
head = html.prepend_child(XML::Node.new('head', self))
-
head.prepend_child(element)
-
when first = children.find { |node|
-
case node
-
when XML::Element, XML::Text
-
true
-
end
-
}
-
# We reach here only if the underlying document model
-
# allows <html>/<head> elements to be omitted and does not
-
# automatically supply them.
-
first.add_previous_sibling(element)
-
else
-
html = add_child(XML::Node.new('html', self))
-
head = html.add_child(XML::Node.new('head', self))
-
head.prepend_child(element)
-
end
-
end
-
1
private :set_metadata_element
-
-
####
-
# Serialize Node using +options+. Save options can also be set using a
-
# block. See SaveOptions.
-
#
-
# These two statements are equivalent:
-
#
-
# node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML)
-
#
-
# or
-
#
-
# node.serialize(:encoding => 'UTF-8') do |config|
-
# config.format.as_xml
-
# end
-
#
-
1
def serialize options = {}
-
options[:save_with] ||= XML::Node::SaveOptions::DEFAULT_HTML
-
super
-
end
-
-
####
-
# Create a Nokogiri::XML::DocumentFragment from +tags+
-
1
def fragment tags = nil
-
DocumentFragment.new(self, tags, self.root)
-
end
-
-
1
class << self
-
###
-
# Parse HTML. +string_or_io+ may be a String, or any object that
-
# responds to _read_ and _close_ such as an IO, or StringIO.
-
# +url+ is resource where this document is located. +encoding+ is the
-
# encoding that should be used when processing the document. +options+
-
# is a number that sets options in the parser, such as
-
# Nokogiri::XML::ParseOptions::RECOVER. See the constants in
-
# Nokogiri::XML::ParseOptions.
-
1
def parse string_or_io, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML
-
-
69
options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
-
# Give the options to the user
-
69
yield options if block_given?
-
-
69
if string_or_io.respond_to?(:encoding)
-
69
unless string_or_io.encoding.name == "ASCII-8BIT"
-
69
encoding ||= string_or_io.encoding.name
-
end
-
end
-
-
69
if string_or_io.respond_to?(:read)
-
url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil
-
unless encoding
-
# Libxml2's parser has poor support for encoding
-
# detection. First, it does not recognize the HTML5
-
# style meta charset declaration. Secondly, even if it
-
# successfully detects an encoding hint, it does not
-
# re-decode or re-parse the preceding part which may be
-
# garbled.
-
#
-
# EncodingReader aims to perform advanced encoding
-
# detection beyond what Libxml2 does, and to emulate
-
# rewinding of a stream and make Libxml2 redo parsing
-
# from the start when an encoding hint is found.
-
string_or_io = EncodingReader.new(string_or_io)
-
begin
-
return read_io(string_or_io, url, encoding, options.to_i)
-
rescue EncodingFound => e
-
encoding = e.found_encoding
-
end
-
end
-
return read_io(string_or_io, url, encoding, options.to_i)
-
end
-
-
# read_memory pukes on empty docs
-
69
if string_or_io.nil? or string_or_io.empty?
-
36
return encoding ? new.tap { |i| i.encoding = encoding } : new
-
end
-
-
51
encoding ||= EncodingReader.detect_encoding(string_or_io)
-
-
51
read_memory(string_or_io, url, encoding, options.to_i)
-
end
-
end
-
-
1
class EncodingFound < StandardError # :nodoc:
-
1
attr_reader :found_encoding
-
-
1
def initialize(encoding)
-
@found_encoding = encoding
-
super("encoding found: %s" % encoding)
-
end
-
end
-
-
1
class EncodingReader # :nodoc:
-
1
class SAXHandler < Nokogiri::XML::SAX::Document # :nodoc:
-
1
attr_reader :encoding
-
-
1
def initialize
-
@encoding = nil
-
super()
-
end
-
-
1
def start_element(name, attrs = [])
-
return unless name == 'meta'
-
attr = Hash[attrs]
-
charset = attr['charset'] and
-
@encoding = charset
-
http_equiv = attr['http-equiv'] and
-
http_equiv.match(/\AContent-Type\z/i) and
-
content = attr['content'] and
-
m = content.match(/;\s*charset\s*=\s*([\w-]+)/) and
-
@encoding = m[1]
-
end
-
end
-
-
1
class JumpSAXHandler < SAXHandler
-
1
def initialize(jumptag)
-
@jumptag = jumptag
-
super()
-
end
-
-
1
def start_element(name, attrs = [])
-
super
-
throw @jumptag, @encoding if @encoding
-
throw @jumptag, nil if name =~ /\A(?:div|h1|img|p|br)\z/
-
end
-
end
-
-
1
def self.detect_encoding(chunk)
-
if Nokogiri.jruby? && EncodingReader.is_jruby_without_fix?
-
return EncodingReader.detect_encoding_for_jruby_without_fix(chunk)
-
end
-
m = chunk.match(/\A(<\?xml[ \t\r\n]+[^>]*>)/) and
-
return Nokogiri.XML(m[1]).encoding
-
-
if Nokogiri.jruby?
-
m = chunk.match(/(<meta\s)(.*)(charset\s*=\s*([\w-]+))(.*)/i) and
-
return m[4]
-
catch(:encoding_found) {
-
Nokogiri::HTML::SAX::Parser.new(JumpSAXHandler.new(:encoding_found)).parse(chunk)
-
nil
-
}
-
else
-
handler = SAXHandler.new
-
parser = Nokogiri::HTML::SAX::PushParser.new(handler)
-
parser << chunk rescue Nokogiri::SyntaxError
-
handler.encoding
-
end
-
end
-
-
1
def self.is_jruby_without_fix?
-
JRUBY_VERSION.split('.').join.to_i < 165
-
end
-
-
1
def self.detect_encoding_for_jruby_without_fix(chunk)
-
m = chunk.match(/\A(<\?xml[ \t\r\n]+[^>]*>)/) and
-
return Nokogiri.XML(m[1]).encoding
-
-
m = chunk.match(/(<meta\s)(.*)(charset\s*=\s*([\w-]+))(.*)/i) and
-
return m[4]
-
-
catch(:encoding_found) {
-
Nokogiri::HTML::SAX::Parser.new(JumpSAXHandler.new(:encoding_found.to_s)).parse(chunk)
-
nil
-
}
-
rescue Nokogiri::SyntaxError, RuntimeError
-
# Ignore parser errors that nokogiri may raise
-
nil
-
end
-
-
1
def initialize(io)
-
@io = io
-
@firstchunk = nil
-
@encoding_found = nil
-
end
-
-
# This method is used by the C extension so that
-
# Nokogiri::HTML::Document#read_io() does not leak memory when
-
# EncodingFound is raised.
-
1
attr_reader :encoding_found
-
-
1
def read(len)
-
# no support for a call without len
-
-
if !@firstchunk
-
@firstchunk = @io.read(len) or return nil
-
-
# This implementation expects that the first call from
-
# htmlReadIO() is made with a length long enough (~1KB) to
-
# achieve advanced encoding detection.
-
if encoding = EncodingReader.detect_encoding(@firstchunk)
-
# The first chunk is stored for the next read in retry.
-
raise @encoding_found = EncodingFound.new(encoding)
-
end
-
end
-
@encoding_found = nil
-
-
ret = @firstchunk.slice!(0, len)
-
if (len -= ret.length) > 0
-
rest = @io.read(len) and ret << rest
-
end
-
if ret.empty?
-
nil
-
else
-
ret
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
class DocumentFragment < Nokogiri::XML::DocumentFragment
-
####
-
# Create a Nokogiri::XML::DocumentFragment from +tags+, using +encoding+
-
1
def self.parse tags, encoding = nil
-
doc = HTML::Document.new
-
-
encoding ||= tags.respond_to?(:encoding) ? tags.encoding.name : 'UTF-8'
-
doc.encoding = encoding
-
-
new(doc, tags)
-
end
-
-
1
def initialize document, tags = nil, ctx = nil
-
return self unless tags
-
-
if ctx
-
preexisting_errors = document.errors.dup
-
node_set = ctx.parse("<div>#{tags}</div>")
-
node_set.first.children.each { |child| child.parent = self } unless node_set.empty?
-
self.errors = document.errors - preexisting_errors
-
else
-
# This is a horrible hack, but I don't care
-
if tags.strip =~ /^<body/i
-
path = "/html/body"
-
else
-
path = "/html/body/node()"
-
end
-
-
temp_doc = HTML::Document.parse "<html><body>#{tags}", nil, document.encoding
-
temp_doc.xpath(path).each { |child| child.parent = self }
-
self.errors = temp_doc.errors
-
end
-
children
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
class ElementDescription
-
###
-
# Is this element a block element?
-
1
def block?
-
!inline?
-
end
-
-
###
-
# Convert this description to a string
-
1
def to_s
-
"#{name}: #{description}"
-
end
-
-
###
-
# Inspection information
-
1
def inspect
-
"#<#{self.class.name}: #{name} #{description}>"
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
class ElementDescription
-
-
# Methods are defined protected by method_defined? because at
-
# this point the C-library or Java library is already loaded,
-
# and we don't want to clobber any methods that have been
-
# defined there.
-
-
1
Desc = Struct.new("HTMLElementDescription", :name,
-
:startTag, :endTag, :saveEndTag,
-
:empty, :depr, :dtd, :isinline,
-
:desc,
-
:subelts, :defaultsubelt,
-
:attrs_opt, :attrs_depr, :attrs_req)
-
-
# This is filled in down below.
-
1
DefaultDescriptions = Hash.new()
-
-
1
def default_desc
-
DefaultDescriptions[name.downcase]
-
end
-
1
private :default_desc
-
-
1
unless method_defined? :implied_start_tag?
-
def implied_start_tag?
-
d = default_desc
-
d ? d.startTag : nil
-
end
-
end
-
-
1
unless method_defined? :implied_end_tag?
-
def implied_end_tag?
-
d = default_desc
-
d ? d.endTag : nil
-
end
-
end
-
-
1
unless method_defined? :save_end_tag?
-
def save_end_tag?
-
d = default_desc
-
d ? d.saveEndTag : nil
-
end
-
end
-
-
1
unless method_defined? :deprecated?
-
def deprecated?
-
d = default_desc
-
d ? d.depr : nil
-
end
-
end
-
-
1
unless method_defined? :description
-
def description
-
d = default_desc
-
d ? d.desc : nil
-
end
-
end
-
-
1
unless method_defined? :default_sub_element
-
def default_sub_element
-
d = default_desc
-
d ? d.defaultsubelt : nil
-
end
-
end
-
-
1
unless method_defined? :optional_attributes
-
def optional_attributes
-
d = default_desc
-
d ? d.attrs_opt : []
-
end
-
end
-
-
1
unless method_defined? :deprecated_attributes
-
def deprecated_attributes
-
d = default_desc
-
d ? d.attrs_depr : []
-
end
-
end
-
-
1
unless method_defined? :required_attributes
-
def required_attributes
-
d = default_desc
-
d ? d.attrs_req : []
-
end
-
end
-
-
###
-
# Default Element Descriptions (HTML 4.0) copied from
-
# libxml2/HTMLparser.c and libxml2/include/libxml/HTMLparser.h
-
#
-
# The copyright notice for those files and the following list of
-
# element and attribute descriptions is reproduced here:
-
#
-
# Except where otherwise noted in the source code (e.g. the
-
# files hash.c, list.c and the trio files, which are covered by
-
# a similar licence but with different Copyright notices) all
-
# the files are:
-
#
-
# Copyright (C) 1998-2003 Daniel Veillard. All Rights Reserved.
-
#
-
# Permission is hereby granted, free of charge, to any person
-
# obtaining a copy of this software and associated documentation
-
# files (the "Software"), to deal in the Software without
-
# restriction, including without limitation the rights to use,
-
# copy, modify, merge, publish, distribute, sublicense, and/or
-
# sell copies of the Software, and to permit persons to whom the
-
# Software is fur- nished to do so, subject to the following
-
# conditions:
-
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the
-
# Software.
-
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
-
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
-
# WARRANTIES OF MERCHANTABILITY, FIT- NESS FOR A PARTICULAR
-
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE DANIEL
-
# VEILLARD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-
# FROM, OUT OF OR IN CON- NECTION WITH THE SOFTWARE OR THE USE
-
# OR OTHER DEALINGS IN THE SOFTWARE.
-
-
# Except as contained in this notice, the name of Daniel
-
# Veillard shall not be used in advertising or otherwise to
-
# promote the sale, use or other deal- ings in this Software
-
# without prior written authorization from him.
-
-
# Attributes defined and categorized
-
1
FONTSTYLE = ["tt", "i", "b", "u", "s", "strike", "big", "small"]
-
1
PHRASE = ['em', 'strong', 'dfn', 'code', 'samp',
-
'kbd', 'var', 'cite', 'abbr', 'acronym']
-
1
SPECIAL = ['a', 'img', 'applet', 'embed', 'object', 'font','basefont',
-
'br', 'script', 'map', 'q', 'sub', 'sup', 'span', 'bdo',
-
'iframe']
-
1
PCDATA = []
-
1
HEADING = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
-
1
LIST = ['ul', 'ol', 'dir', 'menu']
-
1
FORMCTRL = ['input', 'select', 'textarea', 'label', 'button']
-
1
BLOCK = [HEADING, LIST, 'pre', 'p', 'dl', 'div', 'center', 'noscript',
-
'noframes', 'blockquote', 'form', 'isindex', 'hr', 'table',
-
'fieldset', 'address']
-
1
INLINE = [PCDATA, FONTSTYLE, PHRASE, SPECIAL, FORMCTRL]
-
1
FLOW = [BLOCK, INLINE]
-
1
MODIFIER = []
-
1
EMPTY = []
-
-
1
HTML_FLOW = FLOW
-
1
HTML_INLINE = INLINE
-
1
HTML_PCDATA = PCDATA
-
1
HTML_CDATA = HTML_PCDATA
-
-
1
COREATTRS = ['id', 'class', 'style', 'title']
-
1
I18N = ['lang', 'dir']
-
1
EVENTS = ['onclick', 'ondblclick', 'onmousedown', 'onmouseup',
-
'onmouseover', 'onmouseout', 'onkeypress', 'onkeydown',
-
'onkeyup']
-
1
ATTRS = [COREATTRS, I18N,EVENTS]
-
1
CELLHALIGN = ['align', 'char', 'charoff']
-
1
CELLVALIGN = ['valign']
-
-
1
HTML_ATTRS = ATTRS
-
1
CORE_I18N_ATTRS = [COREATTRS, I18N]
-
1
CORE_ATTRS = COREATTRS
-
1
I18N_ATTRS = I18N
-
-
-
1
A_ATTRS = [ATTRS, 'charset', 'type', 'name',
-
'href', 'hreflang', 'rel', 'rev', 'accesskey', 'shape',
-
'coords', 'tabindex', 'onfocus', 'onblur']
-
1
TARGET_ATTR = ['target']
-
1
ROWS_COLS_ATTR = ['rows', 'cols']
-
1
ALT_ATTR = ['alt']
-
1
SRC_ALT_ATTRS = ['src', 'alt']
-
1
HREF_ATTRS = ['href']
-
1
CLEAR_ATTRS = ['clear']
-
1
INLINE_P = [INLINE, 'p']
-
-
1
FLOW_PARAM = [FLOW, 'param']
-
1
APPLET_ATTRS = [COREATTRS , 'codebase',
-
'archive', 'alt', 'name', 'height', 'width', 'align',
-
'hspace', 'vspace']
-
1
AREA_ATTRS = ['shape', 'coords', 'href', 'nohref',
-
'tabindex', 'accesskey', 'onfocus', 'onblur']
-
1
BASEFONT_ATTRS = ['id', 'size', 'color', 'face']
-
1
QUOTE_ATTRS = [ATTRS, 'cite']
-
1
BODY_CONTENTS = [FLOW, 'ins', 'del']
-
1
BODY_ATTRS = [ATTRS, 'onload', 'onunload']
-
1
BODY_DEPR = ['background', 'bgcolor', 'text',
-
'link', 'vlink', 'alink']
-
1
BUTTON_ATTRS = [ATTRS, 'name', 'value', 'type',
-
'disabled', 'tabindex', 'accesskey', 'onfocus', 'onblur']
-
-
-
1
COL_ATTRS = [ATTRS, 'span', 'width', CELLHALIGN, CELLVALIGN]
-
1
COL_ELT = ['col']
-
1
EDIT_ATTRS = [ATTRS, 'datetime', 'cite']
-
1
COMPACT_ATTRS = [ATTRS, 'compact']
-
1
DL_CONTENTS = ['dt', 'dd']
-
1
COMPACT_ATTR = ['compact']
-
1
LABEL_ATTR = ['label']
-
1
FIELDSET_CONTENTS = [FLOW, 'legend' ]
-
1
FONT_ATTRS = [COREATTRS, I18N, 'size', 'color', 'face' ]
-
1
FORM_CONTENTS = [HEADING, LIST, INLINE, 'pre', 'p', 'div', 'center',
-
'noscript', 'noframes', 'blockquote', 'isindex', 'hr',
-
'table', 'fieldset', 'address']
-
1
FORM_ATTRS = [ATTRS, 'method', 'enctype', 'accept', 'name', 'onsubmit',
-
'onreset', 'accept-charset']
-
1
FRAME_ATTRS = [COREATTRS, 'longdesc', 'name', 'src', 'frameborder',
-
'marginwidth', 'marginheight', 'noresize', 'scrolling' ]
-
1
FRAMESET_ATTRS = [COREATTRS, 'rows', 'cols', 'onload', 'onunload']
-
1
FRAMESET_CONTENTS = ['frameset', 'frame', 'noframes']
-
1
HEAD_ATTRS = [I18N, 'profile']
-
1
HEAD_CONTENTS = ['title', 'isindex', 'base', 'script', 'style', 'meta',
-
'link', 'object']
-
1
HR_DEPR = ['align', 'noshade', 'size', 'width']
-
1
VERSION_ATTR = ['version']
-
1
HTML_CONTENT = ['head', 'body', 'frameset']
-
1
IFRAME_ATTRS = [COREATTRS, 'longdesc', 'name', 'src', 'frameborder',
-
'marginwidth', 'marginheight', 'scrolling', 'align',
-
'height', 'width']
-
1
IMG_ATTRS = [ATTRS, 'longdesc', 'name', 'height', 'width', 'usemap',
-
'ismap']
-
1
EMBED_ATTRS = [COREATTRS, 'align', 'alt', 'border', 'code', 'codebase',
-
'frameborder', 'height', 'hidden', 'hspace', 'name',
-
'palette', 'pluginspace', 'pluginurl', 'src', 'type',
-
'units', 'vspace', 'width']
-
1
INPUT_ATTRS = [ATTRS, 'type', 'name', 'value', 'checked', 'disabled',
-
'readonly', 'size', 'maxlength', 'src', 'alt', 'usemap',
-
'ismap', 'tabindex', 'accesskey', 'onfocus', 'onblur',
-
'onselect', 'onchange', 'accept']
-
1
PROMPT_ATTRS = [COREATTRS, I18N, 'prompt']
-
1
LABEL_ATTRS = [ATTRS, 'for', 'accesskey', 'onfocus', 'onblur']
-
1
LEGEND_ATTRS = [ATTRS, 'accesskey']
-
1
ALIGN_ATTR = ['align']
-
1
LINK_ATTRS = [ATTRS, 'charset', 'href', 'hreflang', 'type', 'rel', 'rev',
-
'media']
-
1
MAP_CONTENTS = [BLOCK, 'area']
-
1
NAME_ATTR = ['name']
-
1
ACTION_ATTR = ['action']
-
1
BLOCKLI_ELT = [BLOCK, 'li']
-
1
META_ATTRS = [I18N, 'http-equiv', 'name', 'scheme']
-
1
CONTENT_ATTR = ['content']
-
1
TYPE_ATTR = ['type']
-
1
NOFRAMES_CONTENT = ['body', FLOW, MODIFIER]
-
1
OBJECT_CONTENTS = [FLOW, 'param']
-
1
OBJECT_ATTRS = [ATTRS, 'declare', 'classid', 'codebase', 'data', 'type',
-
'codetype', 'archive', 'standby', 'height', 'width',
-
'usemap', 'name', 'tabindex']
-
1
OBJECT_DEPR = ['align', 'border', 'hspace', 'vspace']
-
1
OL_ATTRS = ['type', 'compact', 'start']
-
1
OPTION_ELT = ['option']
-
1
OPTGROUP_ATTRS = [ATTRS, 'disabled']
-
1
OPTION_ATTRS = [ATTRS, 'disabled', 'label', 'selected', 'value']
-
1
PARAM_ATTRS = ['id', 'value', 'valuetype', 'type']
-
1
WIDTH_ATTR = ['width']
-
1
PRE_CONTENT = [PHRASE, 'tt', 'i', 'b', 'u', 's', 'strike', 'a', 'br',
-
'script', 'map', 'q', 'span', 'bdo', 'iframe']
-
1
SCRIPT_ATTRS = ['charset', 'src', 'defer', 'event', 'for']
-
1
LANGUAGE_ATTR = ['language']
-
1
SELECT_CONTENT = ['optgroup', 'option']
-
1
SELECT_ATTRS = [ATTRS, 'name', 'size', 'multiple', 'disabled', 'tabindex',
-
'onfocus', 'onblur', 'onchange']
-
1
STYLE_ATTRS = [I18N, 'media', 'title']
-
1
TABLE_ATTRS = [ATTRS, 'summary', 'width', 'border', 'frame', 'rules',
-
'cellspacing', 'cellpadding', 'datapagesize']
-
1
TABLE_DEPR = ['align', 'bgcolor']
-
1
TABLE_CONTENTS = ['caption', 'col', 'colgroup', 'thead', 'tfoot', 'tbody',
-
'tr']
-
1
TR_ELT = ['tr']
-
1
TALIGN_ATTRS = [ATTRS, CELLHALIGN, CELLVALIGN]
-
1
TH_TD_DEPR = ['nowrap', 'bgcolor', 'width', 'height']
-
1
TH_TD_ATTR = [ATTRS, 'abbr', 'axis', 'headers', 'scope', 'rowspan',
-
'colspan', CELLHALIGN, CELLVALIGN]
-
1
TEXTAREA_ATTRS = [ATTRS, 'name', 'disabled', 'readonly', 'tabindex',
-
'accesskey', 'onfocus', 'onblur', 'onselect',
-
'onchange']
-
1
TR_CONTENTS = ['th', 'td']
-
1
BGCOLOR_ATTR = ['bgcolor']
-
1
LI_ELT = ['li']
-
1
UL_DEPR = ['type', 'compact']
-
1
DIR_ATTR = ['dir']
-
-
[
-
['a', false, false, false, false, false, :any, true,
-
'anchor ',
-
HTML_INLINE, nil, A_ATTRS, TARGET_ATTR, []
-
],
-
['abbr', false, false, false, false, false, :any, true,
-
'abbreviated form',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['acronym', false, false, false, false, false, :any, true, '',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['address', false, false, false, false, false, :any, false,
-
'information on author',
-
INLINE_P , nil, HTML_ATTRS, [], []
-
],
-
['applet', false, false, false, false, true, :loose, true,
-
'java applet ',
-
FLOW_PARAM, nil, [], APPLET_ATTRS, []
-
],
-
['area', false, true, true, true, false, :any, false,
-
'client-side image map area ',
-
EMPTY, nil, AREA_ATTRS, TARGET_ATTR, ALT_ATTR
-
],
-
['b', false, true, false, false, false, :any, true,
-
'bold text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['base', false, true, true, true, false, :any, false,
-
'document base uri ',
-
EMPTY, nil, [], TARGET_ATTR, HREF_ATTRS
-
],
-
['basefont', false, true, true, true, true, :loose, true,
-
'base font size ',
-
EMPTY, nil, [], BASEFONT_ATTRS, []
-
],
-
['bdo', false, false, false, false, false, :any, true,
-
'i18n bidi over-ride ',
-
HTML_INLINE, nil, CORE_I18N_ATTRS, [], DIR_ATTR
-
],
-
['big', false, true, false, false, false, :any, true,
-
'large text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['blockquote', false, false, false, false, false, :any, false,
-
'long quotation ',
-
HTML_FLOW, nil, QUOTE_ATTRS, [], []
-
],
-
['body', true, true, false, false, false, :any, false,
-
'document body ',
-
BODY_CONTENTS, 'div', BODY_ATTRS, BODY_DEPR, []
-
],
-
['br', false, true, true, true, false, :any, true,
-
'forced line break ',
-
EMPTY, nil, CORE_ATTRS, CLEAR_ATTRS, []
-
],
-
['button', false, false, false, false, false, :any, true,
-
'push button ',
-
[HTML_FLOW, MODIFIER], nil, BUTTON_ATTRS, [], []
-
],
-
['caption', false, false, false, false, false, :any, false,
-
'table caption ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['center', false, true, false, false, true, :loose, false,
-
'shorthand for div align=center ',
-
HTML_FLOW, nil, [], HTML_ATTRS, []
-
],
-
['cite', false, false, false, false, false, :any, true, 'citation',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['code', false, false, false, false, false, :any, true,
-
'computer code fragment',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['col', false, true, true, true, false, :any, false, 'table column ',
-
EMPTY, nil, COL_ATTRS, [], []
-
],
-
['colgroup', false, true, false, false, false, :any, false,
-
'table column group ',
-
COL_ELT, 'col', COL_ATTRS, [], []
-
],
-
['dd', false, true, false, false, false, :any, false,
-
'definition description ',
-
HTML_FLOW, nil, HTML_ATTRS, [], []
-
],
-
['del', false, false, false, false, false, :any, true,
-
'deleted text ',
-
HTML_FLOW, nil, EDIT_ATTRS, [], []
-
],
-
['dfn', false, false, false, false, false, :any, true,
-
'instance definition',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['dir', false, false, false, false, true, :loose, false,
-
'directory list',
-
BLOCKLI_ELT, 'li', [], COMPACT_ATTRS, []
-
],
-
['div', false, false, false, false, false, :any, false,
-
'generic language/style container',
-
HTML_FLOW, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['dl', false, false, false, false, false, :any, false,
-
'definition list ',
-
DL_CONTENTS, 'dd', HTML_ATTRS, COMPACT_ATTR, []
-
],
-
['dt', false, true, false, false, false, :any, false,
-
'definition term ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['em', false, true, false, false, false, :any, true,
-
'emphasis',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['embed', false, true, false, false, true, :loose, true,
-
'generic embedded object ',
-
EMPTY, nil, EMBED_ATTRS, [], []
-
],
-
['fieldset', false, false, false, false, false, :any, false,
-
'form control group ',
-
FIELDSET_CONTENTS, nil, HTML_ATTRS, [], []
-
],
-
['font', false, true, false, false, true, :loose, true,
-
'local change to font ',
-
HTML_INLINE, nil, [], FONT_ATTRS, []
-
],
-
['form', false, false, false, false, false, :any, false,
-
'interactive form ',
-
FORM_CONTENTS, 'fieldset', FORM_ATTRS, TARGET_ATTR, ACTION_ATTR
-
],
-
['frame', false, true, true, true, false, :frameset, false,
-
'subwindow ',
-
EMPTY, nil, [], FRAME_ATTRS, []
-
],
-
['frameset', false, false, false, false, false, :frameset, false,
-
'window subdivision',
-
FRAMESET_CONTENTS, 'noframes', [], FRAMESET_ATTRS, []
-
],
-
['htrue', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['htrue', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['htrue', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['h4', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['h5', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['h6', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['head', true, true, false, false, false, :any, false,
-
'document head ',
-
HEAD_CONTENTS, nil, HEAD_ATTRS, [], []
-
],
-
['hr', false, true, true, true, false, :any, false,
-
'horizontal rule ',
-
EMPTY, nil, HTML_ATTRS, HR_DEPR, []
-
],
-
['html', true, true, false, false, false, :any, false,
-
'document root element ',
-
HTML_CONTENT, nil, I18N_ATTRS, VERSION_ATTR, []
-
],
-
['i', false, true, false, false, false, :any, true,
-
'italic text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['iframe', false, false, false, false, false, :any, true,
-
'inline subwindow ',
-
HTML_FLOW, nil, [], IFRAME_ATTRS, []
-
],
-
['img', false, true, true, true, false, :any, true,
-
'embedded image ',
-
EMPTY, nil, IMG_ATTRS, ALIGN_ATTR, SRC_ALT_ATTRS
-
],
-
['input', false, true, true, true, false, :any, true,
-
'form control ',
-
EMPTY, nil, INPUT_ATTRS, ALIGN_ATTR, []
-
],
-
['ins', false, false, false, false, false, :any, true,
-
'inserted text',
-
HTML_FLOW, nil, EDIT_ATTRS, [], []
-
],
-
['isindex', false, true, true, true, true, :loose, false,
-
'single line prompt ',
-
EMPTY, nil, [], PROMPT_ATTRS, []
-
],
-
['kbd', false, false, false, false, false, :any, true,
-
'text to be entered by the user',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['label', false, false, false, false, false, :any, true,
-
'form field label text ',
-
[HTML_INLINE, MODIFIER], nil, LABEL_ATTRS, [], []
-
],
-
['legend', false, false, false, false, false, :any, false,
-
'fieldset legend ',
-
HTML_INLINE, nil, LEGEND_ATTRS, ALIGN_ATTR, []
-
],
-
['li', false, true, true, false, false, :any, false,
-
'list item ',
-
HTML_FLOW, nil, HTML_ATTRS, [], []
-
],
-
['link', false, true, true, true, false, :any, false,
-
'a media-independent link ',
-
EMPTY, nil, LINK_ATTRS, TARGET_ATTR, []
-
],
-
['map', false, false, false, false, false, :any, true,
-
'client-side image map ',
-
MAP_CONTENTS, nil, HTML_ATTRS, [], NAME_ATTR
-
],
-
['menu', false, false, false, false, true, :loose, false,
-
'menu list ',
-
BLOCKLI_ELT, nil, [], COMPACT_ATTRS, []
-
],
-
['meta', false, true, true, true, false, :any, false,
-
'generic metainformation ',
-
EMPTY, nil, META_ATTRS, [], CONTENT_ATTR
-
],
-
['noframes', false, false, false, false, false, :frameset, false,
-
'alternate content container for non frame-based rendering ',
-
NOFRAMES_CONTENT, 'body', HTML_ATTRS, [], []
-
],
-
['noscript', false, false, false, false, false, :any, false,
-
'alternate content container for non script-based rendering ',
-
HTML_FLOW, 'div', HTML_ATTRS, [], []
-
],
-
['object', false, false, false, false, false, :any, true,
-
'generic embedded object ',
-
OBJECT_CONTENTS, 'div', OBJECT_ATTRS, OBJECT_DEPR, []
-
],
-
['ol', false, false, false, false, false, :any, false,
-
'ordered list ',
-
LI_ELT, 'li', HTML_ATTRS, OL_ATTRS, []
-
],
-
['optgroup', false, false, false, false, false, :any, false,
-
'option group ',
-
OPTION_ELT, 'option', OPTGROUP_ATTRS, [], LABEL_ATTR
-
],
-
['option', false, true, false, false, false, :any, false,
-
'selectable choice ',
-
HTML_PCDATA, nil, OPTION_ATTRS, [], []
-
],
-
['p', false, true, false, false, false, :any, false,
-
'paragraph ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['param', false, true, true, true, false, :any, false,
-
'named property value ',
-
EMPTY, nil, PARAM_ATTRS, [], NAME_ATTR
-
],
-
['pre', false, false, false, false, false, :any, false,
-
'preformatted text ',
-
PRE_CONTENT, nil, HTML_ATTRS, WIDTH_ATTR, []
-
],
-
['q', false, false, false, false, false, :any, true,
-
'short inline quotation ',
-
HTML_INLINE, nil, QUOTE_ATTRS, [], []
-
],
-
['s', false, true, false, false, true, :loose, true,
-
'strike-through text style',
-
HTML_INLINE, nil, [], HTML_ATTRS, []
-
],
-
['samp', false, false, false, false, false, :any, true,
-
'sample program output, scripts, etc.',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['script', false, false, false, false, false, :any, true,
-
'script statements ',
-
HTML_CDATA, nil, SCRIPT_ATTRS, LANGUAGE_ATTR, TYPE_ATTR
-
],
-
['select', false, false, false, false, false, :any, true,
-
'option selector ',
-
SELECT_CONTENT, nil, SELECT_ATTRS, [], []
-
],
-
['small', false, true, false, false, false, :any, true,
-
'small text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['span', false, false, false, false, false, :any, true,
-
'generic language/style container ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['strike', false, true, false, false, true, :loose, true,
-
'strike-through text',
-
HTML_INLINE, nil, [], HTML_ATTRS, []
-
],
-
['strong', false, true, false, false, false, :any, true,
-
'strong emphasis',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['style', false, false, false, false, false, :any, false,
-
'style info ',
-
HTML_CDATA, nil, STYLE_ATTRS, [], TYPE_ATTR
-
],
-
['sub', false, true, false, false, false, :any, true,
-
'subscript',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['sup', false, true, false, false, false, :any, true,
-
'superscript ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['table', false, false, false, false, false, :any, false,
-
'',
-
TABLE_CONTENTS, 'tr', TABLE_ATTRS, TABLE_DEPR, []
-
],
-
['tbody', true, false, false, false, false, :any, false,
-
'table body ',
-
TR_ELT, 'tr', TALIGN_ATTRS, [], []
-
],
-
['td', false, false, false, false, false, :any, false,
-
'table data cell',
-
HTML_FLOW, nil, TH_TD_ATTR, TH_TD_DEPR, []
-
],
-
['textarea', false, false, false, false, false, :any, true,
-
'multi-line text field ',
-
HTML_PCDATA, nil, TEXTAREA_ATTRS, [], ROWS_COLS_ATTR
-
],
-
['tfoot', false, true, false, false, false, :any, false,
-
'table footer ',
-
TR_ELT, 'tr', TALIGN_ATTRS, [], []
-
],
-
['th', false, true, false, false, false, :any, false,
-
'table header cell',
-
HTML_FLOW, nil, TH_TD_ATTR, TH_TD_DEPR, []
-
],
-
['thead', false, true, false, false, false, :any, false,
-
'table header ',
-
TR_ELT, 'tr', TALIGN_ATTRS, [], []
-
],
-
['title', false, false, false, false, false, :any, false,
-
'document title ',
-
HTML_PCDATA, nil, I18N_ATTRS, [], []
-
],
-
['tr', false, false, false, false, false, :any, false,
-
'table row ',
-
TR_CONTENTS, 'td', TALIGN_ATTRS, BGCOLOR_ATTR, []
-
],
-
['tt', false, true, false, false, false, :any, true,
-
'teletype or monospaced text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['u', false, true, false, false, true, :loose, true,
-
'underlined text style',
-
HTML_INLINE, nil, [], HTML_ATTRS, []
-
],
-
['ul', false, false, false, false, false, :any, false,
-
'unordered list ',
-
LI_ELT, 'li', HTML_ATTRS, UL_DEPR, []
-
],
-
['var', false, false, false, false, false, :any, true,
-
'instance of a variable or program argument',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
]
-
1
].each do |descriptor|
-
92
name = descriptor[0]
-
-
92
begin
-
92
d = Desc.new(*descriptor)
-
-
# flatten all the attribute lists (Ruby1.9, *[a,b,c] can be
-
# used to flatten a literal list, but not in Ruby1.8).
-
92
d[:subelts] = d[:subelts].flatten
-
92
d[:attrs_opt] = d[:attrs_opt].flatten
-
92
d[:attrs_depr] = d[:attrs_depr].flatten
-
92
d[:attrs_req] = d[:attrs_req].flatten
-
rescue => e
-
p name
-
raise e
-
end
-
-
92
DefaultDescriptions[name] = d
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
class EntityDescription < Struct.new(:value, :name, :description); end
-
-
1
class EntityLookup
-
###
-
# Look up entity with +name+
-
1
def [] name
-
(val = get(name)) && val.value
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
###
-
# Nokogiri lets you write a SAX parser to process HTML but get HTML
-
# correction features.
-
#
-
# See Nokogiri::HTML::SAX::Parser for a basic example of using a
-
# SAX parser with HTML.
-
#
-
# For more information on SAX parsers, see Nokogiri::XML::SAX
-
1
module SAX
-
###
-
# This class lets you perform SAX style parsing on HTML with HTML
-
# error correction.
-
#
-
# Here is a basic usage example:
-
#
-
# class MyDoc < Nokogiri::XML::SAX::Document
-
# def start_element name, attributes = []
-
# puts "found a #{name}"
-
# end
-
# end
-
#
-
# parser = Nokogiri::HTML::SAX::Parser.new(MyDoc.new)
-
# parser.parse(File.read(ARGV[0], mode: 'rb'))
-
#
-
# For more information on SAX parsers, see Nokogiri::XML::SAX
-
1
class Parser < Nokogiri::XML::SAX::Parser
-
###
-
# Parse html stored in +data+ using +encoding+
-
1
def parse_memory data, encoding = 'UTF-8'
-
raise ArgumentError unless data
-
return unless data.length > 0
-
ctx = ParserContext.memory(data, encoding)
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
###
-
# Parse given +io+
-
1
def parse_io io, encoding = 'UTF-8'
-
check_encoding(encoding)
-
@encoding = encoding
-
ctx = ParserContext.io(io, ENCODINGS[encoding])
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
###
-
# Parse a file with +filename+
-
1
def parse_file filename, encoding = 'UTF-8'
-
raise ArgumentError unless filename
-
raise Errno::ENOENT unless File.exist?(filename)
-
raise Errno::EISDIR if File.directory?(filename)
-
ctx = ParserContext.file(filename, encoding)
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
module SAX
-
###
-
# Context for HTML SAX parsers. This class is usually not instantiated
-
# by the user. Instead, you should be looking at
-
# Nokogiri::HTML::SAX::Parser
-
1
class ParserContext < Nokogiri::XML::SAX::ParserContext
-
1
def self.new thing, encoding = 'UTF-8'
-
[:read, :close].all? { |x| thing.respond_to?(x) } ? super :
-
memory(thing, encoding)
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
module SAX
-
1
class PushParser
-
-
# The Nokogiri::HTML::SAX::Document on which the PushParser will be
-
# operating
-
1
attr_accessor :document
-
-
1
def initialize(doc = HTML::SAX::Document.new, file_name = nil, encoding = 'UTF-8')
-
@document = doc
-
@encoding = encoding
-
@sax_parser = HTML::SAX::Parser.new(doc, @encoding)
-
-
## Create our push parser context
-
initialize_native(@sax_parser, file_name, encoding)
-
end
-
-
###
-
# Write a +chunk+ of HTML to the PushParser. Any callback methods
-
# that can be called will be called immediately.
-
1
def write chunk, last_chunk = false
-
native_write(chunk, last_chunk)
-
end
-
1
alias :<< :write
-
-
###
-
# Finish the parsing. This method is only necessary for
-
# Nokogiri::HTML::SAX::Document#end_document to be called.
-
1
def finish
-
write '', true
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
class SyntaxError < ::StandardError
-
end
-
end
-
1
require 'nokogiri/xml/pp'
-
1
require 'nokogiri/xml/parse_options'
-
1
require 'nokogiri/xml/sax'
-
1
require 'nokogiri/xml/searchable'
-
1
require 'nokogiri/xml/node'
-
1
require 'nokogiri/xml/attribute_decl'
-
1
require 'nokogiri/xml/element_decl'
-
1
require 'nokogiri/xml/element_content'
-
1
require 'nokogiri/xml/character_data'
-
1
require 'nokogiri/xml/namespace'
-
1
require 'nokogiri/xml/attr'
-
1
require 'nokogiri/xml/dtd'
-
1
require 'nokogiri/xml/cdata'
-
1
require 'nokogiri/xml/text'
-
1
require 'nokogiri/xml/document'
-
1
require 'nokogiri/xml/document_fragment'
-
1
require 'nokogiri/xml/processing_instruction'
-
1
require 'nokogiri/xml/node_set'
-
1
require 'nokogiri/xml/syntax_error'
-
1
require 'nokogiri/xml/xpath'
-
1
require 'nokogiri/xml/xpath_context'
-
1
require 'nokogiri/xml/builder'
-
1
require 'nokogiri/xml/reader'
-
1
require 'nokogiri/xml/notation'
-
1
require 'nokogiri/xml/entity_decl'
-
1
require 'nokogiri/xml/schema'
-
1
require 'nokogiri/xml/relax_ng'
-
-
1
module Nokogiri
-
1
class << self
-
###
-
# Parse XML. Convenience method for Nokogiri::XML::Document.parse
-
1
def XML thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_XML, &block
-
Nokogiri::XML::Document.parse(thing, url, encoding, options, &block)
-
end
-
end
-
-
1
module XML
-
# Original C14N 1.0 spec canonicalization
-
1
XML_C14N_1_0 = 0
-
# Exclusive C14N 1.0 spec canonicalization
-
1
XML_C14N_EXCLUSIVE_1_0 = 1
-
# C14N 1.1 spec canonicalization
-
1
XML_C14N_1_1 = 2
-
1
class << self
-
###
-
# Parse an XML document using the Nokogiri::XML::Reader API. See
-
# Nokogiri::XML::Reader for mor information
-
1
def Reader string_or_io, url = nil, encoding = nil, options = ParseOptions::STRICT
-
-
options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
-
# Give the options to the user
-
yield options if block_given?
-
-
if string_or_io.respond_to? :read
-
return Reader.from_io(string_or_io, url, encoding, options.to_i)
-
end
-
Reader.from_memory(string_or_io, url, encoding, options.to_i)
-
end
-
-
###
-
# Parse XML. Convenience method for Nokogiri::XML::Document.parse
-
1
def parse thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block
-
Document.parse(thing, url, encoding, options, &block)
-
end
-
-
####
-
# Parse a fragment from +string+ in to a NodeSet.
-
1
def fragment string
-
XML::DocumentFragment.parse(string)
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class Attr < Node
-
1
alias :value :content
-
1
alias :to_s :content
-
1
alias :content= :value=
-
-
1
private
-
1
def inspect_attributes
-
[:name, :namespace, :value]
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
###
-
# Represents an attribute declaration in a DTD
-
1
class AttributeDecl < Nokogiri::XML::Node
-
1
undef_method :attribute_nodes
-
1
undef_method :attributes
-
1
undef_method :content
-
1
undef_method :namespace
-
1
undef_method :namespace_definitions
-
1
undef_method :line if method_defined?(:line)
-
-
1
def inspect
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{to_s.inspect}>"
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
###
-
# Nokogiri builder can be used for building XML and HTML documents.
-
#
-
# == Synopsis:
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.products {
-
# xml.widget {
-
# xml.id_ "10"
-
# xml.name "Awesome widget"
-
# }
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# Will output:
-
#
-
# <?xml version="1.0"?>
-
# <root>
-
# <products>
-
# <widget>
-
# <id>10</id>
-
# <name>Awesome widget</name>
-
# </widget>
-
# </products>
-
# </root>
-
#
-
#
-
# === Builder scope
-
#
-
# The builder allows two forms. When the builder is supplied with a block
-
# that has a parameter, the outside scope is maintained. This means you
-
# can access variables that are outside your builder. If you don't need
-
# outside scope, you can use the builder without the "xml" prefix like
-
# this:
-
#
-
# builder = Nokogiri::XML::Builder.new do
-
# root {
-
# products {
-
# widget {
-
# id_ "10"
-
# name "Awesome widget"
-
# }
-
# }
-
# }
-
# end
-
#
-
# == Special Tags
-
#
-
# The builder works by taking advantage of method_missing. Unfortunately
-
# some methods are defined in ruby that are difficult or dangerous to
-
# remove. You may want to create tags with the name "type", "class", and
-
# "id" for example. In that case, you can use an underscore to
-
# disambiguate your tag name from the method call.
-
#
-
# Here is an example of using the underscore to disambiguate tag names from
-
# ruby methods:
-
#
-
# @objects = [Object.new, Object.new, Object.new]
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.objects {
-
# @objects.each do |o|
-
# xml.object {
-
# xml.type_ o.type
-
# xml.class_ o.class.name
-
# xml.id_ o.id
-
# }
-
# end
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# The underscore may be used with any tag name, and the last underscore
-
# will just be removed. This code will output the following XML:
-
#
-
# <?xml version="1.0"?>
-
# <root>
-
# <objects>
-
# <object>
-
# <type>Object</type>
-
# <class>Object</class>
-
# <id>48390</id>
-
# </object>
-
# <object>
-
# <type>Object</type>
-
# <class>Object</class>
-
# <id>48380</id>
-
# </object>
-
# <object>
-
# <type>Object</type>
-
# <class>Object</class>
-
# <id>48370</id>
-
# </object>
-
# </objects>
-
# </root>
-
#
-
# == Tag Attributes
-
#
-
# Tag attributes may be supplied as method arguments. Here is our
-
# previous example, but using attributes rather than tags:
-
#
-
# @objects = [Object.new, Object.new, Object.new]
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.objects {
-
# @objects.each do |o|
-
# xml.object(:type => o.type, :class => o.class, :id => o.id)
-
# end
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# === Tag Attribute Short Cuts
-
#
-
# A couple attribute short cuts are available when building tags. The
-
# short cuts are available by special method calls when building a tag.
-
#
-
# This example builds an "object" tag with the class attribute "classy"
-
# and the id of "thing":
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.objects {
-
# xml.object.classy.thing!
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# Which will output:
-
#
-
# <?xml version="1.0"?>
-
# <root>
-
# <objects>
-
# <object class="classy" id="thing"/>
-
# </objects>
-
# </root>
-
#
-
# All other options are still supported with this syntax, including
-
# blocks and extra tag attributes.
-
#
-
# == Namespaces
-
#
-
# Namespaces are added similarly to attributes. Nokogiri::XML::Builder
-
# assumes that when an attribute starts with "xmlns", it is meant to be
-
# a namespace:
-
#
-
# builder = Nokogiri::XML::Builder.new { |xml|
-
# xml.root('xmlns' => 'default', 'xmlns:foo' => 'bar') do
-
# xml.tenderlove
-
# end
-
# }
-
# puts builder.to_xml
-
#
-
# Will output XML like this:
-
#
-
# <?xml version="1.0"?>
-
# <root xmlns:foo="bar" xmlns="default">
-
# <tenderlove/>
-
# </root>
-
#
-
# === Referencing declared namespaces
-
#
-
# Tags that reference non-default namespaces (i.e. a tag "foo:bar") can be
-
# built by using the Nokogiri::XML::Builder#[] method.
-
#
-
# For example:
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root('xmlns:foo' => 'bar') {
-
# xml.objects {
-
# xml['foo'].object.classy.thing!
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# Will output this XML:
-
#
-
# <?xml version="1.0"?>
-
# <root xmlns:foo="bar">
-
# <objects>
-
# <foo:object class="classy" id="thing"/>
-
# </objects>
-
# </root>
-
#
-
# Note the "foo:object" tag.
-
#
-
# == Document Types
-
#
-
# To create a document type (DTD), access use the Builder#doc method to get
-
# the current context document. Then call Node#create_internal_subset to
-
# create the DTD node.
-
#
-
# For example, this Ruby:
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.doc.create_internal_subset(
-
# 'html',
-
# "-//W3C//DTD HTML 4.01 Transitional//EN",
-
# "http://www.w3.org/TR/html4/loose.dtd"
-
# )
-
# xml.root do
-
# xml.foo
-
# end
-
# end
-
#
-
# puts builder.to_xml
-
#
-
# Will output this xml:
-
#
-
# <?xml version="1.0"?>
-
# <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
-
# <root>
-
# <foo/>
-
# </root>
-
#
-
1
class Builder
-
# The current Document object being built
-
1
attr_accessor :doc
-
-
# The parent of the current node being built
-
1
attr_accessor :parent
-
-
# A context object for use when the block has no arguments
-
1
attr_accessor :context
-
-
1
attr_accessor :arity # :nodoc:
-
-
###
-
# Create a builder with an existing root object. This is for use when
-
# you have an existing document that you would like to augment with
-
# builder methods. The builder context created will start with the
-
# given +root+ node.
-
#
-
# For example:
-
#
-
# doc = Nokogiri::XML(open('somedoc.xml'))
-
# Nokogiri::XML::Builder.with(doc.at('some_tag')) do |xml|
-
# # ... Use normal builder methods here ...
-
# xml.awesome # add the "awesome" tag below "some_tag"
-
# end
-
#
-
1
def self.with root, &block
-
new({}, root, &block)
-
end
-
-
###
-
# Create a new Builder object. +options+ are sent to the top level
-
# Document that is being built.
-
#
-
# Building a document with a particular encoding for example:
-
#
-
# Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
-
# ...
-
# end
-
1
def initialize options = {}, root = nil, &block
-
-
if root
-
@doc = root.document
-
@parent = root
-
else
-
namespace = self.class.name.split('::')
-
namespace[-1] = 'Document'
-
@doc = eval(namespace.join('::')).new
-
@parent = @doc
-
end
-
-
@context = nil
-
@arity = nil
-
@ns = nil
-
-
options.each do |k,v|
-
@doc.send(:"#{k}=", v)
-
end
-
-
return unless block_given?
-
-
@arity = block.arity
-
if @arity <= 0
-
@context = eval('self', block.binding)
-
instance_eval(&block)
-
else
-
yield self
-
end
-
-
@parent = @doc
-
end
-
-
###
-
# Create a Text Node with content of +string+
-
1
def text string
-
insert @doc.create_text_node(string)
-
end
-
-
###
-
# Create a CDATA Node with content of +string+
-
1
def cdata string
-
insert doc.create_cdata(string)
-
end
-
-
###
-
# Create a Comment Node with content of +string+
-
1
def comment string
-
insert doc.create_comment(string)
-
end
-
-
###
-
# Build a tag that is associated with namespace +ns+. Raises an
-
# ArgumentError if +ns+ has not been defined higher in the tree.
-
1
def [] ns
-
if @parent != @doc
-
@ns = @parent.namespace_definitions.find { |x| x.prefix == ns.to_s }
-
end
-
return self if @ns
-
-
@parent.ancestors.each do |a|
-
next if a == doc
-
@ns = a.namespace_definitions.find { |x| x.prefix == ns.to_s }
-
return self if @ns
-
end
-
-
@ns = { :pending => ns.to_s }
-
return self
-
end
-
-
###
-
# Convert this Builder object to XML
-
1
def to_xml(*args)
-
if Nokogiri.jruby?
-
options = args.first.is_a?(Hash) ? args.shift : {}
-
if !options[:save_with]
-
options[:save_with] = Node::SaveOptions::AS_BUILDER
-
end
-
args.insert(0, options)
-
end
-
@doc.to_xml(*args)
-
end
-
-
###
-
# Append the given raw XML +string+ to the document
-
1
def << string
-
@doc.fragment(string).children.each { |x| insert(x) }
-
end
-
-
1
def method_missing method, *args, &block # :nodoc:
-
if @context && @context.respond_to?(method)
-
@context.send(method, *args, &block)
-
else
-
node = @doc.create_element(method.to_s.sub(/[_!]$/, ''),*args) { |n|
-
# Set up the namespace
-
if @ns.is_a? Nokogiri::XML::Namespace
-
n.namespace = @ns
-
@ns = nil
-
end
-
}
-
-
if @ns.is_a? Hash
-
node.namespace = node.namespace_definitions.find { |x| x.prefix == @ns[:pending] }
-
if node.namespace.nil?
-
raise ArgumentError, "Namespace #{@ns[:pending]} has not been defined"
-
end
-
@ns = nil
-
end
-
-
insert(node, &block)
-
end
-
end
-
-
1
private
-
###
-
# Insert +node+ as a child of the current Node
-
1
def insert(node, &block)
-
node = @parent.add_child(node)
-
if block_given?
-
old_parent = @parent
-
@parent = node
-
@arity ||= block.arity
-
if @arity <= 0
-
instance_eval(&block)
-
else
-
block.call(self)
-
end
-
@parent = old_parent
-
end
-
NodeBuilder.new(node, self)
-
end
-
-
1
class NodeBuilder # :nodoc:
-
1
def initialize node, doc_builder
-
@node = node
-
@doc_builder = doc_builder
-
end
-
-
1
def []= k, v
-
@node[k] = v
-
end
-
-
1
def [] k
-
@node[k]
-
end
-
-
1
def method_missing(method, *args, &block)
-
opts = args.last.is_a?(Hash) ? args.pop : {}
-
case method.to_s
-
when /^(.*)!$/
-
@node['id'] = $1
-
@node.content = args.first if args.first
-
when /^(.*)=/
-
@node[$1] = args.first
-
else
-
@node['class'] =
-
((@node['class'] || '').split(/\s/) + [method.to_s]).join(' ')
-
@node.content = args.first if args.first
-
end
-
-
# Assign any extra options
-
opts.each do |k,v|
-
@node[k.to_s] = ((@node[k.to_s] || '').split(/\s/) + [v]).join(' ')
-
end
-
-
if block_given?
-
old_parent = @doc_builder.parent
-
@doc_builder.parent = @node
-
value = @doc_builder.instance_eval(&block)
-
@doc_builder.parent = old_parent
-
return value
-
end
-
self
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class CDATA < Nokogiri::XML::Text
-
###
-
# Get the name of this CDATA node
-
1
def name
-
'#cdata-section'
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class CharacterData < Nokogiri::XML::Node
-
1
include Nokogiri::XML::PP::CharacterData
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
##
-
# Nokogiri::XML::Document is the main entry point for dealing with
-
# XML documents. The Document is created by parsing an XML document.
-
# See Nokogiri::XML::Document.parse() for more information on parsing.
-
#
-
# For searching a Document, see Nokogiri::XML::Searchable#css and
-
# Nokogiri::XML::Searchable#xpath
-
#
-
1
class Document < Nokogiri::XML::Node
-
# I'm ignoring unicode characters here.
-
# See http://www.w3.org/TR/REC-xml-names/#ns-decl for more details.
-
1
NCNAME_START_CHAR = "A-Za-z_"
-
1
NCNAME_CHAR = NCNAME_START_CHAR + "\\-.0-9"
-
1
NCNAME_RE = /^xmlns(:[#{NCNAME_START_CHAR}][#{NCNAME_CHAR}]*)?$/
-
-
##
-
# Parse an XML file.
-
#
-
# +string_or_io+ may be a String, or any object that responds to
-
# _read_ and _close_ such as an IO, or StringIO.
-
#
-
# +url+ (optional) is the URI where this document is located.
-
#
-
# +encoding+ (optional) is the encoding that should be used when processing
-
# the document.
-
#
-
# +options+ (optional) is a configuration object that sets options during
-
# parsing, such as Nokogiri::XML::ParseOptions::RECOVER. See the
-
# Nokogiri::XML::ParseOptions for more information.
-
#
-
# +block+ (optional) is passed a configuration object on which
-
# parse options may be set.
-
#
-
# By default, Nokogiri treats documents as untrusted, and so
-
# does not attempt to load DTDs or access the network. See
-
# Nokogiri::XML::ParseOptions for a complete list of options;
-
# and that module's DEFAULT_XML constant for what's set (and not
-
# set) by default.
-
#
-
# Nokogiri.XML() is a convenience method which will call this method.
-
#
-
1
def self.parse string_or_io, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block
-
options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
-
# Give the options to the user
-
yield options if block_given?
-
-
if empty_doc?(string_or_io)
-
if options.strict?
-
raise Nokogiri::XML::SyntaxError.new("Empty document")
-
else
-
return encoding ? new.tap { |i| i.encoding = encoding } : new
-
end
-
end
-
-
doc = if string_or_io.respond_to?(:read)
-
url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil
-
read_io(string_or_io, url, encoding, options.to_i)
-
else
-
# read_memory pukes on empty docs
-
read_memory(string_or_io, url, encoding, options.to_i)
-
end
-
-
# do xinclude processing
-
doc.do_xinclude(options) if options.xinclude?
-
-
return doc
-
end
-
-
# A list of Nokogiri::XML::SyntaxError found when parsing a document
-
1
attr_accessor :errors
-
-
1
def initialize *args # :nodoc:
-
87
@errors = []
-
87
@decorators = nil
-
end
-
-
##
-
# Create an element with +name+, and optionally setting the content and attributes.
-
#
-
# doc.create_element "div" # <div></div>
-
# doc.create_element "div", :class => "container" # <div class='container'></div>
-
# doc.create_element "div", "contents" # <div>contents</div>
-
# doc.create_element "div", "contents", :class => "container" # <div class='container'>contents</div>
-
# doc.create_element "div" { |node| node['class'] = "container" } # <div class='container'></div>
-
#
-
1
def create_element name, *args, &block
-
6
elm = Nokogiri::XML::Element.new(name, self, &block)
-
6
args.each do |arg|
-
case arg
-
when Hash
-
arg.each { |k,v|
-
key = k.to_s
-
if key =~ NCNAME_RE
-
ns_name = key.split(":", 2)[1]
-
elm.add_namespace_definition ns_name, v
-
else
-
elm[k.to_s] = v.to_s
-
end
-
}
-
else
-
elm.content = arg
-
end
-
end
-
6
if ns = elm.namespace_definitions.find { |n| n.prefix.nil? or n.prefix == '' }
-
elm.namespace = ns
-
end
-
6
elm
-
end
-
-
# Create a Text Node with +string+
-
1
def create_text_node string, &block
-
Nokogiri::XML::Text.new string.to_s, self, &block
-
end
-
-
# Create a CDATA Node containing +string+
-
1
def create_cdata string, &block
-
Nokogiri::XML::CDATA.new self, string.to_s, &block
-
end
-
-
# Create a Comment Node containing +string+
-
1
def create_comment string, &block
-
Nokogiri::XML::Comment.new self, string.to_s, &block
-
end
-
-
# The name of this document. Always returns "document"
-
1
def name
-
'document'
-
end
-
-
# A reference to +self+
-
1
def document
-
462
self
-
end
-
-
##
-
# Recursively get all namespaces from this node and its subtree and
-
# return them as a hash.
-
#
-
# For example, given this document:
-
#
-
# <root xmlns:foo="bar">
-
# <bar xmlns:hello="world" />
-
# </root>
-
#
-
# This method will return:
-
#
-
# { 'xmlns:foo' => 'bar', 'xmlns:hello' => 'world' }
-
#
-
# WARNING: this method will clobber duplicate names in the keys.
-
# For example, given this document:
-
#
-
# <root xmlns:foo="bar">
-
# <bar xmlns:foo="baz" />
-
# </root>
-
#
-
# The hash returned will look like this: { 'xmlns:foo' => 'bar' }
-
#
-
# Non-prefixed default namespaces (as in "xmlns=") are not included
-
# in the hash.
-
#
-
# Note that this method does an xpath lookup for nodes with
-
# namespaces, and as a result the order may be dependent on the
-
# implementation of the underlying XML library.
-
#
-
1
def collect_namespaces
-
xpath("//namespace::*").inject({}) do |hash, ns|
-
hash[["xmlns",ns.prefix].compact.join(":")] = ns.href if ns.prefix != "xml"
-
hash
-
end
-
end
-
-
# Get the list of decorators given +key+
-
1
def decorators key
-
@decorators ||= Hash.new
-
@decorators[key] ||= []
-
end
-
-
##
-
# Validate this Document against it's DTD. Returns a list of errors on
-
# the document or +nil+ when there is no DTD.
-
1
def validate
-
return nil unless internal_subset
-
internal_subset.validate self
-
end
-
-
##
-
# Explore a document with shortcut methods. See Nokogiri::Slop for details.
-
#
-
# Note that any nodes that have been instantiated before #slop!
-
# is called will not be decorated with sloppy behavior. So, if you're in
-
# irb, the preferred idiom is:
-
#
-
# irb> doc = Nokogiri::Slop my_markup
-
#
-
# and not
-
#
-
# irb> doc = Nokogiri::HTML my_markup
-
# ... followed by irb's implicit inspect (and therefore instantiation of every node) ...
-
# irb> doc.slop!
-
# ... which does absolutely nothing.
-
#
-
1
def slop!
-
unless decorators(XML::Node).include? Nokogiri::Decorators::Slop
-
decorators(XML::Node) << Nokogiri::Decorators::Slop
-
decorate!
-
end
-
-
self
-
end
-
-
##
-
# Apply any decorators to +node+
-
1
def decorate node
-
1828
return unless @decorators
-
@decorators.each { |klass,list|
-
next unless node.is_a?(klass)
-
list.each { |moodule| node.extend(moodule) }
-
}
-
end
-
-
1
alias :to_xml :serialize
-
1
alias :clone :dup
-
-
# Get the hash of namespaces on the root Nokogiri::XML::Node
-
1
def namespaces
-
root ? root.namespaces : {}
-
end
-
-
##
-
# Create a Nokogiri::XML::DocumentFragment from +tags+
-
# Returns an empty fragment if +tags+ is nil.
-
1
def fragment tags = nil
-
DocumentFragment.new(self, tags, self.root)
-
end
-
-
1
undef_method :swap, :parent, :namespace, :default_namespace=
-
1
undef_method :add_namespace_definition, :attributes
-
1
undef_method :namespace_definitions, :line, :add_namespace
-
-
1
def add_child node_or_tags
-
raise "A document may not have multiple root nodes." if (root && root.name != 'nokogiri_text_wrapper') && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
-
node_or_tags = coerce(node_or_tags)
-
if node_or_tags.is_a?(XML::NodeSet)
-
raise "A document may not have multiple root nodes." if node_or_tags.size > 1
-
super(node_or_tags.first)
-
else
-
super
-
end
-
end
-
1
alias :<< :add_child
-
-
##
-
# +JRuby+
-
# Wraps Java's org.w3c.dom.document and returns Nokogiri::XML::Document
-
1
def self.wrap document
-
raise "JRuby only method" unless Nokogiri.jruby?
-
return wrapJavaDocument(document)
-
end
-
-
##
-
# +JRuby+
-
# Returns Java's org.w3c.dom.document of this Document.
-
1
def to_java
-
raise "JRuby only method" unless Nokogiri.jruby?
-
return toJavaDocument()
-
end
-
-
1
private
-
1
def self.empty_doc? string_or_io
-
string_or_io.nil? ||
-
(string_or_io.respond_to?(:empty?) && string_or_io.empty?) ||
-
(string_or_io.respond_to?(:eof?) && string_or_io.eof?)
-
end
-
-
# @private
-
1
IMPLIED_XPATH_CONTEXTS = [ '//'.freeze ].freeze # :nodoc:
-
-
1
def inspect_attributes
-
[:name, :children]
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class DocumentFragment < Nokogiri::XML::Node
-
##
-
# Create a new DocumentFragment from +tags+.
-
#
-
# If +ctx+ is present, it is used as a context node for the
-
# subtree created, e.g., namespaces will be resolved relative
-
# to +ctx+.
-
1
def initialize document, tags = nil, ctx = nil
-
return self unless tags
-
-
children = if ctx
-
# Fix for issue#490
-
if Nokogiri.jruby?
-
# fix for issue #770
-
ctx.parse("<root #{namespace_declarations(ctx)}>#{tags}</root>").children
-
else
-
ctx.parse(tags)
-
end
-
else
-
XML::Document.parse("<root>#{tags}</root>") \
-
.xpath("/root/node()")
-
end
-
children.each { |child| child.parent = self }
-
end
-
-
###
-
# return the name for DocumentFragment
-
1
def name
-
'#document-fragment'
-
end
-
-
###
-
# Convert this DocumentFragment to a string
-
1
def to_s
-
children.to_s
-
end
-
-
###
-
# Convert this DocumentFragment to html
-
# See Nokogiri::XML::NodeSet#to_html
-
1
def to_html *args
-
if Nokogiri.jruby?
-
options = args.first.is_a?(Hash) ? args.shift : {}
-
if !options[:save_with]
-
options[:save_with] = Node::SaveOptions::NO_DECLARATION | Node::SaveOptions::NO_EMPTY_TAGS | Node::SaveOptions::AS_HTML
-
end
-
args.insert(0, options)
-
end
-
children.to_html(*args)
-
end
-
-
###
-
# Convert this DocumentFragment to xhtml
-
# See Nokogiri::XML::NodeSet#to_xhtml
-
1
def to_xhtml *args
-
if Nokogiri.jruby?
-
options = args.first.is_a?(Hash) ? args.shift : {}
-
if !options[:save_with]
-
options[:save_with] = Node::SaveOptions::NO_DECLARATION | Node::SaveOptions::NO_EMPTY_TAGS | Node::SaveOptions::AS_XHTML
-
end
-
args.insert(0, options)
-
end
-
children.to_xhtml(*args)
-
end
-
-
###
-
# Convert this DocumentFragment to xml
-
# See Nokogiri::XML::NodeSet#to_xml
-
1
def to_xml *args
-
children.to_xml(*args)
-
end
-
-
###
-
# call-seq: css *rules, [namespace-bindings, custom-pseudo-class]
-
#
-
# Search this fragment for CSS +rules+. +rules+ must be one or more CSS
-
# selectors. For example:
-
#
-
# For more information see Nokogiri::XML::Searchable#css
-
1
def css *args
-
if children.any?
-
children.css(*args) # 'children' is a smell here
-
else
-
NodeSet.new(document)
-
end
-
end
-
-
#
-
# NOTE that we don't delegate #xpath to children ... another smell.
-
# def xpath ; end
-
#
-
-
###
-
# call-seq: search *paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]
-
#
-
# Search this fragment for +paths+. +paths+ must be one or more XPath or CSS queries.
-
#
-
# For more information see Nokogiri::XML::Searchable#search
-
1
def search *rules
-
rules, handler, ns, binds = extract_params(rules)
-
-
rules.inject(NodeSet.new(document)) do |set, rule|
-
set += if rule =~ Searchable::LOOKS_LIKE_XPATH
-
xpath(*([rule, ns, handler, binds].compact))
-
else
-
children.css(*([rule, ns, handler].compact)) # 'children' is a smell here
-
end
-
end
-
end
-
-
1
alias :serialize :to_s
-
-
1
class << self
-
####
-
# Create a Nokogiri::XML::DocumentFragment from +tags+
-
1
def parse tags
-
self.new(XML::Document.new, tags)
-
end
-
end
-
-
# A list of Nokogiri::XML::SyntaxError found when parsing a document
-
1
def errors
-
document.errors
-
end
-
-
1
def errors= things # :nodoc:
-
document.errors = things
-
end
-
-
1
private
-
-
# fix for issue 770
-
1
def namespace_declarations ctx
-
ctx.namespace_scopes.map do |namespace|
-
prefix = namespace.prefix.nil? ? "" : ":#{namespace.prefix}"
-
%Q{xmlns#{prefix}="#{namespace.href}"}
-
end.join ' '
-
end
-
-
1
def coerce data
-
return super unless String === data
-
-
document.fragment(data).children
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class DTD < Nokogiri::XML::Node
-
1
undef_method :attribute_nodes
-
1
undef_method :values
-
1
undef_method :content
-
1
undef_method :namespace
-
1
undef_method :namespace_definitions
-
1
undef_method :line if method_defined?(:line)
-
-
1
def keys
-
attributes.keys
-
end
-
-
1
def each
-
attributes.each do |key, value|
-
yield([key, value])
-
end
-
end
-
-
1
def html_dtd?
-
name.casecmp('html').zero?
-
end
-
-
1
def html5_dtd?
-
html_dtd? &&
-
external_id.nil? &&
-
(system_id.nil? || system_id == 'about:legacy-compat')
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
###
-
# Represents the allowed content in an Element Declaration inside a DTD:
-
#
-
# <?xml version="1.0"?><?TEST-STYLE PIDATA?>
-
# <!DOCTYPE staff SYSTEM "staff.dtd" [
-
# <!ELEMENT div1 (head, (p | list | note)*, div2*)>
-
# ]>
-
# </root>
-
#
-
# ElementContent represents the tree inside the <!ELEMENT> tag shown above
-
# that lists the possible content for the div1 tag.
-
1
class ElementContent
-
# Possible definitions of type
-
1
PCDATA = 1
-
1
ELEMENT = 2
-
1
SEQ = 3
-
1
OR = 4
-
-
# Possible content occurrences
-
1
ONCE = 1
-
1
OPT = 2
-
1
MULT = 3
-
1
PLUS = 4
-
-
1
attr_reader :document
-
-
###
-
# Get the children of this ElementContent node
-
1
def children
-
[c1, c2].compact
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class ElementDecl < Nokogiri::XML::Node
-
1
undef_method :namespace
-
1
undef_method :namespace_definitions
-
1
undef_method :line if method_defined?(:line)
-
-
1
def inspect
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{to_s.inspect}>"
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class EntityDecl < Nokogiri::XML::Node
-
1
undef_method :attribute_nodes
-
1
undef_method :attributes
-
1
undef_method :namespace
-
1
undef_method :namespace_definitions
-
1
undef_method :line if method_defined?(:line)
-
-
1
def self.new name, doc, *args
-
doc.create_entity(name, *args)
-
end
-
-
1
def inspect
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{to_s.inspect}>"
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class Namespace
-
1
include Nokogiri::XML::PP::Node
-
1
attr_reader :document
-
-
1
private
-
1
def inspect_attributes
-
[:prefix, :href]
-
end
-
end
-
end
-
end
-
# encoding: UTF-8
-
1
require 'stringio'
-
1
require 'nokogiri/xml/node/save_options'
-
-
1
module Nokogiri
-
1
module XML
-
####
-
# Nokogiri::XML::Node is your window to the fun filled world of dealing
-
# with XML and HTML tags. A Nokogiri::XML::Node may be treated similarly
-
# to a hash with regard to attributes. For example (from irb):
-
#
-
# irb(main):004:0> node
-
# => <a href="#foo" id="link">link</a>
-
# irb(main):005:0> node['href']
-
# => "#foo"
-
# irb(main):006:0> node.keys
-
# => ["href", "id"]
-
# irb(main):007:0> node.values
-
# => ["#foo", "link"]
-
# irb(main):008:0> node['class'] = 'green'
-
# => "green"
-
# irb(main):009:0> node
-
# => <a href="#foo" id="link" class="green">link</a>
-
# irb(main):010:0>
-
#
-
# See Nokogiri::XML::Node#[] and Nokogiri::XML#[]= for more information.
-
#
-
# Nokogiri::XML::Node also has methods that let you move around your
-
# tree. For navigating your tree, see:
-
#
-
# * Nokogiri::XML::Node#parent
-
# * Nokogiri::XML::Node#children
-
# * Nokogiri::XML::Node#next
-
# * Nokogiri::XML::Node#previous
-
#
-
#
-
# When printing or otherwise emitting a document or a node (and
-
# its subtree), there are a few methods you might want to use:
-
#
-
# * content, text, inner_text, to_str: emit plaintext
-
#
-
# These methods will all emit the plaintext version of your
-
# document, meaning that entities will be replaced (e.g., "<"
-
# will be replaced with "<"), meaning that any sanitizing will
-
# likely be un-done in the output.
-
#
-
# * to_s, to_xml, to_html, inner_html: emit well-formed markup
-
#
-
# These methods will all emit properly-escaped markup, meaning
-
# that it's suitable for consumption by browsers, parsers, etc.
-
#
-
# You may search this node's subtree using Searchable#xpath and Searchable#css
-
1
class Node
-
1
include Nokogiri::XML::PP::Node
-
1
include Nokogiri::XML::Searchable
-
1
include Enumerable
-
-
# Element node type, see Nokogiri::XML::Node#element?
-
1
ELEMENT_NODE = 1
-
# Attribute node type
-
1
ATTRIBUTE_NODE = 2
-
# Text node type, see Nokogiri::XML::Node#text?
-
1
TEXT_NODE = 3
-
# CDATA node type, see Nokogiri::XML::Node#cdata?
-
1
CDATA_SECTION_NODE = 4
-
# Entity reference node type
-
1
ENTITY_REF_NODE = 5
-
# Entity node type
-
1
ENTITY_NODE = 6
-
# PI node type
-
1
PI_NODE = 7
-
# Comment node type, see Nokogiri::XML::Node#comment?
-
1
COMMENT_NODE = 8
-
# Document node type, see Nokogiri::XML::Node#xml?
-
1
DOCUMENT_NODE = 9
-
# Document type node type
-
1
DOCUMENT_TYPE_NODE = 10
-
# Document fragment node type
-
1
DOCUMENT_FRAG_NODE = 11
-
# Notation node type
-
1
NOTATION_NODE = 12
-
# HTML document node type, see Nokogiri::XML::Node#html?
-
1
HTML_DOCUMENT_NODE = 13
-
# DTD node type
-
1
DTD_NODE = 14
-
# Element declaration type
-
1
ELEMENT_DECL = 15
-
# Attribute declaration type
-
1
ATTRIBUTE_DECL = 16
-
# Entity declaration type
-
1
ENTITY_DECL = 17
-
# Namespace declaration type
-
1
NAMESPACE_DECL = 18
-
# XInclude start type
-
1
XINCLUDE_START = 19
-
# XInclude end type
-
1
XINCLUDE_END = 20
-
# DOCB document node type
-
1
DOCB_DOCUMENT_NODE = 21
-
-
1
def initialize name, document # :nodoc:
-
# ... Ya. This is empty on purpose.
-
end
-
-
###
-
# Decorate this node with the decorators set up in this node's Document
-
1
def decorate!
-
3
document.decorate(self)
-
end
-
-
###
-
# Search this node's immediate children using CSS selector +selector+
-
1
def > selector
-
ns = document.root.namespaces
-
xpath CSS.xpath_for(selector, :prefix => "./", :ns => ns).first
-
end
-
-
###
-
# Get the attribute value for the attribute +name+
-
1
def [] name
-
1539
get(name.to_s)
-
end
-
-
###
-
# Set the attribute value for the attribute +name+ to +value+
-
1
def []= name, value
-
30
set name.to_s, value.to_s
-
end
-
-
###
-
# Add +node_or_tags+ as a child of this Node.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +<<+.
-
1
def add_child node_or_tags
-
3
node_or_tags = coerce(node_or_tags)
-
3
if node_or_tags.is_a?(XML::NodeSet)
-
node_or_tags.each { |n| add_child_node_and_reparent_attrs n }
-
else
-
3
add_child_node_and_reparent_attrs node_or_tags
-
end
-
3
node_or_tags
-
end
-
-
###
-
# Add +node_or_tags+ as the first child of this Node.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +add_child+.
-
1
def prepend_child node_or_tags
-
if first = children.first
-
# Mimic the error add_child would raise.
-
raise RuntimeError, "Document already has a root node" if document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
-
first.__send__(:add_sibling, :previous, node_or_tags)
-
else
-
add_child(node_or_tags)
-
end
-
end
-
-
###
-
# Add +node_or_tags+ as a child of this Node.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls (e.g., root << child1 << child2)
-
#
-
# Also see related method +add_child+.
-
1
def << node_or_tags
-
add_child node_or_tags
-
self
-
end
-
-
###
-
# Insert +node_or_tags+ before this Node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +before+.
-
1
def add_previous_sibling node_or_tags
-
raise ArgumentError.new("A document may not have multiple root nodes.") if (parent && parent.document?) && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
-
-
add_sibling :previous, node_or_tags
-
end
-
-
###
-
# Insert +node_or_tags+ after this Node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +after+.
-
1
def add_next_sibling node_or_tags
-
raise ArgumentError.new("A document may not have multiple root nodes.") if (parent && parent.document?) && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
-
-
add_sibling :next, node_or_tags
-
end
-
-
####
-
# Insert +node_or_tags+ before this node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls.
-
#
-
# Also see related method +add_previous_sibling+.
-
1
def before node_or_tags
-
add_previous_sibling node_or_tags
-
self
-
end
-
-
####
-
# Insert +node_or_tags+ after this node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls.
-
#
-
# Also see related method +add_next_sibling+.
-
1
def after node_or_tags
-
add_next_sibling node_or_tags
-
self
-
end
-
-
####
-
# Set the inner html for this Node to +node_or_tags+
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
-
#
-
# Returns self.
-
#
-
# Also see related method +children=+
-
1
def inner_html= node_or_tags
-
self.children = node_or_tags
-
self
-
end
-
-
####
-
# Set the inner html for this Node +node_or_tags+
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +inner_html=+
-
1
def children= node_or_tags
-
node_or_tags = coerce(node_or_tags)
-
children.unlink
-
if node_or_tags.is_a?(XML::NodeSet)
-
node_or_tags.each { |n| add_child_node_and_reparent_attrs n }
-
else
-
add_child_node_and_reparent_attrs node_or_tags
-
end
-
node_or_tags
-
end
-
-
####
-
# Replace this Node with +node_or_tags+.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +swap+.
-
1
def replace node_or_tags
-
# We cannot replace a text node directly, otherwise libxml will return
-
# an internal error at parser.c:13031, I don't know exactly why
-
# libxml is trying to find a parent node that is an element or document
-
# so I can't tell if this is bug in libxml or not. issue #775.
-
if text?
-
replacee = Nokogiri::XML::Node.new 'dummy', document
-
add_previous_sibling_node replacee
-
unlink
-
return replacee.replace node_or_tags
-
end
-
-
node_or_tags = coerce(node_or_tags)
-
-
if node_or_tags.is_a?(XML::NodeSet)
-
node_or_tags.each { |n| add_previous_sibling n }
-
unlink
-
else
-
replace_node node_or_tags
-
end
-
node_or_tags
-
end
-
-
####
-
# Swap this Node for +node_or_tags+
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls.
-
#
-
# Also see related method +replace+.
-
1
def swap node_or_tags
-
replace node_or_tags
-
self
-
end
-
-
1
alias :next :next_sibling
-
1
alias :previous :previous_sibling
-
-
# :stopdoc:
-
# HACK: This is to work around an RDoc bug
-
1
alias :next= :add_next_sibling
-
# :startdoc:
-
-
1
alias :previous= :add_previous_sibling
-
1
alias :remove :unlink
-
1
alias :get_attribute :[]
-
1
alias :attr :[]
-
1
alias :set_attribute :[]=
-
1
alias :text :content
-
1
alias :inner_text :content
-
1
alias :has_attribute? :key?
-
1
alias :name :node_name
-
1
alias :name= :node_name=
-
1
alias :type :node_type
-
1
alias :to_str :text
-
1
alias :clone :dup
-
1
alias :elements :element_children
-
-
####
-
# Returns a hash containing the node's attributes. The key is
-
# the attribute name without any namespace, the value is a Nokogiri::XML::Attr
-
# representing the attribute.
-
# If you need to distinguish attributes with the same name, with different namespaces
-
# use #attribute_nodes instead.
-
1
def attributes
-
Hash[attribute_nodes.map { |node|
-
[node.node_name, node]
-
}]
-
end
-
-
###
-
# Get the attribute values for this Node.
-
1
def values
-
attribute_nodes.map(&:value)
-
end
-
-
###
-
# Get the attribute names for this Node.
-
1
def keys
-
attribute_nodes.map(&:node_name)
-
end
-
-
###
-
# Iterate over each attribute name and value pair for this Node.
-
1
def each
-
attribute_nodes.each { |node|
-
yield [node.node_name, node.value]
-
}
-
end
-
-
###
-
# Remove the attribute named +name+
-
1
def remove_attribute name
-
attr = attributes[name].remove if key? name
-
clear_xpath_context if Nokogiri.jruby?
-
attr
-
end
-
1
alias :delete :remove_attribute
-
-
###
-
# Returns true if this Node matches +selector+
-
1
def matches? selector
-
ancestors.last.search(selector).include?(self)
-
end
-
-
###
-
# Create a DocumentFragment containing +tags+ that is relative to _this_
-
# context node.
-
1
def fragment tags
-
type = document.html? ? Nokogiri::HTML : Nokogiri::XML
-
type::DocumentFragment.new(document, tags, self)
-
end
-
-
###
-
# Parse +string_or_io+ as a document fragment within the context of
-
# *this* node. Returns a XML::NodeSet containing the nodes parsed from
-
# +string_or_io+.
-
1
def parse string_or_io, options = nil
-
##
-
# When the current node is unparented and not an element node, use the
-
# document as the parsing context instead. Otherwise, the in-context
-
# parser cannot find an element or a document node.
-
# Document Fragments are also not usable by the in-context parser.
-
if !element? && !document? && (!parent || parent.fragment?)
-
return document.parse(string_or_io, options)
-
end
-
-
options ||= (document.html? ? ParseOptions::DEFAULT_HTML : ParseOptions::DEFAULT_XML)
-
if Integer === options
-
options = Nokogiri::XML::ParseOptions.new(options)
-
end
-
# Give the options to the user
-
yield options if block_given?
-
-
contents = string_or_io.respond_to?(:read) ?
-
string_or_io.read :
-
string_or_io
-
-
return Nokogiri::XML::NodeSet.new(document) if contents.empty?
-
-
##
-
# This is a horrible hack, but I don't care. See #313 for background.
-
error_count = document.errors.length
-
node_set = in_context(contents, options.to_i)
-
if node_set.empty? and document.errors.length > error_count and options.recover?
-
fragment = Nokogiri::HTML::DocumentFragment.parse contents
-
node_set = fragment.children
-
end
-
node_set
-
end
-
-
####
-
# Set the Node's content to a Text node containing +string+. The string gets XML escaped, not interpreted as markup.
-
1
def content= string
-
self.native_content = encode_special_chars(string.to_s)
-
end
-
-
###
-
# Set the parent Node for this Node
-
1
def parent= parent_node
-
parent_node.add_child(self)
-
parent_node
-
end
-
-
###
-
# Returns a Hash of {prefix => value} for all namespaces on this
-
# node and its ancestors.
-
#
-
# This method returns the same namespaces as #namespace_scopes.
-
#
-
# Returns namespaces in scope for self -- those defined on self
-
# element directly or any ancestor node -- as a Hash of
-
# attribute-name/value pairs. Note that the keys in this hash
-
# XML attributes that would be used to define this namespace,
-
# such as "xmlns:prefix", not just the prefix. Default namespace
-
# set on self will be included with key "xmlns". However,
-
# default namespaces set on ancestor will NOT be, even if self
-
# has no explicit default namespace.
-
1
def namespaces
-
267
Hash[namespace_scopes.map { |nd|
-
key = ['xmlns', nd.prefix].compact.join(':')
-
[key, nd.href]
-
}]
-
end
-
-
# Returns true if this is a Comment
-
1
def comment?
-
type == COMMENT_NODE
-
end
-
-
# Returns true if this is a CDATA
-
1
def cdata?
-
type == CDATA_SECTION_NODE
-
end
-
-
# Returns true if this is an XML::Document node
-
1
def xml?
-
type == DOCUMENT_NODE
-
end
-
-
# Returns true if this is an HTML::Document node
-
1
def html?
-
type == HTML_DOCUMENT_NODE
-
end
-
-
# Returns true if this is a Document
-
1
def document?
-
is_a? XML::Document
-
end
-
-
# Returns true if this is a ProcessingInstruction node
-
1
def processing_instruction?
-
type == PI_NODE
-
end
-
-
# Returns true if this is a Text node
-
1
def text?
-
968
type == TEXT_NODE
-
end
-
-
# Returns true if this is a DocumentFragment
-
1
def fragment?
-
type == DOCUMENT_FRAG_NODE
-
end
-
-
###
-
# Fetch the Nokogiri::HTML::ElementDescription for this node. Returns
-
# nil on XML documents and on unknown tags.
-
1
def description
-
return nil if document.xml?
-
Nokogiri::HTML::ElementDescription[name]
-
end
-
-
###
-
# Is this a read only node?
-
1
def read_only?
-
# According to gdome2, these are read-only node types
-
[NOTATION_NODE, ENTITY_NODE, ENTITY_DECL].include?(type)
-
end
-
-
# Returns true if this is an Element node
-
1
def element?
-
366
type == ELEMENT_NODE
-
end
-
1
alias :elem? :element?
-
-
###
-
# Turn this node in to a string. If the document is HTML, this method
-
# returns html. If the document is XML, this method returns XML.
-
1
def to_s
-
document.xml? ? to_xml : to_html
-
end
-
-
# Get the inner_html for this node's Node#children
-
1
def inner_html *args
-
children.map { |x| x.to_html(*args) }.join
-
end
-
-
# Get the path to this node as a CSS expression
-
1
def css_path
-
path.split(/\//).map { |part|
-
part.length == 0 ? nil : part.gsub(/\[(\d+)\]/, ':nth-of-type(\1)')
-
}.compact.join(' > ')
-
end
-
-
###
-
# Get a list of ancestor Node for this Node. If +selector+ is given,
-
# the ancestors must match +selector+
-
1
def ancestors selector = nil
-
8
return NodeSet.new(document) unless respond_to?(:parent)
-
8
return NodeSet.new(document) unless parent
-
-
8
parents = [parent]
-
-
8
while parents.last.respond_to?(:parent)
-
40
break unless ctx_parent = parents.last.parent
-
40
parents << ctx_parent
-
end
-
-
8
return NodeSet.new(document, parents) unless selector
-
-
8
root = parents.last
-
8
search_results = root.search(selector)
-
-
8
NodeSet.new(document, parents.find_all { |parent|
-
48
search_results.include?(parent)
-
})
-
end
-
-
###
-
# Adds a default namespace supplied as a string +url+ href, to self.
-
# The consequence is as an xmlns attribute with supplied argument were
-
# present in parsed XML. A default namespace set with this method will
-
# now show up in #attributes, but when this node is serialized to XML an
-
# "xmlns" attribute will appear. See also #namespace and #namespace=
-
1
def default_namespace= url
-
add_namespace_definition(nil, url)
-
end
-
1
alias :add_namespace :add_namespace_definition
-
-
###
-
# Set the default namespace on this node (as would be defined with an
-
# "xmlns=" attribute in XML source), as a Namespace object +ns+. Note that
-
# a Namespace added this way will NOT be serialized as an xmlns attribute
-
# for this node. You probably want #default_namespace= instead, or perhaps
-
# #add_namespace_definition with a nil prefix argument.
-
1
def namespace= ns
-
return set_namespace(ns) unless ns
-
-
unless Nokogiri::XML::Namespace === ns
-
raise TypeError, "#{ns.class} can't be coerced into Nokogiri::XML::Namespace"
-
end
-
if ns.document != document
-
raise ArgumentError, 'namespace must be declared on the same document'
-
end
-
-
set_namespace ns
-
end
-
-
####
-
# Yields self and all children to +block+ recursively.
-
1
def traverse &block
-
children.each{|j| j.traverse(&block) }
-
block.call(self)
-
end
-
-
###
-
# Accept a visitor. This method calls "visit" on +visitor+ with self.
-
1
def accept visitor
-
visitor.visit(self)
-
end
-
-
###
-
# Test to see if this Node is equal to +other+
-
1
def == other
-
return false unless other
-
return false unless other.respond_to?(:pointer_id)
-
pointer_id == other.pointer_id
-
end
-
-
###
-
# Serialize Node using +options+. Save options can also be set using a
-
# block. See SaveOptions.
-
#
-
# These two statements are equivalent:
-
#
-
# node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML)
-
#
-
# or
-
#
-
# node.serialize(:encoding => 'UTF-8') do |config|
-
# config.format.as_xml
-
# end
-
#
-
1
def serialize *args, &block
-
options = args.first.is_a?(Hash) ? args.shift : {
-
:encoding => args[0],
-
:save_with => args[1]
-
}
-
-
encoding = options[:encoding] || document.encoding
-
options[:encoding] = encoding
-
-
outstring = String.new
-
if encoding && outstring.respond_to?(:force_encoding)
-
outstring.force_encoding(Encoding.find(encoding))
-
end
-
io = StringIO.new(outstring)
-
write_to io, options, &block
-
io.string
-
end
-
-
###
-
# Serialize this Node to HTML
-
#
-
# doc.to_html
-
#
-
# See Node#write_to for a list of +options+. For formatted output,
-
# use Node#to_xhtml instead.
-
1
def to_html options = {}
-
to_format SaveOptions::DEFAULT_HTML, options
-
end
-
-
###
-
# Serialize this Node to XML using +options+
-
#
-
# doc.to_xml(:indent => 5, :encoding => 'UTF-8')
-
#
-
# See Node#write_to for a list of +options+
-
1
def to_xml options = {}
-
options[:save_with] ||= SaveOptions::DEFAULT_XML
-
serialize(options)
-
end
-
-
###
-
# Serialize this Node to XHTML using +options+
-
#
-
# doc.to_xhtml(:indent => 5, :encoding => 'UTF-8')
-
#
-
# See Node#write_to for a list of +options+
-
1
def to_xhtml options = {}
-
to_format SaveOptions::DEFAULT_XHTML, options
-
end
-
-
###
-
# Write Node to +io+ with +options+. +options+ modify the output of
-
# this method. Valid options are:
-
#
-
# * +:encoding+ for changing the encoding
-
# * +:indent_text+ the indentation text, defaults to one space
-
# * +:indent+ the number of +:indent_text+ to use, defaults to 2
-
# * +:save_with+ a combination of SaveOptions constants.
-
#
-
# To save with UTF-8 indented twice:
-
#
-
# node.write_to(io, :encoding => 'UTF-8', :indent => 2)
-
#
-
# To save indented with two dashes:
-
#
-
# node.write_to(io, :indent_text => '-', :indent => 2
-
#
-
1
def write_to io, *options
-
options = options.first.is_a?(Hash) ? options.shift : {}
-
encoding = options[:encoding] || options[0]
-
if Nokogiri.jruby?
-
save_options = options[:save_with] || options[1]
-
indent_times = options[:indent] || 0
-
else
-
save_options = options[:save_with] || options[1] || SaveOptions::FORMAT
-
indent_times = options[:indent] || 2
-
end
-
indent_text = options[:indent_text] || ' '
-
-
config = SaveOptions.new(save_options.to_i)
-
yield config if block_given?
-
-
native_write_to(io, encoding, indent_text * indent_times, config.options)
-
end
-
-
###
-
# Write Node as HTML to +io+ with +options+
-
#
-
# See Node#write_to for a list of +options+
-
1
def write_html_to io, options = {}
-
write_format_to SaveOptions::DEFAULT_HTML, io, options
-
end
-
-
###
-
# Write Node as XHTML to +io+ with +options+
-
#
-
# See Node#write_to for a list of +options+
-
1
def write_xhtml_to io, options = {}
-
write_format_to SaveOptions::DEFAULT_XHTML, io, options
-
end
-
-
###
-
# Write Node as XML to +io+ with +options+
-
#
-
# doc.write_xml_to io, :encoding => 'UTF-8'
-
#
-
# See Node#write_to for a list of options
-
1
def write_xml_to io, options = {}
-
options[:save_with] ||= SaveOptions::DEFAULT_XML
-
write_to io, options
-
end
-
-
###
-
# Compare two Node objects with respect to their Document. Nodes from
-
# different documents cannot be compared.
-
1
def <=> other
-
return nil unless other.is_a?(Nokogiri::XML::Node)
-
return nil unless document == other.document
-
compare other
-
end
-
-
###
-
# Do xinclude substitution on the subtree below node. If given a block, a
-
# Nokogiri::XML::ParseOptions object initialized from +options+, will be
-
# passed to it, allowing more convenient modification of the parser options.
-
1
def do_xinclude options = XML::ParseOptions::DEFAULT_XML, &block
-
options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
-
-
# give options to user
-
yield options if block_given?
-
-
# call c extension
-
process_xincludes(options.to_i)
-
end
-
-
1
def canonicalize(mode=XML::XML_C14N_1_0,inclusive_namespaces=nil,with_comments=false)
-
c14n_root = self
-
document.canonicalize(mode, inclusive_namespaces, with_comments) do |node, parent|
-
tn = node.is_a?(XML::Node) ? node : parent
-
tn == c14n_root || tn.ancestors.include?(c14n_root)
-
end
-
end
-
-
1
private
-
-
1
def add_sibling next_or_previous, node_or_tags
-
impl = (next_or_previous == :next) ? :add_next_sibling_node : :add_previous_sibling_node
-
iter = (next_or_previous == :next) ? :reverse_each : :each
-
-
node_or_tags = coerce node_or_tags
-
if node_or_tags.is_a?(XML::NodeSet)
-
if text?
-
pivot = Nokogiri::XML::Node.new 'dummy', document
-
send impl, pivot
-
else
-
pivot = self
-
end
-
node_or_tags.send(iter) { |n| pivot.send impl, n }
-
pivot.unlink if text?
-
else
-
send impl, node_or_tags
-
end
-
node_or_tags
-
end
-
-
1
def to_format save_option, options
-
# FIXME: this is a hack around broken libxml versions
-
return dump_html if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]
-
-
options[:save_with] = save_option unless options[:save_with]
-
serialize(options)
-
end
-
-
1
def write_format_to save_option, io, options
-
# FIXME: this is a hack around broken libxml versions
-
return (io << dump_html) if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]
-
-
options[:save_with] ||= save_option
-
write_to io, options
-
end
-
-
1
def inspect_attributes
-
[:name, :namespace, :attribute_nodes, :children]
-
end
-
-
1
def coerce data # :nodoc:
-
3
case data
-
when XML::NodeSet
-
return data
-
when XML::DocumentFragment
-
return data.children
-
when String
-
return fragment(data).children
-
when Document, XML::Attr
-
# unacceptable
-
when XML::Node
-
3
return data
-
end
-
-
raise ArgumentError, <<-EOERR
-
Requires a Node, NodeSet or String argument, and cannot accept a #{data.class}.
-
(You probably want to select a node from the Document with at() or search(), or create a new Node via Node.new().)
-
EOERR
-
end
-
-
# @private
-
1
IMPLIED_XPATH_CONTEXTS = [ './/'.freeze ].freeze # :nodoc:
-
-
1
def add_child_node_and_reparent_attrs node # :nodoc:
-
3
add_child_node node
-
12
node.attribute_nodes.find_all { |a| a.name =~ /:/ }.each do |attr_node|
-
attr_node.remove
-
node[attr_node.name] = attr_node.value
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class Node
-
###
-
# Save options for serializing nodes
-
1
class SaveOptions
-
# Format serialized xml
-
1
FORMAT = 1
-
# Do not include declarations
-
1
NO_DECLARATION = 2
-
# Do not include empty tags
-
1
NO_EMPTY_TAGS = 4
-
# Do not save XHTML
-
1
NO_XHTML = 8
-
# Save as XHTML
-
1
AS_XHTML = 16
-
# Save as XML
-
1
AS_XML = 32
-
# Save as HTML
-
1
AS_HTML = 64
-
-
1
if Nokogiri.jruby?
-
# Save builder created document
-
AS_BUILDER = 128
-
# the default for XML documents
-
DEFAULT_XML = AS_XML # https://github.com/sparklemotion/nokogiri/issues/#issue/415
-
# the default for HTML document
-
DEFAULT_HTML = NO_DECLARATION | NO_EMPTY_TAGS | AS_HTML
-
else
-
# the default for XML documents
-
1
DEFAULT_XML = FORMAT | AS_XML
-
# the default for HTML document
-
1
DEFAULT_HTML = FORMAT | NO_DECLARATION | NO_EMPTY_TAGS | AS_HTML
-
end
-
# the default for XHTML document
-
1
DEFAULT_XHTML = FORMAT | NO_DECLARATION | NO_EMPTY_TAGS | AS_XHTML
-
-
# Integer representation of the SaveOptions
-
1
attr_reader :options
-
-
# Create a new SaveOptions object with +options+
-
1
def initialize options = 0; @options = options; end
-
-
1
constants.each do |constant|
-
10
class_eval %{
-
def #{constant.downcase}
-
@options |= #{constant}
-
self
-
end
-
-
def #{constant.downcase}?
-
#{constant} & @options == #{constant}
-
end
-
}
-
end
-
-
1
alias :to_i :options
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
####
-
# A NodeSet contains a list of Nokogiri::XML::Node objects. Typically
-
# a NodeSet is return as a result of searching a Document via
-
# Nokogiri::XML::Searchable#css or Nokogiri::XML::Searchable#xpath
-
1
class NodeSet
-
1
include Nokogiri::XML::Searchable
-
1
include Enumerable
-
-
# The Document this NodeSet is associated with
-
1
attr_accessor :document
-
-
1
alias :clone :dup
-
-
# Create a NodeSet with +document+ defaulting to +list+
-
1
def initialize document, list = []
-
8
@document = document
-
8
document.decorate(self)
-
16
list.each { |x| self << x }
-
8
yield self if block_given?
-
end
-
-
###
-
# Get the first element of the NodeSet.
-
1
def first n = nil
-
24
return self[0] unless n
-
list = []
-
n.times { |i| list << self[i] }
-
list
-
end
-
-
###
-
# Get the last element of the NodeSet.
-
1
def last
-
self[-1]
-
end
-
-
###
-
# Is this NodeSet empty?
-
1
def empty?
-
length == 0
-
end
-
-
###
-
# Returns the index of the first node in self that is == to +node+. Returns nil if no match is found.
-
1
def index(node)
-
each_with_index { |member, j| return j if member == node }
-
nil
-
end
-
-
###
-
# Insert +datum+ before the first Node in this NodeSet
-
1
def before datum
-
first.before datum
-
end
-
-
###
-
# Insert +datum+ after the last Node in this NodeSet
-
1
def after datum
-
last.after datum
-
end
-
-
1
alias :<< :push
-
1
alias :remove :unlink
-
-
###
-
# call-seq: css *rules, [namespace-bindings, custom-pseudo-class]
-
#
-
# Search this node set for CSS +rules+. +rules+ must be one or more CSS
-
# selectors. For example:
-
#
-
# For more information see Nokogiri::XML::Searchable#css
-
1
def css *args
-
rules, handler, ns, _ = extract_params(args)
-
paths = css_rules_to_xpath(rules, ns)
-
-
inject(NodeSet.new(document)) do |set, node|
-
set + xpath_internal(node, paths, handler, ns, nil)
-
end
-
end
-
-
###
-
# call-seq: xpath *paths, [namespace-bindings, variable-bindings, custom-handler-class]
-
#
-
# Search this node set for XPath +paths+. +paths+ must be one or more XPath
-
# queries.
-
#
-
# For more information see Nokogiri::XML::Searchable#xpath
-
1
def xpath *args
-
paths, handler, ns, binds = extract_params(args)
-
-
inject(NodeSet.new(document)) do |set, node|
-
set + xpath_internal(node, paths, handler, ns, binds)
-
end
-
end
-
-
###
-
# Search this NodeSet's nodes' immediate children using CSS selector +selector+
-
1
def > selector
-
ns = document.root.namespaces
-
xpath CSS.xpath_for(selector, :prefix => "./", :ns => ns).first
-
end
-
-
###
-
# call-seq: search *paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]
-
#
-
# Search this object for +paths+, and return only the first
-
# result. +paths+ must be one or more XPath or CSS queries.
-
#
-
# See Searchable#search for more information.
-
#
-
# Or, if passed an integer, index into the NodeSet:
-
#
-
# node_set.at(3) # same as node_set[3]
-
#
-
1
def at *args
-
if args.length == 1 && args.first.is_a?(Numeric)
-
return self[args.first]
-
end
-
-
super(*args)
-
end
-
1
alias :% :at
-
-
###
-
# Filter this list for nodes that match +expr+
-
1
def filter expr
-
find_all { |node| node.matches?(expr) }
-
end
-
-
###
-
# Append the class attribute +name+ to all Node objects in the NodeSet.
-
1
def add_class name
-
each do |el|
-
classes = el['class'].to_s.split(/\s+/)
-
el['class'] = classes.push(name).uniq.join " "
-
end
-
self
-
end
-
-
###
-
# Remove the class attribute +name+ from all Node objects in the NodeSet.
-
# If +name+ is nil, remove the class attribute from all Nodes in the
-
# NodeSet.
-
1
def remove_class name = nil
-
each do |el|
-
if name
-
classes = el['class'].to_s.split(/\s+/)
-
if classes.empty?
-
el.delete 'class'
-
else
-
el['class'] = (classes - [name]).uniq.join " "
-
end
-
else
-
el.delete "class"
-
end
-
end
-
self
-
end
-
-
###
-
# Set the attribute +key+ to +value+ or the return value of +blk+
-
# on all Node objects in the NodeSet.
-
1
def attr key, value = nil, &blk
-
unless Hash === key || key && (value || blk)
-
return first.attribute(key)
-
end
-
-
hash = key.is_a?(Hash) ? key : { key => value }
-
-
hash.each { |k,v| each { |el| el[k] = v || blk[el] } }
-
-
self
-
end
-
1
alias :set :attr
-
1
alias :attribute :attr
-
-
###
-
# Remove the attributed named +name+ from all Node objects in the NodeSet
-
1
def remove_attr name
-
each { |el| el.delete name }
-
self
-
end
-
-
###
-
# Iterate over each node, yielding to +block+
-
1
def each(&block)
-
543
0.upto(length - 1) do |x|
-
1090
yield self[x]
-
end
-
end
-
-
###
-
# Get the inner text of all contained Node objects
-
#
-
# Note: This joins the text of all Node objects in the NodeSet:
-
#
-
# doc = Nokogiri::XML('<xml><a><d>foo</d><d>bar</d></a></xml>')
-
# doc.css('d').text # => "foobar"
-
#
-
# Instead, if you want to return the text of all nodes in the NodeSet:
-
#
-
# doc.css('d').map(&:text) # => ["foo", "bar"]
-
#
-
# See Nokogiri::XML::Node#content for more information.
-
1
def inner_text
-
collect(&:inner_text).join('')
-
end
-
1
alias :text :inner_text
-
-
###
-
# Get the inner html of all contained Node objects
-
1
def inner_html *args
-
collect{|j| j.inner_html(*args) }.join('')
-
end
-
-
###
-
# Wrap this NodeSet with +html+ or the results of the builder in +blk+
-
1
def wrap(html, &blk)
-
each do |j|
-
new_parent = document.parse(html).first
-
j.add_next_sibling(new_parent)
-
new_parent.add_child(j)
-
end
-
self
-
end
-
-
###
-
# Convert this NodeSet to a string.
-
1
def to_s
-
map(&:to_s).join
-
end
-
-
###
-
# Convert this NodeSet to HTML
-
1
def to_html *args
-
if Nokogiri.jruby?
-
options = args.first.is_a?(Hash) ? args.shift : {}
-
if !options[:save_with]
-
options[:save_with] = Node::SaveOptions::NO_DECLARATION | Node::SaveOptions::NO_EMPTY_TAGS | Node::SaveOptions::AS_HTML
-
end
-
args.insert(0, options)
-
end
-
map { |x| x.to_html(*args) }.join
-
end
-
-
###
-
# Convert this NodeSet to XHTML
-
1
def to_xhtml *args
-
map { |x| x.to_xhtml(*args) }.join
-
end
-
-
###
-
# Convert this NodeSet to XML
-
1
def to_xml *args
-
map { |x| x.to_xml(*args) }.join
-
end
-
-
1
alias :size :length
-
1
alias :to_ary :to_a
-
-
###
-
# Removes the last element from set and returns it, or +nil+ if
-
# the set is empty
-
1
def pop
-
return nil if length == 0
-
delete last
-
end
-
-
###
-
# Returns the first element of the NodeSet and removes it. Returns
-
# +nil+ if the set is empty.
-
1
def shift
-
return nil if length == 0
-
delete first
-
end
-
-
###
-
# Equality -- Two NodeSets are equal if the contain the same number
-
# of elements and if each element is equal to the corresponding
-
# element in the other NodeSet
-
1
def == other
-
return false unless other.is_a?(Nokogiri::XML::NodeSet)
-
return false unless length == other.length
-
each_with_index do |node, i|
-
return false unless node == other[i]
-
end
-
true
-
end
-
-
###
-
# Returns a new NodeSet containing all the children of all the nodes in
-
# the NodeSet
-
1
def children
-
node_set = NodeSet.new(document)
-
each do |node|
-
node.children.each { |n| node_set.push(n) }
-
end
-
node_set
-
end
-
-
###
-
# Returns a new NodeSet containing all the nodes in the NodeSet
-
# in reverse order
-
1
def reverse
-
node_set = NodeSet.new(document)
-
(length - 1).downto(0) do |x|
-
node_set.push self[x]
-
end
-
node_set
-
end
-
-
###
-
# Return a nicely formated string representation
-
1
def inspect
-
"[#{map(&:inspect).join ', '}]"
-
end
-
-
1
alias :+ :|
-
-
# @private
-
1
IMPLIED_XPATH_CONTEXTS = [ './/'.freeze, 'self::'.freeze ].freeze # :nodoc:
-
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class Notation < Struct.new(:name, :public_id, :system_id)
-
end
-
end
-
end
-
1
require 'nokogiri/xml/pp/node'
-
1
require 'nokogiri/xml/pp/character_data'
-
1
module Nokogiri
-
1
module XML
-
1
module PP
-
1
module CharacterData
-
1
def pretty_print pp # :nodoc:
-
nice_name = self.class.name.split('::').last
-
pp.group(2, "#(#{nice_name} ", ')') do
-
pp.pp text
-
end
-
end
-
-
1
def inspect # :nodoc:
-
"#<#{self.class.name}:#{sprintf("0x%x",object_id)} #{text.inspect}>"
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
module PP
-
1
module Node
-
1
def inspect # :nodoc:
-
attributes = inspect_attributes.reject { |x|
-
begin
-
attribute = send x
-
!attribute || (attribute.respond_to?(:empty?) && attribute.empty?)
-
rescue NoMethodError
-
true
-
end
-
}.map { |attribute|
-
"#{attribute.to_s.sub(/_\w+/, 's')}=#{send(attribute).inspect}"
-
}.join ' '
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{attributes}>"
-
end
-
-
1
def pretty_print pp # :nodoc:
-
nice_name = self.class.name.split('::').last
-
pp.group(2, "#(#{nice_name}:#{sprintf("0x%x", object_id)} {", '})') do
-
-
pp.breakable
-
attrs = inspect_attributes.map { |t|
-
[t, send(t)] if respond_to?(t)
-
}.compact.find_all { |x|
-
if x.last
-
if [:attribute_nodes, :children].include? x.first
-
!x.last.empty?
-
else
-
true
-
end
-
end
-
}
-
-
pp.seplist(attrs) do |v|
-
if [:attribute_nodes, :children].include? v.first
-
pp.group(2, "#{v.first.to_s.sub(/_\w+$/, 's')} = [", "]") do
-
pp.breakable
-
pp.seplist(v.last) do |item|
-
pp.pp item
-
end
-
end
-
else
-
pp.text "#{v.first} = "
-
pp.pp v.last
-
end
-
end
-
pp.breakable
-
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class ProcessingInstruction < Node
-
1
def initialize document, name, content
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class << self
-
###
-
# Create a new Nokogiri::XML::RelaxNG document from +string_or_io+.
-
# See Nokogiri::XML::RelaxNG for an example.
-
1
def RelaxNG string_or_io
-
RelaxNG.new(string_or_io)
-
end
-
end
-
-
###
-
# Nokogiri::XML::RelaxNG is used for validating XML against a
-
# RelaxNG schema.
-
#
-
# == Synopsis
-
#
-
# Validate an XML document against a RelaxNG schema. Loop over the errors
-
# that are returned and print them out:
-
#
-
# schema = Nokogiri::XML::RelaxNG(File.open(ADDRESS_SCHEMA_FILE))
-
# doc = Nokogiri::XML(File.open(ADDRESS_XML_FILE))
-
#
-
# schema.validate(doc).each do |error|
-
# puts error.message
-
# end
-
#
-
# The list of errors are Nokogiri::XML::SyntaxError objects.
-
1
class RelaxNG < Nokogiri::XML::Schema
-
end
-
end
-
end
-
1
require 'nokogiri/xml/sax/document'
-
1
require 'nokogiri/xml/sax/parser_context'
-
1
require 'nokogiri/xml/sax/parser'
-
1
require 'nokogiri/xml/sax/push_parser'
-
1
module Nokogiri
-
1
module XML
-
###
-
# SAX Parsers are event driven parsers. Nokogiri provides two different
-
# event based parsers when dealing with XML. If you want to do SAX style
-
# parsing using HTML, check out Nokogiri::HTML::SAX.
-
#
-
# The basic way a SAX style parser works is by creating a parser,
-
# telling the parser about the events we're interested in, then giving
-
# the parser some XML to process. The parser will notify you when
-
# it encounters events you said you would like to know about.
-
#
-
# To register for events, you simply subclass Nokogiri::XML::SAX::Document,
-
# and implement the methods for which you would like notification.
-
#
-
# For example, if I want to be notified when a document ends, and when an
-
# element starts, I would write a class like this:
-
#
-
# class MyDocument < Nokogiri::XML::SAX::Document
-
# def end_document
-
# puts "the document has ended"
-
# end
-
#
-
# def start_element name, attributes = []
-
# puts "#{name} started"
-
# end
-
# end
-
#
-
# Then I would instantiate a SAX parser with this document, and feed the
-
# parser some XML
-
#
-
# # Create a new parser
-
# parser = Nokogiri::XML::SAX::Parser.new(MyDocument.new)
-
#
-
# # Feed the parser some XML
-
# parser.parse(File.open(ARGV[0]))
-
#
-
# Now my document handler will be called when each node starts, and when
-
# then document ends. To see what kinds of events are available, take
-
# a look at Nokogiri::XML::SAX::Document.
-
#
-
# Two SAX parsers for XML are available, a parser that reads from a string
-
# or IO object as it feels necessary, and a parser that lets you spoon
-
# feed it XML. If you want to let Nokogiri deal with reading your XML,
-
# use the Nokogiri::XML::SAX::Parser. If you want to have fine grain
-
# control over the XML input, use the Nokogiri::XML::SAX::PushParser.
-
1
module SAX
-
###
-
# This class is used for registering types of events you are interested
-
# in handling. All of the methods on this class are available as
-
# possible events while parsing an XML document. To register for any
-
# particular event, just subclass this class and implement the methods
-
# you are interested in knowing about.
-
#
-
# To only be notified about start and end element events, write a class
-
# like this:
-
#
-
# class MyDocument < Nokogiri::XML::SAX::Document
-
# def start_element name, attrs = []
-
# puts "#{name} started!"
-
# end
-
#
-
# def end_element name
-
# puts "#{name} ended"
-
# end
-
# end
-
#
-
# You can use this event handler for any SAX style parser included with
-
# Nokogiri. See Nokogiri::XML::SAX, and Nokogiri::HTML::SAX.
-
1
class Document
-
###
-
# Called when an XML declaration is parsed
-
1
def xmldecl version, encoding, standalone
-
end
-
-
###
-
# Called when document starts parsing
-
1
def start_document
-
end
-
-
###
-
# Called when document ends parsing
-
1
def end_document
-
end
-
-
###
-
# Called at the beginning of an element
-
# * +name+ is the name of the tag
-
# * +attrs+ are an assoc list of namespaces and attributes, e.g.:
-
# [ ["xmlns:foo", "http://sample.net"], ["size", "large"] ]
-
1
def start_element name, attrs = []
-
end
-
-
###
-
# Called at the end of an element
-
# +name+ is the tag name
-
1
def end_element name
-
end
-
-
###
-
# Called at the beginning of an element
-
# +name+ is the element name
-
# +attrs+ is a list of attributes
-
# +prefix+ is the namespace prefix for the element
-
# +uri+ is the associated namespace URI
-
# +ns+ is a hash of namespace prefix:urls associated with the element
-
1
def start_element_namespace name, attrs = [], prefix = nil, uri = nil, ns = []
-
###
-
# Deal with SAX v1 interface
-
name = [prefix, name].compact.join(':')
-
attributes = ns.map { |ns_prefix,ns_uri|
-
[['xmlns', ns_prefix].compact.join(':'), ns_uri]
-
} + attrs.map { |attr|
-
[[attr.prefix, attr.localname].compact.join(':'), attr.value]
-
}
-
start_element name, attributes
-
end
-
-
###
-
# Called at the end of an element
-
# +name+ is the element's name
-
# +prefix+ is the namespace prefix associated with the element
-
# +uri+ is the associated namespace URI
-
1
def end_element_namespace name, prefix = nil, uri = nil
-
###
-
# Deal with SAX v1 interface
-
end_element [prefix, name].compact.join(':')
-
end
-
-
###
-
# Characters read between a tag. This method might be called multiple
-
# times given one contiguous string of characters.
-
#
-
# +string+ contains the character data
-
1
def characters string
-
end
-
-
###
-
# Called when comments are encountered
-
# +string+ contains the comment data
-
1
def comment string
-
end
-
-
###
-
# Called on document warnings
-
# +string+ contains the warning
-
1
def warning string
-
end
-
-
###
-
# Called on document errors
-
# +string+ contains the error
-
1
def error string
-
end
-
-
###
-
# Called when cdata blocks are found
-
# +string+ contains the cdata content
-
1
def cdata_block string
-
end
-
-
###
-
# Called when processing instructions are found
-
# +name+ is the target of the instruction
-
# +content+ is the value of the instruction
-
1
def processing_instruction name, content
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
module SAX
-
###
-
# This parser is a SAX style parser that reads it's input as it
-
# deems necessary. The parser takes a Nokogiri::XML::SAX::Document,
-
# an optional encoding, then given an XML input, sends messages to
-
# the Nokogiri::XML::SAX::Document.
-
#
-
# Here is an example of using this parser:
-
#
-
# # Create a subclass of Nokogiri::XML::SAX::Document and implement
-
# # the events we care about:
-
# class MyDoc < Nokogiri::XML::SAX::Document
-
# def start_element name, attrs = []
-
# puts "starting: #{name}"
-
# end
-
#
-
# def end_element name
-
# puts "ending: #{name}"
-
# end
-
# end
-
#
-
# # Create our parser
-
# parser = Nokogiri::XML::SAX::Parser.new(MyDoc.new)
-
#
-
# # Send some XML to the parser
-
# parser.parse(File.open(ARGV[0]))
-
#
-
# For more information about SAX parsers, see Nokogiri::XML::SAX. Also
-
# see Nokogiri::XML::SAX::Document for the available events.
-
1
class Parser
-
1
class Attribute < Struct.new(:localname, :prefix, :uri, :value)
-
end
-
-
# Encodinds this parser supports
-
1
ENCODINGS = {
-
'NONE' => 0, # No char encoding detected
-
'UTF-8' => 1, # UTF-8
-
'UTF16LE' => 2, # UTF-16 little endian
-
'UTF16BE' => 3, # UTF-16 big endian
-
'UCS4LE' => 4, # UCS-4 little endian
-
'UCS4BE' => 5, # UCS-4 big endian
-
'EBCDIC' => 6, # EBCDIC uh!
-
'UCS4-2143' => 7, # UCS-4 unusual ordering
-
'UCS4-3412' => 8, # UCS-4 unusual ordering
-
'UCS2' => 9, # UCS-2
-
'ISO-8859-1' => 10, # ISO-8859-1 ISO Latin 1
-
'ISO-8859-2' => 11, # ISO-8859-2 ISO Latin 2
-
'ISO-8859-3' => 12, # ISO-8859-3
-
'ISO-8859-4' => 13, # ISO-8859-4
-
'ISO-8859-5' => 14, # ISO-8859-5
-
'ISO-8859-6' => 15, # ISO-8859-6
-
'ISO-8859-7' => 16, # ISO-8859-7
-
'ISO-8859-8' => 17, # ISO-8859-8
-
'ISO-8859-9' => 18, # ISO-8859-9
-
'ISO-2022-JP' => 19, # ISO-2022-JP
-
'SHIFT-JIS' => 20, # Shift_JIS
-
'EUC-JP' => 21, # EUC-JP
-
'ASCII' => 22, # pure ASCII
-
}
-
-
# The Nokogiri::XML::SAX::Document where events will be sent.
-
1
attr_accessor :document
-
-
# The encoding beings used for this document.
-
1
attr_accessor :encoding
-
-
# Create a new Parser with +doc+ and +encoding+
-
1
def initialize doc = Nokogiri::XML::SAX::Document.new, encoding = 'UTF-8'
-
@encoding = check_encoding(encoding)
-
@document = doc
-
@warned = false
-
end
-
-
###
-
# Parse given +thing+ which may be a string containing xml, or an
-
# IO object.
-
1
def parse thing, &block
-
if thing.respond_to?(:read) && thing.respond_to?(:close)
-
parse_io(thing, &block)
-
else
-
parse_memory(thing, &block)
-
end
-
end
-
-
###
-
# Parse given +io+
-
1
def parse_io io, encoding = 'ASCII'
-
@encoding = check_encoding(encoding)
-
ctx = ParserContext.io(io, ENCODINGS[@encoding])
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
###
-
# Parse a file with +filename+
-
1
def parse_file filename
-
raise ArgumentError unless filename
-
raise Errno::ENOENT unless File.exist?(filename)
-
raise Errno::EISDIR if File.directory?(filename)
-
ctx = ParserContext.file filename
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
1
def parse_memory data
-
ctx = ParserContext.memory data
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
1
private
-
1
def check_encoding(encoding)
-
encoding.upcase.tap do |enc|
-
raise ArgumentError.new("'#{enc}' is not a valid encoding") unless ENCODINGS[enc]
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
module SAX
-
###
-
# Context for XML SAX parsers. This class is usually not instantiated
-
# by the user. Instead, you should be looking at
-
# Nokogiri::XML::SAX::Parser
-
1
class ParserContext
-
1
def self.new thing, encoding = 'UTF-8'
-
[:read, :close].all? { |x| thing.respond_to?(x) } ?
-
io(thing, Parser::ENCODINGS[encoding]) : memory(thing)
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
module SAX
-
###
-
# PushParser can parse a document that is fed to it manually. It
-
# must be given a SAX::Document object which will be called with
-
# SAX events as the document is being parsed.
-
#
-
# Calling PushParser#<< writes XML to the parser, calling any SAX
-
# callbacks it can.
-
#
-
# PushParser#finish tells the parser that the document is finished
-
# and calls the end_document SAX method.
-
#
-
# Example:
-
#
-
# parser = PushParser.new(Class.new(XML::SAX::Document) {
-
# def start_document
-
# puts "start document called"
-
# end
-
# }.new)
-
# parser << "<div>hello<"
-
# parser << "/div>"
-
# parser.finish
-
1
class PushParser
-
-
# The Nokogiri::XML::SAX::Document on which the PushParser will be
-
# operating
-
1
attr_accessor :document
-
-
###
-
# Create a new PushParser with +doc+ as the SAX Document, providing
-
# an optional +file_name+ and +encoding+
-
1
def initialize(doc = XML::SAX::Document.new, file_name = nil, encoding = 'UTF-8')
-
@document = doc
-
@encoding = encoding
-
@sax_parser = XML::SAX::Parser.new(doc)
-
-
## Create our push parser context
-
initialize_native(@sax_parser, file_name)
-
end
-
-
###
-
# Write a +chunk+ of XML to the PushParser. Any callback methods
-
# that can be called will be called immediately.
-
1
def write chunk, last_chunk = false
-
native_write(chunk, last_chunk)
-
end
-
1
alias :<< :write
-
-
###
-
# Finish the parsing. This method is only necessary for
-
# Nokogiri::XML::SAX::Document#end_document to be called.
-
1
def finish
-
write '', true
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class << self
-
###
-
# Create a new Nokogiri::XML::Schema object using a +string_or_io+
-
# object.
-
1
def Schema string_or_io
-
Schema.new(string_or_io)
-
end
-
end
-
-
###
-
# Nokogiri::XML::Schema is used for validating XML against a schema
-
# (usually from an xsd file).
-
#
-
# == Synopsis
-
#
-
# Validate an XML document against a Schema. Loop over the errors that
-
# are returned and print them out:
-
#
-
# xsd = Nokogiri::XML::Schema(File.read(PO_SCHEMA_FILE))
-
# doc = Nokogiri::XML(File.read(PO_XML_FILE))
-
#
-
# xsd.validate(doc).each do |error|
-
# puts error.message
-
# end
-
#
-
# The list of errors are Nokogiri::XML::SyntaxError objects.
-
1
class Schema
-
# Errors while parsing the schema file
-
1
attr_accessor :errors
-
-
###
-
# Create a new Nokogiri::XML::Schema object using a +string_or_io+
-
# object.
-
1
def self.new string_or_io
-
from_document Nokogiri::XML(string_or_io)
-
end
-
-
###
-
# Validate +thing+ against this schema. +thing+ can be a
-
# Nokogiri::XML::Document object, or a filename. An Array of
-
# Nokogiri::XML::SyntaxError objects found while validating the
-
# +thing+ is returned.
-
1
def validate thing
-
if thing.is_a?(Nokogiri::XML::Document)
-
validate_document(thing)
-
elsif File.file?(thing)
-
validate_file(thing)
-
else
-
raise ArgumentError, "Must provide Nokogiri::Xml::Document or the name of an existing file"
-
end
-
end
-
-
###
-
# Returns true if +thing+ is a valid Nokogiri::XML::Document or
-
# file.
-
1
def valid? thing
-
validate(thing).length == 0
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
#
-
# The Searchable module declares the interface used for searching your DOM.
-
#
-
# It implements the public methods `search`, `css`, and `xpath`,
-
# as well as allowing specific implementations to specialize some
-
# of the important behaviors.
-
#
-
1
module Searchable
-
# Regular expression used by Searchable#search to determine if a query
-
# string is CSS or XPath
-
1
LOOKS_LIKE_XPATH = /^(\.\/|\/|\.\.|\.$)/
-
-
###
-
# call-seq: search *paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]
-
#
-
# Search this object for +paths+. +paths+ must be one or more XPath or CSS queries:
-
#
-
# node.search("div.employee", ".//title")
-
#
-
# A hash of namespace bindings may be appended:
-
#
-
# node.search('.//bike:tire', {'bike' => 'http://schwinn.com/'})
-
# node.search('bike|tire', {'bike' => 'http://schwinn.com/'})
-
#
-
# For XPath queries, a hash of variable bindings may also be
-
# appended to the namespace bindings. For example:
-
#
-
# node.search('.//address[@domestic=$value]', nil, {:value => 'Yes'})
-
#
-
# Custom XPath functions and CSS pseudo-selectors may also be
-
# defined. To define custom functions create a class and
-
# implement the function you want to define. The first argument
-
# to the method will be the current matching NodeSet. Any other
-
# arguments are ones that you pass in. Note that this class may
-
# appear anywhere in the argument list. For example:
-
#
-
# node.search('.//title[regex(., "\w+")]', 'div.employee:regex("[0-9]+")'
-
# Class.new {
-
# def regex node_set, regex
-
# node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
-
# end
-
# }.new
-
# )
-
#
-
# See Searchable#xpath and Searchable#css for further usage help.
-
1
def search *args
-
8
paths, handler, ns, binds = extract_params(args)
-
-
8
xpaths = paths.map(&:to_s).map do |path|
-
8
(path =~ LOOKS_LIKE_XPATH) ? path : xpath_query_from_css_rule(path, ns)
-
end.flatten.uniq
-
-
8
xpath(*(xpaths + [ns, handler, binds].compact))
-
end
-
1
alias :/ :search
-
-
###
-
# call-seq: search *paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]
-
#
-
# Search this object for +paths+, and return only the first
-
# result. +paths+ must be one or more XPath or CSS queries.
-
#
-
# See Searchable#search for more information.
-
1
def at *args
-
search(*args).first
-
end
-
1
alias :% :at
-
-
###
-
# call-seq: css *rules, [namespace-bindings, custom-pseudo-class]
-
#
-
# Search this object for CSS +rules+. +rules+ must be one or more CSS
-
# selectors. For example:
-
#
-
# node.css('title')
-
# node.css('body h1.bold')
-
# node.css('div + p.green', 'div#one')
-
#
-
# A hash of namespace bindings may be appended. For example:
-
#
-
# node.css('bike|tire', {'bike' => 'http://schwinn.com/'})
-
#
-
# Custom CSS pseudo classes may also be defined. To define
-
# custom pseudo classes, create a class and implement the custom
-
# pseudo class you want defined. The first argument to the
-
# method will be the current matching NodeSet. Any other
-
# arguments are ones that you pass in. For example:
-
#
-
# node.css('title:regex("\w+")', Class.new {
-
# def regex node_set, regex
-
# node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
-
# end
-
# }.new)
-
#
-
# Note that the CSS query string is case-sensitive with regards
-
# to your document type. That is, if you're looking for "H1" in
-
# an HTML document, you'll never find anything, since HTML tags
-
# will match only lowercase CSS queries. However, "H1" might be
-
# found in an XML document, where tags names are case-sensitive
-
# (e.g., "H1" is distinct from "h1").
-
#
-
1
def css *args
-
7
rules, handler, ns, _ = extract_params(args)
-
-
7
css_internal self, rules, handler, ns
-
end
-
-
##
-
# call-seq: css *rules, [namespace-bindings, custom-pseudo-class]
-
#
-
# Search this object for CSS +rules+, and return only the first
-
# match. +rules+ must be one or more CSS selectors.
-
#
-
# See Searchable#css for more information.
-
1
def at_css *args
-
css(*args).first
-
end
-
-
###
-
# call-seq: xpath *paths, [namespace-bindings, variable-bindings, custom-handler-class]
-
#
-
# Search this node for XPath +paths+. +paths+ must be one or more XPath
-
# queries.
-
#
-
# node.xpath('.//title')
-
#
-
# A hash of namespace bindings may be appended. For example:
-
#
-
# node.xpath('.//foo:name', {'foo' => 'http://example.org/'})
-
# node.xpath('.//xmlns:name', node.root.namespaces)
-
#
-
# A hash of variable bindings may also be appended to the namespace bindings. For example:
-
#
-
# node.xpath('.//address[@domestic=$value]', nil, {:value => 'Yes'})
-
#
-
# Custom XPath functions may also be defined. To define custom
-
# functions create a class and implement the function you want
-
# to define. The first argument to the method will be the
-
# current matching NodeSet. Any other arguments are ones that
-
# you pass in. Note that this class may appear anywhere in the
-
# argument list. For example:
-
#
-
# node.xpath('.//title[regex(., "\w+")]', Class.new {
-
# def regex node_set, regex
-
# node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
-
# end
-
# }.new)
-
#
-
1
def xpath *args
-
296
paths, handler, ns, binds = extract_params(args)
-
-
296
xpath_internal self, paths, handler, ns, binds
-
end
-
-
##
-
# call-seq: xpath *paths, [namespace-bindings, variable-bindings, custom-handler-class]
-
#
-
# Search this node for XPath +paths+, and return only the first
-
# match. +paths+ must be one or more XPath queries.
-
#
-
# See Searchable#xpath for more information.
-
1
def at_xpath *args
-
3
xpath(*args).first
-
end
-
-
1
private
-
-
1
def css_internal node, rules, handler, ns
-
7
xpath_internal node, css_rules_to_xpath(rules, ns), handler, ns, nil
-
end
-
-
1
def xpath_internal node, paths, handler, ns, binds
-
303
document = node.document
-
303
return NodeSet.new(document) unless document
-
-
303
if paths.length == 1
-
303
return xpath_impl(node, paths.first, handler, ns, binds)
-
end
-
-
NodeSet.new(document) do |combined|
-
paths.each do |path|
-
xpath_impl(node, path, handler, ns, binds).each { |set| combined << set }
-
end
-
end
-
end
-
-
1
def xpath_impl node, path, handler, ns, binds
-
303
ctx = XPathContext.new(node)
-
303
ctx.register_namespaces(ns)
-
303
path = path.gsub(/xmlns:/, ' :') unless Nokogiri.uses_libxml?
-
-
binds.each do |key,value|
-
ctx.register_variable key.to_s, value
-
303
end if binds
-
-
303
ctx.evaluate(path, handler)
-
end
-
-
1
def css_rules_to_xpath(rules, ns)
-
14
rules.map { |rule| xpath_query_from_css_rule(rule, ns) }
-
end
-
-
1
def xpath_query_from_css_rule rule, ns
-
self.class::IMPLIED_XPATH_CONTEXTS.map do |implied_xpath_context|
-
15
CSS.xpath_for(rule.to_s, :prefix => implied_xpath_context, :ns => ns)
-
15
end.join(' | ')
-
end
-
-
1
def extract_params params # :nodoc:
-
311
handler = params.find do |param|
-
326
![Hash, String, Symbol].include?(param.class)
-
end
-
311
params -= [handler] if handler
-
-
311
hashes = []
-
311
while Hash === params.last || params.last.nil?
-
8
hashes << params.pop
-
8
break if params.empty?
-
end
-
311
ns, binds = hashes.reverse
-
-
311
ns ||= document.root ? document.root.namespaces : {}
-
-
311
[params, handler, ns, binds]
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
###
-
# This class provides information about XML SyntaxErrors. These
-
# exceptions are typically stored on Nokogiri::XML::Document#errors.
-
1
class SyntaxError < ::Nokogiri::SyntaxError
-
1
attr_reader :domain
-
1
attr_reader :code
-
1
attr_reader :level
-
1
attr_reader :file
-
1
attr_reader :line
-
1
attr_reader :str1
-
1
attr_reader :str2
-
1
attr_reader :str3
-
1
attr_reader :int1
-
1
attr_reader :column
-
-
###
-
# return true if this is a non error
-
1
def none?
-
level == 0
-
end
-
-
###
-
# return true if this is a warning
-
1
def warning?
-
level == 1
-
end
-
-
###
-
# return true if this is an error
-
1
def error?
-
level == 2
-
end
-
-
###
-
# return true if this error is fatal
-
1
def fatal?
-
level == 3
-
end
-
-
1
def to_s
-
message = super.chomp
-
[location_to_s, level_to_s, message].
-
compact.join(": ").
-
force_encoding(message.encoding)
-
end
-
-
1
private
-
-
1
def level_to_s
-
case level
-
when 3 then "FATAL"
-
when 2 then "ERROR"
-
when 1 then "WARNING"
-
else nil
-
end
-
end
-
-
1
def nil_or_zero?(attribute)
-
attribute.nil? || attribute.zero?
-
end
-
-
1
def location_to_s
-
return nil if nil_or_zero?(line) && nil_or_zero?(column)
-
"#{line}:#{column}"
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class Text < Nokogiri::XML::CharacterData
-
1
def content=(string)
-
self.native_content = string.to_s
-
end
-
end
-
end
-
end
-
1
require 'nokogiri/xml/xpath/syntax_error'
-
-
1
module Nokogiri
-
1
module XML
-
1
class XPath
-
# The Nokogiri::XML::Document tied to this XPath instance
-
1
attr_accessor :document
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class XPath
-
1
class SyntaxError < XML::SyntaxError
-
1
def to_s
-
[super.chomp, str1].compact.join(': ')
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class XPathContext
-
-
###
-
# Register namespaces in +namespaces+
-
1
def register_namespaces(namespaces)
-
303
namespaces.each do |k, v|
-
k = k.to_s.gsub(/.*:/,'') # strip off 'xmlns:' or 'xml:'
-
register_ns(k, v)
-
end
-
end
-
-
end
-
end
-
end
-
1
require 'nokogiri/xslt/stylesheet'
-
-
1
module Nokogiri
-
1
class << self
-
###
-
# Create a Nokogiri::XSLT::Stylesheet with +stylesheet+.
-
#
-
# Example:
-
#
-
# xslt = Nokogiri::XSLT(File.read(ARGV[0]))
-
#
-
1
def XSLT stylesheet, modules = {}
-
XSLT.parse(stylesheet, modules)
-
end
-
end
-
-
###
-
# See Nokogiri::XSLT::Stylesheet for creating and manipulating
-
# Stylesheet object.
-
1
module XSLT
-
1
class << self
-
###
-
# Parse the stylesheet in +string+, register any +modules+
-
1
def parse string, modules = {}
-
modules.each do |url, klass|
-
XSLT.register url, klass
-
end
-
-
if Nokogiri.jruby?
-
Stylesheet.parse_stylesheet_doc(XML.parse(string), string)
-
else
-
Stylesheet.parse_stylesheet_doc(XML.parse(string))
-
end
-
end
-
-
###
-
# Quote parameters in +params+ for stylesheet safety
-
1
def quote_params params
-
parray = (params.instance_of?(Hash) ? params.to_a.flatten : params).dup
-
parray.each_with_index do |v,i|
-
if i % 2 > 0
-
parray[i]=
-
if v =~ /'/
-
"concat('#{ v.gsub(/'/, %q{', "'", '}) }')"
-
else
-
"'#{v}'";
-
end
-
else
-
parray[i] = v.to_s
-
end
-
end
-
parray.flatten
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XSLT
-
###
-
# A Stylesheet represents an XSLT Stylesheet object. Stylesheet creation
-
# is done through Nokogiri.XSLT. Here is an example of transforming
-
# an XML::Document with a Stylesheet:
-
#
-
# doc = Nokogiri::XML(File.read('some_file.xml'))
-
# xslt = Nokogiri::XSLT(File.read('some_transformer.xslt'))
-
#
-
# puts xslt.transform(doc)
-
#
-
# See Nokogiri::XSLT::Stylesheet#transform for more transformation
-
# information.
-
1
class Stylesheet
-
###
-
# Apply an XSLT stylesheet to an XML::Document.
-
# +params+ is an array of strings used as XSLT parameters.
-
# returns serialized document
-
1
def apply_to document, params = []
-
serialize(transform(document, params))
-
end
-
end
-
end
-
end
-
# = Public Suffix
-
#
-
# Domain name parser based on the Public Suffix List.
-
#
-
# Copyright (c) 2009-2017 Simone Carletti <weppos@weppos.net>
-
-
1
require "public_suffix/domain"
-
1
require "public_suffix/version"
-
1
require "public_suffix/errors"
-
1
require "public_suffix/rule"
-
1
require "public_suffix/list"
-
-
# PublicSuffix is a Ruby domain name parser based on the Public Suffix List.
-
#
-
# The [Public Suffix List](https://publicsuffix.org) is a cross-vendor initiative
-
# to provide an accurate list of domain name suffixes.
-
#
-
# The Public Suffix List is an initiative of the Mozilla Project,
-
# but is maintained as a community resource. It is available for use in any software,
-
# but was originally created to meet the needs of browser manufacturers.
-
1
module PublicSuffix
-
-
1
DOT = ".".freeze
-
1
BANG = "!".freeze
-
1
STAR = "*".freeze
-
-
# Parses +name+ and returns the {PublicSuffix::Domain} instance.
-
#
-
# @example Parse a valid domain
-
# PublicSuffix.parse("google.com")
-
# # => #<PublicSuffix::Domain ...>
-
#
-
# @example Parse a valid subdomain
-
# PublicSuffix.parse("www.google.com")
-
# # => #<PublicSuffix::Domain ...>
-
#
-
# @example Parse a fully qualified domain
-
# PublicSuffix.parse("google.com.")
-
# # => #<PublicSuffix::Domain ...>
-
#
-
# @example Parse a fully qualified domain (subdomain)
-
# PublicSuffix.parse("www.google.com.")
-
# # => #<PublicSuffix::Domain ...>
-
#
-
# @example Parse an invalid domain
-
# PublicSuffix.parse("x.yz")
-
# # => PublicSuffix::DomainInvalid
-
#
-
# @example Parse an URL (not supported, only domains)
-
# PublicSuffix.parse("http://www.google.com")
-
# # => PublicSuffix::DomainInvalid
-
#
-
#
-
# @param [String, #to_s] name The domain name or fully qualified domain name to parse.
-
# @param [PublicSuffix::List] list The rule list to search, defaults to the default {PublicSuffix::List}
-
# @param [Boolean] ignore_private
-
# @return [PublicSuffix::Domain]
-
#
-
# @raise [PublicSuffix::DomainInvalid]
-
# If domain is not a valid domain.
-
# @raise [PublicSuffix::DomainNotAllowed]
-
# If a rule for +domain+ is found, but the rule doesn't allow +domain+.
-
1
def self.parse(name, list: List.default, default_rule: list.default_rule, ignore_private: false)
-
what = normalize(name)
-
raise what if what.is_a?(DomainInvalid)
-
-
rule = list.find(what, default: default_rule, ignore_private: ignore_private)
-
-
# rubocop:disable Style/IfUnlessModifier
-
if rule.nil?
-
raise DomainInvalid, "`#{what}` is not a valid domain"
-
end
-
if rule.decompose(what).last.nil?
-
raise DomainNotAllowed, "`#{what}` is not allowed according to Registry policy"
-
end
-
# rubocop:enable Style/IfUnlessModifier
-
-
decompose(what, rule)
-
end
-
-
# Checks whether +domain+ is assigned and allowed, without actually parsing it.
-
#
-
# This method doesn't care whether domain is a domain or subdomain.
-
# The validation is performed using the default {PublicSuffix::List}.
-
#
-
# @example Validate a valid domain
-
# PublicSuffix.valid?("example.com")
-
# # => true
-
#
-
# @example Validate a valid subdomain
-
# PublicSuffix.valid?("www.example.com")
-
# # => true
-
#
-
# @example Validate a not-listed domain
-
# PublicSuffix.valid?("example.tldnotlisted")
-
# # => true
-
#
-
# @example Validate a not-allowed domain
-
# PublicSuffix.valid?("example.do")
-
# # => false
-
# PublicSuffix.valid?("www.example.do")
-
# # => true
-
#
-
# @example Validate a fully qualified domain
-
# PublicSuffix.valid?("google.com.")
-
# # => true
-
# PublicSuffix.valid?("www.google.com.")
-
# # => true
-
#
-
# @example Check an URL (which is not a valid domain)
-
# PublicSuffix.valid?("http://www.example.com")
-
# # => false
-
#
-
#
-
# @param [String, #to_s] name The domain name or fully qualified domain name to validate.
-
# @param [Boolean] ignore_private
-
# @return [Boolean]
-
1
def self.valid?(name, list: List.default, default_rule: list.default_rule, ignore_private: false)
-
what = normalize(name)
-
return false if what.is_a?(DomainInvalid)
-
-
rule = list.find(what, default: default_rule, ignore_private: ignore_private)
-
-
!rule.nil? && !rule.decompose(what).last.nil?
-
end
-
-
# Attempt to parse the name and returns the domain, if valid.
-
#
-
# This method doesn't raise. Instead, it returns nil if the domain is not valid for whatever reason.
-
#
-
# @param [String, #to_s] name The domain name or fully qualified domain name to parse.
-
# @param [PublicSuffix::List] list The rule list to search, defaults to the default {PublicSuffix::List}
-
# @param [Boolean] ignore_private
-
# @return [String]
-
1
def self.domain(name, **options)
-
parse(name, **options).domain
-
rescue PublicSuffix::Error
-
nil
-
end
-
-
-
# private
-
-
1
def self.decompose(name, rule)
-
left, right = rule.decompose(name)
-
-
parts = left.split(DOT)
-
# If we have 0 parts left, there is just a tld and no domain or subdomain
-
# If we have 1 part left, there is just a tld, domain and not subdomain
-
# If we have 2 parts left, the last part is the domain, the other parts (combined) are the subdomain
-
tld = right
-
sld = parts.empty? ? nil : parts.pop
-
trd = parts.empty? ? nil : parts.join(DOT)
-
-
Domain.new(tld, sld, trd)
-
end
-
-
# Pretend we know how to deal with user input.
-
1
def self.normalize(name)
-
name = name.to_s.dup
-
name.strip!
-
name.chomp!(DOT)
-
name.downcase!
-
-
return DomainInvalid.new("Name is blank") if name.empty?
-
return DomainInvalid.new("Name starts with a dot") if name.start_with?(DOT)
-
return DomainInvalid.new("%s is not expected to contain a scheme" % name) if name.include?("://")
-
name
-
end
-
-
end
-
# = Public Suffix
-
#
-
# Domain name parser based on the Public Suffix List.
-
#
-
# Copyright (c) 2009-2017 Simone Carletti <weppos@weppos.net>
-
-
1
module PublicSuffix
-
-
# Domain represents a domain name, composed by a TLD, SLD and TRD.
-
1
class Domain
-
-
# Splits a string into the labels, that is the dot-separated parts.
-
#
-
# The input is not validated, but it is assumed to be a valid domain name.
-
#
-
# @example
-
#
-
# name_to_labels('example.com')
-
# # => ['example', 'com']
-
#
-
# name_to_labels('example.co.uk')
-
# # => ['example', 'co', 'uk']
-
#
-
# @param name [String, #to_s] The domain name to split.
-
# @return [Array<String>]
-
1
def self.name_to_labels(name)
-
name.to_s.split(DOT)
-
end
-
-
-
1
attr_reader :tld, :sld, :trd
-
-
# Creates and returns a new {PublicSuffix::Domain} instance.
-
#
-
# @overload initialize(tld)
-
# Initializes with a +tld+.
-
# @param [String] tld The TLD (extension)
-
# @overload initialize(tld, sld)
-
# Initializes with a +tld+ and +sld+.
-
# @param [String] tld The TLD (extension)
-
# @param [String] sld The TRD (domain)
-
# @overload initialize(tld, sld, trd)
-
# Initializes with a +tld+, +sld+ and +trd+.
-
# @param [String] tld The TLD (extension)
-
# @param [String] sld The SLD (domain)
-
# @param [String] tld The TRD (subdomain)
-
#
-
# @yield [self] Yields on self.
-
# @yieldparam [PublicSuffix::Domain] self The newly creates instance
-
#
-
# @example Initialize with a TLD
-
# PublicSuffix::Domain.new("com")
-
# # => #<PublicSuffix::Domain @tld="com">
-
#
-
# @example Initialize with a TLD and SLD
-
# PublicSuffix::Domain.new("com", "example")
-
# # => #<PublicSuffix::Domain @tld="com", @trd=nil>
-
#
-
# @example Initialize with a TLD, SLD and TRD
-
# PublicSuffix::Domain.new("com", "example", "wwww")
-
# # => #<PublicSuffix::Domain @tld="com", @trd=nil, @sld="example">
-
#
-
1
def initialize(*args)
-
@tld, @sld, @trd = args
-
yield(self) if block_given?
-
end
-
-
# Returns a string representation of this object.
-
#
-
# @return [String]
-
1
def to_s
-
name
-
end
-
-
# Returns an array containing the domain parts.
-
#
-
# @return [Array<String, nil>]
-
#
-
# @example
-
#
-
# PublicSuffix::Domain.new("google.com").to_a
-
# # => [nil, "google", "com"]
-
#
-
# PublicSuffix::Domain.new("www.google.com").to_a
-
# # => [nil, "google", "com"]
-
#
-
1
def to_a
-
[@trd, @sld, @tld]
-
end
-
-
# Returns the full domain name.
-
#
-
# @return [String]
-
#
-
# @example Gets the domain name of a domain
-
# PublicSuffix::Domain.new("com", "google").name
-
# # => "google.com"
-
#
-
# @example Gets the domain name of a subdomain
-
# PublicSuffix::Domain.new("com", "google", "www").name
-
# # => "www.google.com"
-
#
-
1
def name
-
[@trd, @sld, @tld].compact.join(DOT)
-
end
-
-
# Returns a domain-like representation of this object
-
# if the object is a {#domain?}, <tt>nil</tt> otherwise.
-
#
-
# PublicSuffix::Domain.new("com").domain
-
# # => nil
-
#
-
# PublicSuffix::Domain.new("com", "google").domain
-
# # => "google.com"
-
#
-
# PublicSuffix::Domain.new("com", "google", "www").domain
-
# # => "www.google.com"
-
#
-
# This method doesn't validate the input. It handles the domain
-
# as a valid domain name and simply applies the necessary transformations.
-
#
-
# This method returns a FQD, not just the domain part.
-
# To get the domain part, use <tt>#sld</tt> (aka second level domain).
-
#
-
# PublicSuffix::Domain.new("com", "google", "www").domain
-
# # => "google.com"
-
#
-
# PublicSuffix::Domain.new("com", "google", "www").sld
-
# # => "google"
-
#
-
# @see #domain?
-
# @see #subdomain
-
#
-
# @return [String]
-
1
def domain
-
[@sld, @tld].join(DOT) if domain?
-
end
-
-
# Returns a subdomain-like representation of this object
-
# if the object is a {#subdomain?}, <tt>nil</tt> otherwise.
-
#
-
# PublicSuffix::Domain.new("com").subdomain
-
# # => nil
-
#
-
# PublicSuffix::Domain.new("com", "google").subdomain
-
# # => nil
-
#
-
# PublicSuffix::Domain.new("com", "google", "www").subdomain
-
# # => "www.google.com"
-
#
-
# This method doesn't validate the input. It handles the domain
-
# as a valid domain name and simply applies the necessary transformations.
-
#
-
# This method returns a FQD, not just the subdomain part.
-
# To get the subdomain part, use <tt>#trd</tt> (aka third level domain).
-
#
-
# PublicSuffix::Domain.new("com", "google", "www").subdomain
-
# # => "www.google.com"
-
#
-
# PublicSuffix::Domain.new("com", "google", "www").trd
-
# # => "www"
-
#
-
# @see #subdomain?
-
# @see #domain
-
#
-
# @return [String]
-
1
def subdomain
-
[@trd, @sld, @tld].join(DOT) if subdomain?
-
end
-
-
# Checks whether <tt>self</tt> looks like a domain.
-
#
-
# This method doesn't actually validate the domain.
-
# It only checks whether the instance contains
-
# a value for the {#tld} and {#sld} attributes.
-
# If you also want to validate the domain,
-
# use {#valid_domain?} instead.
-
#
-
# @example
-
#
-
# PublicSuffix::Domain.new("com").domain?
-
# # => false
-
#
-
# PublicSuffix::Domain.new("com", "google").domain?
-
# # => true
-
#
-
# PublicSuffix::Domain.new("com", "google", "www").domain?
-
# # => true
-
#
-
# # This is an invalid domain, but returns true
-
# # because this method doesn't validate the content.
-
# PublicSuffix::Domain.new("com", nil).domain?
-
# # => true
-
#
-
# @see #subdomain?
-
#
-
# @return [Boolean]
-
1
def domain?
-
!(@tld.nil? || @sld.nil?)
-
end
-
-
# Checks whether <tt>self</tt> looks like a subdomain.
-
#
-
# This method doesn't actually validate the subdomain.
-
# It only checks whether the instance contains
-
# a value for the {#tld}, {#sld} and {#trd} attributes.
-
# If you also want to validate the domain,
-
# use {#valid_subdomain?} instead.
-
#
-
# @example
-
#
-
# PublicSuffix::Domain.new("com").subdomain?
-
# # => false
-
#
-
# PublicSuffix::Domain.new("com", "google").subdomain?
-
# # => false
-
#
-
# PublicSuffix::Domain.new("com", "google", "www").subdomain?
-
# # => true
-
#
-
# # This is an invalid domain, but returns true
-
# # because this method doesn't validate the content.
-
# PublicSuffix::Domain.new("com", "example", nil).subdomain?
-
# # => true
-
#
-
# @see #domain?
-
#
-
# @return [Boolean]
-
1
def subdomain?
-
!(@tld.nil? || @sld.nil? || @trd.nil?)
-
end
-
-
end
-
-
end
-
# = Public Suffix
-
#
-
# Domain name parser based on the Public Suffix List.
-
#
-
# Copyright (c) 2009-2017 Simone Carletti <weppos@weppos.net>
-
-
1
module PublicSuffix
-
-
1
class Error < StandardError
-
end
-
-
# Raised when trying to parse an invalid name.
-
# A name is considered invalid when no rule is found in the definition list.
-
#
-
# @example
-
#
-
# PublicSuffix.parse("nic.test")
-
# # => PublicSuffix::DomainInvalid
-
#
-
# PublicSuffix.parse("http://www.nic.it")
-
# # => PublicSuffix::DomainInvalid
-
#
-
1
class DomainInvalid < Error
-
end
-
-
# Raised when trying to parse a name that matches a suffix.
-
#
-
# @example
-
#
-
# PublicSuffix.parse("nic.do")
-
# # => PublicSuffix::DomainNotAllowed
-
#
-
# PublicSuffix.parse("www.nic.do")
-
# # => PublicSuffix::Domain
-
#
-
1
class DomainNotAllowed < DomainInvalid
-
end
-
-
end
-
# = Public Suffix
-
#
-
# Domain name parser based on the Public Suffix List.
-
#
-
# Copyright (c) 2009-2017 Simone Carletti <weppos@weppos.net>
-
-
1
module PublicSuffix
-
-
# A {PublicSuffix::List} is a collection of one
-
# or more {PublicSuffix::Rule}.
-
#
-
# Given a {PublicSuffix::List},
-
# you can add or remove {PublicSuffix::Rule},
-
# iterate all items in the list or search for the first rule
-
# which matches a specific domain name.
-
#
-
# # Create a new list
-
# list = PublicSuffix::List.new
-
#
-
# # Push two rules to the list
-
# list << PublicSuffix::Rule.factory("it")
-
# list << PublicSuffix::Rule.factory("com")
-
#
-
# # Get the size of the list
-
# list.size
-
# # => 2
-
#
-
# # Search for the rule matching given domain
-
# list.find("example.com")
-
# # => #<PublicSuffix::Rule::Normal>
-
# list.find("example.org")
-
# # => nil
-
#
-
# You can create as many {PublicSuffix::List} you want.
-
# The {PublicSuffix::List.default} rule list is used
-
# to tokenize and validate a domain.
-
#
-
# {PublicSuffix::List} implements +Enumerable+ module.
-
#
-
1
class List
-
1
include Enumerable
-
-
1
DEFAULT_LIST_PATH = File.join(File.dirname(__FILE__), "..", "..", "data", "list.txt")
-
-
# Gets the default rule list.
-
#
-
# Initializes a new {PublicSuffix::List} parsing the content
-
# of {PublicSuffix::List.default_list_content}, if required.
-
#
-
# @return [PublicSuffix::List]
-
1
def self.default(**options)
-
@default ||= parse(File.read(DEFAULT_LIST_PATH), options)
-
end
-
-
# Sets the default rule list to +value+.
-
#
-
# @param [PublicSuffix::List] value
-
# The new rule list.
-
#
-
# @return [PublicSuffix::List]
-
1
def self.default=(value)
-
@default = value
-
end
-
-
# Sets the default rule list to +nil+.
-
#
-
# @return [self]
-
1
def self.clear
-
self.default = nil
-
self
-
end
-
-
# rubocop:disable Metrics/MethodLength
-
-
# Parse given +input+ treating the content as Public Suffix List.
-
#
-
# See http://publicsuffix.org/format/ for more details about input format.
-
#
-
# @param string [#each_line] The list to parse.
-
# @param private_domain [Boolean] whether to ignore the private domains section.
-
# @return [Array<PublicSuffix::Rule::*>]
-
1
def self.parse(input, private_domains: true)
-
comment_token = "//".freeze
-
private_token = "===BEGIN PRIVATE DOMAINS===".freeze
-
section = nil # 1 == ICANN, 2 == PRIVATE
-
-
new do |list|
-
input.each_line do |line|
-
line.strip!
-
case # rubocop:disable Style/EmptyCaseCondition
-
-
# skip blank lines
-
when line.empty?
-
next
-
-
# include private domains or stop scanner
-
when line.include?(private_token)
-
break if !private_domains
-
section = 2
-
-
# skip comments
-
when line.start_with?(comment_token)
-
next
-
-
else
-
list.add(Rule.factory(line, private: section == 2), reindex: false)
-
-
end
-
end
-
end
-
end
-
# rubocop:enable Metrics/MethodLength
-
-
-
# Gets the array of rules.
-
#
-
# @return [Array<PublicSuffix::Rule::*>]
-
1
attr_reader :rules
-
-
-
# Initializes an empty {PublicSuffix::List}.
-
#
-
# @yield [self] Yields on self.
-
# @yieldparam [PublicSuffix::List] self The newly created instance.
-
#
-
1
def initialize
-
@rules = []
-
yield(self) if block_given?
-
reindex!
-
end
-
-
-
# Creates a naive index for +@rules+. Just a hash that will tell
-
# us where the elements of +@rules+ are relative to its first
-
# {PublicSuffix::Rule::Base#labels} element.
-
#
-
# For instance if @rules[5] and @rules[4] are the only elements of the list
-
# where Rule#labels.first is 'us' @indexes['us'] #=> [5,4], that way in
-
# select we can avoid mapping every single rule against the candidate domain.
-
1
def reindex!
-
@indexes = {}
-
@rules.each_with_index do |rule, index|
-
tld = Domain.name_to_labels(rule.value).last
-
@indexes[tld] ||= []
-
@indexes[tld] << index
-
end
-
end
-
-
# Gets the naive index, a hash that with the keys being the first label of
-
# every rule pointing to an array of integers (indexes of the rules in @rules).
-
1
def indexes
-
@indexes.dup
-
end
-
-
-
# Checks whether two lists are equal.
-
#
-
# List <tt>one</tt> is equal to <tt>two</tt>, if <tt>two</tt> is an instance of
-
# {PublicSuffix::List} and each +PublicSuffix::Rule::*+
-
# in list <tt>one</tt> is available in list <tt>two</tt>, in the same order.
-
#
-
# @param [PublicSuffix::List] other
-
# The List to compare.
-
#
-
# @return [Boolean]
-
1
def ==(other)
-
return false unless other.is_a?(List)
-
equal?(other) || rules == other.rules
-
end
-
1
alias eql? ==
-
-
# Iterates each rule in the list.
-
1
def each(*args, &block)
-
@rules.each(*args, &block)
-
end
-
-
-
# Adds the given object to the list and optionally refreshes the rule index.
-
#
-
# @param [PublicSuffix::Rule::*] rule
-
# The rule to add to the list.
-
# @param [Boolean] reindex
-
# Set to true to recreate the rule index
-
# after the rule has been added to the list.
-
#
-
# @return [self]
-
#
-
# @see #reindex!
-
#
-
1
def add(rule, reindex: true)
-
@rules << rule
-
reindex! if reindex
-
self
-
end
-
1
alias << add
-
-
# Gets the number of elements in the list.
-
#
-
# @return [Integer]
-
1
def size
-
@rules.size
-
end
-
-
# Checks whether the list is empty.
-
#
-
# @return [Boolean]
-
1
def empty?
-
@rules.empty?
-
end
-
-
# Removes all elements.
-
#
-
# @return [self]
-
1
def clear
-
@rules.clear
-
reindex!
-
self
-
end
-
-
# Finds and returns the most appropriate rule for the domain name.
-
#
-
# From the Public Suffix List documentation:
-
#
-
# - If a hostname matches more than one rule in the file,
-
# the longest matching rule (the one with the most levels) will be used.
-
# - An exclamation mark (!) at the start of a rule marks an exception to a previous wildcard rule.
-
# An exception rule takes priority over any other matching rule.
-
#
-
# ## Algorithm description
-
#
-
# 1. Match domain against all rules and take note of the matching ones.
-
# 2. If no rules match, the prevailing rule is "*".
-
# 3. If more than one rule matches, the prevailing rule is the one which is an exception rule.
-
# 4. If there is no matching exception rule, the prevailing rule is the one with the most labels.
-
# 5. If the prevailing rule is a exception rule, modify it by removing the leftmost label.
-
# 6. The public suffix is the set of labels from the domain
-
# which directly match the labels of the prevailing rule (joined by dots).
-
# 7. The registered domain is the public suffix plus one additional label.
-
#
-
# @param name [String, #to_s] The domain name.
-
# @param [PublicSuffix::Rule::*] default The default rule to return in case no rule matches.
-
# @return [PublicSuffix::Rule::*]
-
1
def find(name, default: default_rule, **options)
-
rule = select(name, **options).inject do |l, r|
-
return r if r.class == Rule::Exception
-
l.length > r.length ? l : r
-
end
-
rule || default
-
end
-
-
# Selects all the rules matching given domain.
-
#
-
# Internally, the lookup heavily rely on the `@indexes`. The input is split into labels,
-
# and we retriever from the index only the rules that end with the input label. After that,
-
# a sequential scan is performed. In most cases, where the number of rules for the same label
-
# is limited, this algorithm is efficient enough.
-
#
-
# If `ignore_private` is set to true, the algorithm will skip the rules that are flagged as private domain.
-
# Note that the rules will still be part of the loop. If you frequently need to access lists
-
# ignoring the private domains, you should create a list that doesn't include these domains setting the
-
# `private_domains: false` option when calling {.parse}.
-
#
-
# @param [String, #to_s] name The domain name.
-
# @param [Boolean] ignore_private
-
# @return [Array<PublicSuffix::Rule::*>]
-
1
def select(name, ignore_private: false)
-
name = name.to_s
-
indices = (@indexes[Domain.name_to_labels(name).last] || [])
-
-
finder = @rules.values_at(*indices).lazy
-
finder = finder.select { |rule| rule.match?(name) }
-
finder = finder.select { |rule| !rule.private } if ignore_private
-
finder.to_a
-
end
-
-
# Gets the default rule.
-
#
-
# @see PublicSuffix::Rule.default_rule
-
#
-
# @return [PublicSuffix::Rule::*]
-
1
def default_rule
-
PublicSuffix::Rule.default
-
end
-
-
end
-
end
-
# = Public Suffix
-
#
-
# Domain name parser based on the Public Suffix List.
-
#
-
# Copyright (c) 2009-2017 Simone Carletti <weppos@weppos.net>
-
-
1
module PublicSuffix
-
-
# A Rule is a special object which holds a single definition
-
# of the Public Suffix List.
-
#
-
# There are 3 types of rules, each one represented by a specific
-
# subclass within the +PublicSuffix::Rule+ namespace.
-
#
-
# To create a new Rule, use the {PublicSuffix::Rule#factory} method.
-
#
-
# PublicSuffix::Rule.factory("ar")
-
# # => #<PublicSuffix::Rule::Normal>
-
#
-
1
module Rule
-
-
# = Abstract rule class
-
#
-
# This represent the base class for a Rule definition
-
# in the {Public Suffix List}[https://publicsuffix.org].
-
#
-
# This is intended to be an Abstract class
-
# and you shouldn't create a direct instance. The only purpose
-
# of this class is to expose a common interface
-
# for all the available subclasses.
-
#
-
# * {PublicSuffix::Rule::Normal}
-
# * {PublicSuffix::Rule::Exception}
-
# * {PublicSuffix::Rule::Wildcard}
-
#
-
# ## Properties
-
#
-
# A rule is composed by 4 properties:
-
#
-
# value - A normalized version of the rule name.
-
# The normalization process depends on rule tpe.
-
#
-
# Here's an example
-
#
-
# PublicSuffix::Rule.factory("*.google.com")
-
# #<PublicSuffix::Rule::Wildcard:0x1015c14b0
-
# @value="google.com"
-
# >
-
#
-
# ## Rule Creation
-
#
-
# The best way to create a new rule is passing the rule name
-
# to the <tt>PublicSuffix::Rule.factory</tt> method.
-
#
-
# PublicSuffix::Rule.factory("com")
-
# # => PublicSuffix::Rule::Normal
-
#
-
# PublicSuffix::Rule.factory("*.com")
-
# # => PublicSuffix::Rule::Wildcard
-
#
-
# This method will detect the rule type and create an instance
-
# from the proper rule class.
-
#
-
# ## Rule Usage
-
#
-
# A rule describes the composition of a domain name and explains how to tokenize
-
# the name into tld, sld and trd.
-
#
-
# To use a rule, you first need to be sure the name you want to tokenize
-
# can be handled by the current rule.
-
# You can use the <tt>#match?</tt> method.
-
#
-
# rule = PublicSuffix::Rule.factory("com")
-
#
-
# rule.match?("google.com")
-
# # => true
-
#
-
# rule.match?("google.com")
-
# # => false
-
#
-
# Rule order is significant. A name can match more than one rule.
-
# See the {Public Suffix Documentation}[http://publicsuffix.org/format/]
-
# to learn more about rule priority.
-
#
-
# When you have the right rule, you can use it to tokenize the domain name.
-
#
-
# rule = PublicSuffix::Rule.factory("com")
-
#
-
# rule.decompose("google.com")
-
# # => ["google", "com"]
-
#
-
# rule.decompose("www.google.com")
-
# # => ["www.google", "com"]
-
#
-
# @abstract
-
#
-
1
class Base
-
-
# @return [String] the rule definition
-
1
attr_reader :value
-
-
# @return [Boolean] true if the rule is a private domain
-
1
attr_reader :private
-
-
-
# Initializes a new rule with name and value.
-
# If value is +nil+, name also becomes the value for this rule.
-
#
-
# @param value [String] the value of the rule
-
1
def initialize(value, private: false)
-
@value = value.to_s
-
@private = private
-
end
-
-
# Checks whether this rule is equal to <tt>other</tt>.
-
#
-
# @param [PublicSuffix::Rule::*] other The rule to compare
-
# @return [Boolean]
-
# Returns true if this rule and other are instances of the same class
-
# and has the same value, false otherwise.
-
1
def ==(other)
-
equal?(other) || (self.class == other.class && value == other.value)
-
end
-
1
alias eql? ==
-
-
# Checks if this rule matches +name+.
-
#
-
# A domain name is said to match a rule if and only if
-
# all of the following conditions are met:
-
#
-
# - When the domain and rule are split into corresponding labels,
-
# that the domain contains as many or more labels than the rule.
-
# - Beginning with the right-most labels of both the domain and the rule,
-
# and continuing for all labels in the rule, one finds that for every pair,
-
# either they are identical, or that the label from the rule is "*".
-
#
-
# @see https://publicsuffix.org/list/
-
#
-
# @example
-
# Rule.factory("com").match?("example.com")
-
# # => true
-
# Rule.factory("com").match?("example.net")
-
# # => false
-
#
-
# @param name [String, #to_s] The domain name to check.
-
# @return [Boolean]
-
1
def match?(name)
-
# Note: it works because of the assumption there are no
-
# rules like foo.*.com. If the assumption is incorrect,
-
# we need to properly walk the input and skip parts according
-
# to wildcard component.
-
diff = name.chomp(value)
-
diff.empty? || diff[-1] == "."
-
end
-
-
# @abstract
-
1
def parts
-
raise NotImplementedError
-
end
-
-
# @abstract
-
1
def length
-
raise NotImplementedError
-
end
-
-
# @abstract
-
# @param [String, #to_s] name The domain name to decompose
-
# @return [Array<String, nil>]
-
1
def decompose(*)
-
raise NotImplementedError
-
end
-
-
end
-
-
# Normal represents a standard rule (e.g. com).
-
1
class Normal < Base
-
-
# Gets the original rule definition.
-
#
-
# @return [String] The rule definition.
-
1
def rule
-
value
-
end
-
-
# Decomposes the domain name according to rule properties.
-
#
-
# @param [String, #to_s] name The domain name to decompose
-
# @return [Array<String>] The array with [trd + sld, tld].
-
1
def decompose(domain)
-
suffix = parts.join('\.')
-
matches = domain.to_s.match(/^(.*)\.(#{suffix})$/)
-
matches ? matches[1..2] : [nil, nil]
-
end
-
-
# dot-split rule value and returns all rule parts
-
# in the order they appear in the value.
-
#
-
# @return [Array<String>]
-
1
def parts
-
@value.split(DOT)
-
end
-
-
# Gets the length of this rule for comparison,
-
# represented by the number of dot-separated parts in the rule.
-
#
-
# @return [Integer] The length of the rule.
-
1
def length
-
@length ||= parts.length
-
end
-
-
end
-
-
# Wildcard represents a wildcard rule (e.g. *.co.uk).
-
1
class Wildcard < Base
-
-
# Initializes a new rule from +definition+.
-
#
-
# The wildcard "*" is removed from the value, as it's common
-
# for each wildcard rule.
-
#
-
# @param definition [String] the rule as defined in the PSL
-
1
def initialize(definition, private: false)
-
super(definition.to_s[2..-1], private: private)
-
end
-
-
# Gets the original rule definition.
-
#
-
# @return [String] The rule definition.
-
1
def rule
-
value == "" ? STAR : STAR + DOT + value
-
end
-
-
# Decomposes the domain name according to rule properties.
-
#
-
# @param [String, #to_s] name The domain name to decompose
-
# @return [Array<String>] The array with [trd + sld, tld].
-
1
def decompose(domain)
-
suffix = ([".*?"] + parts).join('\.')
-
matches = domain.to_s.match(/^(.*)\.(#{suffix})$/)
-
matches ? matches[1..2] : [nil, nil]
-
end
-
-
# dot-split rule value and returns all rule parts
-
# in the order they appear in the value.
-
#
-
# @return [Array<String>]
-
1
def parts
-
@value.split(DOT)
-
end
-
-
# Gets the length of this rule for comparison,
-
# represented by the number of dot-separated parts in the rule
-
# plus 1 for the *.
-
#
-
# @return [Integer] The length of the rule.
-
1
def length
-
@length ||= parts.length + 1 # * counts as 1
-
end
-
-
end
-
-
# Exception represents an exception rule (e.g. !parliament.uk).
-
1
class Exception < Base
-
-
# Initializes a new rule from +definition+.
-
#
-
# The bang ! is removed from the value, as it's common
-
# for each wildcard rule.
-
#
-
# @param definition [String] the rule as defined in the PSL
-
1
def initialize(definition, private: false)
-
super(definition.to_s[1..-1], private: private)
-
end
-
-
# Gets the original rule definition.
-
#
-
# @return [String] The rule definition.
-
1
def rule
-
BANG + value
-
end
-
-
# Decomposes the domain name according to rule properties.
-
#
-
# @param [String, #to_s] name The domain name to decompose
-
# @return [Array<String>] The array with [trd + sld, tld].
-
1
def decompose(domain)
-
suffix = parts.join('\.')
-
matches = domain.to_s.match(/^(.*)\.(#{suffix})$/)
-
matches ? matches[1..2] : [nil, nil]
-
end
-
-
# dot-split rule value and returns all rule parts
-
# in the order they appear in the value.
-
# The leftmost label is not considered a label.
-
#
-
# See http://publicsuffix.org/format/:
-
# If the prevailing rule is a exception rule,
-
# modify it by removing the leftmost label.
-
#
-
# @return [Array<String>]
-
1
def parts
-
@value.split(DOT)[1..-1]
-
end
-
-
# Gets the length of this rule for comparison,
-
# represented by the number of dot-separated parts in the rule.
-
#
-
# @return [Integer] The length of the rule.
-
1
def length
-
@length ||= parts.length
-
end
-
-
end
-
-
-
# Takes the +name+ of the rule, detects the specific rule class
-
# and creates a new instance of that class.
-
# The +name+ becomes the rule +value+.
-
#
-
# @example Creates a Normal rule
-
# PublicSuffix::Rule.factory("ar")
-
# # => #<PublicSuffix::Rule::Normal>
-
#
-
# @example Creates a Wildcard rule
-
# PublicSuffix::Rule.factory("*.ar")
-
# # => #<PublicSuffix::Rule::Wildcard>
-
#
-
# @example Creates an Exception rule
-
# PublicSuffix::Rule.factory("!congresodelalengua3.ar")
-
# # => #<PublicSuffix::Rule::Exception>
-
#
-
# @param [String] content The rule content.
-
# @return [PublicSuffix::Rule::*] A rule instance.
-
1
def self.factory(content, private: false)
-
case content.to_s[0, 1]
-
when STAR
-
Wildcard
-
when BANG
-
Exception
-
else
-
Normal
-
end.new(content, private: private)
-
end
-
-
# The default rule to use if no rule match.
-
#
-
# The default rule is "*". From https://publicsuffix.org/list/:
-
#
-
# > If no rules match, the prevailing rule is "*".
-
#
-
# @return [PublicSuffix::Rule::Wildcard] The default rule.
-
1
def self.default
-
factory(STAR)
-
end
-
-
end
-
-
end
-
# = Public Suffix
-
#
-
# Domain name parser based on the Public Suffix List.
-
#
-
# Copyright (c) 2009-2017 Simone Carletti <weppos@weppos.net>
-
-
1
module PublicSuffix
-
# The current library version.
-
1
VERSION = "2.0.5".freeze
-
end
-
# Copyright (C) 2007, 2008, 2009, 2010 Christian Neukirchen <purl.org/net/chneukirchen>
-
#
-
# Rack is freely distributable under the terms of an MIT-style license.
-
# See COPYING or http://www.opensource.org/licenses/mit-license.php.
-
-
# The Rack main module, serving as a namespace for all core Rack
-
# modules and classes.
-
#
-
# All modules meant for use in your application are <tt>autoload</tt>ed here,
-
# so it should be enough just to <tt>require rack.rb</tt> in your code.
-
-
1
module Rack
-
# The Rack protocol version number implemented.
-
1
VERSION = [1,3]
-
-
# Return the Rack protocol version as a dotted string.
-
1
def self.version
-
VERSION.join(".")
-
end
-
-
# Return the Rack release as a dotted string.
-
1
def self.release
-
"1.6.8"
-
end
-
1
PATH_INFO = 'PATH_INFO'.freeze
-
1
REQUEST_METHOD = 'REQUEST_METHOD'.freeze
-
1
SCRIPT_NAME = 'SCRIPT_NAME'.freeze
-
1
QUERY_STRING = 'QUERY_STRING'.freeze
-
1
CACHE_CONTROL = 'Cache-Control'.freeze
-
1
CONTENT_LENGTH = 'Content-Length'.freeze
-
1
CONTENT_TYPE = 'Content-Type'.freeze
-
-
1
GET = 'GET'.freeze
-
1
HEAD = 'HEAD'.freeze
-
-
1
autoload :Builder, "rack/builder"
-
1
autoload :BodyProxy, "rack/body_proxy"
-
1
autoload :Cascade, "rack/cascade"
-
1
autoload :Chunked, "rack/chunked"
-
1
autoload :CommonLogger, "rack/commonlogger"
-
1
autoload :ConditionalGet, "rack/conditionalget"
-
1
autoload :Config, "rack/config"
-
1
autoload :ContentLength, "rack/content_length"
-
1
autoload :ContentType, "rack/content_type"
-
1
autoload :ETag, "rack/etag"
-
1
autoload :File, "rack/file"
-
1
autoload :Deflater, "rack/deflater"
-
1
autoload :Directory, "rack/directory"
-
1
autoload :ForwardRequest, "rack/recursive"
-
1
autoload :Handler, "rack/handler"
-
1
autoload :Head, "rack/head"
-
1
autoload :Lint, "rack/lint"
-
1
autoload :Lock, "rack/lock"
-
1
autoload :Logger, "rack/logger"
-
1
autoload :MethodOverride, "rack/methodoverride"
-
1
autoload :Mime, "rack/mime"
-
1
autoload :NullLogger, "rack/nulllogger"
-
1
autoload :Recursive, "rack/recursive"
-
1
autoload :Reloader, "rack/reloader"
-
1
autoload :Runtime, "rack/runtime"
-
1
autoload :Sendfile, "rack/sendfile"
-
1
autoload :Server, "rack/server"
-
1
autoload :ShowExceptions, "rack/showexceptions"
-
1
autoload :ShowStatus, "rack/showstatus"
-
1
autoload :Static, "rack/static"
-
1
autoload :TempfileReaper, "rack/tempfile_reaper"
-
1
autoload :URLMap, "rack/urlmap"
-
1
autoload :Utils, "rack/utils"
-
1
autoload :Multipart, "rack/multipart"
-
-
1
autoload :MockRequest, "rack/mock"
-
1
autoload :MockResponse, "rack/mock"
-
-
1
autoload :Request, "rack/request"
-
1
autoload :Response, "rack/response"
-
-
1
module Auth
-
1
autoload :Basic, "rack/auth/basic"
-
1
autoload :AbstractRequest, "rack/auth/abstract/request"
-
1
autoload :AbstractHandler, "rack/auth/abstract/handler"
-
1
module Digest
-
1
autoload :MD5, "rack/auth/digest/md5"
-
1
autoload :Nonce, "rack/auth/digest/nonce"
-
1
autoload :Params, "rack/auth/digest/params"
-
1
autoload :Request, "rack/auth/digest/request"
-
end
-
end
-
-
1
module Session
-
1
autoload :Cookie, "rack/session/cookie"
-
1
autoload :Pool, "rack/session/pool"
-
1
autoload :Memcache, "rack/session/memcache"
-
end
-
-
1
module Utils
-
1
autoload :OkJson, "rack/utils/okjson"
-
end
-
end
-
1
module Rack
-
1
class BodyProxy
-
1
def initialize(body, &block)
-
451
@body, @block, @closed = body, block, false
-
end
-
-
1
def respond_to?(*args)
-
1221
return false if args.first.to_s =~ /^to_ary$/
-
1221
super or @body.respond_to?(*args)
-
end
-
-
1
def close
-
385
return if @closed
-
385
@closed = true
-
385
begin
-
385
@body.close if @body.respond_to? :close
-
ensure
-
385
@block.call
-
end
-
end
-
-
1
def closed?
-
@closed
-
end
-
-
# N.B. This method is a special case to address the bug described by #434.
-
# We are applying this special case for #each only. Future bugs of this
-
# class will be handled by requesting users to patch their ruby
-
# implementation, to save adding too many methods in this class.
-
1
def each(*args, &block)
-
385
@body.each(*args, &block)
-
end
-
-
1
def method_missing(*args, &block)
-
super if args.first.to_s =~ /^to_ary$/
-
@body.__send__(*args, &block)
-
end
-
end
-
end
-
1
module Rack
-
# Rack::Builder implements a small DSL to iteratively construct Rack
-
# applications.
-
#
-
# Example:
-
#
-
# require 'rack/lobster'
-
# app = Rack::Builder.new do
-
# use Rack::CommonLogger
-
# use Rack::ShowExceptions
-
# map "/lobster" do
-
# use Rack::Lint
-
# run Rack::Lobster.new
-
# end
-
# end
-
#
-
# run app
-
#
-
# Or
-
#
-
# app = Rack::Builder.app do
-
# use Rack::CommonLogger
-
# run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] }
-
# end
-
#
-
# run app
-
#
-
# +use+ adds middleware to the stack, +run+ dispatches to an application.
-
# You can use +map+ to construct a Rack::URLMap in a convenient way.
-
-
1
class Builder
-
1
def self.parse_file(config, opts = Server::Options.new)
-
options = {}
-
if config =~ /\.ru$/
-
cfgfile = ::File.read(config)
-
if cfgfile[/^#\\(.*)/] && opts
-
options = opts.parse! $1.split(/\s+/)
-
end
-
cfgfile.sub!(/^__END__\n.*\Z/m, '')
-
app = new_from_string cfgfile, config
-
else
-
require config
-
app = Object.const_get(::File.basename(config, '.rb').capitalize)
-
end
-
return app, options
-
end
-
-
1
def self.new_from_string(builder_script, file="(rackup)")
-
eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app",
-
TOPLEVEL_BINDING, file, 0
-
end
-
-
1
def initialize(default_app = nil,&block)
-
2
@use, @map, @run, @warmup = [], nil, default_app, nil
-
2
instance_eval(&block) if block_given?
-
end
-
-
1
def self.app(default_app = nil, &block)
-
self.new(default_app, &block).to_app
-
end
-
-
# Specifies middleware to use in a stack.
-
#
-
# class Middleware
-
# def initialize(app)
-
# @app = app
-
# end
-
#
-
# def call(env)
-
# env["rack.some_header"] = "setting an example"
-
# @app.call(env)
-
# end
-
# end
-
#
-
# use Middleware
-
# run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] }
-
#
-
# All requests through to this application will first be processed by the middleware class.
-
# The +call+ method in this example sets an additional environment key which then can be
-
# referenced in the application if required.
-
1
def use(middleware, *args, &block)
-
if @map
-
mapping, @map = @map, nil
-
@use << proc { |app| generate_map app, mapping }
-
end
-
@use << proc { |app| middleware.new(app, *args, &block) }
-
end
-
-
# Takes an argument that is an object that responds to #call and returns a Rack response.
-
# The simplest form of this is a lambda object:
-
#
-
# run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] }
-
#
-
# However this could also be a class:
-
#
-
# class Heartbeat
-
# def self.call(env)
-
# [200, { "Content-Type" => "text/plain" }, ["OK"]]
-
# end
-
# end
-
#
-
# run Heartbeat
-
1
def run(app)
-
1
@run = app
-
end
-
-
# Takes a lambda or block that is used to warm-up the application.
-
#
-
# warmup do |app|
-
# client = Rack::MockRequest.new(app)
-
# client.get('/')
-
# end
-
#
-
# use SomeMiddleware
-
# run MyApp
-
1
def warmup(prc=nil, &block)
-
@warmup = prc || block
-
end
-
-
# Creates a route within the application.
-
#
-
# Rack::Builder.app do
-
# map '/' do
-
# run Heartbeat
-
# end
-
# end
-
#
-
# The +use+ method can also be used here to specify middleware to run under a specific path:
-
#
-
# Rack::Builder.app do
-
# map '/' do
-
# use Middleware
-
# run Heartbeat
-
# end
-
# end
-
#
-
# This example includes a piece of middleware which will run before requests hit +Heartbeat+.
-
#
-
1
def map(path, &block)
-
1
@map ||= {}
-
1
@map[path] = block
-
end
-
-
1
def to_app
-
2
app = @map ? generate_map(@run, @map) : @run
-
2
fail "missing run or map statement" unless app
-
2
app = @use.reverse.inject(app) { |a,e| e[a] }
-
2
@warmup.call(app) if @warmup
-
2
app
-
end
-
-
1
def call(env)
-
to_app.call(env)
-
end
-
-
1
private
-
-
1
def generate_map(default_app, mapping)
-
1
mapped = default_app ? {'/' => default_app} : {}
-
2
mapping.each { |r,b| mapped[r] = self.class.new(default_app, &b).to_app }
-
1
URLMap.new(mapped)
-
end
-
end
-
end
-
1
require 'rack/utils'
-
-
1
module Rack
-
-
# Middleware that applies chunked transfer encoding to response bodies
-
# when the response does not include a Content-Length header.
-
1
class Chunked
-
1
include Rack::Utils
-
-
# A body wrapper that emits chunked responses
-
1
class Body
-
1
TERM = "\r\n"
-
1
TAIL = "0#{TERM}#{TERM}"
-
-
1
include Rack::Utils
-
-
1
def initialize(body)
-
@body = body
-
end
-
-
1
def each
-
term = TERM
-
@body.each do |chunk|
-
size = bytesize(chunk)
-
next if size == 0
-
-
chunk = chunk.dup.force_encoding(Encoding::BINARY) if chunk.respond_to?(:force_encoding)
-
yield [size.to_s(16), term, chunk, term].join
-
end
-
yield TAIL
-
end
-
-
1
def close
-
@body.close if @body.respond_to?(:close)
-
end
-
end
-
-
1
def initialize(app)
-
@app = app
-
end
-
-
# pre-HTTP/1.0 (informally "HTTP/0.9") HTTP requests did not have
-
# a version (nor response headers)
-
1
def chunkable_version?(ver)
-
case ver
-
when "HTTP/1.0", nil, "HTTP/0.9"
-
false
-
else
-
true
-
end
-
end
-
-
1
def call(env)
-
status, headers, body = @app.call(env)
-
headers = HeaderHash.new(headers)
-
-
if ! chunkable_version?(env['HTTP_VERSION']) ||
-
STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
-
headers[CONTENT_LENGTH] ||
-
headers['Transfer-Encoding']
-
[status, headers, body]
-
else
-
headers.delete(CONTENT_LENGTH)
-
headers['Transfer-Encoding'] = 'chunked'
-
[status, headers, Body.new(body)]
-
end
-
end
-
end
-
end
-
1
require 'rack/utils'
-
-
1
module Rack
-
-
# Middleware that enables conditional GET using If-None-Match and
-
# If-Modified-Since. The application should set either or both of the
-
# Last-Modified or Etag response headers according to RFC 2616. When
-
# either of the conditions is met, the response body is set to be zero
-
# length and the response status is set to 304 Not Modified.
-
#
-
# Applications that defer response body generation until the body's each
-
# message is received will avoid response body generation completely when
-
# a conditional GET matches.
-
#
-
# Adapted from Michael Klishin's Merb implementation:
-
# https://github.com/wycats/merb/blob/master/merb-core/lib/merb-core/rack/middleware/conditional_get.rb
-
1
class ConditionalGet
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
66
case env[REQUEST_METHOD]
-
when "GET", "HEAD"
-
55
status, headers, body = @app.call(env)
-
55
headers = Utils::HeaderHash.new(headers)
-
55
if status == 200 && fresh?(env, headers)
-
status = 304
-
headers.delete(CONTENT_TYPE)
-
headers.delete(CONTENT_LENGTH)
-
original_body = body
-
body = Rack::BodyProxy.new([]) do
-
original_body.close if original_body.respond_to?(:close)
-
end
-
end
-
55
[status, headers, body]
-
else
-
11
@app.call(env)
-
end
-
end
-
-
1
private
-
-
1
def fresh?(env, headers)
-
55
modified_since = env['HTTP_IF_MODIFIED_SINCE']
-
55
none_match = env['HTTP_IF_NONE_MATCH']
-
-
55
return false unless modified_since || none_match
-
-
success = true
-
success &&= modified_since?(to_rfc2822(modified_since), headers) if modified_since
-
success &&= etag_matches?(none_match, headers) if none_match
-
success
-
end
-
-
1
def etag_matches?(none_match, headers)
-
etag = headers['ETag'] and etag == none_match
-
end
-
-
1
def modified_since?(modified_since, headers)
-
last_modified = to_rfc2822(headers['Last-Modified']) and
-
modified_since and
-
modified_since >= last_modified
-
end
-
-
1
def to_rfc2822(since)
-
# shortest possible valid date is the obsolete: 1 Nov 97 09:55 A
-
# anything shorter is invalid, this avoids exceptions for common cases
-
# most common being the empty string
-
if since && since.length >= 16
-
# NOTE: there is no trivial way to write this in a non execption way
-
# _rfc2822 returns a hash but is not that usable
-
Time.rfc2822(since) rescue nil
-
else
-
nil
-
end
-
end
-
end
-
end
-
1
require 'digest/md5'
-
-
1
module Rack
-
# Automatically sets the ETag header on all String bodies.
-
#
-
# The ETag header is skipped if ETag or Last-Modified headers are sent or if
-
# a sendfile body (body.responds_to :to_path) is given (since such cases
-
# should be handled by apache/nginx).
-
#
-
# On initialization, you can pass two parameters: a Cache-Control directive
-
# used when Etag is absent and a directive when it is present. The first
-
# defaults to nil, while the second defaults to "max-age=0, private, must-revalidate"
-
1
class ETag
-
1
ETAG_STRING = 'ETag'.freeze
-
1
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze
-
-
1
def initialize(app, no_cache_control = nil, cache_control = DEFAULT_CACHE_CONTROL)
-
1
@app = app
-
1
@cache_control = cache_control
-
1
@no_cache_control = no_cache_control
-
end
-
-
1
def call(env)
-
66
status, headers, body = @app.call(env)
-
-
66
if etag_status?(status) && etag_body?(body) && !skip_caching?(headers)
-
55
original_body = body
-
55
digest, new_body = digest_body(body)
-
55
body = Rack::BodyProxy.new(new_body) do
-
55
original_body.close if original_body.respond_to?(:close)
-
end
-
55
headers[ETAG_STRING] = %(W/"#{digest}") if digest
-
end
-
-
66
unless headers[CACHE_CONTROL]
-
66
if digest
-
55
headers[CACHE_CONTROL] = @cache_control if @cache_control
-
else
-
11
headers[CACHE_CONTROL] = @no_cache_control if @no_cache_control
-
end
-
end
-
-
66
[status, headers, body]
-
end
-
-
1
private
-
-
1
def etag_status?(status)
-
66
status == 200 || status == 201
-
end
-
-
1
def etag_body?(body)
-
55
!body.respond_to?(:to_path)
-
end
-
-
1
def skip_caching?(headers)
-
55
(headers[CACHE_CONTROL] && headers[CACHE_CONTROL].include?('no-cache')) ||
-
55
headers.key?(ETAG_STRING) || headers.key?('Last-Modified')
-
end
-
-
1
def digest_body(body)
-
55
parts = []
-
55
digest = nil
-
-
55
body.each do |part|
-
55
parts << part
-
55
(digest ||= Digest::MD5.new) << part unless part.empty?
-
end
-
-
55
[digest && digest.hexdigest, parts]
-
end
-
end
-
end
-
1
require 'time'
-
1
require 'rack/utils'
-
1
require 'rack/mime'
-
-
1
module Rack
-
# Rack::File serves files below the +root+ directory given, according to the
-
# path info of the Rack request.
-
# e.g. when Rack::File.new("/etc") is used, you can access 'passwd' file
-
# as http://localhost:9292/passwd
-
#
-
# Handlers can detect if bodies are a Rack::File, and use mechanisms
-
# like sendfile on the +path+.
-
-
1
class File
-
1
ALLOWED_VERBS = %w[GET HEAD OPTIONS]
-
1
ALLOW_HEADER = ALLOWED_VERBS.join(', ')
-
-
1
attr_accessor :root
-
1
attr_accessor :path
-
1
attr_accessor :cache_control
-
-
1
alias :to_path :path
-
-
1
def initialize(root, headers={}, default_mime = 'text/plain')
-
1
@root = root
-
1
@headers = headers
-
1
@default_mime = default_mime
-
end
-
-
1
def call(env)
-
dup._call(env)
-
end
-
-
1
F = ::File
-
-
1
def _call(env)
-
unless ALLOWED_VERBS.include? env[REQUEST_METHOD]
-
return fail(405, "Method Not Allowed", {'Allow' => ALLOW_HEADER})
-
end
-
-
path_info = Utils.unescape(env[PATH_INFO])
-
clean_path_info = Utils.clean_path_info(path_info)
-
-
@path = F.join(@root, clean_path_info)
-
-
available = begin
-
F.file?(@path) && F.readable?(@path)
-
rescue SystemCallError
-
false
-
end
-
-
if available
-
serving(env)
-
else
-
fail(404, "File not found: #{path_info}")
-
end
-
end
-
-
1
def serving(env)
-
if env["REQUEST_METHOD"] == "OPTIONS"
-
return [200, {'Allow' => ALLOW_HEADER, CONTENT_LENGTH => '0'}, []]
-
end
-
last_modified = F.mtime(@path).httpdate
-
return [304, {}, []] if env['HTTP_IF_MODIFIED_SINCE'] == last_modified
-
-
headers = { "Last-Modified" => last_modified }
-
headers[CONTENT_TYPE] = mime_type if mime_type
-
-
# Set custom headers
-
@headers.each { |field, content| headers[field] = content } if @headers
-
-
response = [ 200, headers, env[REQUEST_METHOD] == "HEAD" ? [] : self ]
-
-
size = filesize
-
-
ranges = Rack::Utils.byte_ranges(env, size)
-
if ranges.nil? || ranges.length > 1
-
# No ranges, or multiple ranges (which we don't support):
-
# TODO: Support multiple byte-ranges
-
response[0] = 200
-
@range = 0..size-1
-
elsif ranges.empty?
-
# Unsatisfiable. Return error, and file size:
-
response = fail(416, "Byte range unsatisfiable")
-
response[1]["Content-Range"] = "bytes */#{size}"
-
return response
-
else
-
# Partial content:
-
@range = ranges[0]
-
response[0] = 206
-
response[1]["Content-Range"] = "bytes #{@range.begin}-#{@range.end}/#{size}"
-
size = @range.end - @range.begin + 1
-
end
-
-
response[2] = [response_body] unless response_body.nil?
-
-
response[1][CONTENT_LENGTH] = size.to_s
-
response
-
end
-
-
1
def each
-
F.open(@path, "rb") do |file|
-
file.seek(@range.begin)
-
remaining_len = @range.end-@range.begin+1
-
while remaining_len > 0
-
part = file.read([8192, remaining_len].min)
-
break unless part
-
remaining_len -= part.length
-
-
yield part
-
end
-
end
-
end
-
-
1
private
-
-
1
def fail(status, body, headers = {})
-
body += "\n"
-
[
-
status,
-
{
-
CONTENT_TYPE => "text/plain",
-
CONTENT_LENGTH => body.size.to_s,
-
"X-Cascade" => "pass"
-
}.merge!(headers),
-
[body]
-
]
-
end
-
-
# The MIME type for the contents of the file located at @path
-
1
def mime_type
-
Mime.mime_type(F.extname(@path), @default_mime)
-
end
-
-
1
def filesize
-
# If response_body is present, use its size.
-
return Rack::Utils.bytesize(response_body) if response_body
-
-
# We check via File::size? whether this file provides size info
-
# via stat (e.g. /proc files often don't), otherwise we have to
-
# figure it out by reading the whole file into memory.
-
F.size?(@path) || Utils.bytesize(F.read(@path))
-
end
-
-
# By default, the response body for file requests is nil.
-
# In this case, the response body will be generated later
-
# from the file at @path
-
1
def response_body
-
nil
-
end
-
end
-
end
-
1
require 'rack/body_proxy'
-
-
1
module Rack
-
-
1
class Head
-
# Rack::Head returns an empty body for all HEAD requests. It leaves
-
# all other requests unchanged.
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
66
status, headers, body = @app.call(env)
-
-
66
if env[REQUEST_METHOD] == HEAD
-
[
-
status, headers, Rack::BodyProxy.new([]) do
-
body.close if body.respond_to? :close
-
end
-
]
-
else
-
66
[status, headers, body]
-
end
-
end
-
end
-
-
end
-
1
require 'rack/utils'
-
1
require 'forwardable'
-
-
1
module Rack
-
# Rack::Lint validates your application and the requests and
-
# responses according to the Rack spec.
-
-
1
class Lint
-
1
def initialize(app)
-
@app = app
-
@content_length = nil
-
end
-
-
# :stopdoc:
-
-
1
class LintError < RuntimeError; end
-
1
module Assertion
-
1
def assert(message, &block)
-
unless block.call
-
raise LintError, message
-
end
-
end
-
end
-
1
include Assertion
-
-
## This specification aims to formalize the Rack protocol. You
-
## can (and should) use Rack::Lint to enforce it.
-
##
-
## When you develop middleware, be sure to add a Lint before and
-
## after to catch all mistakes.
-
-
## = Rack applications
-
-
## A Rack application is a Ruby object (not a class) that
-
## responds to +call+.
-
1
def call(env=nil)
-
dup._call(env)
-
end
-
-
1
def _call(env)
-
## It takes exactly one argument, the *environment*
-
assert("No env given") { env }
-
check_env env
-
-
env['rack.input'] = InputWrapper.new(env['rack.input'])
-
env['rack.errors'] = ErrorWrapper.new(env['rack.errors'])
-
-
## and returns an Array of exactly three values:
-
status, headers, @body = @app.call(env)
-
## The *status*,
-
check_status status
-
## the *headers*,
-
check_headers headers
-
-
check_hijack_response headers, env
-
-
## and the *body*.
-
check_content_type status, headers
-
check_content_length status, headers
-
@head_request = env[REQUEST_METHOD] == "HEAD"
-
[status, headers, self]
-
end
-
-
## == The Environment
-
1
def check_env(env)
-
## The environment must be an instance of Hash that includes
-
## CGI-like headers. The application is free to modify the
-
## environment.
-
assert("env #{env.inspect} is not a Hash, but #{env.class}") {
-
env.kind_of? Hash
-
}
-
-
##
-
## The environment is required to include these variables
-
## (adopted from PEP333), except when they'd be empty, but see
-
## below.
-
-
## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
-
## "GET" or "POST". This cannot ever
-
## be an empty string, and so is
-
## always required.
-
-
## <tt>SCRIPT_NAME</tt>:: The initial portion of the request
-
## URL's "path" that corresponds to the
-
## application object, so that the
-
## application knows its virtual
-
## "location". This may be an empty
-
## string, if the application corresponds
-
## to the "root" of the server.
-
-
## <tt>PATH_INFO</tt>:: The remainder of the request URL's
-
## "path", designating the virtual
-
## "location" of the request's target
-
## within the application. This may be an
-
## empty string, if the request URL targets
-
## the application root and does not have a
-
## trailing slash. This value may be
-
## percent-encoded when I originating from
-
## a URL.
-
-
## <tt>QUERY_STRING</tt>:: The portion of the request URL that
-
## follows the <tt>?</tt>, if any. May be
-
## empty, but is always required!
-
-
## <tt>SERVER_NAME</tt>, <tt>SERVER_PORT</tt>::
-
## When combined with <tt>SCRIPT_NAME</tt> and
-
## <tt>PATH_INFO</tt>, these variables can be
-
## used to complete the URL. Note, however,
-
## that <tt>HTTP_HOST</tt>, if present,
-
## should be used in preference to
-
## <tt>SERVER_NAME</tt> for reconstructing
-
## the request URL.
-
## <tt>SERVER_NAME</tt> and <tt>SERVER_PORT</tt>
-
## can never be empty strings, and so
-
## are always required.
-
-
## <tt>HTTP_</tt> Variables:: Variables corresponding to the
-
## client-supplied HTTP request
-
## headers (i.e., variables whose
-
## names begin with <tt>HTTP_</tt>). The
-
## presence or absence of these
-
## variables should correspond with
-
## the presence or absence of the
-
## appropriate HTTP header in the
-
## request. See
-
## <a href="https://tools.ietf.org/html/rfc3875#section-4.1.18">
-
## RFC3875 section 4.1.18</a> for
-
## specific behavior.
-
-
## In addition to this, the Rack environment must include these
-
## Rack-specific variables:
-
-
## <tt>rack.version</tt>:: The Array representing this version of Rack
-
## See Rack::VERSION, that corresponds to
-
## the version of this SPEC.
-
-
## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the
-
## request URL.
-
-
## <tt>rack.input</tt>:: See below, the input stream.
-
-
## <tt>rack.errors</tt>:: See below, the error stream.
-
-
## <tt>rack.multithread</tt>:: true if the application object may be
-
## simultaneously invoked by another thread
-
## in the same process, false otherwise.
-
-
## <tt>rack.multiprocess</tt>:: true if an equivalent application object
-
## may be simultaneously invoked by another
-
## process, false otherwise.
-
-
## <tt>rack.run_once</tt>:: true if the server expects
-
## (but does not guarantee!) that the
-
## application will only be invoked this one
-
## time during the life of its containing
-
## process. Normally, this will only be true
-
## for a server based on CGI
-
## (or something similar).
-
-
## <tt>rack.hijack?</tt>:: present and true if the server supports
-
## connection hijacking. See below, hijacking.
-
-
## <tt>rack.hijack</tt>:: an object responding to #call that must be
-
## called at least once before using
-
## rack.hijack_io.
-
## It is recommended #call return rack.hijack_io
-
## as well as setting it in env if necessary.
-
-
## <tt>rack.hijack_io</tt>:: if rack.hijack? is true, and rack.hijack
-
## has received #call, this will contain
-
## an object resembling an IO. See hijacking.
-
-
## Additional environment specifications have approved to
-
## standardized middleware APIs. None of these are required to
-
## be implemented by the server.
-
-
## <tt>rack.session</tt>:: A hash like interface for storing
-
## request session data.
-
## The store must implement:
-
if session = env['rack.session']
-
## store(key, value) (aliased as []=);
-
assert("session #{session.inspect} must respond to store and []=") {
-
session.respond_to?(:store) && session.respond_to?(:[]=)
-
}
-
-
## fetch(key, default = nil) (aliased as []);
-
assert("session #{session.inspect} must respond to fetch and []") {
-
session.respond_to?(:fetch) && session.respond_to?(:[])
-
}
-
-
## delete(key);
-
assert("session #{session.inspect} must respond to delete") {
-
session.respond_to?(:delete)
-
}
-
-
## clear;
-
assert("session #{session.inspect} must respond to clear") {
-
session.respond_to?(:clear)
-
}
-
end
-
-
## <tt>rack.logger</tt>:: A common object interface for logging messages.
-
## The object must implement:
-
if logger = env['rack.logger']
-
## info(message, &block)
-
assert("logger #{logger.inspect} must respond to info") {
-
logger.respond_to?(:info)
-
}
-
-
## debug(message, &block)
-
assert("logger #{logger.inspect} must respond to debug") {
-
logger.respond_to?(:debug)
-
}
-
-
## warn(message, &block)
-
assert("logger #{logger.inspect} must respond to warn") {
-
logger.respond_to?(:warn)
-
}
-
-
## error(message, &block)
-
assert("logger #{logger.inspect} must respond to error") {
-
logger.respond_to?(:error)
-
}
-
-
## fatal(message, &block)
-
assert("logger #{logger.inspect} must respond to fatal") {
-
logger.respond_to?(:fatal)
-
}
-
end
-
-
## <tt>rack.multipart.buffer_size</tt>:: An Integer hint to the multipart parser as to what chunk size to use for reads and writes.
-
if bufsize = env['rack.multipart.buffer_size']
-
assert("rack.multipart.buffer_size must be an Integer > 0 if specified") {
-
bufsize.is_a?(Integer) && bufsize > 0
-
}
-
end
-
-
## <tt>rack.multipart.tempfile_factory</tt>:: An object responding to #call with two arguments, the filename and content_type given for the multipart form field, and returning an IO-like object that responds to #<< and optionally #rewind. This factory will be used to instantiate the tempfile for each multipart form file upload field, rather than the default class of Tempfile.
-
if tempfile_factory = env['rack.multipart.tempfile_factory']
-
assert("rack.multipart.tempfile_factory must respond to #call") { tempfile_factory.respond_to?(:call) }
-
env['rack.multipart.tempfile_factory'] = lambda do |filename, content_type|
-
io = tempfile_factory.call(filename, content_type)
-
assert("rack.multipart.tempfile_factory return value must respond to #<<") { io.respond_to?(:<<) }
-
io
-
end
-
end
-
-
## The server or the application can store their own data in the
-
## environment, too. The keys must contain at least one dot,
-
## and should be prefixed uniquely. The prefix <tt>rack.</tt>
-
## is reserved for use with the Rack core distribution and other
-
## accepted specifications and must not be used otherwise.
-
##
-
-
%w[REQUEST_METHOD SERVER_NAME SERVER_PORT
-
QUERY_STRING
-
rack.version rack.input rack.errors
-
rack.multithread rack.multiprocess rack.run_once].each { |header|
-
assert("env missing required key #{header}") { env.include? header }
-
}
-
-
## The environment must not contain the keys
-
## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
-
## (use the versions without <tt>HTTP_</tt>).
-
%w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
-
assert("env contains #{header}, must use #{header[5,-1]}") {
-
not env.include? header
-
}
-
}
-
-
## The CGI keys (named without a period) must have String values.
-
env.each { |key, value|
-
next if key.include? "." # Skip extensions
-
assert("env variable #{key} has non-string value #{value.inspect}") {
-
value.kind_of? String
-
}
-
}
-
-
## There are the following restrictions:
-
-
## * <tt>rack.version</tt> must be an array of Integers.
-
assert("rack.version must be an Array, was #{env["rack.version"].class}") {
-
env["rack.version"].kind_of? Array
-
}
-
## * <tt>rack.url_scheme</tt> must either be +http+ or +https+.
-
assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") {
-
%w[http https].include? env["rack.url_scheme"]
-
}
-
-
## * There must be a valid input stream in <tt>rack.input</tt>.
-
check_input env["rack.input"]
-
## * There must be a valid error stream in <tt>rack.errors</tt>.
-
check_error env["rack.errors"]
-
## * There may be a valid hijack stream in <tt>rack.hijack_io</tt>
-
check_hijack env
-
-
## * The <tt>REQUEST_METHOD</tt> must be a valid token.
-
assert("REQUEST_METHOD unknown: #{env[REQUEST_METHOD]}") {
-
env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
-
}
-
-
## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
-
assert("SCRIPT_NAME must start with /") {
-
!env.include?("SCRIPT_NAME") ||
-
env["SCRIPT_NAME"] == "" ||
-
env["SCRIPT_NAME"] =~ /\A\//
-
}
-
## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
-
assert("PATH_INFO must start with /") {
-
!env.include?("PATH_INFO") ||
-
env["PATH_INFO"] == "" ||
-
env["PATH_INFO"] =~ /\A\//
-
}
-
## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
-
assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") {
-
!env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/
-
}
-
-
## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
-
## set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
-
## <tt>SCRIPT_NAME</tt> is empty.
-
assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
-
env["SCRIPT_NAME"] || env["PATH_INFO"]
-
}
-
## <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
-
assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
-
env["SCRIPT_NAME"] != "/"
-
}
-
end
-
-
## === The Input Stream
-
##
-
## The input stream is an IO-like object which contains the raw HTTP
-
## POST data.
-
1
def check_input(input)
-
## When applicable, its external encoding must be "ASCII-8BIT" and it
-
## must be opened in binary mode, for Ruby 1.9 compatibility.
-
assert("rack.input #{input} does not have ASCII-8BIT as its external encoding") {
-
input.external_encoding.name == "ASCII-8BIT"
-
} if input.respond_to?(:external_encoding)
-
assert("rack.input #{input} is not opened in binary mode") {
-
input.binmode?
-
} if input.respond_to?(:binmode?)
-
-
## The input stream must respond to +gets+, +each+, +read+ and +rewind+.
-
[:gets, :each, :read, :rewind].each { |method|
-
assert("rack.input #{input} does not respond to ##{method}") {
-
input.respond_to? method
-
}
-
}
-
end
-
-
1
class InputWrapper
-
1
include Assertion
-
-
1
def initialize(input)
-
@input = input
-
end
-
-
## * +gets+ must be called without arguments and return a string,
-
## or +nil+ on EOF.
-
1
def gets(*args)
-
assert("rack.input#gets called with arguments") { args.size == 0 }
-
v = @input.gets
-
assert("rack.input#gets didn't return a String") {
-
v.nil? or v.kind_of? String
-
}
-
v
-
end
-
-
## * +read+ behaves like IO#read.
-
## Its signature is <tt>read([length, [buffer]])</tt>.
-
##
-
## If given, +length+ must be a non-negative Integer (>= 0) or +nil+,
-
## and +buffer+ must be a String and may not be nil.
-
##
-
## If +length+ is given and not nil, then this method reads at most
-
## +length+ bytes from the input stream.
-
##
-
## If +length+ is not given or nil, then this method reads
-
## all data until EOF.
-
##
-
## When EOF is reached, this method returns nil if +length+ is given
-
## and not nil, or "" if +length+ is not given or is nil.
-
##
-
## If +buffer+ is given, then the read data will be placed
-
## into +buffer+ instead of a newly created String object.
-
1
def read(*args)
-
assert("rack.input#read called with too many arguments") {
-
args.size <= 2
-
}
-
if args.size >= 1
-
assert("rack.input#read called with non-integer and non-nil length") {
-
args.first.kind_of?(Integer) || args.first.nil?
-
}
-
assert("rack.input#read called with a negative length") {
-
args.first.nil? || args.first >= 0
-
}
-
end
-
if args.size >= 2
-
assert("rack.input#read called with non-String buffer") {
-
args[1].kind_of?(String)
-
}
-
end
-
-
v = @input.read(*args)
-
-
assert("rack.input#read didn't return nil or a String") {
-
v.nil? or v.kind_of? String
-
}
-
if args[0].nil?
-
assert("rack.input#read(nil) returned nil on EOF") {
-
!v.nil?
-
}
-
end
-
-
v
-
end
-
-
## * +each+ must be called without arguments and only yield Strings.
-
1
def each(*args)
-
assert("rack.input#each called with arguments") { args.size == 0 }
-
@input.each { |line|
-
assert("rack.input#each didn't yield a String") {
-
line.kind_of? String
-
}
-
yield line
-
}
-
end
-
-
## * +rewind+ must be called without arguments. It rewinds the input
-
## stream back to the beginning. It must not raise Errno::ESPIPE:
-
## that is, it may not be a pipe or a socket. Therefore, handler
-
## developers must buffer the input data into some rewindable object
-
## if the underlying input stream is not rewindable.
-
1
def rewind(*args)
-
assert("rack.input#rewind called with arguments") { args.size == 0 }
-
assert("rack.input#rewind raised Errno::ESPIPE") {
-
begin
-
@input.rewind
-
true
-
rescue Errno::ESPIPE
-
false
-
end
-
}
-
end
-
-
## * +close+ must never be called on the input stream.
-
1
def close(*args)
-
assert("rack.input#close must not be called") { false }
-
end
-
end
-
-
## === The Error Stream
-
1
def check_error(error)
-
## The error stream must respond to +puts+, +write+ and +flush+.
-
[:puts, :write, :flush].each { |method|
-
assert("rack.error #{error} does not respond to ##{method}") {
-
error.respond_to? method
-
}
-
}
-
end
-
-
1
class ErrorWrapper
-
1
include Assertion
-
-
1
def initialize(error)
-
@error = error
-
end
-
-
## * +puts+ must be called with a single argument that responds to +to_s+.
-
1
def puts(str)
-
@error.puts str
-
end
-
-
## * +write+ must be called with a single argument that is a String.
-
1
def write(str)
-
assert("rack.errors#write not called with a String") { str.kind_of? String }
-
@error.write str
-
end
-
-
## * +flush+ must be called without arguments and must be called
-
## in order to make the error appear for sure.
-
1
def flush
-
@error.flush
-
end
-
-
## * +close+ must never be called on the error stream.
-
1
def close(*args)
-
assert("rack.errors#close must not be called") { false }
-
end
-
end
-
-
1
class HijackWrapper
-
1
include Assertion
-
1
extend Forwardable
-
-
1
REQUIRED_METHODS = [
-
:read, :write, :read_nonblock, :write_nonblock, :flush, :close,
-
:close_read, :close_write, :closed?
-
]
-
-
1
def_delegators :@io, *REQUIRED_METHODS
-
-
1
def initialize(io)
-
@io = io
-
REQUIRED_METHODS.each do |meth|
-
assert("rack.hijack_io must respond to #{meth}") { io.respond_to? meth }
-
end
-
end
-
end
-
-
## === Hijacking
-
#
-
# AUTHORS: n.b. The trailing whitespace between paragraphs is important and
-
# should not be removed. The whitespace creates paragraphs in the RDoc
-
# output.
-
#
-
## ==== Request (before status)
-
1
def check_hijack(env)
-
if env['rack.hijack?']
-
## If rack.hijack? is true then rack.hijack must respond to #call.
-
original_hijack = env['rack.hijack']
-
assert("rack.hijack must respond to call") { original_hijack.respond_to?(:call) }
-
env['rack.hijack'] = proc do
-
## rack.hijack must return the io that will also be assigned (or is
-
## already present, in rack.hijack_io.
-
io = original_hijack.call
-
HijackWrapper.new(io)
-
##
-
## rack.hijack_io must respond to:
-
## <tt>read, write, read_nonblock, write_nonblock, flush, close,
-
## close_read, close_write, closed?</tt>
-
##
-
## The semantics of these IO methods must be a best effort match to
-
## those of a normal ruby IO or Socket object, using standard
-
## arguments and raising standard exceptions. Servers are encouraged
-
## to simply pass on real IO objects, although it is recognized that
-
## this approach is not directly compatible with SPDY and HTTP 2.0.
-
##
-
## IO provided in rack.hijack_io should preference the
-
## IO::WaitReadable and IO::WaitWritable APIs wherever supported.
-
##
-
## There is a deliberate lack of full specification around
-
## rack.hijack_io, as semantics will change from server to server.
-
## Users are encouraged to utilize this API with a knowledge of their
-
## server choice, and servers may extend the functionality of
-
## hijack_io to provide additional features to users. The purpose of
-
## rack.hijack is for Rack to "get out of the way", as such, Rack only
-
## provides the minimum of specification and support.
-
env['rack.hijack_io'] = HijackWrapper.new(env['rack.hijack_io'])
-
io
-
end
-
else
-
##
-
## If rack.hijack? is false, then rack.hijack should not be set.
-
assert("rack.hijack? is false, but rack.hijack is present") { env['rack.hijack'].nil? }
-
##
-
## If rack.hijack? is false, then rack.hijack_io should not be set.
-
assert("rack.hijack? is false, but rack.hijack_io is present") { env['rack.hijack_io'].nil? }
-
end
-
end
-
-
## ==== Response (after headers)
-
## It is also possible to hijack a response after the status and headers
-
## have been sent.
-
1
def check_hijack_response(headers, env)
-
-
# this check uses headers like a hash, but the spec only requires
-
# headers respond to #each
-
headers = Rack::Utils::HeaderHash.new(headers)
-
-
## In order to do this, an application may set the special header
-
## <tt>rack.hijack</tt> to an object that responds to <tt>call</tt>
-
## accepting an argument that conforms to the <tt>rack.hijack_io</tt>
-
## protocol.
-
##
-
## After the headers have been sent, and this hijack callback has been
-
## called, the application is now responsible for the remaining lifecycle
-
## of the IO. The application is also responsible for maintaining HTTP
-
## semantics. Of specific note, in almost all cases in the current SPEC,
-
## applications will have wanted to specify the header Connection:close in
-
## HTTP/1.1, and not Connection:keep-alive, as there is no protocol for
-
## returning hijacked sockets to the web server. For that purpose, use the
-
## body streaming API instead (progressively yielding strings via each).
-
##
-
## Servers must ignore the <tt>body</tt> part of the response tuple when
-
## the <tt>rack.hijack</tt> response API is in use.
-
-
if env['rack.hijack?'] && headers['rack.hijack']
-
assert('rack.hijack header must respond to #call') {
-
headers['rack.hijack'].respond_to? :call
-
}
-
original_hijack = headers['rack.hijack']
-
headers['rack.hijack'] = proc do |io|
-
original_hijack.call HijackWrapper.new(io)
-
end
-
else
-
##
-
## The special response header <tt>rack.hijack</tt> must only be set
-
## if the request env has <tt>rack.hijack?</tt> <tt>true</tt>.
-
assert('rack.hijack header must not be present if server does not support hijacking') {
-
headers['rack.hijack'].nil?
-
}
-
end
-
end
-
## ==== Conventions
-
## * Middleware should not use hijack unless it is handling the whole
-
## response.
-
## * Middleware may wrap the IO object for the response pattern.
-
## * Middleware should not wrap the IO object for the request pattern. The
-
## request pattern is intended to provide the hijacker with "raw tcp".
-
-
## == The Response
-
-
## === The Status
-
1
def check_status(status)
-
## This is an HTTP status. When parsed as integer (+to_i+), it must be
-
## greater than or equal to 100.
-
assert("Status must be >=100 seen as integer") { status.to_i >= 100 }
-
end
-
-
## === The Headers
-
1
def check_headers(header)
-
## The header must respond to +each+, and yield values of key and value.
-
assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
-
header.respond_to? :each
-
}
-
header.each { |key, value|
-
## Special headers starting "rack." are for communicating with the
-
## server, and must not be sent back to the client.
-
next if key =~ /^rack\..+$/
-
-
## The header keys must be Strings.
-
assert("header key must be a string, was #{key.class}") {
-
key.kind_of? String
-
}
-
## The header must not contain a +Status+ key.
-
assert("header must not contain Status") { key.downcase != "status" }
-
## The header must conform to RFC7230 token specification, i.e. cannot
-
## contain non-printable ASCII, DQUOTE or "(),/:;<=>?@[\]{}".
-
assert("invalid header name: #{key}") { key !~ /[\(\),\/:;<=>\?@\[\\\]{}[:cntrl:]]/ }
-
-
## The values of the header must be Strings,
-
assert("a header value must be a String, but the value of " +
-
"'#{key}' is a #{value.class}") { value.kind_of? String }
-
## consisting of lines (for multiple header values, e.g. multiple
-
## <tt>Set-Cookie</tt> values) separated by "\\n".
-
value.split("\n").each { |item|
-
## The lines must not contain characters below 037.
-
assert("invalid header value #{key}: #{item.inspect}") {
-
item !~ /[\000-\037]/
-
}
-
}
-
}
-
end
-
-
## === The Content-Type
-
1
def check_content_type(status, headers)
-
headers.each { |key, value|
-
## There must not be a <tt>Content-Type</tt>, when the +Status+ is 1xx,
-
## 204, 205 or 304.
-
if key.downcase == "content-type"
-
assert("Content-Type header found in #{status} response, not allowed") {
-
not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
-
}
-
return
-
end
-
}
-
end
-
-
## === The Content-Length
-
1
def check_content_length(status, headers)
-
headers.each { |key, value|
-
if key.downcase == 'content-length'
-
## There must not be a <tt>Content-Length</tt> header when the
-
## +Status+ is 1xx, 204, 205 or 304.
-
assert("Content-Length header found in #{status} response, not allowed") {
-
not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
-
}
-
@content_length = value
-
end
-
}
-
end
-
-
1
def verify_content_length(bytes)
-
if @head_request
-
assert("Response body was given for HEAD request, but should be empty") {
-
bytes == 0
-
}
-
elsif @content_length
-
assert("Content-Length header was #{@content_length}, but should be #{bytes}") {
-
@content_length == bytes.to_s
-
}
-
end
-
end
-
-
## === The Body
-
1
def each
-
@closed = false
-
bytes = 0
-
-
## The Body must respond to +each+
-
assert("Response body must respond to each") do
-
@body.respond_to?(:each)
-
end
-
-
@body.each { |part|
-
## and must only yield String values.
-
assert("Body yielded non-string value #{part.inspect}") {
-
part.kind_of? String
-
}
-
bytes += Rack::Utils.bytesize(part)
-
yield part
-
}
-
verify_content_length(bytes)
-
-
##
-
## The Body itself should not be an instance of String, as this will
-
## break in Ruby 1.9.
-
##
-
## If the Body responds to +close+, it will be called after iteration. If
-
## the body is replaced by a middleware after action, the original body
-
## must be closed first, if it responds to close.
-
# XXX howto: assert("Body has not been closed") { @closed }
-
-
-
##
-
## If the Body responds to +to_path+, it must return a String
-
## identifying the location of a file whose contents are identical
-
## to that produced by calling +each+; this may be used by the
-
## server as an alternative, possibly more efficient way to
-
## transport the response.
-
-
if @body.respond_to?(:to_path)
-
assert("The file identified by body.to_path does not exist") {
-
::File.exist? @body.to_path
-
}
-
end
-
-
##
-
## The Body commonly is an Array of Strings, the application
-
## instance itself, or a File-like object.
-
end
-
-
1
def close
-
@closed = true
-
@body.close if @body.respond_to?(:close)
-
end
-
-
# :startdoc:
-
-
end
-
end
-
-
## == Thanks
-
## Some parts of this specification are adopted from PEP333: Python
-
## Web Server Gateway Interface
-
## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
-
## everyone involved in that effort.
-
1
require 'thread'
-
1
require 'rack/body_proxy'
-
-
1
module Rack
-
# Rack::Lock locks every request inside a mutex, so that every request
-
# will effectively be executed synchronously.
-
1
class Lock
-
1
FLAG = 'rack.multithread'.freeze
-
-
1
def initialize(app, mutex = Mutex.new)
-
1
@app, @mutex = app, mutex
-
end
-
-
1
def call(env)
-
66
old, env[FLAG] = env[FLAG], false
-
66
@mutex.lock
-
66
response = @app.call(env)
-
132
body = BodyProxy.new(response[2]) { @mutex.unlock }
-
66
response[2] = body
-
66
response
-
ensure
-
66
@mutex.unlock unless body
-
66
env[FLAG] = old
-
end
-
end
-
end
-
1
module Rack
-
1
class MethodOverride
-
1
HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS PATCH LINK UNLINK)
-
-
1
METHOD_OVERRIDE_PARAM_KEY = "_method".freeze
-
1
HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze
-
1
ALLOWED_METHODS = ["POST"]
-
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
66
if allowed_methods.include?(env[REQUEST_METHOD])
-
11
method = method_override(env)
-
11
if HTTP_METHODS.include?(method)
-
7
env["rack.methodoverride.original_method"] = env[REQUEST_METHOD]
-
7
env[REQUEST_METHOD] = method
-
end
-
end
-
-
66
@app.call(env)
-
end
-
-
1
def method_override(env)
-
11
req = Request.new(env)
-
11
method = method_override_param(req) ||
-
env[HTTP_METHOD_OVERRIDE_HEADER]
-
11
method.to_s.upcase
-
end
-
-
1
private
-
-
1
def allowed_methods
-
66
ALLOWED_METHODS
-
end
-
-
1
def method_override_param(req)
-
11
req.POST[METHOD_OVERRIDE_PARAM_KEY]
-
rescue Utils::InvalidParameterError, Utils::ParameterTypeError
-
end
-
end
-
end
-
1
module Rack
-
1
module Mime
-
# Returns String with mime type if found, otherwise use +fallback+.
-
# +ext+ should be filename extension in the '.ext' format that
-
# File.extname(file) returns.
-
# +fallback+ may be any object
-
#
-
# Also see the documentation for MIME_TYPES
-
#
-
# Usage:
-
# Rack::Mime.mime_type('.foo')
-
#
-
# This is a shortcut for:
-
# Rack::Mime::MIME_TYPES.fetch('.foo', 'application/octet-stream')
-
-
1
def mime_type(ext, fallback='application/octet-stream')
-
MIME_TYPES.fetch(ext.to_s.downcase, fallback)
-
end
-
1
module_function :mime_type
-
-
# Returns true if the given value is a mime match for the given mime match
-
# specification, false otherwise.
-
#
-
# Rack::Mime.match?('text/html', 'text/*') => true
-
# Rack::Mime.match?('text/plain', '*') => true
-
# Rack::Mime.match?('text/html', 'application/json') => false
-
-
1
def match?(value, matcher)
-
v1, v2 = value.split('/', 2)
-
m1, m2 = matcher.split('/', 2)
-
-
(m1 == '*' || v1 == m1) && (m2.nil? || m2 == '*' || m2 == v2)
-
end
-
1
module_function :match?
-
-
# List of most common mime-types, selected various sources
-
# according to their usefulness in a webserving scope for Ruby
-
# users.
-
#
-
# To amend this list with your local mime.types list you can use:
-
#
-
# require 'webrick/httputils'
-
# list = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types')
-
# Rack::Mime::MIME_TYPES.merge!(list)
-
#
-
# N.B. On Ubuntu the mime.types file does not include the leading period, so
-
# users may need to modify the data before merging into the hash.
-
#
-
# To add the list mongrel provides, use:
-
#
-
# require 'mongrel/handlers'
-
# Rack::Mime::MIME_TYPES.merge!(Mongrel::DirHandler::MIME_TYPES)
-
-
1
MIME_TYPES = {
-
".123" => "application/vnd.lotus-1-2-3",
-
".3dml" => "text/vnd.in3d.3dml",
-
".3g2" => "video/3gpp2",
-
".3gp" => "video/3gpp",
-
".a" => "application/octet-stream",
-
".acc" => "application/vnd.americandynamics.acc",
-
".ace" => "application/x-ace-compressed",
-
".acu" => "application/vnd.acucobol",
-
".aep" => "application/vnd.audiograph",
-
".afp" => "application/vnd.ibm.modcap",
-
".ai" => "application/postscript",
-
".aif" => "audio/x-aiff",
-
".aiff" => "audio/x-aiff",
-
".ami" => "application/vnd.amiga.ami",
-
".appcache" => "text/cache-manifest",
-
".apr" => "application/vnd.lotus-approach",
-
".asc" => "application/pgp-signature",
-
".asf" => "video/x-ms-asf",
-
".asm" => "text/x-asm",
-
".aso" => "application/vnd.accpac.simply.aso",
-
".asx" => "video/x-ms-asf",
-
".atc" => "application/vnd.acucorp",
-
".atom" => "application/atom+xml",
-
".atomcat" => "application/atomcat+xml",
-
".atomsvc" => "application/atomsvc+xml",
-
".atx" => "application/vnd.antix.game-component",
-
".au" => "audio/basic",
-
".avi" => "video/x-msvideo",
-
".bat" => "application/x-msdownload",
-
".bcpio" => "application/x-bcpio",
-
".bdm" => "application/vnd.syncml.dm+wbxml",
-
".bh2" => "application/vnd.fujitsu.oasysprs",
-
".bin" => "application/octet-stream",
-
".bmi" => "application/vnd.bmi",
-
".bmp" => "image/bmp",
-
".box" => "application/vnd.previewsystems.box",
-
".btif" => "image/prs.btif",
-
".bz" => "application/x-bzip",
-
".bz2" => "application/x-bzip2",
-
".c" => "text/x-c",
-
".c4g" => "application/vnd.clonk.c4group",
-
".cab" => "application/vnd.ms-cab-compressed",
-
".cc" => "text/x-c",
-
".ccxml" => "application/ccxml+xml",
-
".cdbcmsg" => "application/vnd.contact.cmsg",
-
".cdkey" => "application/vnd.mediastation.cdkey",
-
".cdx" => "chemical/x-cdx",
-
".cdxml" => "application/vnd.chemdraw+xml",
-
".cdy" => "application/vnd.cinderella",
-
".cer" => "application/pkix-cert",
-
".cgm" => "image/cgm",
-
".chat" => "application/x-chat",
-
".chm" => "application/vnd.ms-htmlhelp",
-
".chrt" => "application/vnd.kde.kchart",
-
".cif" => "chemical/x-cif",
-
".cii" => "application/vnd.anser-web-certificate-issue-initiation",
-
".cil" => "application/vnd.ms-artgalry",
-
".cla" => "application/vnd.claymore",
-
".class" => "application/octet-stream",
-
".clkk" => "application/vnd.crick.clicker.keyboard",
-
".clkp" => "application/vnd.crick.clicker.palette",
-
".clkt" => "application/vnd.crick.clicker.template",
-
".clkw" => "application/vnd.crick.clicker.wordbank",
-
".clkx" => "application/vnd.crick.clicker",
-
".clp" => "application/x-msclip",
-
".cmc" => "application/vnd.cosmocaller",
-
".cmdf" => "chemical/x-cmdf",
-
".cml" => "chemical/x-cml",
-
".cmp" => "application/vnd.yellowriver-custom-menu",
-
".cmx" => "image/x-cmx",
-
".com" => "application/x-msdownload",
-
".conf" => "text/plain",
-
".cpio" => "application/x-cpio",
-
".cpp" => "text/x-c",
-
".cpt" => "application/mac-compactpro",
-
".crd" => "application/x-mscardfile",
-
".crl" => "application/pkix-crl",
-
".crt" => "application/x-x509-ca-cert",
-
".csh" => "application/x-csh",
-
".csml" => "chemical/x-csml",
-
".csp" => "application/vnd.commonspace",
-
".css" => "text/css",
-
".csv" => "text/csv",
-
".curl" => "application/vnd.curl",
-
".cww" => "application/prs.cww",
-
".cxx" => "text/x-c",
-
".daf" => "application/vnd.mobius.daf",
-
".davmount" => "application/davmount+xml",
-
".dcr" => "application/x-director",
-
".dd2" => "application/vnd.oma.dd2+xml",
-
".ddd" => "application/vnd.fujixerox.ddd",
-
".deb" => "application/x-debian-package",
-
".der" => "application/x-x509-ca-cert",
-
".dfac" => "application/vnd.dreamfactory",
-
".diff" => "text/x-diff",
-
".dis" => "application/vnd.mobius.dis",
-
".djv" => "image/vnd.djvu",
-
".djvu" => "image/vnd.djvu",
-
".dll" => "application/x-msdownload",
-
".dmg" => "application/octet-stream",
-
".dna" => "application/vnd.dna",
-
".doc" => "application/msword",
-
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
-
".dot" => "application/msword",
-
".dp" => "application/vnd.osgi.dp",
-
".dpg" => "application/vnd.dpgraph",
-
".dsc" => "text/prs.lines.tag",
-
".dtd" => "application/xml-dtd",
-
".dts" => "audio/vnd.dts",
-
".dtshd" => "audio/vnd.dts.hd",
-
".dv" => "video/x-dv",
-
".dvi" => "application/x-dvi",
-
".dwf" => "model/vnd.dwf",
-
".dwg" => "image/vnd.dwg",
-
".dxf" => "image/vnd.dxf",
-
".dxp" => "application/vnd.spotfire.dxp",
-
".ear" => "application/java-archive",
-
".ecelp4800" => "audio/vnd.nuera.ecelp4800",
-
".ecelp7470" => "audio/vnd.nuera.ecelp7470",
-
".ecelp9600" => "audio/vnd.nuera.ecelp9600",
-
".ecma" => "application/ecmascript",
-
".edm" => "application/vnd.novadigm.edm",
-
".edx" => "application/vnd.novadigm.edx",
-
".efif" => "application/vnd.picsel",
-
".ei6" => "application/vnd.pg.osasli",
-
".eml" => "message/rfc822",
-
".eol" => "audio/vnd.digital-winds",
-
".eot" => "application/vnd.ms-fontobject",
-
".eps" => "application/postscript",
-
".es3" => "application/vnd.eszigno3+xml",
-
".esf" => "application/vnd.epson.esf",
-
".etx" => "text/x-setext",
-
".exe" => "application/x-msdownload",
-
".ext" => "application/vnd.novadigm.ext",
-
".ez" => "application/andrew-inset",
-
".ez2" => "application/vnd.ezpix-album",
-
".ez3" => "application/vnd.ezpix-package",
-
".f" => "text/x-fortran",
-
".f77" => "text/x-fortran",
-
".f90" => "text/x-fortran",
-
".fbs" => "image/vnd.fastbidsheet",
-
".fdf" => "application/vnd.fdf",
-
".fe_launch" => "application/vnd.denovo.fcselayout-link",
-
".fg5" => "application/vnd.fujitsu.oasysgp",
-
".fli" => "video/x-fli",
-
".flo" => "application/vnd.micrografx.flo",
-
".flv" => "video/x-flv",
-
".flw" => "application/vnd.kde.kivio",
-
".flx" => "text/vnd.fmi.flexstor",
-
".fly" => "text/vnd.fly",
-
".fm" => "application/vnd.framemaker",
-
".fnc" => "application/vnd.frogans.fnc",
-
".for" => "text/x-fortran",
-
".fpx" => "image/vnd.fpx",
-
".fsc" => "application/vnd.fsc.weblaunch",
-
".fst" => "image/vnd.fst",
-
".ftc" => "application/vnd.fluxtime.clip",
-
".fti" => "application/vnd.anser-web-funds-transfer-initiation",
-
".fvt" => "video/vnd.fvt",
-
".fzs" => "application/vnd.fuzzysheet",
-
".g3" => "image/g3fax",
-
".gac" => "application/vnd.groove-account",
-
".gdl" => "model/vnd.gdl",
-
".gem" => "application/octet-stream",
-
".gemspec" => "text/x-script.ruby",
-
".ghf" => "application/vnd.groove-help",
-
".gif" => "image/gif",
-
".gim" => "application/vnd.groove-identity-message",
-
".gmx" => "application/vnd.gmx",
-
".gph" => "application/vnd.flographit",
-
".gqf" => "application/vnd.grafeq",
-
".gram" => "application/srgs",
-
".grv" => "application/vnd.groove-injector",
-
".grxml" => "application/srgs+xml",
-
".gtar" => "application/x-gtar",
-
".gtm" => "application/vnd.groove-tool-message",
-
".gtw" => "model/vnd.gtw",
-
".gv" => "text/vnd.graphviz",
-
".gz" => "application/x-gzip",
-
".h" => "text/x-c",
-
".h261" => "video/h261",
-
".h263" => "video/h263",
-
".h264" => "video/h264",
-
".hbci" => "application/vnd.hbci",
-
".hdf" => "application/x-hdf",
-
".hh" => "text/x-c",
-
".hlp" => "application/winhlp",
-
".hpgl" => "application/vnd.hp-hpgl",
-
".hpid" => "application/vnd.hp-hpid",
-
".hps" => "application/vnd.hp-hps",
-
".hqx" => "application/mac-binhex40",
-
".htc" => "text/x-component",
-
".htke" => "application/vnd.kenameaapp",
-
".htm" => "text/html",
-
".html" => "text/html",
-
".hvd" => "application/vnd.yamaha.hv-dic",
-
".hvp" => "application/vnd.yamaha.hv-voice",
-
".hvs" => "application/vnd.yamaha.hv-script",
-
".icc" => "application/vnd.iccprofile",
-
".ice" => "x-conference/x-cooltalk",
-
".ico" => "image/vnd.microsoft.icon",
-
".ics" => "text/calendar",
-
".ief" => "image/ief",
-
".ifb" => "text/calendar",
-
".ifm" => "application/vnd.shana.informed.formdata",
-
".igl" => "application/vnd.igloader",
-
".igs" => "model/iges",
-
".igx" => "application/vnd.micrografx.igx",
-
".iif" => "application/vnd.shana.informed.interchange",
-
".imp" => "application/vnd.accpac.simply.imp",
-
".ims" => "application/vnd.ms-ims",
-
".ipk" => "application/vnd.shana.informed.package",
-
".irm" => "application/vnd.ibm.rights-management",
-
".irp" => "application/vnd.irepository.package+xml",
-
".iso" => "application/octet-stream",
-
".itp" => "application/vnd.shana.informed.formtemplate",
-
".ivp" => "application/vnd.immervision-ivp",
-
".ivu" => "application/vnd.immervision-ivu",
-
".jad" => "text/vnd.sun.j2me.app-descriptor",
-
".jam" => "application/vnd.jam",
-
".jar" => "application/java-archive",
-
".java" => "text/x-java-source",
-
".jisp" => "application/vnd.jisp",
-
".jlt" => "application/vnd.hp-jlyt",
-
".jnlp" => "application/x-java-jnlp-file",
-
".joda" => "application/vnd.joost.joda-archive",
-
".jp2" => "image/jp2",
-
".jpeg" => "image/jpeg",
-
".jpg" => "image/jpeg",
-
".jpgv" => "video/jpeg",
-
".jpm" => "video/jpm",
-
".js" => "application/javascript",
-
".json" => "application/json",
-
".karbon" => "application/vnd.kde.karbon",
-
".kfo" => "application/vnd.kde.kformula",
-
".kia" => "application/vnd.kidspiration",
-
".kml" => "application/vnd.google-earth.kml+xml",
-
".kmz" => "application/vnd.google-earth.kmz",
-
".kne" => "application/vnd.kinar",
-
".kon" => "application/vnd.kde.kontour",
-
".kpr" => "application/vnd.kde.kpresenter",
-
".ksp" => "application/vnd.kde.kspread",
-
".ktz" => "application/vnd.kahootz",
-
".kwd" => "application/vnd.kde.kword",
-
".latex" => "application/x-latex",
-
".lbd" => "application/vnd.llamagraphics.life-balance.desktop",
-
".lbe" => "application/vnd.llamagraphics.life-balance.exchange+xml",
-
".les" => "application/vnd.hhe.lesson-player",
-
".link66" => "application/vnd.route66.link66+xml",
-
".log" => "text/plain",
-
".lostxml" => "application/lost+xml",
-
".lrm" => "application/vnd.ms-lrm",
-
".ltf" => "application/vnd.frogans.ltf",
-
".lvp" => "audio/vnd.lucent.voice",
-
".lwp" => "application/vnd.lotus-wordpro",
-
".m3u" => "audio/x-mpegurl",
-
".m4a" => "audio/mp4a-latm",
-
".m4v" => "video/mp4",
-
".ma" => "application/mathematica",
-
".mag" => "application/vnd.ecowin.chart",
-
".man" => "text/troff",
-
".manifest" => "text/cache-manifest",
-
".mathml" => "application/mathml+xml",
-
".mbk" => "application/vnd.mobius.mbk",
-
".mbox" => "application/mbox",
-
".mc1" => "application/vnd.medcalcdata",
-
".mcd" => "application/vnd.mcd",
-
".mdb" => "application/x-msaccess",
-
".mdi" => "image/vnd.ms-modi",
-
".mdoc" => "text/troff",
-
".me" => "text/troff",
-
".mfm" => "application/vnd.mfmp",
-
".mgz" => "application/vnd.proteus.magazine",
-
".mid" => "audio/midi",
-
".midi" => "audio/midi",
-
".mif" => "application/vnd.mif",
-
".mime" => "message/rfc822",
-
".mj2" => "video/mj2",
-
".mlp" => "application/vnd.dolby.mlp",
-
".mmd" => "application/vnd.chipnuts.karaoke-mmd",
-
".mmf" => "application/vnd.smaf",
-
".mml" => "application/mathml+xml",
-
".mmr" => "image/vnd.fujixerox.edmics-mmr",
-
".mng" => "video/x-mng",
-
".mny" => "application/x-msmoney",
-
".mov" => "video/quicktime",
-
".movie" => "video/x-sgi-movie",
-
".mp3" => "audio/mpeg",
-
".mp4" => "video/mp4",
-
".mp4a" => "audio/mp4",
-
".mp4s" => "application/mp4",
-
".mp4v" => "video/mp4",
-
".mpc" => "application/vnd.mophun.certificate",
-
".mpeg" => "video/mpeg",
-
".mpg" => "video/mpeg",
-
".mpga" => "audio/mpeg",
-
".mpkg" => "application/vnd.apple.installer+xml",
-
".mpm" => "application/vnd.blueice.multipass",
-
".mpn" => "application/vnd.mophun.application",
-
".mpp" => "application/vnd.ms-project",
-
".mpy" => "application/vnd.ibm.minipay",
-
".mqy" => "application/vnd.mobius.mqy",
-
".mrc" => "application/marc",
-
".ms" => "text/troff",
-
".mscml" => "application/mediaservercontrol+xml",
-
".mseq" => "application/vnd.mseq",
-
".msf" => "application/vnd.epson.msf",
-
".msh" => "model/mesh",
-
".msi" => "application/x-msdownload",
-
".msl" => "application/vnd.mobius.msl",
-
".msty" => "application/vnd.muvee.style",
-
".mts" => "model/vnd.mts",
-
".mus" => "application/vnd.musician",
-
".mvb" => "application/x-msmediaview",
-
".mwf" => "application/vnd.mfer",
-
".mxf" => "application/mxf",
-
".mxl" => "application/vnd.recordare.musicxml",
-
".mxml" => "application/xv+xml",
-
".mxs" => "application/vnd.triscape.mxs",
-
".mxu" => "video/vnd.mpegurl",
-
".n" => "application/vnd.nokia.n-gage.symbian.install",
-
".nc" => "application/x-netcdf",
-
".ngdat" => "application/vnd.nokia.n-gage.data",
-
".nlu" => "application/vnd.neurolanguage.nlu",
-
".nml" => "application/vnd.enliven",
-
".nnd" => "application/vnd.noblenet-directory",
-
".nns" => "application/vnd.noblenet-sealer",
-
".nnw" => "application/vnd.noblenet-web",
-
".npx" => "image/vnd.net-fpx",
-
".nsf" => "application/vnd.lotus-notes",
-
".oa2" => "application/vnd.fujitsu.oasys2",
-
".oa3" => "application/vnd.fujitsu.oasys3",
-
".oas" => "application/vnd.fujitsu.oasys",
-
".obd" => "application/x-msbinder",
-
".oda" => "application/oda",
-
".odc" => "application/vnd.oasis.opendocument.chart",
-
".odf" => "application/vnd.oasis.opendocument.formula",
-
".odg" => "application/vnd.oasis.opendocument.graphics",
-
".odi" => "application/vnd.oasis.opendocument.image",
-
".odp" => "application/vnd.oasis.opendocument.presentation",
-
".ods" => "application/vnd.oasis.opendocument.spreadsheet",
-
".odt" => "application/vnd.oasis.opendocument.text",
-
".oga" => "audio/ogg",
-
".ogg" => "application/ogg",
-
".ogv" => "video/ogg",
-
".ogx" => "application/ogg",
-
".org" => "application/vnd.lotus-organizer",
-
".otc" => "application/vnd.oasis.opendocument.chart-template",
-
".otf" => "application/vnd.oasis.opendocument.formula-template",
-
".otg" => "application/vnd.oasis.opendocument.graphics-template",
-
".oth" => "application/vnd.oasis.opendocument.text-web",
-
".oti" => "application/vnd.oasis.opendocument.image-template",
-
".otm" => "application/vnd.oasis.opendocument.text-master",
-
".ots" => "application/vnd.oasis.opendocument.spreadsheet-template",
-
".ott" => "application/vnd.oasis.opendocument.text-template",
-
".oxt" => "application/vnd.openofficeorg.extension",
-
".p" => "text/x-pascal",
-
".p10" => "application/pkcs10",
-
".p12" => "application/x-pkcs12",
-
".p7b" => "application/x-pkcs7-certificates",
-
".p7m" => "application/pkcs7-mime",
-
".p7r" => "application/x-pkcs7-certreqresp",
-
".p7s" => "application/pkcs7-signature",
-
".pas" => "text/x-pascal",
-
".pbd" => "application/vnd.powerbuilder6",
-
".pbm" => "image/x-portable-bitmap",
-
".pcl" => "application/vnd.hp-pcl",
-
".pclxl" => "application/vnd.hp-pclxl",
-
".pcx" => "image/x-pcx",
-
".pdb" => "chemical/x-pdb",
-
".pdf" => "application/pdf",
-
".pem" => "application/x-x509-ca-cert",
-
".pfr" => "application/font-tdpfr",
-
".pgm" => "image/x-portable-graymap",
-
".pgn" => "application/x-chess-pgn",
-
".pgp" => "application/pgp-encrypted",
-
".pic" => "image/x-pict",
-
".pict" => "image/pict",
-
".pkg" => "application/octet-stream",
-
".pki" => "application/pkixcmp",
-
".pkipath" => "application/pkix-pkipath",
-
".pl" => "text/x-script.perl",
-
".plb" => "application/vnd.3gpp.pic-bw-large",
-
".plc" => "application/vnd.mobius.plc",
-
".plf" => "application/vnd.pocketlearn",
-
".pls" => "application/pls+xml",
-
".pm" => "text/x-script.perl-module",
-
".pml" => "application/vnd.ctc-posml",
-
".png" => "image/png",
-
".pnm" => "image/x-portable-anymap",
-
".pntg" => "image/x-macpaint",
-
".portpkg" => "application/vnd.macports.portpkg",
-
".ppd" => "application/vnd.cups-ppd",
-
".ppm" => "image/x-portable-pixmap",
-
".pps" => "application/vnd.ms-powerpoint",
-
".ppt" => "application/vnd.ms-powerpoint",
-
".prc" => "application/vnd.palm",
-
".pre" => "application/vnd.lotus-freelance",
-
".prf" => "application/pics-rules",
-
".ps" => "application/postscript",
-
".psb" => "application/vnd.3gpp.pic-bw-small",
-
".psd" => "image/vnd.adobe.photoshop",
-
".ptid" => "application/vnd.pvi.ptid1",
-
".pub" => "application/x-mspublisher",
-
".pvb" => "application/vnd.3gpp.pic-bw-var",
-
".pwn" => "application/vnd.3m.post-it-notes",
-
".py" => "text/x-script.python",
-
".pya" => "audio/vnd.ms-playready.media.pya",
-
".pyv" => "video/vnd.ms-playready.media.pyv",
-
".qam" => "application/vnd.epson.quickanime",
-
".qbo" => "application/vnd.intu.qbo",
-
".qfx" => "application/vnd.intu.qfx",
-
".qps" => "application/vnd.publishare-delta-tree",
-
".qt" => "video/quicktime",
-
".qtif" => "image/x-quicktime",
-
".qxd" => "application/vnd.quark.quarkxpress",
-
".ra" => "audio/x-pn-realaudio",
-
".rake" => "text/x-script.ruby",
-
".ram" => "audio/x-pn-realaudio",
-
".rar" => "application/x-rar-compressed",
-
".ras" => "image/x-cmu-raster",
-
".rb" => "text/x-script.ruby",
-
".rcprofile" => "application/vnd.ipunplugged.rcprofile",
-
".rdf" => "application/rdf+xml",
-
".rdz" => "application/vnd.data-vision.rdz",
-
".rep" => "application/vnd.businessobjects",
-
".rgb" => "image/x-rgb",
-
".rif" => "application/reginfo+xml",
-
".rl" => "application/resource-lists+xml",
-
".rlc" => "image/vnd.fujixerox.edmics-rlc",
-
".rld" => "application/resource-lists-diff+xml",
-
".rm" => "application/vnd.rn-realmedia",
-
".rmp" => "audio/x-pn-realaudio-plugin",
-
".rms" => "application/vnd.jcp.javame.midlet-rms",
-
".rnc" => "application/relax-ng-compact-syntax",
-
".roff" => "text/troff",
-
".rpm" => "application/x-redhat-package-manager",
-
".rpss" => "application/vnd.nokia.radio-presets",
-
".rpst" => "application/vnd.nokia.radio-preset",
-
".rq" => "application/sparql-query",
-
".rs" => "application/rls-services+xml",
-
".rsd" => "application/rsd+xml",
-
".rss" => "application/rss+xml",
-
".rtf" => "application/rtf",
-
".rtx" => "text/richtext",
-
".ru" => "text/x-script.ruby",
-
".s" => "text/x-asm",
-
".saf" => "application/vnd.yamaha.smaf-audio",
-
".sbml" => "application/sbml+xml",
-
".sc" => "application/vnd.ibm.secure-container",
-
".scd" => "application/x-msschedule",
-
".scm" => "application/vnd.lotus-screencam",
-
".scq" => "application/scvp-cv-request",
-
".scs" => "application/scvp-cv-response",
-
".sdkm" => "application/vnd.solent.sdkm+xml",
-
".sdp" => "application/sdp",
-
".see" => "application/vnd.seemail",
-
".sema" => "application/vnd.sema",
-
".semd" => "application/vnd.semd",
-
".semf" => "application/vnd.semf",
-
".setpay" => "application/set-payment-initiation",
-
".setreg" => "application/set-registration-initiation",
-
".sfd" => "application/vnd.hydrostatix.sof-data",
-
".sfs" => "application/vnd.spotfire.sfs",
-
".sgm" => "text/sgml",
-
".sgml" => "text/sgml",
-
".sh" => "application/x-sh",
-
".shar" => "application/x-shar",
-
".shf" => "application/shf+xml",
-
".sig" => "application/pgp-signature",
-
".sit" => "application/x-stuffit",
-
".sitx" => "application/x-stuffitx",
-
".skp" => "application/vnd.koan",
-
".slt" => "application/vnd.epson.salt",
-
".smi" => "application/smil+xml",
-
".snd" => "audio/basic",
-
".so" => "application/octet-stream",
-
".spf" => "application/vnd.yamaha.smaf-phrase",
-
".spl" => "application/x-futuresplash",
-
".spot" => "text/vnd.in3d.spot",
-
".spp" => "application/scvp-vp-response",
-
".spq" => "application/scvp-vp-request",
-
".src" => "application/x-wais-source",
-
".srx" => "application/sparql-results+xml",
-
".sse" => "application/vnd.kodak-descriptor",
-
".ssf" => "application/vnd.epson.ssf",
-
".ssml" => "application/ssml+xml",
-
".stf" => "application/vnd.wt.stf",
-
".stk" => "application/hyperstudio",
-
".str" => "application/vnd.pg.format",
-
".sus" => "application/vnd.sus-calendar",
-
".sv4cpio" => "application/x-sv4cpio",
-
".sv4crc" => "application/x-sv4crc",
-
".svd" => "application/vnd.svd",
-
".svg" => "image/svg+xml",
-
".svgz" => "image/svg+xml",
-
".swf" => "application/x-shockwave-flash",
-
".swi" => "application/vnd.arastra.swi",
-
".t" => "text/troff",
-
".tao" => "application/vnd.tao.intent-module-archive",
-
".tar" => "application/x-tar",
-
".tbz" => "application/x-bzip-compressed-tar",
-
".tcap" => "application/vnd.3gpp2.tcap",
-
".tcl" => "application/x-tcl",
-
".tex" => "application/x-tex",
-
".texi" => "application/x-texinfo",
-
".texinfo" => "application/x-texinfo",
-
".text" => "text/plain",
-
".tif" => "image/tiff",
-
".tiff" => "image/tiff",
-
".tmo" => "application/vnd.tmobile-livetv",
-
".torrent" => "application/x-bittorrent",
-
".tpl" => "application/vnd.groove-tool-template",
-
".tpt" => "application/vnd.trid.tpt",
-
".tr" => "text/troff",
-
".tra" => "application/vnd.trueapp",
-
".trm" => "application/x-msterminal",
-
".tsv" => "text/tab-separated-values",
-
".ttf" => "application/octet-stream",
-
".twd" => "application/vnd.simtech-mindmapper",
-
".txd" => "application/vnd.genomatix.tuxedo",
-
".txf" => "application/vnd.mobius.txf",
-
".txt" => "text/plain",
-
".ufd" => "application/vnd.ufdl",
-
".umj" => "application/vnd.umajin",
-
".unityweb" => "application/vnd.unity",
-
".uoml" => "application/vnd.uoml+xml",
-
".uri" => "text/uri-list",
-
".ustar" => "application/x-ustar",
-
".utz" => "application/vnd.uiq.theme",
-
".uu" => "text/x-uuencode",
-
".vcd" => "application/x-cdlink",
-
".vcf" => "text/x-vcard",
-
".vcg" => "application/vnd.groove-vcard",
-
".vcs" => "text/x-vcalendar",
-
".vcx" => "application/vnd.vcx",
-
".vis" => "application/vnd.visionary",
-
".viv" => "video/vnd.vivo",
-
".vrml" => "model/vrml",
-
".vsd" => "application/vnd.visio",
-
".vsf" => "application/vnd.vsf",
-
".vtu" => "model/vnd.vtu",
-
".vxml" => "application/voicexml+xml",
-
".war" => "application/java-archive",
-
".wav" => "audio/x-wav",
-
".wax" => "audio/x-ms-wax",
-
".wbmp" => "image/vnd.wap.wbmp",
-
".wbs" => "application/vnd.criticaltools.wbs+xml",
-
".wbxml" => "application/vnd.wap.wbxml",
-
".webm" => "video/webm",
-
".wm" => "video/x-ms-wm",
-
".wma" => "audio/x-ms-wma",
-
".wmd" => "application/x-ms-wmd",
-
".wmf" => "application/x-msmetafile",
-
".wml" => "text/vnd.wap.wml",
-
".wmlc" => "application/vnd.wap.wmlc",
-
".wmls" => "text/vnd.wap.wmlscript",
-
".wmlsc" => "application/vnd.wap.wmlscriptc",
-
".wmv" => "video/x-ms-wmv",
-
".wmx" => "video/x-ms-wmx",
-
".wmz" => "application/x-ms-wmz",
-
".woff" => "application/font-woff",
-
".woff2" => "application/font-woff2",
-
".wpd" => "application/vnd.wordperfect",
-
".wpl" => "application/vnd.ms-wpl",
-
".wps" => "application/vnd.ms-works",
-
".wqd" => "application/vnd.wqd",
-
".wri" => "application/x-mswrite",
-
".wrl" => "model/vrml",
-
".wsdl" => "application/wsdl+xml",
-
".wspolicy" => "application/wspolicy+xml",
-
".wtb" => "application/vnd.webturbo",
-
".wvx" => "video/x-ms-wvx",
-
".x3d" => "application/vnd.hzn-3d-crossword",
-
".xar" => "application/vnd.xara",
-
".xbd" => "application/vnd.fujixerox.docuworks.binder",
-
".xbm" => "image/x-xbitmap",
-
".xdm" => "application/vnd.syncml.dm+xml",
-
".xdp" => "application/vnd.adobe.xdp+xml",
-
".xdw" => "application/vnd.fujixerox.docuworks",
-
".xenc" => "application/xenc+xml",
-
".xer" => "application/patch-ops-error+xml",
-
".xfdf" => "application/vnd.adobe.xfdf",
-
".xfdl" => "application/vnd.xfdl",
-
".xhtml" => "application/xhtml+xml",
-
".xif" => "image/vnd.xiff",
-
".xls" => "application/vnd.ms-excel",
-
".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
-
".xml" => "application/xml",
-
".xo" => "application/vnd.olpc-sugar",
-
".xop" => "application/xop+xml",
-
".xpm" => "image/x-xpixmap",
-
".xpr" => "application/vnd.is-xpr",
-
".xps" => "application/vnd.ms-xpsdocument",
-
".xpw" => "application/vnd.intercon.formnet",
-
".xsl" => "application/xml",
-
".xslt" => "application/xslt+xml",
-
".xsm" => "application/vnd.syncml+xml",
-
".xspf" => "application/xspf+xml",
-
".xul" => "application/vnd.mozilla.xul+xml",
-
".xwd" => "image/x-xwindowdump",
-
".xyz" => "chemical/x-xyz",
-
".yaml" => "text/yaml",
-
".yml" => "text/yaml",
-
".zaz" => "application/vnd.zzazz.deck+xml",
-
".zip" => "application/zip",
-
".zmm" => "application/vnd.handheld-entertainment+xml",
-
}
-
end
-
end
-
1
require 'uri'
-
1
require 'stringio'
-
1
require 'rack'
-
1
require 'rack/lint'
-
1
require 'rack/utils'
-
1
require 'rack/response'
-
-
1
module Rack
-
# Rack::MockRequest helps testing your Rack application without
-
# actually using HTTP.
-
#
-
# After performing a request on a URL with get/post/put/patch/delete, it
-
# returns a MockResponse with useful helper methods for effective
-
# testing.
-
#
-
# You can pass a hash with additional configuration to the
-
# get/post/put/patch/delete.
-
# <tt>:input</tt>:: A String or IO-like to be used as rack.input.
-
# <tt>:fatal</tt>:: Raise a FatalWarning if the app writes to rack.errors.
-
# <tt>:lint</tt>:: If true, wrap the application in a Rack::Lint.
-
-
1
class MockRequest
-
1
class FatalWarning < RuntimeError
-
end
-
-
1
class FatalWarner
-
1
def puts(warning)
-
raise FatalWarning, warning
-
end
-
-
1
def write(warning)
-
raise FatalWarning, warning
-
end
-
-
1
def flush
-
end
-
-
1
def string
-
""
-
end
-
end
-
-
1
DEFAULT_ENV = {
-
"rack.version" => Rack::VERSION,
-
"rack.input" => StringIO.new,
-
"rack.errors" => StringIO.new,
-
"rack.multithread" => true,
-
"rack.multiprocess" => true,
-
"rack.run_once" => false,
-
}
-
-
1
def initialize(app)
-
@app = app
-
end
-
-
1
def get(uri, opts={}) request("GET", uri, opts) end
-
1
def post(uri, opts={}) request("POST", uri, opts) end
-
1
def put(uri, opts={}) request("PUT", uri, opts) end
-
1
def patch(uri, opts={}) request("PATCH", uri, opts) end
-
1
def delete(uri, opts={}) request("DELETE", uri, opts) end
-
1
def head(uri, opts={}) request("HEAD", uri, opts) end
-
1
def options(uri, opts={}) request("OPTIONS", uri, opts) end
-
-
1
def request(method="GET", uri="", opts={})
-
env = self.class.env_for(uri, opts.merge(:method => method))
-
-
if opts[:lint]
-
app = Rack::Lint.new(@app)
-
else
-
app = @app
-
end
-
-
errors = env["rack.errors"]
-
status, headers, body = app.call(env)
-
MockResponse.new(status, headers, body, errors)
-
ensure
-
body.close if body.respond_to?(:close)
-
end
-
-
# For historical reasons, we're pinning to RFC 2396. It's easier for users
-
# and we get support from ruby 1.8 to 2.2 using this method.
-
1
def self.parse_uri_rfc2396(uri)
-
67
@parser ||= defined?(URI::RFC2396_Parser) ? URI::RFC2396_Parser.new : URI
-
67
@parser.parse(uri)
-
end
-
-
# Return the Rack environment used for a request to +uri+.
-
1
def self.env_for(uri="", opts={})
-
67
uri = parse_uri_rfc2396(uri)
-
67
uri.path = "/#{uri.path}" unless uri.path[0] == ?/
-
-
67
env = DEFAULT_ENV.dup
-
-
67
env_with_encoding(env, opts, uri)
-
-
67
env[SCRIPT_NAME] = opts[:script_name] || ""
-
-
67
if opts[:fatal]
-
env["rack.errors"] = FatalWarner.new
-
else
-
67
env["rack.errors"] = StringIO.new
-
end
-
-
67
if params = opts[:params]
-
if env[REQUEST_METHOD] == "GET"
-
params = Utils.parse_nested_query(params) if params.is_a?(String)
-
params.update(Utils.parse_nested_query(env[QUERY_STRING]))
-
env[QUERY_STRING] = Utils.build_nested_query(params)
-
elsif !opts.has_key?(:input)
-
opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
-
if params.is_a?(Hash)
-
if data = Utils::Multipart.build_multipart(params)
-
opts[:input] = data
-
opts["CONTENT_LENGTH"] ||= data.length.to_s
-
opts["CONTENT_TYPE"] = "multipart/form-data; boundary=#{Utils::Multipart::MULTIPART_BOUNDARY}"
-
else
-
opts[:input] = Utils.build_nested_query(params)
-
end
-
else
-
opts[:input] = params
-
end
-
end
-
end
-
-
67
empty_str = ""
-
67
empty_str.force_encoding("ASCII-8BIT") if empty_str.respond_to? :force_encoding
-
67
opts[:input] ||= empty_str
-
67
if String === opts[:input]
-
67
rack_input = StringIO.new(opts[:input])
-
else
-
rack_input = opts[:input]
-
end
-
-
67
rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding)
-
67
env['rack.input'] = rack_input
-
-
67
env["CONTENT_LENGTH"] ||= env["rack.input"].length.to_s
-
-
67
opts.each { |field, value|
-
459
env[field] = value if String === field
-
}
-
-
67
env
-
end
-
-
1
if "<3".respond_to? :b
-
1
def self.env_with_encoding(env, opts, uri)
-
67
env[REQUEST_METHOD] = (opts[:method] ? opts[:method].to_s.upcase : "GET").b
-
67
env["SERVER_NAME"] = (uri.host || "example.org").b
-
67
env["SERVER_PORT"] = (uri.port ? uri.port.to_s : "80").b
-
67
env[QUERY_STRING] = (uri.query.to_s).b
-
67
env[PATH_INFO] = ((!uri.path || uri.path.empty?) ? "/" : uri.path).b
-
67
env["rack.url_scheme"] = (uri.scheme || "http").b
-
67
env["HTTPS"] = (env["rack.url_scheme"] == "https" ? "on" : "off").b
-
end
-
else
-
def self.env_with_encoding(env, opts, uri)
-
env[REQUEST_METHOD] = opts[:method] ? opts[:method].to_s.upcase : "GET"
-
env["SERVER_NAME"] = uri.host || "example.org"
-
env["SERVER_PORT"] = uri.port ? uri.port.to_s : "80"
-
env[QUERY_STRING] = uri.query.to_s
-
env[PATH_INFO] = (!uri.path || uri.path.empty?) ? "/" : uri.path
-
env["rack.url_scheme"] = uri.scheme || "http"
-
env["HTTPS"] = env["rack.url_scheme"] == "https" ? "on" : "off"
-
end
-
end
-
end
-
-
# Rack::MockResponse provides useful helpers for testing your apps.
-
# Usually, you don't create the MockResponse on your own, but use
-
# MockRequest.
-
-
1
class MockResponse < Rack::Response
-
# Headers
-
1
attr_reader :original_headers
-
-
# Errors
-
1
attr_accessor :errors
-
-
1
def initialize(status, headers, body, errors=StringIO.new(""))
-
66
@original_headers = headers
-
66
@errors = errors.string if errors.respond_to?(:string)
-
66
@body_string = nil
-
-
66
super(body, status, headers)
-
end
-
-
1
def =~(other)
-
body =~ other
-
end
-
-
1
def match(other)
-
body.match other
-
end
-
-
1
def body
-
# FIXME: apparently users of MockResponse expect the return value of
-
# MockResponse#body to be a string. However, the real response object
-
# returns the body as a list.
-
#
-
# See spec_showstatus.rb:
-
#
-
# should "not replace existing messages" do
-
# ...
-
# res.body.should == "foo!"
-
# end
-
51
super.join
-
end
-
-
1
def empty?
-
[201, 204, 205, 304].include? status
-
end
-
end
-
end
-
1
module Rack
-
# A multipart form data parser, adapted from IOWA.
-
#
-
# Usually, Rack::Request#POST takes care of calling this.
-
1
module Multipart
-
1
autoload :UploadedFile, 'rack/multipart/uploaded_file'
-
1
autoload :Parser, 'rack/multipart/parser'
-
1
autoload :Generator, 'rack/multipart/generator'
-
-
1
EOL = "\r\n"
-
1
MULTIPART_BOUNDARY = "AaB03x"
-
1
MULTIPART = %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|ni
-
1
TOKEN = /[^\s()<>,;:\\"\/\[\]?=]+/
-
1
CONDISP = /Content-Disposition:\s*#{TOKEN}\s*/i
-
1
DISPPARM = /;\s*(#{TOKEN})=("(?:\\"|[^"])*"|#{TOKEN})/
-
1
RFC2183 = /^#{CONDISP}(#{DISPPARM})+$/i
-
1
BROKEN_QUOTED = /^#{CONDISP}.*;\sfilename="(.*?)"(?:\s*$|\s*;\s*#{TOKEN}=)/i
-
1
BROKEN_UNQUOTED = /^#{CONDISP}.*;\sfilename=(#{TOKEN})/i
-
1
MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{EOL}/ni
-
1
MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*\s+name="?([^\";]*)"?/ni
-
1
MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{EOL}]*)/ni
-
-
1
class << self
-
1
def parse_multipart(env)
-
11
Parser.create(env).parse
-
end
-
-
1
def build_multipart(params, first = true)
-
Generator.new(params, first).dump
-
end
-
end
-
-
end
-
end
-
1
require 'rack/utils'
-
-
1
module Rack
-
1
module Multipart
-
1
class MultipartPartLimitError < Errno::EMFILE; end
-
-
1
class Parser
-
1
BUFSIZE = 16384
-
1
DUMMY = Struct.new(:parse).new
-
-
1
def self.create(env)
-
11
return DUMMY unless env['CONTENT_TYPE'] =~ MULTIPART
-
-
io = env['rack.input']
-
io.rewind
-
-
content_length = env['CONTENT_LENGTH']
-
content_length = content_length.to_i if content_length
-
-
tempfile = env['rack.multipart.tempfile_factory'] ||
-
lambda { |filename, content_type| Tempfile.new(["RackMultipart", ::File.extname(filename.gsub("\0".freeze, '%00'.freeze))]) }
-
bufsize = env['rack.multipart.buffer_size'] || BUFSIZE
-
-
new($1, io, content_length, env, tempfile, bufsize)
-
end
-
-
1
def initialize(boundary, io, content_length, env, tempfile, bufsize)
-
@buf = ""
-
-
if @buf.respond_to? :force_encoding
-
@buf.force_encoding Encoding::ASCII_8BIT
-
end
-
-
@params = Utils::KeySpaceConstrainedParams.new
-
@boundary = "--#{boundary}"
-
@io = io
-
@content_length = content_length
-
@boundary_size = Utils.bytesize(@boundary) + EOL.size
-
@env = env
-
@tempfile = tempfile
-
@bufsize = bufsize
-
-
if @content_length
-
@content_length -= @boundary_size
-
end
-
-
@rx = /(?:#{EOL})?#{Regexp.quote(@boundary)}(#{EOL}|--)/n
-
@full_boundary = @boundary + EOL
-
end
-
-
1
def parse
-
fast_forward_to_first_boundary
-
-
opened_files = 0
-
loop do
-
-
head, filename, content_type, name, body =
-
get_current_head_and_filename_and_content_type_and_name_and_body
-
-
if Utils.multipart_part_limit > 0
-
opened_files += 1 if filename
-
raise MultipartPartLimitError, 'Maximum file multiparts in content reached' if opened_files >= Utils.multipart_part_limit
-
end
-
-
# Save the rest.
-
if i = @buf.index(rx)
-
body << @buf.slice!(0, i)
-
@buf.slice!(0, @boundary_size+2)
-
-
@content_length = -1 if $1 == "--"
-
end
-
-
get_data(filename, body, content_type, name, head) do |data|
-
tag_multipart_encoding(filename, content_type, name, data)
-
-
Utils.normalize_params(@params, name, data)
-
end
-
-
# break if we're at the end of a buffer, but not if it is the end of a field
-
break if (@buf.empty? && $1 != EOL) || @content_length == -1
-
end
-
-
@io.rewind
-
-
@params.to_params_hash
-
end
-
-
1
private
-
1
def full_boundary; @full_boundary; end
-
-
1
def rx; @rx; end
-
-
1
def fast_forward_to_first_boundary
-
loop do
-
content = @io.read(@bufsize)
-
raise EOFError, "bad content body" unless content
-
@buf << content
-
-
while @buf.gsub!(/\A([^\n]*\n)/, '')
-
read_buffer = $1
-
return if read_buffer == full_boundary
-
end
-
-
raise EOFError, "bad content body" if Utils.bytesize(@buf) >= @bufsize
-
end
-
end
-
-
1
def get_current_head_and_filename_and_content_type_and_name_and_body
-
head = nil
-
body = ''
-
-
if body.respond_to? :force_encoding
-
body.force_encoding Encoding::ASCII_8BIT
-
end
-
-
filename = content_type = name = nil
-
-
until head && @buf =~ rx
-
if !head && i = @buf.index(EOL+EOL)
-
head = @buf.slice!(0, i+2) # First \r\n
-
-
@buf.slice!(0, 2) # Second \r\n
-
-
content_type = head[MULTIPART_CONTENT_TYPE, 1]
-
name = head[MULTIPART_CONTENT_DISPOSITION, 1] || head[MULTIPART_CONTENT_ID, 1]
-
-
filename = get_filename(head)
-
-
if name.nil? || name.empty? && filename
-
name = filename
-
end
-
-
if filename
-
(@env['rack.tempfiles'] ||= []) << body = @tempfile.call(filename, content_type)
-
body.binmode if body.respond_to?(:binmode)
-
end
-
-
next
-
end
-
-
# Save the read body part.
-
if head && (@boundary_size+4 < @buf.size)
-
body << @buf.slice!(0, @buf.size - (@boundary_size+4))
-
end
-
-
content = @io.read(@content_length && @bufsize >= @content_length ? @content_length : @bufsize)
-
raise EOFError, "bad content body" if content.nil? || content.empty?
-
-
@buf << content
-
@content_length -= content.size if @content_length
-
end
-
-
[head, filename, content_type, name, body]
-
end
-
-
1
def get_filename(head)
-
filename = nil
-
case head
-
when RFC2183
-
filename = Hash[head.scan(DISPPARM)]['filename']
-
filename = $1 if filename and filename =~ /^"(.*)"$/
-
when BROKEN_QUOTED, BROKEN_UNQUOTED
-
filename = $1
-
end
-
-
return unless filename
-
-
if filename.scan(/%.?.?/).all? { |s| s =~ /%[0-9a-fA-F]{2}/ }
-
filename = Utils.unescape(filename)
-
end
-
-
scrub_filename filename
-
-
if filename !~ /\\[^\\"]/
-
filename = filename.gsub(/\\(.)/, '\1')
-
end
-
filename
-
end
-
-
1
if "<3".respond_to? :valid_encoding?
-
1
def scrub_filename(filename)
-
unless filename.valid_encoding?
-
# FIXME: this force_encoding is for Ruby 2.0 and 1.9 support.
-
# We can remove it after they are dropped
-
filename.force_encoding(Encoding::ASCII_8BIT)
-
filename.encode!(:invalid => :replace, :undef => :replace)
-
end
-
end
-
-
1
CHARSET = "charset"
-
1
TEXT_PLAIN = "text/plain"
-
-
1
def tag_multipart_encoding(filename, content_type, name, body)
-
name.force_encoding Encoding::UTF_8
-
-
return if filename
-
-
encoding = Encoding::UTF_8
-
-
if content_type
-
list = content_type.split(';')
-
type_subtype = list.first
-
type_subtype.strip!
-
if TEXT_PLAIN == type_subtype
-
rest = list.drop 1
-
rest.each do |param|
-
k,v = param.split('=', 2)
-
k.strip!
-
v.strip!
-
encoding = Encoding.find v if k == CHARSET
-
end
-
end
-
end
-
-
name.force_encoding encoding
-
body.force_encoding encoding
-
end
-
else
-
def scrub_filename(filename)
-
end
-
def tag_multipart_encoding(filename, content_type, name, body)
-
end
-
end
-
-
1
def get_data(filename, body, content_type, name, head)
-
data = body
-
if filename == ""
-
# filename is blank which means no file has been selected
-
return
-
elsif filename
-
body.rewind if body.respond_to?(:rewind)
-
-
# Take the basename of the upload's original filename.
-
# This handles the full Windows paths given by Internet Explorer
-
# (and perhaps other broken user agents) without affecting
-
# those which give the lone filename.
-
filename = filename.split(/[\/\\]/).last
-
-
data = {:filename => filename, :type => content_type,
-
:name => name, :tempfile => body, :head => head}
-
elsif !filename && content_type && body.is_a?(IO)
-
body.rewind
-
-
# Generic multipart cases, not coming from a form
-
data = {:type => content_type,
-
:name => name, :tempfile => body, :head => head}
-
end
-
-
yield data
-
end
-
end
-
end
-
end
-
1
require 'rack/utils'
-
-
1
module Rack
-
# Rack::Request provides a convenient interface to a Rack
-
# environment. It is stateless, the environment +env+ passed to the
-
# constructor will be directly modified.
-
#
-
# req = Rack::Request.new(env)
-
# req.post?
-
# req.params["data"]
-
-
1
class Request
-
# The environment of the request.
-
1
attr_reader :env
-
-
1
def initialize(env)
-
418
@env = env
-
end
-
-
1
def body; @env["rack.input"] end
-
542
def script_name; @env[SCRIPT_NAME].to_s end
-
534
def path_info; @env[PATH_INFO].to_s end
-
1
def request_method; @env["REQUEST_METHOD"] end
-
372
def query_string; @env[QUERY_STRING].to_s end
-
67
def content_length; @env['CONTENT_LENGTH'] end
-
-
1
def content_type
-
22
content_type = @env['CONTENT_TYPE']
-
22
content_type.nil? || content_type.empty? ? nil : content_type
-
end
-
-
193
def session; @env['rack.session'] ||= {} end
-
1
def session_options; @env['rack.session.options'] ||= {} end
-
1
def logger; @env['rack.logger'] end
-
-
# The media type (type/subtype) portion of the CONTENT_TYPE header
-
# without any media type parameters. e.g., when CONTENT_TYPE is
-
# "text/plain;charset=utf-8", the media-type is "text/plain".
-
#
-
# For more information on the use of media types in HTTP, see:
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
-
1
def media_type
-
11
content_type && content_type.split(/\s*[;,]\s*/, 2).first.downcase
-
end
-
-
# The media type parameters provided in CONTENT_TYPE as a Hash, or
-
# an empty Hash if no CONTENT_TYPE or media-type parameters were
-
# provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
-
# this method responds with the following Hash:
-
# { 'charset' => 'utf-8' }
-
1
def media_type_params
-
return {} if content_type.nil?
-
Hash[*content_type.split(/\s*[;,]\s*/)[1..-1].
-
collect { |s| s.split('=', 2) }.
-
map { |k,v| [k.downcase, strip_doublequotes(v)] }.flatten]
-
end
-
-
# The character set of the request body if a "charset" media type
-
# parameter was given, or nil if no "charset" was specified. Note
-
# that, per RFC2616, text/* media types that specify no explicit
-
# charset are to be considered ISO-8859-1.
-
1
def content_charset
-
media_type_params['charset']
-
end
-
-
1
def scheme
-
214
if @env['HTTPS'] == 'on'
-
'https'
-
214
elsif @env['HTTP_X_FORWARDED_SSL'] == 'on'
-
'https'
-
214
elsif @env['HTTP_X_FORWARDED_SCHEME']
-
@env['HTTP_X_FORWARDED_SCHEME']
-
214
elsif @env['HTTP_X_FORWARDED_PROTO']
-
@env['HTTP_X_FORWARDED_PROTO'].split(',')[0]
-
else
-
214
@env["rack.url_scheme"]
-
end
-
end
-
-
1
def ssl?
-
132
scheme == 'https'
-
end
-
-
1
def host_with_port
-
82
if forwarded = @env["HTTP_X_FORWARDED_HOST"]
-
forwarded.split(/,\s?/).last
-
else
-
82
@env['HTTP_HOST'] || "#{@env['SERVER_NAME'] || @env['SERVER_ADDR']}:#{@env['SERVER_PORT']}"
-
end
-
end
-
-
1
def port
-
41
if port = host_with_port.split(/:/)[1]
-
port.to_i
-
41
elsif port = @env['HTTP_X_FORWARDED_PORT']
-
port.to_i
-
41
elsif @env.has_key?("HTTP_X_FORWARDED_HOST")
-
DEFAULT_PORTS[scheme]
-
41
elsif @env.has_key?("HTTP_X_FORWARDED_PROTO")
-
DEFAULT_PORTS[@env['HTTP_X_FORWARDED_PROTO'].split(',')[0]]
-
else
-
41
@env["SERVER_PORT"].to_i
-
end
-
end
-
-
1
def host
-
# Remove port number.
-
41
host_with_port.to_s.sub(/:\d+\z/, '')
-
end
-
-
1
def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
-
67
def path_info=(s); @env["PATH_INFO"] = s.to_s end
-
-
-
# Checks the HTTP request method (or verb) to see if it was of type DELETE
-
1
def delete?; request_method == "DELETE" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type GET
-
1
def get?; request_method == GET end
-
-
# Checks the HTTP request method (or verb) to see if it was of type HEAD
-
1
def head?; request_method == HEAD end
-
-
# Checks the HTTP request method (or verb) to see if it was of type OPTIONS
-
1
def options?; request_method == "OPTIONS" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type LINK
-
1
def link?; request_method == "LINK" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type PATCH
-
1
def patch?; request_method == "PATCH" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type POST
-
1
def post?; request_method == "POST" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type PUT
-
1
def put?; request_method == "PUT" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type TRACE
-
1
def trace?; request_method == "TRACE" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type UNLINK
-
1
def unlink?; request_method == "UNLINK" end
-
-
-
# The set of form-data media-types. Requests that do not indicate
-
# one of the media types presents in this list will not be eligible
-
# for form-data / param parsing.
-
1
FORM_DATA_MEDIA_TYPES = [
-
'application/x-www-form-urlencoded',
-
'multipart/form-data'
-
]
-
-
# The set of media-types. Requests that do not indicate
-
# one of the media types presents in this list will not be eligible
-
# for param parsing like soap attachments or generic multiparts
-
1
PARSEABLE_DATA_MEDIA_TYPES = [
-
'multipart/related',
-
'multipart/mixed'
-
]
-
-
# Default ports depending on scheme. Used to decide whether or not
-
# to include the port in a generated URI.
-
1
DEFAULT_PORTS = { 'http' => 80, 'https' => 443, 'coffee' => 80 }
-
-
# Determine whether the request body contains form-data by checking
-
# the request Content-Type for one of the media-types:
-
# "application/x-www-form-urlencoded" or "multipart/form-data". The
-
# list of form-data media types can be modified through the
-
# +FORM_DATA_MEDIA_TYPES+ array.
-
#
-
# A request body is also assumed to contain form-data when no
-
# Content-Type header is provided and the request_method is POST.
-
1
def form_data?
-
11
type = media_type
-
11
meth = env["rack.methodoverride.original_method"] || env[REQUEST_METHOD]
-
11
(meth == 'POST' && type.nil?) || FORM_DATA_MEDIA_TYPES.include?(type)
-
end
-
-
# Determine whether the request body contains data by checking
-
# the request media_type against registered parse-data media-types
-
1
def parseable_data?
-
55
PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
-
end
-
-
# Returns the data received in the query string.
-
1
def GET
-
66
if @env["rack.request.query_string"] == query_string
-
@env["rack.request.query_hash"]
-
else
-
66
p = parse_query({ :query => query_string, :separator => '&;' })
-
66
@env["rack.request.query_string"] = query_string
-
66
@env["rack.request.query_hash"] = p
-
end
-
end
-
-
# Returns the data received in the request body.
-
#
-
# This method support both application/x-www-form-urlencoded and
-
# multipart/form-data.
-
1
def POST
-
77
if @env["rack.input"].nil?
-
raise "Missing rack.input"
-
77
elsif @env["rack.request.form_input"].equal? @env["rack.input"]
-
11
@env["rack.request.form_hash"]
-
66
elsif form_data? || parseable_data?
-
11
unless @env["rack.request.form_hash"] = parse_multipart(env)
-
11
form_vars = @env["rack.input"].read
-
-
# Fix for Safari Ajax postings that always append \0
-
# form_vars.sub!(/\0\z/, '') # performance replacement:
-
11
form_vars.slice!(-1) if form_vars[-1] == ?\0
-
-
11
@env["rack.request.form_vars"] = form_vars
-
11
@env["rack.request.form_hash"] = parse_query({ :query => form_vars, :separator => '&' })
-
-
11
@env["rack.input"].rewind
-
end
-
11
@env["rack.request.form_input"] = @env["rack.input"]
-
11
@env["rack.request.form_hash"]
-
else
-
55
{}
-
end
-
end
-
-
# The union of GET and POST data.
-
#
-
# Note that modifications will not be persisted in the env. Use update_param or delete_param if you want to destructively modify params.
-
1
def params
-
@params ||= self.GET.merge(self.POST)
-
rescue EOFError
-
self.GET.dup
-
end
-
-
# Destructively update a parameter, whether it's in GET and/or POST. Returns nil.
-
#
-
# The parameter is updated wherever it was previous defined, so GET, POST, or both. If it wasn't previously defined, it's inserted into GET.
-
#
-
# env['rack.input'] is not touched.
-
1
def update_param(k, v)
-
found = false
-
if self.GET.has_key?(k)
-
found = true
-
self.GET[k] = v
-
end
-
if self.POST.has_key?(k)
-
found = true
-
self.POST[k] = v
-
end
-
unless found
-
self.GET[k] = v
-
end
-
@params = nil
-
nil
-
end
-
-
# Destructively delete a parameter, whether it's in GET or POST. Returns the value of the deleted parameter.
-
#
-
# If the parameter is in both GET and POST, the POST value takes precedence since that's how #params works.
-
#
-
# env['rack.input'] is not touched.
-
1
def delete_param(k)
-
v = [ self.POST.delete(k), self.GET.delete(k) ].compact.first
-
@params = nil
-
v
-
end
-
-
# shortcut for request.params[key]
-
1
def [](key)
-
params[key.to_s]
-
end
-
-
# shortcut for request.params[key] = value
-
#
-
# Note that modifications will not be persisted in the env. Use update_param or delete_param if you want to destructively modify params.
-
1
def []=(key, value)
-
params[key.to_s] = value
-
end
-
-
# like Hash#values_at
-
1
def values_at(*keys)
-
keys.map{|key| params[key] }
-
end
-
-
# the referer of the client
-
1
def referer
-
@env['HTTP_REFERER']
-
end
-
1
alias referrer referer
-
-
1
def user_agent
-
@env['HTTP_USER_AGENT']
-
end
-
-
1
def cookies
-
66
hash = @env["rack.request.cookie_hash"] ||= {}
-
66
string = @env["HTTP_COOKIE"]
-
-
66
return hash if string == @env["rack.request.cookie_string"]
-
66
hash.clear
-
-
# According to RFC 2109:
-
# If multiple cookies satisfy the criteria above, they are ordered in
-
# the Cookie header such that those with more specific Path attributes
-
# precede those with less specific. Ordering with respect to other
-
# attributes (e.g., Domain) is unspecified.
-
78
cookies = Utils.parse_query(string, ';,') { |s| Rack::Utils.unescape(s) rescue s }
-
72
cookies.each { |k,v| hash[k] = Array === v ? v.first : v }
-
66
@env["rack.request.cookie_string"] = string
-
66
hash
-
end
-
-
1
def xhr?
-
@env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
-
end
-
-
1
def base_url
-
41
url = "#{scheme}://#{host}"
-
41
url << ":#{port}" if port != DEFAULT_PORTS[scheme]
-
41
url
-
end
-
-
# Tries to return a remake of the original request URL as a string.
-
1
def url
-
41
base_url + fullpath
-
end
-
-
1
def path
-
199
script_name + path_info
-
end
-
-
1
def fullpath
-
107
query_string.empty? ? path : "#{path}?#{query_string}"
-
end
-
-
1
def accept_encoding
-
parse_http_accept_header(@env["HTTP_ACCEPT_ENCODING"])
-
end
-
-
1
def accept_language
-
parse_http_accept_header(@env["HTTP_ACCEPT_LANGUAGE"])
-
end
-
-
1
def trusted_proxy?(ip)
-
66
ip =~ /\A127\.0\.0\.1\Z|\A(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.|\A::1\Z|\Afd[0-9a-f]{2}:.+|\Alocalhost\Z|\Aunix\Z|\Aunix:/i
-
end
-
-
1
def ip
-
66
remote_addrs = split_ip_addresses(@env['REMOTE_ADDR'])
-
66
remote_addrs = reject_trusted_ip_addresses(remote_addrs)
-
-
66
return remote_addrs.first if remote_addrs.any?
-
-
66
forwarded_ips = split_ip_addresses(@env['HTTP_X_FORWARDED_FOR'])
-
-
66
return reject_trusted_ip_addresses(forwarded_ips).last || @env["REMOTE_ADDR"]
-
end
-
-
1
protected
-
1
def split_ip_addresses(ip_addresses)
-
132
ip_addresses ? ip_addresses.strip.split(/[,\s]+/) : []
-
end
-
-
1
def reject_trusted_ip_addresses(ip_addresses)
-
198
ip_addresses.reject { |ip| trusted_proxy?(ip) }
-
end
-
-
1
def parse_query(qs)
-
77
d = '&'
-
77
qs, d = qs[:query], qs[:separator] if Hash === qs
-
77
Utils.parse_nested_query(qs, d)
-
end
-
-
1
def parse_multipart(env)
-
11
Rack::Multipart.parse_multipart(env)
-
end
-
-
1
def parse_http_accept_header(header)
-
header.to_s.split(/\s*,\s*/).map do |part|
-
attribute, parameters = part.split(/\s*;\s*/, 2)
-
quality = 1.0
-
if parameters and /\Aq=([\d.]+)/ =~ parameters
-
quality = $1.to_f
-
end
-
[attribute, quality]
-
end
-
end
-
-
1
private
-
1
def strip_doublequotes(s)
-
if s[0] == ?" && s[-1] == ?"
-
s[1..-2]
-
else
-
s
-
end
-
end
-
end
-
end
-
1
require 'rack/request'
-
1
require 'rack/utils'
-
1
require 'rack/body_proxy'
-
1
require 'time'
-
-
1
module Rack
-
# Rack::Response provides a convenient interface to create a Rack
-
# response.
-
#
-
# It allows setting of headers and cookies, and provides useful
-
# defaults (a OK response containing HTML).
-
#
-
# You can use Response#write to iteratively generate your response,
-
# but note that this is buffered by Rack::Response until you call
-
# +finish+. +finish+ however can take a block inside which calls to
-
# +write+ are synchronous with the Rack response.
-
#
-
# Your application's +call+ should end returning Response#finish.
-
-
1
class Response
-
1
attr_accessor :length
-
-
1
CHUNKED = 'chunked'.freeze
-
1
TRANSFER_ENCODING = 'Transfer-Encoding'.freeze
-
1
def initialize(body=[], status=200, header={})
-
66
@status = status.to_i
-
66
@header = Utils::HeaderHash.new.merge(header)
-
-
66
@chunked = CHUNKED == @header[TRANSFER_ENCODING]
-
132
@writer = lambda { |x| @body << x }
-
66
@block = nil
-
66
@length = 0
-
-
66
@body = []
-
-
66
if body.respond_to? :to_str
-
write body.to_str
-
elsif body.respond_to?(:each)
-
66
body.each { |part|
-
66
write part.to_s
-
}
-
else
-
raise TypeError, "stringable or iterable required"
-
end
-
-
66
yield self if block_given?
-
end
-
-
1
attr_reader :header
-
1
attr_accessor :status, :body
-
-
1
def [](key)
-
11
header[key]
-
end
-
-
1
def []=(key, value)
-
header[key] = value
-
end
-
-
1
def set_cookie(key, value)
-
Utils.set_cookie_header!(header, key, value)
-
end
-
-
1
def delete_cookie(key, value={})
-
Utils.delete_cookie_header!(header, key, value)
-
end
-
-
1
def redirect(target, status=302)
-
self.status = status
-
self["Location"] = target
-
end
-
-
1
def finish(&block)
-
66
@block = block
-
-
66
if [204, 205, 304].include?(status.to_i)
-
header.delete CONTENT_TYPE
-
header.delete CONTENT_LENGTH
-
close
-
[status.to_i, header, []]
-
else
-
66
[status.to_i, header, BodyProxy.new(self){}]
-
end
-
end
-
1
alias to_a finish # For *response
-
1
alias to_ary finish # For implicit-splat on Ruby 1.9.2
-
-
1
def each(&callback)
-
@body.each(&callback)
-
@writer = callback
-
@block.call(self) if @block
-
end
-
-
# Append to body and update Content-Length.
-
#
-
# NOTE: Do not mix #write and direct #body access!
-
#
-
1
def write(str)
-
66
s = str.to_s
-
66
@length += Rack::Utils.bytesize(s) unless @chunked
-
66
@writer.call s
-
-
66
header[CONTENT_LENGTH] = @length.to_s unless @chunked
-
66
str
-
end
-
-
1
def close
-
body.close if body.respond_to?(:close)
-
end
-
-
1
def empty?
-
@block == nil && @body.empty?
-
end
-
-
1
alias headers header
-
-
1
module Helpers
-
1
def invalid?; status < 100 || status >= 600; end
-
-
1
def informational?; status >= 100 && status < 200; end
-
1
def successful?; status >= 200 && status < 300; end
-
1
def redirection?; status >= 300 && status < 400; end
-
1
def client_error?; status >= 400 && status < 500; end
-
1
def server_error?; status >= 500 && status < 600; end
-
-
1
def ok?; status == 200; end
-
1
def created?; status == 201; end
-
1
def accepted?; status == 202; end
-
1
def bad_request?; status == 400; end
-
1
def unauthorized?; status == 401; end
-
1
def forbidden?; status == 403; end
-
1
def not_found?; status == 404; end
-
1
def method_not_allowed?; status == 405; end
-
1
def i_m_a_teapot?; status == 418; end
-
1
def unprocessable?; status == 422; end
-
-
331
def redirect?; [301, 302, 303, 307].include? status; end
-
-
# Headers
-
1
attr_reader :headers, :original_headers
-
-
1
def include?(header)
-
!!headers[header]
-
end
-
-
1
def content_type
-
headers[CONTENT_TYPE]
-
end
-
-
1
def content_length
-
cl = headers[CONTENT_LENGTH]
-
cl ? cl.to_i : cl
-
end
-
-
1
def location
-
headers["Location"]
-
end
-
end
-
-
1
include Helpers
-
end
-
end
-
1
module Rack
-
# Sets an "X-Runtime" response header, indicating the response
-
# time of the request, in seconds
-
#
-
# You can put it right before the application to see the processing
-
# time, or before all the other middlewares to include time for them,
-
# too.
-
1
class Runtime
-
1
def initialize(app, name = nil)
-
1
@app = app
-
1
@header_name = "X-Runtime"
-
1
@header_name << "-#{name}" if name
-
end
-
-
1
FORMAT_STRING = "%0.6f"
-
1
def call(env)
-
66
start_time = clock_time
-
66
status, headers, body = @app.call(env)
-
66
request_time = clock_time - start_time
-
-
66
if !headers.has_key?(@header_name)
-
66
headers[@header_name] = FORMAT_STRING % request_time
-
end
-
-
66
[status, headers, body]
-
end
-
-
1
private
-
-
1
if defined?(Process::CLOCK_MONOTONIC)
-
1
def clock_time
-
132
Process.clock_gettime(Process::CLOCK_MONOTONIC)
-
end
-
else
-
def clock_time
-
Time.now.to_f
-
end
-
end
-
end
-
end
-
1
require 'rack/file'
-
1
require 'rack/body_proxy'
-
-
1
module Rack
-
-
# = Sendfile
-
#
-
# The Sendfile middleware intercepts responses whose body is being
-
# served from a file and replaces it with a server specific X-Sendfile
-
# header. The web server is then responsible for writing the file contents
-
# to the client. This can dramatically reduce the amount of work required
-
# by the Ruby backend and takes advantage of the web server's optimized file
-
# delivery code.
-
#
-
# In order to take advantage of this middleware, the response body must
-
# respond to +to_path+ and the request must include an X-Sendfile-Type
-
# header. Rack::File and other components implement +to_path+ so there's
-
# rarely anything you need to do in your application. The X-Sendfile-Type
-
# header is typically set in your web servers configuration. The following
-
# sections attempt to document
-
#
-
# === Nginx
-
#
-
# Nginx supports the X-Accel-Redirect header. This is similar to X-Sendfile
-
# but requires parts of the filesystem to be mapped into a private URL
-
# hierarchy.
-
#
-
# The following example shows the Nginx configuration required to create
-
# a private "/files/" area, enable X-Accel-Redirect, and pass the special
-
# X-Sendfile-Type and X-Accel-Mapping headers to the backend:
-
#
-
# location ~ /files/(.*) {
-
# internal;
-
# alias /var/www/$1;
-
# }
-
#
-
# location / {
-
# proxy_redirect off;
-
#
-
# proxy_set_header Host $host;
-
# proxy_set_header X-Real-IP $remote_addr;
-
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-
#
-
# proxy_set_header X-Sendfile-Type X-Accel-Redirect;
-
# proxy_set_header X-Accel-Mapping /var/www/=/files/;
-
#
-
# proxy_pass http://127.0.0.1:8080/;
-
# }
-
#
-
# Note that the X-Sendfile-Type header must be set exactly as shown above.
-
# The X-Accel-Mapping header should specify the location on the file system,
-
# followed by an equals sign (=), followed name of the private URL pattern
-
# that it maps to. The middleware performs a simple substitution on the
-
# resulting path.
-
#
-
# See Also: http://wiki.codemongers.com/NginxXSendfile
-
#
-
# === lighttpd
-
#
-
# Lighttpd has supported some variation of the X-Sendfile header for some
-
# time, although only recent version support X-Sendfile in a reverse proxy
-
# configuration.
-
#
-
# $HTTP["host"] == "example.com" {
-
# proxy-core.protocol = "http"
-
# proxy-core.balancer = "round-robin"
-
# proxy-core.backends = (
-
# "127.0.0.1:8000",
-
# "127.0.0.1:8001",
-
# ...
-
# )
-
#
-
# proxy-core.allow-x-sendfile = "enable"
-
# proxy-core.rewrite-request = (
-
# "X-Sendfile-Type" => (".*" => "X-Sendfile")
-
# )
-
# }
-
#
-
# See Also: http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModProxyCore
-
#
-
# === Apache
-
#
-
# X-Sendfile is supported under Apache 2.x using a separate module:
-
#
-
# https://tn123.org/mod_xsendfile/
-
#
-
# Once the module is compiled and installed, you can enable it using
-
# XSendFile config directive:
-
#
-
# RequestHeader Set X-Sendfile-Type X-Sendfile
-
# ProxyPassReverse / http://localhost:8001/
-
# XSendFile on
-
#
-
# === Mapping parameter
-
#
-
# The third parameter allows for an overriding extension of the
-
# X-Accel-Mapping header. Mappings should be provided in tuples of internal to
-
# external. The internal values may contain regular expression syntax, they
-
# will be matched with case indifference.
-
-
1
class Sendfile
-
1
F = ::File
-
-
1
def initialize(app, variation=nil, mappings=[])
-
1
@app = app
-
1
@variation = variation
-
1
@mappings = mappings.map do |internal, external|
-
[/^#{internal}/i, external]
-
end
-
end
-
-
1
def call(env)
-
66
status, headers, body = @app.call(env)
-
66
if body.respond_to?(:to_path)
-
case type = variation(env)
-
when 'X-Accel-Redirect'
-
path = F.expand_path(body.to_path)
-
if url = map_accel_path(env, path)
-
headers[CONTENT_LENGTH] = '0'
-
headers[type] = url
-
obody = body
-
body = Rack::BodyProxy.new([]) do
-
obody.close if obody.respond_to?(:close)
-
end
-
else
-
env['rack.errors'].puts "X-Accel-Mapping header missing"
-
end
-
when 'X-Sendfile', 'X-Lighttpd-Send-File'
-
path = F.expand_path(body.to_path)
-
headers[CONTENT_LENGTH] = '0'
-
headers[type] = path
-
obody = body
-
body = Rack::BodyProxy.new([]) do
-
obody.close if obody.respond_to?(:close)
-
end
-
when '', nil
-
else
-
env['rack.errors'].puts "Unknown x-sendfile variation: '#{type}'.\n"
-
end
-
end
-
66
[status, headers, body]
-
end
-
-
1
private
-
1
def variation(env)
-
@variation ||
-
env['sendfile.type'] ||
-
env['HTTP_X_SENDFILE_TYPE']
-
end
-
-
1
def map_accel_path(env, path)
-
if mapping = @mappings.find { |internal,_| internal =~ path }
-
path.sub(*mapping)
-
elsif mapping = env['HTTP_X_ACCEL_MAPPING']
-
internal, external = mapping.split('=', 2).map{ |p| p.strip }
-
path.sub(/^#{internal}/i, external)
-
end
-
end
-
end
-
end
-
# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net
-
# bugrep: Andreas Zehnder
-
-
1
require 'time'
-
1
require 'rack/request'
-
1
require 'rack/response'
-
1
begin
-
1
require 'securerandom'
-
rescue LoadError
-
# We just won't get securerandom
-
end
-
-
1
module Rack
-
-
1
module Session
-
-
1
module Abstract
-
1
ENV_SESSION_KEY = 'rack.session'.freeze
-
1
ENV_SESSION_OPTIONS_KEY = 'rack.session.options'.freeze
-
-
# SessionHash is responsible to lazily load the session from store.
-
-
1
class SessionHash
-
1
include Enumerable
-
1
attr_writer :id
-
-
1
def self.find(env)
-
env[ENV_SESSION_KEY]
-
end
-
-
1
def self.set(env, session)
-
env[ENV_SESSION_KEY] = session
-
end
-
-
1
def self.set_options(env, options)
-
env[ENV_SESSION_OPTIONS_KEY] = options.dup
-
end
-
-
1
def initialize(store, env)
-
@store = store
-
@env = env
-
@loaded = false
-
end
-
-
1
def id
-
return @id if @loaded or instance_variable_defined?(:@id)
-
@id = @store.send(:extract_session_id, @env)
-
end
-
-
1
def options
-
@env[ENV_SESSION_OPTIONS_KEY]
-
end
-
-
1
def each(&block)
-
load_for_read!
-
@data.each(&block)
-
end
-
-
1
def [](key)
-
load_for_read!
-
@data[key.to_s]
-
end
-
1
alias :fetch :[]
-
-
1
def has_key?(key)
-
load_for_read!
-
@data.has_key?(key.to_s)
-
end
-
1
alias :key? :has_key?
-
1
alias :include? :has_key?
-
-
1
def []=(key, value)
-
load_for_write!
-
@data[key.to_s] = value
-
end
-
1
alias :store :[]=
-
-
1
def clear
-
load_for_write!
-
@data.clear
-
end
-
-
1
def destroy
-
clear
-
@id = @store.send(:destroy_session, @env, id, options)
-
end
-
-
1
def to_hash
-
load_for_read!
-
@data.dup
-
end
-
-
1
def update(hash)
-
load_for_write!
-
@data.update(stringify_keys(hash))
-
end
-
1
alias :merge! :update
-
-
1
def replace(hash)
-
load_for_write!
-
@data.replace(stringify_keys(hash))
-
end
-
-
1
def delete(key)
-
load_for_write!
-
@data.delete(key.to_s)
-
end
-
-
1
def inspect
-
if loaded?
-
@data.inspect
-
else
-
"#<#{self.class}:0x#{self.object_id.to_s(16)} not yet loaded>"
-
end
-
end
-
-
1
def exists?
-
return @exists if instance_variable_defined?(:@exists)
-
@data = {}
-
@exists = @store.send(:session_exists?, @env)
-
end
-
-
1
def loaded?
-
@loaded
-
end
-
-
1
def empty?
-
load_for_read!
-
@data.empty?
-
end
-
-
1
def keys
-
@data.keys
-
end
-
-
1
def values
-
@data.values
-
end
-
-
1
private
-
-
1
def load_for_read!
-
load! if !loaded? && exists?
-
end
-
-
1
def load_for_write!
-
load! unless loaded?
-
end
-
-
1
def load!
-
@id, session = @store.send(:load_session, @env)
-
@data = stringify_keys(session)
-
@loaded = true
-
end
-
-
1
def stringify_keys(other)
-
hash = {}
-
other.each do |key, value|
-
hash[key.to_s] = value
-
end
-
hash
-
end
-
end
-
-
# ID sets up a basic framework for implementing an id based sessioning
-
# service. Cookies sent to the client for maintaining sessions will only
-
# contain an id reference. Only #get_session and #set_session are
-
# required to be overwritten.
-
#
-
# All parameters are optional.
-
# * :key determines the name of the cookie, by default it is
-
# 'rack.session'
-
# * :path, :domain, :expire_after, :secure, and :httponly set the related
-
# cookie options as by Rack::Response#add_cookie
-
# * :skip will not a set a cookie in the response nor update the session state
-
# * :defer will not set a cookie in the response but still update the session
-
# state if it is used with a backend
-
# * :renew (implementation dependent) will prompt the generation of a new
-
# session id, and migration of data to be referenced at the new id. If
-
# :defer is set, it will be overridden and the cookie will be set.
-
# * :sidbits sets the number of bits in length that a generated session
-
# id will be.
-
#
-
# These options can be set on a per request basis, at the location of
-
# env['rack.session.options']. Additionally the id of the session can be
-
# found within the options hash at the key :id. It is highly not
-
# recommended to change its value.
-
#
-
# Is Rack::Utils::Context compatible.
-
#
-
# Not included by default; you must require 'rack/session/abstract/id'
-
# to use.
-
-
1
class ID
-
1
DEFAULT_OPTIONS = {
-
:key => 'rack.session',
-
:path => '/',
-
:domain => nil,
-
:expire_after => nil,
-
:secure => false,
-
:httponly => true,
-
:defer => false,
-
:renew => false,
-
:sidbits => 128,
-
:cookie_only => true,
-
1
:secure_random => (::SecureRandom rescue false)
-
}
-
-
1
attr_reader :key, :default_options
-
-
1
def initialize(app, options={})
-
1
@app = app
-
1
@default_options = self.class::DEFAULT_OPTIONS.merge(options)
-
1
@key = @default_options.delete(:key)
-
1
@cookie_only = @default_options.delete(:cookie_only)
-
1
initialize_sid
-
end
-
-
1
def call(env)
-
66
context(env)
-
end
-
-
1
def context(env, app=@app)
-
66
prepare_session(env)
-
66
status, headers, body = app.call(env)
-
66
commit_session(env, status, headers, body)
-
end
-
-
1
private
-
-
1
def initialize_sid
-
@sidbits = @default_options[:sidbits]
-
@sid_secure = @default_options[:secure_random]
-
@sid_length = @sidbits / 4
-
end
-
-
# Generate a new session id using Ruby #rand. The size of the
-
# session id is controlled by the :sidbits option.
-
# Monkey patch this to use custom methods for session id generation.
-
-
1
def generate_sid(secure = @sid_secure)
-
if secure
-
secure.hex(@sid_length)
-
else
-
"%0#{@sid_length}x" % Kernel.rand(2**@sidbits - 1)
-
end
-
rescue NotImplementedError
-
generate_sid(false)
-
end
-
-
# Sets the lazy session at 'rack.session' and places options and session
-
# metadata into 'rack.session.options'.
-
-
1
def prepare_session(env)
-
session_was = env[ENV_SESSION_KEY]
-
env[ENV_SESSION_KEY] = session_class.new(self, env)
-
env[ENV_SESSION_OPTIONS_KEY] = @default_options.dup
-
env[ENV_SESSION_KEY].merge! session_was if session_was
-
end
-
-
# Extracts the session id from provided cookies and passes it and the
-
# environment to #get_session.
-
-
1
def load_session(env)
-
sid = current_session_id(env)
-
sid, session = get_session(env, sid)
-
[sid, session || {}]
-
end
-
-
# Extract session id from request object.
-
-
1
def extract_session_id(env)
-
request = Rack::Request.new(env)
-
sid = request.cookies[@key]
-
sid ||= request.params[@key] unless @cookie_only
-
sid
-
end
-
-
# Returns the current session id from the SessionHash.
-
-
1
def current_session_id(env)
-
169
env[ENV_SESSION_KEY].id
-
end
-
-
# Check if the session exists or not.
-
-
1
def session_exists?(env)
-
169
value = current_session_id(env)
-
169
value && !value.empty?
-
end
-
-
# Session should be committed if it was loaded, any of specific options like :renew, :drop
-
# or :expire_after was given and the security permissions match. Skips if skip is given.
-
-
1
def commit_session?(env, session, options)
-
66
if options[:skip]
-
false
-
else
-
66
has_session = loaded_session?(session) || forced_session_update?(session, options)
-
66
has_session && security_matches?(env, options)
-
end
-
end
-
-
1
def loaded_session?(session)
-
!session.is_a?(session_class) || session.loaded?
-
end
-
-
1
def forced_session_update?(session, options)
-
55
force_options?(options) && session && !session.empty?
-
end
-
-
1
def force_options?(options)
-
55
options.values_at(:max_age, :renew, :drop, :defer, :expire_after).any?
-
end
-
-
1
def security_matches?(env, options)
-
11
return true unless options[:secure]
-
request = Rack::Request.new(env)
-
request.ssl?
-
end
-
-
# Acquires the session from the environment and the session id from
-
# the session options and passes them to #set_session. If successful
-
# and the :defer option is not true, a cookie will be added to the
-
# response with the session's id.
-
-
1
def commit_session(env, status, headers, body)
-
66
session = env[ENV_SESSION_KEY]
-
66
options = session.options
-
-
66
if options[:drop] || options[:renew]
-
session_id = destroy_session(env, session.id || generate_sid, options)
-
return [status, headers, body] unless session_id
-
end
-
-
66
return [status, headers, body] unless commit_session?(env, session, options)
-
-
11
session.send(:load!) unless loaded_session?(session)
-
11
session_id ||= session.id
-
32
session_data = session.to_hash.delete_if { |k,v| v.nil? }
-
-
11
if not data = set_session(env, session_id, session_data, options)
-
env["rack.errors"].puts("Warning! #{self.class.name} failed to save session. Content dropped.")
-
elsif options[:defer] and not options[:renew]
-
env["rack.errors"].puts("Deferring cookie for #{session_id}") if $VERBOSE
-
else
-
11
cookie = Hash.new
-
11
cookie[:value] = data
-
11
cookie[:expires] = Time.now + options[:expire_after] if options[:expire_after]
-
11
cookie[:expires] = Time.now + options[:max_age] if options[:max_age]
-
11
set_cookie(env, headers, cookie.merge!(options))
-
end
-
-
11
[status, headers, body]
-
end
-
-
# Sets the cookie back to the client with session id. We skip the cookie
-
# setting if the value didn't change (sid is the same) or expires was given.
-
-
1
def set_cookie(env, headers, cookie)
-
request = Rack::Request.new(env)
-
if request.cookies[@key] != cookie[:value] || cookie[:expires]
-
Utils.set_cookie_header!(headers, @key, cookie)
-
end
-
end
-
-
# Allow subclasses to prepare_session for different Session classes
-
-
1
def session_class
-
SessionHash
-
end
-
-
# All thread safety and session retrieval procedures should occur here.
-
# Should return [session_id, session].
-
# If nil is provided as the session id, generation of a new valid id
-
# should occur within.
-
-
1
def get_session(env, sid)
-
raise '#get_session not implemented.'
-
end
-
-
# All thread safety and session storage procedures should occur here.
-
# Must return the session id if the session was saved successfully, or
-
# false if the session could not be saved.
-
-
1
def set_session(env, sid, session, options)
-
raise '#set_session not implemented.'
-
end
-
-
# All thread safety and session destroy procedures should occur here.
-
# Should return a new session id or nil if options[:drop]
-
-
1
def destroy_session(env, sid, options)
-
raise '#destroy_session not implemented'
-
end
-
end
-
end
-
end
-
end
-
1
require 'openssl'
-
1
require 'zlib'
-
1
require 'rack/request'
-
1
require 'rack/response'
-
1
require 'rack/session/abstract/id'
-
-
1
module Rack
-
-
1
module Session
-
-
# Rack::Session::Cookie provides simple cookie based session management.
-
# By default, the session is a Ruby Hash stored as base64 encoded marshalled
-
# data set to :key (default: rack.session). The object that encodes the
-
# session data is configurable and must respond to +encode+ and +decode+.
-
# Both methods must take a string and return a string.
-
#
-
# When the secret key is set, cookie data is checked for data integrity.
-
# The old secret key is also accepted and allows graceful secret rotation.
-
#
-
# Example:
-
#
-
# use Rack::Session::Cookie, :key => 'rack.session',
-
# :domain => 'foo.com',
-
# :path => '/',
-
# :expire_after => 2592000,
-
# :secret => 'change_me',
-
# :old_secret => 'also_change_me'
-
#
-
# All parameters are optional.
-
#
-
# Example of a cookie with no encoding:
-
#
-
# Rack::Session::Cookie.new(application, {
-
# :coder => Rack::Session::Cookie::Identity.new
-
# })
-
#
-
# Example of a cookie with custom encoding:
-
#
-
# Rack::Session::Cookie.new(application, {
-
# :coder => Class.new {
-
# def encode(str); str.reverse; end
-
# def decode(str); str.reverse; end
-
# }.new
-
# })
-
#
-
-
1
class Cookie < Abstract::ID
-
# Encode session cookies as Base64
-
1
class Base64
-
1
def encode(str)
-
[str].pack('m')
-
end
-
-
1
def decode(str)
-
str.unpack('m').first
-
end
-
-
# Encode session cookies as Marshaled Base64 data
-
1
class Marshal < Base64
-
1
def encode(str)
-
super(::Marshal.dump(str))
-
end
-
-
1
def decode(str)
-
return unless str
-
::Marshal.load(super(str)) rescue nil
-
end
-
end
-
-
# N.B. Unlike other encoding methods, the contained objects must be a
-
# valid JSON composite type, either a Hash or an Array.
-
1
class JSON < Base64
-
1
def encode(obj)
-
super(::Rack::Utils::OkJson.encode(obj))
-
end
-
-
1
def decode(str)
-
return unless str
-
::Rack::Utils::OkJson.decode(super(str)) rescue nil
-
end
-
end
-
-
1
class ZipJSON < Base64
-
1
def encode(obj)
-
super(Zlib::Deflate.deflate(::Rack::Utils::OkJson.encode(obj)))
-
end
-
-
1
def decode(str)
-
return unless str
-
::Rack::Utils::OkJson.decode(Zlib::Inflate.inflate(super(str)))
-
rescue
-
nil
-
end
-
end
-
end
-
-
# Use no encoding for session cookies
-
1
class Identity
-
1
def encode(str); str; end
-
1
def decode(str); str; end
-
end
-
-
1
attr_reader :coder
-
-
1
def initialize(app, options={})
-
@secrets = options.values_at(:secret, :old_secret).compact
-
warn <<-MSG unless @secrets.size >= 1
-
SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
-
This poses a security threat. It is strongly recommended that you
-
provide a secret to prevent exploits that may be possible from crafted
-
cookies. This will not be supported in future versions of Rack, and
-
future versions will even invalidate your existing user cookies.
-
-
Called from: #{caller[0]}.
-
MSG
-
@coder = options[:coder] ||= Base64::Marshal.new
-
super(app, options.merge!(:cookie_only => true))
-
end
-
-
1
private
-
-
1
def get_session(env, sid)
-
data = unpacked_cookie_data(env)
-
data = persistent_session_id!(data)
-
[data["session_id"], data]
-
end
-
-
1
def extract_session_id(env)
-
unpacked_cookie_data(env)["session_id"]
-
end
-
-
1
def unpacked_cookie_data(env)
-
env["rack.session.unpacked_cookie_data"] ||= begin
-
request = Rack::Request.new(env)
-
session_data = request.cookies[@key]
-
-
if @secrets.size > 0 && session_data
-
digest, session_data = session_data.reverse.split("--", 2)
-
digest.reverse! if digest
-
session_data.reverse! if session_data
-
session_data = nil unless digest_match?(session_data, digest)
-
end
-
-
coder.decode(session_data) || {}
-
end
-
end
-
-
1
def persistent_session_id!(data, sid=nil)
-
data ||= {}
-
data["session_id"] ||= sid || generate_sid
-
data
-
end
-
-
1
def set_session(env, session_id, session, options)
-
session = session.merge("session_id" => session_id)
-
session_data = coder.encode(session)
-
-
if @secrets.first
-
session_data << "--#{generate_hmac(session_data, @secrets.first)}"
-
end
-
-
if session_data.size > (4096 - @key.size)
-
env["rack.errors"].puts("Warning! Rack::Session::Cookie data size exceeds 4K.")
-
nil
-
else
-
session_data
-
end
-
end
-
-
1
def destroy_session(env, session_id, options)
-
# Nothing to do here, data is in the client
-
generate_sid unless options[:drop]
-
end
-
-
1
def digest_match?(data, digest)
-
return unless data && digest
-
@secrets.any? do |secret|
-
Rack::Utils.secure_compare(digest, generate_hmac(data, secret))
-
end
-
end
-
-
1
def generate_hmac(data, secret)
-
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, data)
-
end
-
-
end
-
end
-
end
-
1
module Rack
-
# Rack::URLMap takes a hash mapping urls or paths to apps, and
-
# dispatches accordingly. Support for HTTP/1.1 host names exists if
-
# the URLs start with <tt>http://</tt> or <tt>https://</tt>.
-
#
-
# URLMap modifies the SCRIPT_NAME and PATH_INFO such that the part
-
# relevant for dispatch is in the SCRIPT_NAME, and the rest in the
-
# PATH_INFO. This should be taken care of when you need to
-
# reconstruct the URL in order to create links.
-
#
-
# URLMap dispatches in such a way that the longest paths are tried
-
# first, since they are most specific.
-
-
1
class URLMap
-
1
NEGATIVE_INFINITY = -1.0 / 0.0
-
1
INFINITY = 1.0 / 0.0
-
-
1
def initialize(map = {})
-
1
remap(map)
-
end
-
-
1
def remap(map)
-
1
@mapping = map.map { |location, app|
-
1
if location =~ %r{\Ahttps?://(.*?)(/.*)}
-
host, location = $1, $2
-
else
-
1
host = nil
-
end
-
-
1
unless location[0] == ?/
-
raise ArgumentError, "paths need to start with /"
-
end
-
-
1
location = location.chomp('/')
-
1
match = Regexp.new("^#{Regexp.quote(location).gsub('/', '/+')}(.*)", nil, 'n')
-
-
1
[host, location, match, app]
-
}.sort_by do |(host, location, _, _)|
-
1
[host ? -host.size : INFINITY, -location.size]
-
end
-
end
-
-
1
def call(env)
-
66
path = env[PATH_INFO]
-
66
script_name = env['SCRIPT_NAME']
-
66
hHost = env['HTTP_HOST']
-
66
sName = env['SERVER_NAME']
-
66
sPort = env['SERVER_PORT']
-
-
66
@mapping.each do |host, location, match, app|
-
unless casecmp?(hHost, host) \
-
|| casecmp?(sName, host) \
-
66
|| (!host && (casecmp?(hHost, sName) ||
-
casecmp?(hHost, sName+':'+sPort)))
-
next
-
end
-
-
66
next unless m = match.match(path.to_s)
-
-
66
rest = m[1]
-
66
next unless !rest || rest.empty? || rest[0] == ?/
-
-
66
env['SCRIPT_NAME'] = (script_name + location)
-
66
env['PATH_INFO'] = rest
-
-
66
return app.call(env)
-
end
-
-
[404, {CONTENT_TYPE => "text/plain", "X-Cascade" => "pass"}, ["Not Found: #{path}"]]
-
-
ensure
-
66
env['PATH_INFO'] = path
-
66
env['SCRIPT_NAME'] = script_name
-
end
-
-
1
private
-
1
def casecmp?(v1, v2)
-
# if both nil, or they're the same string
-
198
return true if v1 == v2
-
-
# if either are nil... (but they're not the same)
-
132
return false if v1.nil?
-
132
return false if v2.nil?
-
-
# otherwise check they're not case-insensitive the same
-
v1.casecmp(v2).zero?
-
end
-
end
-
end
-
-
# -*- encoding: binary -*-
-
1
require 'fileutils'
-
1
require 'set'
-
1
require 'tempfile'
-
1
require 'rack/multipart'
-
1
require 'time'
-
-
4
major, minor, patch = RUBY_VERSION.split('.').map { |v| v.to_i }
-
-
1
if major == 1 && minor < 9
-
require 'rack/backports/uri/common_18'
-
elsif major == 1 && minor == 9 && patch == 2 && RUBY_PATCHLEVEL <= 328 && RUBY_ENGINE != 'jruby'
-
require 'rack/backports/uri/common_192'
-
elsif major == 1 && minor == 9 && patch == 3 && RUBY_PATCHLEVEL < 125
-
require 'rack/backports/uri/common_193'
-
else
-
1
require 'uri/common'
-
end
-
-
1
module Rack
-
# Rack::Utils contains a grab-bag of useful methods for writing web
-
# applications adopted from all kinds of Ruby libraries.
-
-
1
module Utils
-
# ParameterTypeError is the error that is raised when incoming structural
-
# parameters (parsed by parse_nested_query) contain conflicting types.
-
1
class ParameterTypeError < TypeError; end
-
-
# InvalidParameterError is the error that is raised when incoming structural
-
# parameters (parsed by parse_nested_query) contain invalid format or byte
-
# sequence.
-
1
class InvalidParameterError < ArgumentError; end
-
-
# URI escapes. (CGI style space to +)
-
1
def escape(s)
-
136
URI.encode_www_form_component(s)
-
end
-
1
module_function :escape
-
-
# Like URI escaping, but with %20 instead of +. Strictly speaking this is
-
# true URI escaping.
-
1
def escape_path(s)
-
escape(s).gsub('+', '%20')
-
end
-
1
module_function :escape_path
-
-
# Unescapes a URI escaped string with +encoding+. +encoding+ will be the
-
# target encoding of the string returned, and it defaults to UTF-8
-
1
if defined?(::Encoding)
-
1
def unescape(s, encoding = Encoding::UTF_8)
-
173
URI.decode_www_form_component(s, encoding)
-
end
-
else
-
def unescape(s, encoding = nil)
-
URI.decode_www_form_component(s, encoding)
-
end
-
end
-
1
module_function :unescape
-
-
1
DEFAULT_SEP = /[&;] */n
-
-
1
class << self
-
1
attr_accessor :key_space_limit
-
1
attr_accessor :param_depth_limit
-
1
attr_accessor :multipart_part_limit
-
end
-
-
# The default number of bytes to allow parameter keys to take up.
-
# This helps prevent a rogue client from flooding a Request.
-
1
self.key_space_limit = 65536
-
-
# Default depth at which the parameter parser will raise an exception for
-
# being too deep. This helps prevent SystemStackErrors
-
1
self.param_depth_limit = 100
-
-
# The maximum number of parts a request can contain. Accepting too many part
-
# can lead to the server running out of file handles.
-
# Set to `0` for no limit.
-
# FIXME: RACK_MULTIPART_LIMIT was introduced by mistake and it will be removed in 1.7.0
-
1
self.multipart_part_limit = (ENV['RACK_MULTIPART_PART_LIMIT'] || ENV['RACK_MULTIPART_LIMIT'] || 128).to_i
-
-
# Stolen from Mongrel, with some small modifications:
-
# Parses a query string by breaking it up at the '&'
-
# and ';' characters. You can also use this to parse
-
# cookies by changing the characters used in the second
-
# parameter (which defaults to '&;').
-
1
def parse_query(qs, d = nil, &unescaper)
-
88
unescaper ||= method(:unescape)
-
-
88
params = KeySpaceConstrainedParams.new
-
-
88
(qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
-
39
next if p.empty?
-
39
k, v = p.split('=', 2).map(&unescaper)
-
-
39
if cur = params[k]
-
if cur.class == Array
-
params[k] << v
-
else
-
params[k] = [cur, v]
-
end
-
else
-
39
params[k] = v
-
end
-
end
-
-
88
return params.to_params_hash
-
end
-
1
module_function :parse_query
-
-
# parse_nested_query expands a query string into structural types. Supported
-
# types are Arrays, Hashes and basic value types. It is possible to supply
-
# query strings with parameters of conflicting types, in this case a
-
# ParameterTypeError is raised. Users are encouraged to return a 400 in this
-
# case.
-
1
def parse_nested_query(qs, d = nil)
-
132
params = KeySpaceConstrainedParams.new
-
-
132
(qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
-
159
k, v = p.split('=', 2).map { |s| unescape(s) }
-
-
53
normalize_params(params, k, v)
-
end
-
-
132
return params.to_params_hash
-
rescue ArgumentError => e
-
raise InvalidParameterError, e.message
-
end
-
1
module_function :parse_nested_query
-
-
# normalize_params recursively expands parameters into structural types. If
-
# the structural types represented by two different parameter names are in
-
# conflict, a ParameterTypeError is raised.
-
1
def normalize_params(params, name, v = nil, depth = Utils.param_depth_limit)
-
166
raise RangeError if depth <= 0
-
-
166
name =~ %r(\A[\[\]]*([^\[\]]+)\]*)
-
166
k = $1 || ''
-
166
after = $' || ''
-
-
166
return if k.empty?
-
-
166
if after == ""
-
106
params[k] = v
-
elsif after == "["
-
params[name] = v
-
elsif after == "[]"
-
params[k] ||= []
-
raise ParameterTypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
-
params[k] << v
-
elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$)
-
child_key = $1
-
params[k] ||= []
-
raise ParameterTypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
-
if params_hash_type?(params[k].last) && !params[k].last.key?(child_key)
-
normalize_params(params[k].last, child_key, v, depth - 1)
-
else
-
params[k] << normalize_params(params.class.new, child_key, v, depth - 1)
-
end
-
else
-
60
params[k] ||= params.class.new
-
60
raise ParameterTypeError, "expected Hash (got #{params[k].class.name}) for param `#{k}'" unless params_hash_type?(params[k])
-
60
params[k] = normalize_params(params[k], after, v, depth - 1)
-
end
-
-
166
return params
-
end
-
1
module_function :normalize_params
-
-
1
def params_hash_type?(obj)
-
60
obj.kind_of?(KeySpaceConstrainedParams) || obj.kind_of?(Hash)
-
end
-
1
module_function :params_hash_type?
-
-
1
def build_query(params)
-
params.map { |k, v|
-
if v.class == Array
-
build_query(v.map { |x| [k, x] })
-
else
-
v.nil? ? escape(k) : "#{escape(k)}=#{escape(v)}"
-
end
-
}.join("&")
-
end
-
1
module_function :build_query
-
-
1
def build_nested_query(value, prefix = nil)
-
case value
-
when Array
-
value.map { |v|
-
build_nested_query(v, "#{prefix}[]")
-
}.join("&")
-
when Hash
-
value.map { |k, v|
-
build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
-
}.reject(&:empty?).join('&')
-
when nil
-
prefix
-
else
-
raise ArgumentError, "value must be a Hash" if prefix.nil?
-
"#{prefix}=#{escape(value)}"
-
end
-
end
-
1
module_function :build_nested_query
-
-
1
def q_values(q_value_header)
-
q_value_header.to_s.split(/\s*,\s*/).map do |part|
-
value, parameters = part.split(/\s*;\s*/, 2)
-
quality = 1.0
-
if md = /\Aq=([\d.]+)/.match(parameters)
-
quality = md[1].to_f
-
end
-
[value, quality]
-
end
-
end
-
1
module_function :q_values
-
-
1
def best_q_match(q_value_header, available_mimes)
-
values = q_values(q_value_header)
-
-
matches = values.map do |req_mime, quality|
-
match = available_mimes.find { |am| Rack::Mime.match?(am, req_mime) }
-
next unless match
-
[match, quality]
-
end.compact.sort_by do |match, quality|
-
(match.split('/', 2).count('*') * -10) + quality
-
end.last
-
matches && matches.first
-
end
-
1
module_function :best_q_match
-
-
1
ESCAPE_HTML = {
-
"&" => "&",
-
"<" => "<",
-
">" => ">",
-
"'" => "'",
-
'"' => """,
-
"/" => "/"
-
}
-
1
if //.respond_to?(:encoding)
-
1
ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys)
-
else
-
# On 1.8, there is a kcode = 'u' bug that allows for XSS otherwise
-
# TODO doesn't apply to jruby, so a better condition above might be preferable?
-
ESCAPE_HTML_PATTERN = /#{Regexp.union(*ESCAPE_HTML.keys)}/n
-
end
-
-
# Escape ampersands, brackets and quotes to their HTML/XML entities.
-
1
def escape_html(string)
-
string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] }
-
end
-
1
module_function :escape_html
-
-
1
def select_best_encoding(available_encodings, accept_encoding)
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
-
-
expanded_accept_encoding =
-
accept_encoding.map { |m, q|
-
if m == "*"
-
(available_encodings - accept_encoding.map { |m2, _| m2 }).map { |m2| [m2, q] }
-
else
-
[[m, q]]
-
end
-
}.inject([]) { |mem, list|
-
mem + list
-
}
-
-
encoding_candidates = expanded_accept_encoding.sort_by { |_, q| -q }.map { |m, _| m }
-
-
unless encoding_candidates.include?("identity")
-
encoding_candidates.push("identity")
-
end
-
-
expanded_accept_encoding.each { |m, q|
-
encoding_candidates.delete(m) if q == 0.0
-
}
-
-
return (encoding_candidates & available_encodings)[0]
-
end
-
1
module_function :select_best_encoding
-
-
1
def set_cookie_header!(header, key, value)
-
11
case value
-
when Hash
-
11
domain = "; domain=" + value[:domain] if value[:domain]
-
11
path = "; path=" + value[:path] if value[:path]
-
11
max_age = "; max-age=" + value[:max_age].to_s if value[:max_age]
-
# There is an RFC mess in the area of date formatting for Cookies. Not
-
# only are there contradicting RFCs and examples within RFC text, but
-
# there are also numerous conflicting names of fields and partially
-
# cross-applicable specifications.
-
#
-
# These are best described in RFC 2616 3.3.1. This RFC text also
-
# specifies that RFC 822 as updated by RFC 1123 is preferred. That is a
-
# fixed length format with space-date delimeted fields.
-
#
-
# See also RFC 1123 section 5.2.14.
-
#
-
# RFC 6265 also specifies "sane-cookie-date" as RFC 1123 date, defined
-
# in RFC 2616 3.3.1. RFC 6265 also gives examples that clearly denote
-
# the space delimited format. These formats are compliant with RFC 2822.
-
#
-
# For reference, all involved RFCs are:
-
# RFC 822
-
# RFC 1123
-
# RFC 2109
-
# RFC 2616
-
# RFC 2822
-
# RFC 2965
-
# RFC 6265
-
expires = "; expires=" +
-
11
rfc2822(value[:expires].clone.gmtime) if value[:expires]
-
11
secure = "; secure" if value[:secure]
-
11
httponly = "; HttpOnly" if (value.key?(:httponly) ? value[:httponly] : value[:http_only])
-
11
same_site =
-
case value[:same_site]
-
when false, nil
-
11
nil
-
when :lax, 'Lax', :Lax
-
'; SameSite=Lax'.freeze
-
when true, :strict, 'Strict', :Strict
-
'; SameSite=Strict'.freeze
-
else
-
raise ArgumentError, "Invalid SameSite value: #{value[:same_site].inspect}"
-
end
-
11
value = value[:value]
-
end
-
11
value = [value] unless Array === value
-
11
cookie = escape(key) + "=" +
-
11
value.map { |v| escape v }.join("&") +
-
"#{domain}#{path}#{max_age}#{expires}#{secure}#{httponly}#{same_site}"
-
-
11
case header["Set-Cookie"]
-
when nil, ''
-
11
header["Set-Cookie"] = cookie
-
when String
-
header["Set-Cookie"] = [header["Set-Cookie"], cookie].join("\n")
-
when Array
-
header["Set-Cookie"] = (header["Set-Cookie"] + [cookie]).join("\n")
-
end
-
-
nil
-
end
-
1
module_function :set_cookie_header!
-
-
1
def delete_cookie_header!(header, key, value = {})
-
case header["Set-Cookie"]
-
when nil, ''
-
cookies = []
-
when String
-
cookies = header["Set-Cookie"].split("\n")
-
when Array
-
cookies = header["Set-Cookie"]
-
end
-
-
cookies.reject! { |cookie|
-
if value[:domain]
-
cookie =~ /\A#{escape(key)}=.*domain=#{value[:domain]}/
-
elsif value[:path]
-
cookie =~ /\A#{escape(key)}=.*path=#{value[:path]}/
-
else
-
cookie =~ /\A#{escape(key)}=/
-
end
-
}
-
-
header["Set-Cookie"] = cookies.join("\n")
-
-
set_cookie_header!(header, key,
-
{:value => '', :path => nil, :domain => nil,
-
:max_age => '0',
-
:expires => Time.at(0) }.merge(value))
-
-
nil
-
end
-
1
module_function :delete_cookie_header!
-
-
# Return the bytesize of String; uses String#size under Ruby 1.8 and
-
# String#bytesize under 1.9.
-
1
if ''.respond_to?(:bytesize)
-
1
def bytesize(string)
-
66
string.bytesize
-
end
-
else
-
def bytesize(string)
-
string.size
-
end
-
end
-
1
module_function :bytesize
-
-
1
def rfc2822(time)
-
time.rfc2822
-
end
-
1
module_function :rfc2822
-
-
# Modified version of stdlib time.rb Time#rfc2822 to use '%d-%b-%Y' instead
-
# of '% %b %Y'.
-
# It assumes that the time is in GMT to comply to the RFC 2109.
-
#
-
# NOTE: I'm not sure the RFC says it requires GMT, but is ambiguous enough
-
# that I'm certain someone implemented only that option.
-
# Do not use %a and %b from Time.strptime, it would use localized names for
-
# weekday and month.
-
#
-
1
def rfc2109(time)
-
wday = Time::RFC2822_DAY_NAME[time.wday]
-
mon = Time::RFC2822_MONTH_NAME[time.mon - 1]
-
time.strftime("#{wday}, %d-#{mon}-%Y %H:%M:%S GMT")
-
end
-
1
module_function :rfc2109
-
-
# Parses the "Range:" header, if present, into an array of Range objects.
-
# Returns nil if the header is missing or syntactically invalid.
-
# Returns an empty array if none of the ranges are satisfiable.
-
1
def byte_ranges(env, size)
-
# See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35>
-
http_range = env['HTTP_RANGE']
-
return nil unless http_range && http_range =~ /bytes=([^;]+)/
-
ranges = []
-
$1.split(/,\s*/).each do |range_spec|
-
return nil unless range_spec =~ /(\d*)-(\d*)/
-
r0,r1 = $1, $2
-
if r0.empty?
-
return nil if r1.empty?
-
# suffix-byte-range-spec, represents trailing suffix of file
-
r0 = size - r1.to_i
-
r0 = 0 if r0 < 0
-
r1 = size - 1
-
else
-
r0 = r0.to_i
-
if r1.empty?
-
r1 = size - 1
-
else
-
r1 = r1.to_i
-
return nil if r1 < r0 # backwards range is syntactically invalid
-
r1 = size-1 if r1 >= size
-
end
-
end
-
ranges << (r0..r1) if r0 <= r1
-
end
-
ranges
-
end
-
1
module_function :byte_ranges
-
-
# Constant time string comparison.
-
#
-
# NOTE: the values compared should be of fixed length, such as strings
-
# that have already been processed by HMAC. This should not be used
-
# on variable length plaintext strings because it could leak length info
-
# via timing attacks.
-
1
def secure_compare(a, b)
-
return false unless bytesize(a) == bytesize(b)
-
-
l = a.unpack("C*")
-
-
r, i = 0, -1
-
b.each_byte { |v| r |= v ^ l[i+=1] }
-
r == 0
-
end
-
1
module_function :secure_compare
-
-
# Context allows the use of a compatible middleware at different points
-
# in a request handling stack. A compatible middleware must define
-
# #context which should take the arguments env and app. The first of which
-
# would be the request environment. The second of which would be the rack
-
# application that the request would be forwarded to.
-
1
class Context
-
1
attr_reader :for, :app
-
-
1
def initialize(app_f, app_r)
-
raise 'running context does not respond to #context' unless app_f.respond_to? :context
-
@for, @app = app_f, app_r
-
end
-
-
1
def call(env)
-
@for.context(env, @app)
-
end
-
-
1
def recontext(app)
-
self.class.new(@for, app)
-
end
-
-
1
def context(env, app=@app)
-
recontext(app).call(env)
-
end
-
end
-
-
# A case-insensitive Hash that preserves the original case of a
-
# header when set.
-
1
class HeaderHash < Hash
-
1
def self.new(hash={})
-
121
HeaderHash === hash ? hash : super(hash)
-
end
-
-
1
def initialize(hash={})
-
121
super()
-
121
@names = {}
-
451
hash.each { |k, v| self[k] = v }
-
end
-
-
1
def each
-
55
super do |k, v|
-
446
yield(k, v.respond_to?(:to_ary) ? v.to_ary.join("\n") : v)
-
end
-
end
-
-
1
def to_hash
-
hash = {}
-
each { |k,v| hash[k] = v }
-
hash
-
end
-
-
1
def [](k)
-
259
super(k) || super(@names[k.downcase])
-
end
-
-
1
def []=(k, v)
-
1051
canonical = k.downcase
-
1051
delete k if @names[canonical] && @names[canonical] != k # .delete is expensive, don't invoke it unless necessary
-
1051
@names[k] = @names[canonical] = k
-
1051
super k, v
-
end
-
-
1
def delete(k)
-
canonical = k.downcase
-
result = super @names.delete(canonical)
-
@names.delete_if { |name,| name.downcase == canonical }
-
result
-
end
-
-
1
def include?(k)
-
55
@names.include?(k) || @names.include?(k.downcase)
-
end
-
-
1
alias_method :has_key?, :include?
-
1
alias_method :member?, :include?
-
1
alias_method :key?, :include?
-
-
1
def merge!(other)
-
605
other.each { |k, v| self[k] = v }
-
66
self
-
end
-
-
1
def merge(other)
-
66
hash = dup
-
66
hash.merge! other
-
end
-
-
1
def replace(other)
-
clear
-
other.each { |k, v| self[k] = v }
-
self
-
end
-
end
-
-
1
class KeySpaceConstrainedParams
-
1
def initialize(limit = Utils.key_space_limit)
-
228
@limit = limit
-
228
@size = 0
-
228
@params = {}
-
end
-
-
1
def [](key)
-
129
@params[key]
-
end
-
-
1
def []=(key, value)
-
130
@size += key.size if key && !@params.key?(key)
-
130
raise RangeError, 'exceeded available parameter key space' if @size > @limit
-
130
@params[key] = value
-
end
-
-
1
def key?(key)
-
@params.key?(key)
-
end
-
-
1
def to_params_hash
-
228
hash = @params
-
228
hash.keys.each do |key|
-
100
value = hash[key]
-
100
if value.kind_of?(self.class)
-
8
if value.object_id == self.object_id
-
hash[key] = hash
-
else
-
8
hash[key] = value.to_params_hash
-
end
-
elsif value.kind_of?(Array)
-
value.map! {|x| x.kind_of?(self.class) ? x.to_params_hash : x}
-
end
-
end
-
228
hash
-
end
-
end
-
-
# Every standard HTTP code mapped to the appropriate message.
-
# Generated with:
-
# curl -s https://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv | \
-
# ruby -ne 'm = /^(\d{3}),(?!Unassigned|\(Unused\))([^,]+)/.match($_) and \
-
# puts "#{m[1]} => \x27#{m[2].strip}\x27,"'
-
1
HTTP_STATUS_CODES = {
-
100 => 'Continue',
-
101 => 'Switching Protocols',
-
102 => 'Processing',
-
200 => 'OK',
-
201 => 'Created',
-
202 => 'Accepted',
-
203 => 'Non-Authoritative Information',
-
204 => 'No Content',
-
205 => 'Reset Content',
-
206 => 'Partial Content',
-
207 => 'Multi-Status',
-
208 => 'Already Reported',
-
226 => 'IM Used',
-
300 => 'Multiple Choices',
-
301 => 'Moved Permanently',
-
302 => 'Found',
-
303 => 'See Other',
-
304 => 'Not Modified',
-
305 => 'Use Proxy',
-
307 => 'Temporary Redirect',
-
308 => 'Permanent Redirect',
-
400 => 'Bad Request',
-
401 => 'Unauthorized',
-
402 => 'Payment Required',
-
403 => 'Forbidden',
-
404 => 'Not Found',
-
405 => 'Method Not Allowed',
-
406 => 'Not Acceptable',
-
407 => 'Proxy Authentication Required',
-
408 => 'Request Timeout',
-
409 => 'Conflict',
-
410 => 'Gone',
-
411 => 'Length Required',
-
412 => 'Precondition Failed',
-
413 => 'Payload Too Large',
-
414 => 'URI Too Long',
-
415 => 'Unsupported Media Type',
-
416 => 'Range Not Satisfiable',
-
417 => 'Expectation Failed',
-
422 => 'Unprocessable Entity',
-
423 => 'Locked',
-
424 => 'Failed Dependency',
-
426 => 'Upgrade Required',
-
428 => 'Precondition Required',
-
429 => 'Too Many Requests',
-
431 => 'Request Header Fields Too Large',
-
500 => 'Internal Server Error',
-
501 => 'Not Implemented',
-
502 => 'Bad Gateway',
-
503 => 'Service Unavailable',
-
504 => 'Gateway Timeout',
-
505 => 'HTTP Version Not Supported',
-
506 => 'Variant Also Negotiates',
-
507 => 'Insufficient Storage',
-
508 => 'Loop Detected',
-
510 => 'Not Extended',
-
511 => 'Network Authentication Required'
-
}
-
-
# Responses with HTTP status codes that should not have an entity body
-
1
STATUS_WITH_NO_ENTITY_BODY = Set.new((100..199).to_a << 204 << 205 << 304)
-
-
1
SYMBOL_TO_STATUS_CODE = Hash[*HTTP_STATUS_CODES.map { |code, message|
-
57
[message.downcase.gsub(/\s|-|'/, '_').to_sym, code]
-
}.flatten]
-
-
1
def status_code(status)
-
77
if status.is_a?(Symbol)
-
SYMBOL_TO_STATUS_CODE[status] || 500
-
else
-
77
status.to_i
-
end
-
end
-
1
module_function :status_code
-
-
1
Multipart = Rack::Multipart
-
-
1
PATH_SEPS = Regexp.union(*[::File::SEPARATOR, ::File::ALT_SEPARATOR].compact)
-
-
1
def clean_path_info(path_info)
-
165
parts = path_info.split PATH_SEPS
-
-
165
clean = []
-
-
165
parts.each do |part|
-
493
next if part.empty? || part == '.'
-
328
part == '..' ? clean.pop : clean << part
-
end
-
-
165
clean.unshift '/' if parts.empty? || parts.first.empty?
-
-
165
::File.join(*clean)
-
end
-
1
module_function :clean_path_info
-
-
end
-
end
-
1
module Rack
-
-
1
class MockSession # :nodoc:
-
1
attr_writer :cookie_jar
-
1
attr_reader :default_host
-
-
1
def initialize(app, default_host = Rack::Test::DEFAULT_HOST)
-
19
@app = app
-
19
@after_request = []
-
19
@default_host = default_host
-
19
@last_request = nil
-
19
@last_response = nil
-
end
-
-
1
def after_request(&block)
-
@after_request << block
-
end
-
-
1
def clear_cookies
-
@cookie_jar = Rack::Test::CookieJar.new([], @default_host)
-
end
-
-
1
def set_cookie(cookie, uri = nil)
-
cookie_jar.merge(cookie, uri)
-
end
-
-
1
def request(uri, env)
-
66
env["HTTP_COOKIE"] ||= cookie_jar.for(uri)
-
66
@last_request = Rack::Request.new(env)
-
66
status, headers, body = @app.call(@last_request.env)
-
-
66
@last_response = MockResponse.new(status, headers, body, env["rack.errors"].flush)
-
66
body.close if body.respond_to?(:close)
-
-
66
cookie_jar.merge(last_response.headers["Set-Cookie"], uri)
-
-
66
@after_request.each { |hook| hook.call }
-
-
66
if @last_response.respond_to?(:finish)
-
66
@last_response.finish
-
else
-
@last_response
-
end
-
end
-
-
# Return the last request issued in the session. Raises an error if no
-
# requests have been sent yet.
-
1
def last_request
-
67
raise Rack::Test::Error.new("No request yet. Request a page first.") unless @last_request
-
67
@last_request
-
end
-
-
# Return the last response received in the session. Raises an error if
-
# no requests have been sent yet.
-
1
def last_response
-
608
raise Rack::Test::Error.new("No response yet. Request a page first.") unless @last_response
-
590
@last_response
-
end
-
-
1
def cookie_jar
-
132
@cookie_jar ||= Rack::Test::CookieJar.new([], @default_host)
-
end
-
-
end
-
-
end
-
1
require "uri"
-
1
require "rack"
-
1
require "rack/mock_session"
-
1
require "rack/test/cookie_jar"
-
1
require "rack/test/mock_digest_request"
-
1
require "rack/test/utils"
-
1
require "rack/test/methods"
-
1
require "rack/test/uploaded_file"
-
-
1
module Rack
-
1
module Test
-
1
VERSION = "0.6.3"
-
-
1
DEFAULT_HOST = "example.org"
-
1
MULTIPART_BOUNDARY = "----------XnJLe9ZIbbGUYtzPQJ16u1"
-
-
# The common base class for exceptions raised by Rack::Test
-
1
class Error < StandardError; end
-
-
# This class represents a series of requests issued to a Rack app, sharing
-
# a single cookie jar
-
#
-
# Rack::Test::Session's methods are most often called through Rack::Test::Methods,
-
# which will automatically build a session when it's first used.
-
1
class Session
-
1
extend Forwardable
-
1
include Rack::Test::Utils
-
-
1
def_delegators :@rack_mock_session, :clear_cookies, :set_cookie, :last_response, :last_request
-
-
# Creates a Rack::Test::Session for a given Rack app or Rack::MockSession.
-
#
-
# Note: Generally, you won't need to initialize a Rack::Test::Session directly.
-
# Instead, you should include Rack::Test::Methods into your testing context.
-
# (See README.rdoc for an example)
-
1
def initialize(mock_session)
-
19
@headers = {}
-
19
@env = {}
-
-
19
if mock_session.is_a?(MockSession)
-
19
@rack_mock_session = mock_session
-
else
-
@rack_mock_session = MockSession.new(mock_session)
-
end
-
-
19
@default_host = @rack_mock_session.default_host
-
end
-
-
# Issue a GET request for the given URI with the given params and Rack
-
# environment. Stores the issues request object in #last_request and
-
# the app's response in #last_response. Yield #last_response to a block
-
# if given.
-
#
-
# Example:
-
# get "/"
-
1
def get(uri, params = {}, env = {}, &block)
-
55
env = env_for(uri, env.merge(:method => "GET", :params => params))
-
55
process_request(uri, env, &block)
-
end
-
-
# Issue a POST request for the given URI. See #get
-
#
-
# Example:
-
# post "/signup", "name" => "Bryan"
-
1
def post(uri, params = {}, env = {}, &block)
-
11
env = env_for(uri, env.merge(:method => "POST", :params => params))
-
11
process_request(uri, env, &block)
-
end
-
-
# Issue a PUT request for the given URI. See #get
-
#
-
# Example:
-
# put "/"
-
1
def put(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "PUT", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a PATCH request for the given URI. See #get
-
#
-
# Example:
-
# patch "/"
-
1
def patch(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "PATCH", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a DELETE request for the given URI. See #get
-
#
-
# Example:
-
# delete "/"
-
1
def delete(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "DELETE", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue an OPTIONS request for the given URI. See #get
-
#
-
# Example:
-
# options "/"
-
1
def options(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "OPTIONS", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a HEAD request for the given URI. See #get
-
#
-
# Example:
-
# head "/"
-
1
def head(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "HEAD", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a request to the Rack app for the given URI and optional Rack
-
# environment. Stores the issues request object in #last_request and
-
# the app's response in #last_response. Yield #last_response to a block
-
# if given.
-
#
-
# Example:
-
# request "/"
-
1
def request(uri, env = {}, &block)
-
env = env_for(uri, env)
-
process_request(uri, env, &block)
-
end
-
-
# Set a header to be included on all subsequent requests through the
-
# session. Use a value of nil to remove a previously configured header.
-
#
-
# In accordance with the Rack spec, headers will be included in the Rack
-
# environment hash in HTTP_USER_AGENT form.
-
#
-
# Example:
-
# header "User-Agent", "Firefox"
-
1
def header(name, value)
-
if value.nil?
-
@headers.delete(name)
-
else
-
@headers[name] = value
-
end
-
end
-
-
# Set an env var to be included on all subsequent requests through the
-
# session. Use a value of nil to remove a previously configured env.
-
#
-
# Example:
-
# env "rack.session", {:csrf => 'token'}
-
1
def env(name, value)
-
if value.nil?
-
@env.delete(name)
-
else
-
@env[name] = value
-
end
-
end
-
-
# Set the username and password for HTTP Basic authorization, to be
-
# included in subsequent requests in the HTTP_AUTHORIZATION header.
-
#
-
# Example:
-
# basic_authorize "bryan", "secret"
-
1
def basic_authorize(username, password)
-
encoded_login = ["#{username}:#{password}"].pack("m*")
-
header('Authorization', "Basic #{encoded_login}")
-
end
-
-
1
alias_method :authorize, :basic_authorize
-
-
# Set the username and password for HTTP Digest authorization, to be
-
# included in subsequent requests in the HTTP_AUTHORIZATION header.
-
#
-
# Example:
-
# digest_authorize "bryan", "secret"
-
1
def digest_authorize(username, password)
-
@digest_username = username
-
@digest_password = password
-
end
-
-
# Rack::Test will not follow any redirects automatically. This method
-
# will follow the redirect returned (including setting the Referer header
-
# on the new request) in the last response. If the last response was not
-
# a redirect, an error will be raised.
-
1
def follow_redirect!
-
unless last_response.redirect?
-
raise Error.new("Last response was not a redirect. Cannot follow_redirect!")
-
end
-
-
get(last_response["Location"], {}, { "HTTP_REFERER" => last_request.url })
-
end
-
-
1
private
-
-
1
def env_for(path, env)
-
66
uri = URI.parse(path)
-
66
uri.path = "/#{uri.path}" unless uri.path[0] == ?/
-
66
uri.host ||= @default_host
-
-
66
env = default_env.merge(env)
-
-
66
env["HTTP_HOST"] ||= [uri.host, (uri.port if uri.port != uri.default_port)].compact.join(":")
-
-
66
env.update("HTTPS" => "on") if URI::HTTPS === uri
-
66
env["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" if env[:xhr]
-
-
# TODO: Remove this after Rack 1.1 has been released.
-
# Stringifying and upcasing methods has be commit upstream
-
66
env["REQUEST_METHOD"] ||= env[:method] ? env[:method].to_s.upcase : "GET"
-
-
66
if env["REQUEST_METHOD"] == "GET"
-
# merge :params with the query string
-
55
if params = env[:params]
-
55
params = parse_nested_query(params) if params.is_a?(String)
-
55
params.update(parse_nested_query(uri.query))
-
55
uri.query = build_nested_query(params)
-
end
-
elsif !env.has_key?(:input)
-
11
env["CONTENT_TYPE"] ||= "application/x-www-form-urlencoded"
-
-
11
if env[:params].is_a?(Hash)
-
11
if data = build_multipart(env[:params])
-
env[:input] = data
-
env["CONTENT_LENGTH"] ||= data.length.to_s
-
env["CONTENT_TYPE"] = "multipart/form-data; boundary=#{MULTIPART_BOUNDARY}"
-
else
-
11
env[:input] = params_to_string(env[:params])
-
end
-
else
-
env[:input] = env[:params]
-
end
-
end
-
-
66
env.delete(:params)
-
-
66
if env.has_key?(:cookie)
-
set_cookie(env.delete(:cookie), uri)
-
end
-
-
66
Rack::MockRequest.env_for(uri.to_s, env)
-
end
-
-
1
def process_request(uri, env)
-
66
uri = URI.parse(uri)
-
66
uri.host ||= @default_host
-
-
66
@rack_mock_session.request(uri, env)
-
-
66
if retry_with_digest_auth?(env)
-
auth_env = env.merge({
-
"HTTP_AUTHORIZATION" => digest_auth_header,
-
"rack-test.digest_auth_retry" => true
-
})
-
auth_env.delete('rack.request')
-
process_request(uri.path, auth_env)
-
else
-
66
yield last_response if block_given?
-
-
66
last_response
-
end
-
end
-
-
1
def digest_auth_header
-
challenge = last_response["WWW-Authenticate"].split(" ", 2).last
-
params = Rack::Auth::Digest::Params.parse(challenge)
-
-
params.merge!({
-
"username" => @digest_username,
-
"nc" => "00000001",
-
"cnonce" => "nonsensenonce",
-
"uri" => last_request.fullpath,
-
"method" => last_request.env["REQUEST_METHOD"],
-
})
-
-
params["response"] = MockDigestRequest.new(params).response(@digest_password)
-
-
"Digest #{params}"
-
end
-
-
1
def retry_with_digest_auth?(env)
-
last_response.status == 401 &&
-
66
digest_auth_configured? &&
-
!env["rack-test.digest_auth_retry"]
-
end
-
-
1
def digest_auth_configured?
-
@digest_username
-
end
-
-
1
def default_env
-
66
{ "rack.test" => true, "REMOTE_ADDR" => "127.0.0.1" }.merge(@env).merge(headers_for_env)
-
end
-
-
1
def headers_for_env
-
66
converted_headers = {}
-
-
66
@headers.each do |name, value|
-
env_key = name.upcase.gsub("-", "_")
-
env_key = "HTTP_" + env_key unless "CONTENT_TYPE" == env_key
-
converted_headers[env_key] = value
-
end
-
-
66
converted_headers
-
end
-
-
1
def params_to_string(params)
-
11
case params
-
11
when Hash then build_nested_query(params)
-
when nil then ""
-
else params
-
end
-
end
-
-
end
-
-
1
def self.encoding_aware_strings?
-
defined?(Encoding) && "".respond_to?(:encode)
-
end
-
-
end
-
end
-
1
require 'active_support/dependencies/autoload'
-
1
$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/html-scanner"
-
-
1
module HTML
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :CDATA, 'html/node'
-
1
autoload :Document, 'html/document'
-
1
autoload :FullSanitizer, 'html/sanitizer'
-
1
autoload :LinkSanitizer, 'html/sanitizer'
-
1
autoload :Node, 'html/node'
-
1
autoload :Sanitizer, 'html/sanitizer'
-
1
autoload :Selector, 'html/selector'
-
1
autoload :Tag, 'html/node'
-
1
autoload :Text, 'html/node'
-
1
autoload :Tokenizer, 'html/tokenizer'
-
1
autoload :Version, 'html/version'
-
1
autoload :WhiteListSanitizer, 'html/sanitizer'
-
end
-
end
-
1
require 'rails/dom/testing/assertions'
-
1
require 'active_support/concern'
-
1
require 'nokogiri'
-
-
1
module Rails
-
1
module Dom
-
1
module Testing
-
1
module Assertions
-
1
autoload :DomAssertions, 'rails/dom/testing/assertions/dom_assertions'
-
1
autoload :SelectorAssertions, 'rails/dom/testing/assertions/selector_assertions'
-
1
autoload :TagAssertions, 'rails/dom/testing/assertions/tag_assertions'
-
-
1
extend ActiveSupport::Concern
-
-
1
include DomAssertions
-
1
include SelectorAssertions
-
1
include TagAssertions
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
module Dom
-
1
module Testing
-
1
module Assertions
-
1
module DomAssertions
-
# \Test two HTML strings for equivalency (e.g., equal even when attributes are in another order)
-
#
-
# # assert that the referenced method generates the appropriate HTML string
-
# assert_dom_equal '<a href="http://www.example.com">Apples</a>', link_to("Apples", "http://www.example.com")
-
1
def assert_dom_equal(expected, actual, message = nil)
-
expected_dom, actual_dom = fragment(expected), fragment(actual)
-
message ||= "Expected: #{expected}\nActual: #{actual}"
-
assert compare_doms(expected_dom, actual_dom), message
-
end
-
-
# The negated form of +assert_dom_equal+.
-
#
-
# # assert that the referenced method does not generate the specified HTML string
-
# assert_dom_not_equal '<a href="http://www.example.com">Apples</a>', link_to("Oranges", "http://www.example.com")
-
1
def assert_dom_not_equal(expected, actual, message = nil)
-
expected_dom, actual_dom = fragment(expected), fragment(actual)
-
message ||= "Expected: #{expected}\nActual: #{actual}"
-
assert_not compare_doms(expected_dom, actual_dom), message
-
end
-
-
1
protected
-
-
1
def compare_doms(expected, actual)
-
return false unless expected.children.size == actual.children.size
-
-
expected.children.each_with_index do |child, i|
-
return false unless equal_children?(child, actual.children[i])
-
end
-
-
true
-
end
-
-
1
def equal_children?(child, other_child)
-
return false unless child.type == other_child.type
-
-
if child.element?
-
child.name == other_child.name &&
-
equal_attribute_nodes?(child.attribute_nodes, other_child.attribute_nodes) &&
-
compare_doms(child, other_child)
-
else
-
child.to_s == other_child.to_s
-
end
-
end
-
-
1
def equal_attribute_nodes?(nodes, other_nodes)
-
return false unless nodes.size == other_nodes.size
-
-
nodes = nodes.sort_by(&:name)
-
other_nodes = other_nodes.sort_by(&:name)
-
-
nodes.each_with_index do |attr, i|
-
return false unless equal_attribute?(attr, other_nodes[i])
-
end
-
-
true
-
end
-
-
1
def equal_attribute?(attr, other_attr)
-
attr.name == other_attr.name && attr.value == other_attr.value
-
end
-
-
1
private
-
-
1
def fragment(text)
-
Nokogiri::HTML::DocumentFragment.parse(text)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/deprecation'
-
1
require_relative 'selector_assertions/count_describable'
-
1
require_relative 'selector_assertions/html_selector'
-
-
1
module Rails
-
1
module Dom
-
1
module Testing
-
1
module Assertions
-
# Adds the +assert_select+ method for use in Rails functional
-
# test cases, which can be used to make assertions on the response HTML of a controller
-
# action. You can also call +assert_select+ within another +assert_select+ to
-
# make assertions on elements selected by the enclosing assertion.
-
#
-
# Use +css_select+ to select elements without making an assertions, either
-
# from the response HTML or elements selected by the enclosing assertion.
-
#
-
# In addition to HTML responses, you can make the following assertions:
-
#
-
# * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
-
# * +assert_select_email+ - Assertions on the HTML body of an e-mail.
-
1
module SelectorAssertions
-
-
# Select and return all matching elements.
-
#
-
# If called with a single argument, uses that argument as a selector.
-
# Called without an element +css_select+ selects from
-
# the element returned in +document_root_element+
-
#
-
# The default implementation of +document_root_element+ raises an exception explaining this.
-
#
-
# Returns an empty Nokogiri::XML::NodeSet if no match is found.
-
#
-
# If called with two arguments, uses the first argument as the root
-
# element and the second argument as the selector. Attempts to match the
-
# root element and any of its children.
-
# Returns an empty Nokogiri::XML::NodeSet if no match is found.
-
#
-
# The selector may be a CSS selector expression (String).
-
# css_select returns nil if called with an invalid css selector.
-
#
-
# # Selects all div tags
-
# divs = css_select("div")
-
#
-
# # Selects all paragraph tags and does something interesting
-
# pars = css_select("p")
-
# pars.each do |par|
-
# # Do something fun with paragraphs here...
-
# end
-
#
-
# # Selects all list items in unordered lists
-
# items = css_select("ul>li")
-
#
-
# # Selects all form tags and then all inputs inside the form
-
# forms = css_select("form")
-
# forms.each do |form|
-
# inputs = css_select(form, "input")
-
# ...
-
# end
-
1
def css_select(*args)
-
raise ArgumentError, "you at least need a selector argument" if args.empty?
-
-
root = args.size == 1 ? document_root_element : args.shift
-
-
nodeset(root).css(args.first)
-
rescue Nokogiri::CSS::SyntaxError => e
-
ActiveSupport::Deprecation.warn("The assertion was not run because of an invalid css selector.\n#{e}", caller(2))
-
return
-
end
-
-
# An assertion that selects elements and makes one or more equality tests.
-
#
-
# If the first argument is an element, selects all matching elements
-
# starting from (and including) that element and all its children in
-
# depth-first order.
-
#
-
# If no element is specified +assert_select+ selects from
-
# the element returned in +document_root_element+
-
# unless +assert_select+ is called from within an +assert_select+ block.
-
# Override +document_root_element+ to tell +assert_select+ what to select from.
-
# The default implementation raises an exception explaining this.
-
#
-
# When called with a block +assert_select+ passes an array of selected elements
-
# to the block. Calling +assert_select+ from the block, with no element specified,
-
# runs the assertion on the complete set of elements selected by the enclosing assertion.
-
# Alternatively the array may be iterated through so that +assert_select+ can be called
-
# separately for each element.
-
#
-
#
-
# ==== Example
-
# If the response contains two ordered lists, each with four list elements then:
-
# assert_select "ol" do |elements|
-
# elements.each do |element|
-
# assert_select element, "li", 4
-
# end
-
# end
-
#
-
# will pass, as will:
-
# assert_select "ol" do
-
# assert_select "li", 8
-
# end
-
#
-
# The selector may be a CSS selector expression (String) or an expression
-
# with substitution values (Array).
-
# Substitution uses a custom pseudo class match. Pass in whatever attribute you want to match (enclosed in quotes) and a ? for the substitution.
-
# assert_select returns nil if called with an invalid css selector.
-
#
-
# assert_select "div:match('id', ?)", /\d+/
-
#
-
# === Equality Tests
-
#
-
# The equality test may be one of the following:
-
# * <tt>true</tt> - Assertion is true if at least one element selected.
-
# * <tt>false</tt> - Assertion is true if no element selected.
-
# * <tt>String/Regexp</tt> - Assertion is true if the text value of at least
-
# one element matches the string or regular expression.
-
# * <tt>Integer</tt> - Assertion is true if exactly that number of
-
# elements are selected.
-
# * <tt>Range</tt> - Assertion is true if the number of selected
-
# elements fit the range.
-
# If no equality test specified, the assertion is true if at least one
-
# element selected.
-
#
-
# To perform more than one equality tests, use a hash with the following keys:
-
# * <tt>:text</tt> - Narrow the selection to elements that have this text
-
# value (string or regexp).
-
# * <tt>:html</tt> - Narrow the selection to elements that have this HTML
-
# content (string or regexp).
-
# * <tt>:count</tt> - Assertion is true if the number of selected elements
-
# is equal to this value.
-
# * <tt>:minimum</tt> - Assertion is true if the number of selected
-
# elements is at least this value.
-
# * <tt>:maximum</tt> - Assertion is true if the number of selected
-
# elements is at most this value.
-
#
-
# If the method is called with a block, once all equality tests are
-
# evaluated the block is called with an array of all matched elements.
-
#
-
# # At least one form element
-
# assert_select "form"
-
#
-
# # Form element includes four input fields
-
# assert_select "form input", 4
-
#
-
# # Page title is "Welcome"
-
# assert_select "title", "Welcome"
-
#
-
# # Page title is "Welcome" and there is only one title element
-
# assert_select "title", {count: 1, text: "Welcome"},
-
# "Wrong title or more than one title element"
-
#
-
# # Page contains no forms
-
# assert_select "form", false, "This page must contain no forms"
-
#
-
# # Test the content and style
-
# assert_select "body div.header ul.menu"
-
#
-
# # Use substitution values
-
# assert_select "ol>li:match('id', ?)", /item-\d+/
-
#
-
# # All input fields in the form have a name
-
# assert_select "form input" do
-
# assert_select ":match('name', ?)", /.+/ # Not empty
-
# end
-
1
def assert_select(*args, &block)
-
@selected ||= nil
-
-
selector = HTMLSelector.new(args, @selected) { nodeset document_root_element }
-
-
if selecting_no_body?(selector)
-
assert true
-
return
-
end
-
-
selector.select.tap do |matches|
-
assert_size_match!(matches.size, selector.tests, selector.selector, selector.message)
-
-
nest_selection(matches, &block) if block_given? && !matches.empty?
-
end
-
rescue Nokogiri::CSS::SyntaxError => e
-
ActiveSupport::Deprecation.warn("The assertion was not run because of an invalid css selector.\n#{e}", caller(2))
-
return
-
end
-
-
# Extracts the content of an element, treats it as encoded HTML and runs
-
# nested assertion on it.
-
#
-
# You typically call this method within another assertion to operate on
-
# all currently selected elements. You can also pass an element or array
-
# of elements.
-
#
-
# The content of each element is un-encoded, and wrapped in the root
-
# element +encoded+. It then calls the block with all un-encoded elements.
-
#
-
# # Selects all bold tags from within the title of an Atom feed's entries (perhaps to nab a section name prefix)
-
# assert_select "feed[xmlns='http://www.w3.org/2005/Atom']" do
-
# # Select each entry item and then the title item
-
# assert_select "entry>title" do
-
# # Run assertions on the encoded title elements
-
# assert_select_encoded do
-
# assert_select "b"
-
# end
-
# end
-
# end
-
#
-
#
-
# # Selects all paragraph tags from within the description of an RSS feed
-
# assert_select "rss[version=2.0]" do
-
# # Select description element of each feed item.
-
# assert_select "channel>item>description" do
-
# # Run assertions on the encoded elements.
-
# assert_select_encoded do
-
# assert_select "p"
-
# end
-
# end
-
# end
-
1
def assert_select_encoded(element = nil, &block)
-
if !element && !@selected
-
raise ArgumentError, "Element is required when called from a nonnested assert_select"
-
end
-
-
content = nodeset(element || @selected).map do |elem|
-
elem.children.select(&:cdata?).map(&:content)
-
end.join
-
-
selected = Nokogiri::HTML::DocumentFragment.parse(content)
-
nest_selection(selected) do
-
if content.empty?
-
yield selected
-
else
-
assert_select ":root", &block
-
end
-
end
-
end
-
-
# Extracts the body of an email and runs nested assertions on it.
-
#
-
# You must enable deliveries for this assertion to work, use:
-
# ActionMailer::Base.perform_deliveries = true
-
#
-
# assert_select_email do
-
# assert_select "h1", "Email alert"
-
# end
-
#
-
# assert_select_email do
-
# items = assert_select "ol>li"
-
# items.each do
-
# # Work with items here...
-
# end
-
# end
-
1
def assert_select_email(&block)
-
deliveries = ActionMailer::Base.deliveries
-
assert !deliveries.empty?, "No e-mail in delivery list"
-
-
deliveries.each do |delivery|
-
(delivery.parts.empty? ? [delivery] : delivery.parts).each do |part|
-
if part["Content-Type"].to_s =~ /^text\/html\W/
-
root = Nokogiri::HTML::DocumentFragment.parse(part.body.to_s)
-
assert_select root, ":root", &block
-
end
-
end
-
end
-
end
-
-
1
private
-
1
include CountDescribable
-
-
1
def document_root_element
-
raise NotImplementedError, 'Implementing document_root_element makes ' \
-
'assert_select work without needing to specify an element to select from.'
-
end
-
-
# +equals+ must contain :minimum, :maximum and :count keys
-
1
def assert_size_match!(size, equals, css_selector, message = nil)
-
min, max, count = equals[:minimum], equals[:maximum], equals[:count]
-
-
message ||= %(Expected #{count_description(min, max, count)} matching "#{css_selector}", found #{size}.)
-
if count
-
assert_equal count, size, message
-
else
-
assert_operator size, :>=, min, message if min
-
assert_operator size, :<=, max, message if max
-
end
-
end
-
-
1
def selecting_no_body?(html_selector)
-
# Nokogiri gives the document a body element. Which means we can't
-
# run an assertion expecting there to not be a body.
-
html_selector.selector == 'body' && html_selector.tests[:count] == 0
-
end
-
-
1
def nest_selection(selection)
-
# Set @selected to allow nested assert_select.
-
# Can be nested several levels deep.
-
old_selected, @selected = @selected, selection
-
yield @selected
-
ensure
-
@selected = old_selected
-
end
-
-
1
def nodeset(node)
-
if node.is_a?(Nokogiri::XML::NodeSet)
-
node
-
else
-
Nokogiri::XML::NodeSet.new(node.document, [node])
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
-
1
module Rails
-
1
module Dom
-
1
module Testing
-
1
module Assertions
-
1
module SelectorAssertions
-
1
module CountDescribable
-
1
extend ActiveSupport::Concern
-
-
1
private
-
1
def count_description(min, max, count) #:nodoc:
-
if min && max && (max != min)
-
"between #{min} and #{max} elements"
-
elsif min && max && max == min && count
-
"exactly #{count} #{pluralize_element(min)}"
-
elsif min && !(min == 1 && max == 1)
-
"at least #{min} #{pluralize_element(min)}"
-
elsif max
-
"at most #{max} #{pluralize_element(max)}"
-
end
-
end
-
-
1
def pluralize_element(quantity)
-
quantity == 1 ? 'element' : 'elements'
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require_relative 'substitution_context'
-
-
1
class HTMLSelector #:nodoc:
-
1
attr_reader :selector, :tests, :message
-
-
1
def initialize(values, previous_selection = nil, &root_fallback)
-
@values = values
-
@root = extract_root(previous_selection, root_fallback)
-
@selector = extract_selector
-
@tests = extract_equality_tests
-
@message = @values.shift
-
-
if @values.shift
-
raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
-
end
-
end
-
-
1
def select
-
filter @root.css(selector, context)
-
end
-
-
1
private
-
-
1
NO_STRIP = %w{pre script style textarea}
-
-
2
mattr_reader(:context) { SubstitutionContext.new }
-
-
1
def filter(matches)
-
match_with = tests[:text] || tests[:html]
-
return matches if matches.empty? || !match_with
-
-
content_mismatch = nil
-
text_matches = tests.has_key?(:text)
-
regex_matching = match_with.is_a?(Regexp)
-
-
remaining = matches.reject do |match|
-
# Preserve markup with to_s for html elements
-
content = text_matches ? match.text : match.children.to_s
-
-
content.strip! unless NO_STRIP.include?(match.name)
-
content.sub!(/\A\n/, '') if text_matches && match.name == "textarea"
-
-
next if regex_matching ? (content =~ match_with) : (content == match_with)
-
content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, content)
-
true
-
end
-
-
@message ||= content_mismatch if remaining.empty?
-
Nokogiri::XML::NodeSet.new(matches.document, remaining)
-
end
-
-
1
def extract_root(previous_selection, root_fallback)
-
possible_root = @values.first
-
-
if possible_root == nil
-
raise ArgumentError, 'First argument is either selector or element ' \
-
'to select, but nil found. Perhaps you called assert_select with ' \
-
'an element that does not exist?'
-
elsif possible_root.respond_to?(:css)
-
@values.shift # remove the root, so selector is the first argument
-
possible_root
-
elsif previous_selection
-
previous_selection
-
else
-
root_fallback.call
-
end
-
end
-
-
1
def extract_selector
-
selector = @values.shift
-
-
unless selector.is_a? String
-
raise ArgumentError, "Expecting a selector as the first argument"
-
end
-
-
context.substitute!(selector, @values)
-
selector
-
end
-
-
1
def extract_equality_tests
-
comparisons = {}
-
case comparator = @values.shift
-
when Hash
-
comparisons = comparator
-
when String, Regexp
-
comparisons[:text] = comparator
-
when Integer
-
comparisons[:count] = comparator
-
when Range
-
comparisons[:minimum] = comparator.begin
-
comparisons[:maximum] = comparator.end
-
when FalseClass
-
comparisons[:count] = 0
-
when NilClass, TrueClass
-
comparisons[:minimum] = 1
-
else raise ArgumentError, "I don't understand what you're trying to match"
-
end
-
-
# By default we're looking for at least one match.
-
if comparisons[:count]
-
comparisons[:minimum] = comparisons[:maximum] = comparisons[:count]
-
else
-
comparisons[:minimum] ||= 1
-
end
-
comparisons
-
end
-
end
-
1
class SubstitutionContext
-
1
def initialize
-
1
@substitute = '?'
-
end
-
-
1
def substitute!(selector, values)
-
while !values.empty? && substitutable?(values.first) && selector.index(@substitute)
-
selector.sub! @substitute, matcher_for(values.shift)
-
end
-
end
-
-
1
def match(matches, attribute, matcher)
-
matches.find_all { |node| node[attribute] =~ Regexp.new(matcher) }
-
end
-
-
1
private
-
1
def matcher_for(value)
-
value.to_s.inspect # Nokogiri doesn't like arbitrary values without quotes, hence inspect.
-
end
-
-
1
def substitutable?(value)
-
value.is_a?(String) || value.is_a?(Regexp)
-
end
-
end
-
1
require 'active_support/deprecation'
-
1
require 'rails/deprecated_sanitizer/html-scanner'
-
-
1
module Rails
-
1
module Dom
-
1
module Testing
-
1
module Assertions
-
# Pair of assertions to testing elements in the HTML output of the response.
-
1
module TagAssertions
-
# Asserts that there is a tag/node/element in the body of the response
-
# that meets all of the given conditions. The +conditions+ parameter must
-
# be a hash of any of the following keys (all are optional):
-
#
-
# * <tt>:tag</tt>: the node type must match the corresponding value
-
# * <tt>:attributes</tt>: a hash. The node's attributes must match the
-
# corresponding values in the hash.
-
# * <tt>:parent</tt>: a hash. The node's parent must match the
-
# corresponding hash.
-
# * <tt>:child</tt>: a hash. At least one of the node's immediate children
-
# must meet the criteria described by the hash.
-
# * <tt>:ancestor</tt>: a hash. At least one of the node's ancestors must
-
# meet the criteria described by the hash.
-
# * <tt>:descendant</tt>: a hash. At least one of the node's descendants
-
# must meet the criteria described by the hash.
-
# * <tt>:sibling</tt>: a hash. At least one of the node's siblings must
-
# meet the criteria described by the hash.
-
# * <tt>:after</tt>: a hash. The node must be after any sibling meeting
-
# the criteria described by the hash, and at least one sibling must match.
-
# * <tt>:before</tt>: a hash. The node must be before any sibling meeting
-
# the criteria described by the hash, and at least one sibling must match.
-
# * <tt>:children</tt>: a hash, for counting children of a node. Accepts
-
# the keys:
-
# * <tt>:count</tt>: either a number or a range which must equal (or
-
# include) the number of children that match.
-
# * <tt>:less_than</tt>: the number of matching children must be less
-
# than this number.
-
# * <tt>:greater_than</tt>: the number of matching children must be
-
# greater than this number.
-
# * <tt>:only</tt>: another hash consisting of the keys to use
-
# to match on the children, and only matching children will be
-
# counted.
-
# * <tt>:content</tt>: the textual content of the node must match the
-
# given value. This will not match HTML tags in the body of a
-
# tag--only text.
-
#
-
# Conditions are matched using the following algorithm:
-
#
-
# * if the condition is a string, it must be a substring of the value.
-
# * if the condition is a regexp, it must match the value.
-
# * if the condition is a number, the value must match number.to_s.
-
# * if the condition is +true+, the value must not be +nil+.
-
# * if the condition is +false+ or +nil+, the value must be +nil+.
-
#
-
# # Assert that there is a "span" tag
-
# assert_tag tag: "span"
-
#
-
# # Assert that there is a "span" tag with id="x"
-
# assert_tag tag: "span", attributes: { id: "x" }
-
#
-
# # Assert that there is a "span" tag using the short-hand
-
# assert_tag :span
-
#
-
# # Assert that there is a "span" tag with id="x" using the short-hand
-
# assert_tag :span, attributes: { id: "x" }
-
#
-
# # Assert that there is a "span" inside of a "div"
-
# assert_tag tag: "span", parent: { tag: "div" }
-
#
-
# # Assert that there is a "span" somewhere inside a table
-
# assert_tag tag: "span", ancestor: { tag: "table" }
-
#
-
# # Assert that there is a "span" with at least one "em" child
-
# assert_tag tag: "span", child: { tag: "em" }
-
#
-
# # Assert that there is a "span" containing a (possibly nested)
-
# # "strong" tag.
-
# assert_tag tag: "span", descendant: { tag: "strong" }
-
#
-
# # Assert that there is a "span" containing between 2 and 4 "em" tags
-
# # as immediate children
-
# assert_tag tag: "span",
-
# children: { count: 2..4, only: { tag: "em" } }
-
#
-
# # Get funky: assert that there is a "div", with an "ul" ancestor
-
# # and an "li" parent (with "class" = "enum"), and containing a
-
# # "span" descendant that contains text matching /hello world/
-
# assert_tag tag: "div",
-
# ancestor: { tag: "ul" },
-
# parent: { tag: "li",
-
# attributes: { class: "enum" } },
-
# descendant: { tag: "span",
-
# child: /hello world/ }
-
#
-
# <b>Please note</b>: +assert_tag+ and +assert_no_tag+ only work
-
# with well-formed XHTML. They recognize a few tags as implicitly self-closing
-
# (like br and hr and such) but will not work correctly with tags
-
# that allow optional closing tags (p, li, td). <em>You must explicitly
-
# close all of your tags to use these assertions.</em>
-
1
def assert_tag(*opts)
-
ActiveSupport::Deprecation.warn("assert_tag is deprecated and will be removed at Rails 5. Use assert_select to get the same feature.")
-
-
opts = opts.size > 1 ? opts.last.merge({ tag: opts.first.to_s }) : opts.first
-
tag = _find_tag(opts)
-
-
assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
-
end
-
-
# Identical to +assert_tag+, but asserts that a matching tag does _not_
-
# exist. (See +assert_tag+ for a full discussion of the syntax.)
-
#
-
# # Assert that there is not a "div" containing a "p"
-
# assert_no_tag tag: "div", descendant: { tag: "p" }
-
#
-
# # Assert that an unordered list is empty
-
# assert_no_tag tag: "ul", descendant: { tag: "li" }
-
#
-
# # Assert that there is not a "p" tag with between 1 to 3 "img" tags
-
# # as immediate children
-
# assert_no_tag tag: "p",
-
# children: { count: 1..3, only: { tag: "img" } }
-
1
def assert_no_tag(*opts)
-
ActiveSupport::Deprecation.warn("assert_no_tag is deprecated and will be removed at Rails 5. Use assert_select to get the same feature.")
-
-
opts = opts.size > 1 ? opts.last.merge({ tag: opts.first.to_s }) : opts.first
-
tag = _find_tag(opts)
-
-
assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
-
end
-
-
1
def find_tag(conditions)
-
ActiveSupport::Deprecation.warn("find_tag is deprecated and will be removed at Rails 5 without replacement.")
-
-
_find_tag(conditions)
-
end
-
-
1
def find_all_tag(conditions)
-
ActiveSupport::Deprecation.warn("find_all_tag is deprecated and will be removed at Rails 5 without replacement. Use assert_select to get the same feature.")
-
-
html_scanner_document.find_all(conditions)
-
end
-
-
1
private
-
1
def _find_tag(conditions)
-
html_scanner_document.find(conditions)
-
end
-
-
1
def html_scanner_document
-
xml = @response.content_type =~ /xml$/
-
@html_scanner_document ||= HTML::Document.new(@response.body, false, xml)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require "rails/html/sanitizer/version"
-
1
require "loofah"
-
1
require "rails/html/scrubbers"
-
1
require "rails/html/sanitizer"
-
-
1
module Rails
-
1
module Html
-
1
class Sanitizer
-
1
class << self
-
1
def full_sanitizer
-
Html::FullSanitizer
-
end
-
-
1
def link_sanitizer
-
Html::LinkSanitizer
-
end
-
-
1
def white_list_sanitizer
-
Html::WhiteListSanitizer
-
end
-
end
-
end
-
end
-
end
-
-
1
module ActionView
-
1
module Helpers
-
1
module SanitizeHelper
-
1
module ClassMethods
-
# Replaces the allowed tags for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
-
# end
-
#
-
1
def sanitized_allowed_tags=(tags)
-
sanitizer_vendor.white_list_sanitizer.allowed_tags = tags
-
end
-
-
# Replaces the allowed HTML attributes for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_attributes = ['onclick', 'longdesc']
-
# end
-
#
-
1
def sanitized_allowed_attributes=(attributes)
-
sanitizer_vendor.white_list_sanitizer.allowed_attributes = attributes
-
end
-
-
[:protocol_separator,
-
:uri_attributes,
-
:bad_tags,
-
:allowed_css_properties,
-
:allowed_css_keywords,
-
:shorthand_css_properties,
-
1
:allowed_protocols].each do |meth|
-
7
meth_name = "sanitized_#{meth}"
-
-
7
define_method(meth_name) { deprecate_option(meth_name) }
-
7
define_method("#{meth_name}=") { |_| deprecate_option("#{meth_name}=") }
-
end
-
-
1
private
-
1
def deprecate_option(name)
-
ActiveSupport::Deprecation.warn "The #{name} option is deprecated " \
-
"and has no effect. Until Rails 5 the old behavior can still be " \
-
"installed. To do this add the `rails-deprecated-sanitizer` to " \
-
"your Gemfile. Consult the Rails 4.2 upgrade guide for more information."
-
end
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
module Html
-
1
XPATHS_TO_REMOVE = %w{.//script .//form comment()}
-
-
1
class Sanitizer # :nodoc:
-
1
def sanitize(html, options = {})
-
raise NotImplementedError, "subclasses must implement sanitize method."
-
end
-
-
1
private
-
-
1
def remove_xpaths(node, xpaths)
-
node.xpath(*xpaths).remove
-
node
-
end
-
-
1
def properly_encode(fragment, options)
-
fragment.xml? ? fragment.to_xml(options) : fragment.to_html(options)
-
end
-
end
-
-
# === Rails::Html::FullSanitizer
-
# Removes all tags but strips out scripts, forms and comments.
-
#
-
# full_sanitizer = Rails::Html::FullSanitizer.new
-
# full_sanitizer.sanitize("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
-
# # => Bold no more! See more here...
-
1
class FullSanitizer < Sanitizer
-
1
def sanitize(html, options = {})
-
return unless html
-
return html if html.empty?
-
-
loofah_fragment = Loofah.fragment(html)
-
-
remove_xpaths(loofah_fragment, XPATHS_TO_REMOVE)
-
loofah_fragment.scrub!(TextOnlyScrubber.new)
-
-
properly_encode(loofah_fragment, encoding: 'UTF-8')
-
end
-
end
-
-
# === Rails::Html::LinkSanitizer
-
# Removes a tags and href attributes leaving only the link text
-
#
-
# link_sanitizer = Rails::Html::LinkSanitizer.new
-
# link_sanitizer.sanitize('<a href="example.com">Only the link text will be kept.</a>')
-
# # => Only the link text will be kept.
-
1
class LinkSanitizer < Sanitizer
-
1
def initialize
-
@link_scrubber = TargetScrubber.new
-
@link_scrubber.tags = %w(a href)
-
@link_scrubber.attributes = %w(href)
-
end
-
-
1
def sanitize(html, options = {})
-
Loofah.scrub_fragment(html, @link_scrubber).to_s
-
end
-
end
-
-
# === Rails::Html::WhiteListSanitizer
-
# Sanitizes html and css from an extensive white list (see link further down).
-
#
-
# === Whitespace
-
# We can't make any guarentees about whitespace being kept or stripped.
-
# Loofah uses Nokogiri, which wraps either a C or Java parser for the
-
# respective Ruby implementation.
-
# Those two parsers determine how whitespace is ultimately handled.
-
#
-
# When the stripped markup will be rendered the users browser won't take
-
# whitespace into account anyway. It might be better to suggest your users
-
# wrap their whitespace sensitive content in pre tags or that you do
-
# so automatically.
-
#
-
# === Options
-
# Sanitizes both html and css via the white lists found here:
-
# https://github.com/flavorjones/loofah/blob/master/lib/loofah/html5/whitelist.rb
-
#
-
# WhiteListSanitizer also accepts options to configure
-
# the white list used when sanitizing html.
-
# There's a class level option:
-
# Rails::Html::WhiteListSanitizer.allowed_tags = %w(table tr td)
-
# Rails::Html::WhiteListSanitizer.allowed_attributes = %w(id class style)
-
#
-
# Tags and attributes can also be passed to +sanitize+.
-
# Passed options take precedence over the class level options.
-
#
-
# === Examples
-
# white_list_sanitizer = Rails::Html::WhiteListSanitizer.new
-
#
-
# Sanitize css doesn't take options
-
# white_list_sanitizer.sanitize_css('background-color: #000;')
-
#
-
# Default: sanitize via a extensive white list of allowed elements
-
# white_list_sanitizer.sanitize(@article.body)
-
#
-
# White list via the supplied tags and attributes
-
# white_list_sanitizer.sanitize(@article.body, tags: %w(table tr td),
-
# attributes: %w(id class style))
-
#
-
# White list via a custom scrubber
-
# white_list_sanitizer.sanitize(@article.body, scrubber: ArticleScrubber.new)
-
1
class WhiteListSanitizer < Sanitizer
-
1
class << self
-
1
attr_accessor :allowed_tags
-
1
attr_accessor :allowed_attributes
-
end
-
1
self.allowed_tags = Set.new(%w(strong em b i p code pre tt samp kbd var sub
-
sup dfn cite big small address hr br div span h1 h2 h3 h4 h5 h6 ul ol li dl dt dd abbr
-
acronym a img blockquote del ins))
-
1
self.allowed_attributes = Set.new(%w(href src width height alt cite datetime title class name xml:lang abbr))
-
-
1
def initialize
-
@permit_scrubber = PermitScrubber.new
-
end
-
-
1
def sanitize(html, options = {})
-
return unless html
-
return html if html.empty?
-
-
loofah_fragment = Loofah.fragment(html)
-
-
if scrubber = options[:scrubber]
-
# No duck typing, Loofah ensures subclass of Loofah::Scrubber
-
loofah_fragment.scrub!(scrubber)
-
elsif allowed_tags(options) || allowed_attributes(options)
-
@permit_scrubber.tags = allowed_tags(options)
-
@permit_scrubber.attributes = allowed_attributes(options)
-
loofah_fragment.scrub!(@permit_scrubber)
-
else
-
remove_xpaths(loofah_fragment, XPATHS_TO_REMOVE)
-
loofah_fragment.scrub!(:strip)
-
end
-
-
properly_encode(loofah_fragment, encoding: 'UTF-8')
-
end
-
-
1
def sanitize_css(style_string)
-
Loofah::HTML5::Scrub.scrub_css(style_string)
-
end
-
-
1
private
-
-
1
def allowed_tags(options)
-
options[:tags] || self.class.allowed_tags
-
end
-
-
1
def allowed_attributes(options)
-
options[:attributes] || self.class.allowed_attributes
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
module Html
-
1
class Sanitizer
-
1
VERSION = "1.0.3"
-
end
-
end
-
end
-
1
module Rails
-
1
module Html
-
# === Rails::Html::PermitScrubber
-
#
-
# Rails::Html::PermitScrubber allows you to permit only your own tags and/or attributes.
-
#
-
# Rails::Html::PermitScrubber can be subclassed to determine:
-
# - When a node should be skipped via +skip_node?+.
-
# - When a node is allowed via +allowed_node?+.
-
# - When an attribute should be scrubbed via +scrub_attribute?+.
-
#
-
# Subclasses don't need to worry if tags or attributes are set or not.
-
# If tags or attributes are not set, Loofah's behavior will be used.
-
# If you override +allowed_node?+ and no tags are set, it will not be called.
-
# Instead Loofahs behavior will be used.
-
# Likewise for +scrub_attribute?+ and attributes respectively.
-
#
-
# Text and CDATA nodes are skipped by default.
-
# Unallowed elements will be stripped, i.e. element is removed but its subtree kept.
-
# Supplied tags and attributes should be Enumerables.
-
#
-
# +tags=+
-
# If set, elements excluded will be stripped.
-
# If not, elements are stripped based on Loofahs +HTML5::Scrub.allowed_element?+.
-
#
-
# +attributes=+
-
# If set, attributes excluded will be removed.
-
# If not, attributes are removed based on Loofahs +HTML5::Scrub.scrub_attributes+.
-
#
-
# class CommentScrubber < Html::PermitScrubber
-
# def allowed_node?(node)
-
# !%w(form script comment blockquote).include?(node.name)
-
# end
-
#
-
# def skip_node?(node)
-
# node.text?
-
# end
-
#
-
# def scrub_attribute?(name)
-
# name == "style"
-
# end
-
# end
-
#
-
# See the documentation for Nokogiri::XML::Node to understand what's possible
-
# with nodes: http://nokogiri.org/Nokogiri/XML/Node.html
-
1
class PermitScrubber < Loofah::Scrubber
-
1
attr_reader :tags, :attributes
-
-
1
def initialize
-
@direction = :bottom_up
-
@tags, @attributes = nil, nil
-
end
-
-
1
def tags=(tags)
-
@tags = validate!(tags, :tags)
-
end
-
-
1
def attributes=(attributes)
-
@attributes = validate!(attributes, :attributes)
-
end
-
-
1
def scrub(node)
-
if node.cdata?
-
text = node.document.create_text_node node.text
-
node.replace text
-
return CONTINUE
-
end
-
return CONTINUE if skip_node?(node)
-
-
unless keep_node?(node)
-
return STOP if scrub_node(node) == STOP
-
end
-
-
scrub_attributes(node)
-
end
-
-
1
protected
-
-
1
def allowed_node?(node)
-
@tags.include?(node.name)
-
end
-
-
1
def skip_node?(node)
-
node.text?
-
end
-
-
1
def scrub_attribute?(name)
-
!@attributes.include?(name)
-
end
-
-
1
def keep_node?(node)
-
if @tags
-
allowed_node?(node)
-
else
-
Loofah::HTML5::Scrub.allowed_element?(node.name)
-
end
-
end
-
-
1
def scrub_node(node)
-
node.before(node.children) # strip
-
node.remove
-
end
-
-
1
def scrub_attributes(node)
-
if @attributes
-
node.attribute_nodes.each do |attr|
-
attr.remove if scrub_attribute?(attr.name)
-
scrub_attribute(node, attr)
-
end
-
-
scrub_css_attribute(node)
-
else
-
Loofah::HTML5::Scrub.scrub_attributes(node)
-
end
-
end
-
-
1
def scrub_css_attribute(node)
-
if Loofah::HTML5::Scrub.respond_to?(:scrub_css_attribute)
-
Loofah::HTML5::Scrub.scrub_css_attribute(node)
-
else
-
style = node.attributes['style']
-
style.value = Loofah::HTML5::Scrub.scrub_css(style.value) if style
-
end
-
end
-
-
1
def validate!(var, name)
-
if var && !var.is_a?(Enumerable)
-
raise ArgumentError, "You should pass :#{name} as an Enumerable"
-
end
-
var
-
end
-
-
1
def scrub_attribute(node, attr_node)
-
attr_name = if attr_node.namespace
-
"#{attr_node.namespace.prefix}:#{attr_node.node_name}"
-
else
-
attr_node.node_name
-
end
-
-
if Loofah::HTML5::WhiteList::ATTR_VAL_IS_URI.include?(attr_name)
-
# this block lifted nearly verbatim from HTML5 sanitization
-
val_unescaped = CGI.unescapeHTML(attr_node.value).gsub(Loofah::HTML5::Scrub::CONTROL_CHARACTERS,'').downcase
-
if val_unescaped =~ /^[a-z0-9][-+.a-z0-9]*:/ && ! Loofah::HTML5::WhiteList::ALLOWED_PROTOCOLS.include?(val_unescaped.split(Loofah::HTML5::WhiteList::PROTOCOL_SEPARATOR)[0])
-
attr_node.remove
-
end
-
end
-
if Loofah::HTML5::WhiteList::SVG_ATTR_VAL_ALLOWS_REF.include?(attr_name)
-
attr_node.value = attr_node.value.gsub(/url\s*\(\s*[^#\s][^)]+?\)/m, ' ') if attr_node.value
-
end
-
if Loofah::HTML5::WhiteList::SVG_ALLOW_LOCAL_HREF.include?(node.name) && attr_name == 'xlink:href' && attr_node.value =~ /^\s*[^#\s].*/m
-
attr_node.remove
-
end
-
-
node.remove_attribute(attr_node.name) if attr_name == 'src' && attr_node.value !~ /[^[:space:]]/
-
end
-
end
-
-
# === Rails::Html::TargetScrubber
-
#
-
# Where Rails::Html::PermitScrubber picks out tags and attributes to permit in
-
# sanitization, Rails::Html::TargetScrubber targets them for removal.
-
#
-
# +tags=+
-
# If set, elements included will be stripped.
-
#
-
# +attributes=+
-
# If set, attributes included will be removed.
-
1
class TargetScrubber < PermitScrubber
-
1
def allowed_node?(node)
-
!super
-
end
-
-
1
def scrub_attribute?(name)
-
!super
-
end
-
end
-
-
# === Rails::Html::TextOnlyScrubber
-
#
-
# Rails::Html::TextOnlyScrubber allows you to permit text nodes.
-
#
-
# Unallowed elements will be stripped, i.e. element is removed but its subtree kept.
-
1
class TextOnlyScrubber < Loofah::Scrubber
-
1
def initialize
-
@direction = :bottom_up
-
end
-
-
1
def scrub(node)
-
if node.text?
-
CONTINUE
-
else
-
node.before node.children
-
node.remove
-
end
-
end
-
end
-
end
-
end
-
1
require 'rails/ruby_version_check'
-
-
1
require 'pathname'
-
-
1
require 'active_support'
-
1
require 'active_support/dependencies/autoload'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
require 'rails/application'
-
1
require 'rails/version'
-
-
1
require 'active_support/railtie'
-
1
require 'action_dispatch/railtie'
-
-
# For Ruby 1.9, UTF-8 is the default internal and external encoding.
-
1
silence_warnings do
-
1
Encoding.default_external = Encoding::UTF_8
-
1
Encoding.default_internal = Encoding::UTF_8
-
end
-
-
1
module Rails
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Info
-
1
autoload :InfoController
-
1
autoload :MailersController
-
1
autoload :WelcomeController
-
-
1
class << self
-
1
@application = @app_class = nil
-
-
1
attr_writer :application
-
1
attr_accessor :app_class, :cache, :logger
-
1
def application
-
126
@application ||= (app_class.instance if app_class)
-
end
-
-
1
delegate :initialize!, :initialized?, to: :application
-
-
# The Configuration instance used to configure the Rails environment
-
1
def configuration
-
application.config
-
end
-
-
1
def backtrace_cleaner
-
@backtrace_cleaner ||= begin
-
# Relies on Active Support, so we have to lazy load to postpone definition until AS has been loaded
-
1
require 'rails/backtrace_cleaner'
-
1
Rails::BacktraceCleaner.new
-
2
end
-
end
-
-
1
def root
-
57
application && application.config.root
-
end
-
-
1
def env
-
88
@_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
-
end
-
-
1
def env=(environment)
-
@_env = ActiveSupport::StringInquirer.new(environment)
-
end
-
-
# Returns all rails groups for loading based on:
-
#
-
# * The Rails environment;
-
# * The environment variable RAILS_GROUPS;
-
# * The optional envs given as argument and the hash with group dependencies;
-
#
-
# groups assets: [:development, :test]
-
#
-
# # Returns
-
# # => [:default, :development, :assets] for Rails.env == "development"
-
# # => [:default, :production] for Rails.env == "production"
-
1
def groups(*groups)
-
1
hash = groups.extract_options!
-
1
env = Rails.env
-
1
groups.unshift(:default, env)
-
1
groups.concat ENV["RAILS_GROUPS"].to_s.split(",")
-
1
groups.concat hash.map { |k, v| k if v.map(&:to_s).include?(env) }
-
1
groups.compact!
-
1
groups.uniq!
-
1
groups
-
end
-
-
1
def public_path
-
1
application && Pathname.new(application.paths["public"].first)
-
end
-
end
-
end
-
1
require "rails"
-
-
%w(
-
active_record
-
action_controller
-
action_view
-
action_mailer
-
active_job
-
rails/test_unit
-
sprockets
-
1
).each do |framework|
-
7
begin
-
7
require "#{framework}/railtie"
-
rescue LoadError
-
end
-
end
-
1
require 'fileutils'
-
1
require 'yaml'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/key_generator'
-
1
require 'active_support/message_verifier'
-
1
require 'rails/engine'
-
-
1
module Rails
-
# In Rails 3.0, a Rails::Application object was introduced which is nothing more than
-
# an Engine but with the responsibility of coordinating the whole boot process.
-
#
-
# == Initialization
-
#
-
# Rails::Application is responsible for executing all railties and engines
-
# initializers. It also executes some bootstrap initializers (check
-
# Rails::Application::Bootstrap) and finishing initializers, after all the others
-
# are executed (check Rails::Application::Finisher).
-
#
-
# == Configuration
-
#
-
# Besides providing the same configuration as Rails::Engine and Rails::Railtie,
-
# the application object has several specific configurations, for example
-
# "cache_classes", "consider_all_requests_local", "filter_parameters",
-
# "logger" and so forth.
-
#
-
# Check Rails::Application::Configuration to see them all.
-
#
-
# == Routes
-
#
-
# The application object is also responsible for holding the routes and reloading routes
-
# whenever the files change in development.
-
#
-
# == Middlewares
-
#
-
# The Application is also responsible for building the middleware stack.
-
#
-
# == Booting process
-
#
-
# The application is also responsible for setting up and executing the booting
-
# process. From the moment you require "config/application.rb" in your app,
-
# the booting process goes like this:
-
#
-
# 1) require "config/boot.rb" to setup load paths
-
# 2) require railties and engines
-
# 3) Define Rails.application as "class MyApp::Application < Rails::Application"
-
# 4) Run config.before_configuration callbacks
-
# 5) Load config/environments/ENV.rb
-
# 6) Run config.before_initialize callbacks
-
# 7) Run Railtie#initializer defined by railties, engines and application.
-
# One by one, each engine sets up its load paths, routes and runs its config/initializers/* files.
-
# 8) Custom Railtie#initializers added by railties, engines and applications are executed
-
# 9) Build the middleware stack and run to_prepare callbacks
-
# 10) Run config.before_eager_load and eager_load! if eager_load is true
-
# 11) Run config.after_initialize callbacks
-
#
-
# == Multiple Applications
-
#
-
# If you decide to define multiple applications, then the first application
-
# that is initialized will be set to +Rails.application+, unless you override
-
# it with a different application.
-
#
-
# To create a new application, you can instantiate a new instance of a class
-
# that has already been created:
-
#
-
# class Application < Rails::Application
-
# end
-
#
-
# first_application = Application.new
-
# second_application = Application.new(config: first_application.config)
-
#
-
# In the above example, the configuration from the first application was used
-
# to initialize the second application. You can also use the +initialize_copy+
-
# on one of the applications to create a copy of the application which shares
-
# the configuration.
-
#
-
# If you decide to define rake tasks, runners, or initializers in an
-
# application other than +Rails.application+, then you must run those
-
# these manually.
-
1
class Application < Engine
-
1
autoload :Bootstrap, 'rails/application/bootstrap'
-
1
autoload :Configuration, 'rails/application/configuration'
-
1
autoload :DefaultMiddlewareStack, 'rails/application/default_middleware_stack'
-
1
autoload :Finisher, 'rails/application/finisher'
-
1
autoload :Railties, 'rails/engine/railties'
-
1
autoload :RoutesReloader, 'rails/application/routes_reloader'
-
-
1
class << self
-
1
def inherited(base)
-
1
super
-
1
Rails.app_class = base
-
1
add_lib_to_load_path!(find_root(base.called_from))
-
end
-
-
1
def instance
-
2
super.run_load_hooks!
-
end
-
-
1
def create(initial_variable_values = {}, &block)
-
new(initial_variable_values, &block).run_load_hooks!
-
end
-
-
1
def find_root(from)
-
2
find_root_with_flag "config.ru", from, Dir.pwd
-
end
-
-
# Makes the +new+ method public.
-
#
-
# Note that Rails::Application inherits from Rails::Engine, which
-
# inherits from Rails::Railtie and the +new+ method on Rails::Railtie is
-
# private
-
1
public :new
-
end
-
-
1
attr_accessor :assets, :sandbox
-
1
alias_method :sandbox?, :sandbox
-
1
attr_reader :reloaders
-
-
1
delegate :default_url_options, :default_url_options=, to: :routes
-
-
1
INITIAL_VARIABLES = [:config, :railties, :routes_reloader, :reloaders,
-
:routes, :helpers, :app_env_config, :secrets] # :nodoc:
-
-
1
def initialize(initial_variable_values = {}, &block)
-
1
super()
-
1
@initialized = false
-
1
@reloaders = []
-
1
@routes_reloader = nil
-
1
@app_env_config = nil
-
1
@ordered_railties = nil
-
1
@railties = nil
-
1
@message_verifiers = {}
-
1
@ran_load_hooks = false
-
-
# are these actually used?
-
1
@initial_variable_values = initial_variable_values
-
1
@block = block
-
end
-
-
# Returns true if the application is initialized.
-
1
def initialized?
-
@initialized
-
end
-
-
1
def run_load_hooks! # :nodoc:
-
2
return self if @ran_load_hooks
-
1
@ran_load_hooks = true
-
1
ActiveSupport.run_load_hooks(:before_configuration, self)
-
-
1
@initial_variable_values.each do |variable_name, value|
-
if INITIAL_VARIABLES.include?(variable_name)
-
instance_variable_set("@#{variable_name}", value)
-
end
-
end
-
-
1
instance_eval(&@block) if @block
-
1
self
-
end
-
-
# Implements call according to the Rack API. It simply
-
# dispatches the request to the underlying middleware stack.
-
1
def call(env)
-
66
env["ORIGINAL_FULLPATH"] = build_original_fullpath(env)
-
66
env["ORIGINAL_SCRIPT_NAME"] = env["SCRIPT_NAME"]
-
66
super(env)
-
end
-
-
# Reload application routes regardless if they changed or not.
-
1
def reload_routes!
-
routes_reloader.reload!
-
end
-
-
# Return the application's KeyGenerator
-
1
def key_generator
-
# number of iterations selected based on consultation with the google security
-
# team. Details at https://github.com/rails/rails/pull/6952#issuecomment-7661220
-
@caching_key_generator ||=
-
if secrets.secret_key_base
-
1
key_generator = ActiveSupport::KeyGenerator.new(secrets.secret_key_base, iterations: 1000)
-
1
ActiveSupport::CachingKeyGenerator.new(key_generator)
-
else
-
ActiveSupport::LegacyKeyGenerator.new(secrets.secret_token)
-
2
end
-
end
-
-
# Returns a message verifier object.
-
#
-
# This verifier can be used to generate and verify signed messages in the application.
-
#
-
# It is recommended not to use the same verifier for different things, so you can get different
-
# verifiers passing the +verifier_name+ argument.
-
#
-
# ==== Parameters
-
#
-
# * +verifier_name+ - the name of the message verifier.
-
#
-
# ==== Examples
-
#
-
# message = Rails.application.message_verifier('sensitive_data').generate('my sensible data')
-
# Rails.application.message_verifier('sensitive_data').verify(message)
-
# # => 'my sensible data'
-
#
-
# See the +ActiveSupport::MessageVerifier+ documentation for more information.
-
1
def message_verifier(verifier_name)
-
@message_verifiers[verifier_name] ||= begin
-
secret = key_generator.generate_key(verifier_name.to_s)
-
ActiveSupport::MessageVerifier.new(secret)
-
end
-
end
-
-
# Convenience for loading config/foo.yml for the current Rails env.
-
#
-
# Example:
-
#
-
# # config/exception_notification.yml:
-
# production:
-
# url: http://127.0.0.1:8080
-
# namespace: my_app_production
-
# development:
-
# url: http://localhost:3001
-
# namespace: my_app_development
-
#
-
# # config/production.rb
-
# Rails.application.configure do
-
# config.middleware.use ExceptionNotifier, config_for(:exception_notification)
-
# end
-
1
def config_for(name)
-
yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml")
-
-
if yaml.exist?
-
require "erb"
-
(YAML.load(ERB.new(yaml.read).result) || {})[Rails.env] || {}
-
else
-
raise "Could not load configuration. No such file - #{yaml}"
-
end
-
rescue Psych::SyntaxError => e
-
raise "YAML syntax error occurred while parsing #{yaml}. " \
-
"Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
-
"Error: #{e.message}"
-
end
-
-
# Stores some of the Rails initial environment parameters which
-
# will be used by middlewares and engines to configure themselves.
-
1
def env_config
-
@app_env_config ||= begin
-
1
validate_secret_key_config!
-
-
1
super.merge({
-
"action_dispatch.parameter_filter" => config.filter_parameters,
-
"action_dispatch.redirect_filter" => config.filter_redirect,
-
"action_dispatch.secret_token" => secrets.secret_token,
-
"action_dispatch.secret_key_base" => secrets.secret_key_base,
-
"action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
-
"action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
-
"action_dispatch.logger" => Rails.logger,
-
"action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner,
-
"action_dispatch.key_generator" => key_generator,
-
"action_dispatch.http_auth_salt" => config.action_dispatch.http_auth_salt,
-
"action_dispatch.signed_cookie_salt" => config.action_dispatch.signed_cookie_salt,
-
"action_dispatch.encrypted_cookie_salt" => config.action_dispatch.encrypted_cookie_salt,
-
"action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt,
-
"action_dispatch.cookies_serializer" => config.action_dispatch.cookies_serializer,
-
"action_dispatch.cookies_digest" => config.action_dispatch.cookies_digest
-
})
-
66
end
-
end
-
-
# If you try to define a set of rake tasks on the instance, these will get
-
# passed up to the rake tasks defined on the application's class.
-
1
def rake_tasks(&block)
-
self.class.rake_tasks(&block)
-
end
-
-
# Sends the initializers to the +initializer+ method defined in the
-
# Rails::Initializable module. Each Rails::Application class has its own
-
# set of initializers, as defined by the Initializable module.
-
1
def initializer(name, opts={}, &block)
-
self.class.initializer(name, opts, &block)
-
end
-
-
# Sends any runner called in the instance of a new application up
-
# to the +runner+ method defined in Rails::Railtie.
-
1
def runner(&blk)
-
self.class.runner(&blk)
-
end
-
-
# Sends any console called in the instance of a new application up
-
# to the +console+ method defined in Rails::Railtie.
-
1
def console(&blk)
-
self.class.console(&blk)
-
end
-
-
# Sends any generators called in the instance of a new application up
-
# to the +generators+ method defined in Rails::Railtie.
-
1
def generators(&blk)
-
self.class.generators(&blk)
-
end
-
-
# Sends the +isolate_namespace+ method up to the class method.
-
1
def isolate_namespace(mod)
-
self.class.isolate_namespace(mod)
-
end
-
-
## Rails internal API
-
-
# This method is called just after an application inherits from Rails::Application,
-
# allowing the developer to load classes in lib and use them during application
-
# configuration.
-
#
-
# class MyApplication < Rails::Application
-
# require "my_backend" # in lib/my_backend
-
# config.i18n.backend = MyBackend
-
# end
-
#
-
# Notice this method takes into consideration the default root path. So if you
-
# are changing config.root inside your application definition or having a custom
-
# Rails application, you will need to add lib to $LOAD_PATH on your own in case
-
# you need to load files in lib/ during the application configuration as well.
-
1
def self.add_lib_to_load_path!(root) #:nodoc:
-
1
path = File.join root, 'lib'
-
1
if File.exist?(path) && !$LOAD_PATH.include?(path)
-
1
$LOAD_PATH.unshift(path)
-
end
-
end
-
-
1
def require_environment! #:nodoc:
-
environment = paths["config/environment"].existent.first
-
require environment if environment
-
end
-
-
1
def routes_reloader #:nodoc:
-
3
@routes_reloader ||= RoutesReloader.new
-
end
-
-
# Returns an array of file paths appended with a hash of
-
# directories-extensions suitable for ActiveSupport::FileUpdateChecker
-
# API.
-
1
def watchable_args #:nodoc:
-
1
files, dirs = config.watchable_files.dup, config.watchable_dirs.dup
-
-
1
ActiveSupport::Dependencies.autoload_paths.each do |path|
-
7
dirs[path.to_s] = [:rb]
-
end
-
-
1
[files, dirs]
-
end
-
-
# Initialize the application passing the given group. By default, the
-
# group is :default
-
1
def initialize!(group=:default) #:nodoc:
-
1
raise "Application has been already initialized." if @initialized
-
1
run_initializers(group, self)
-
1
@initialized = true
-
1
self
-
end
-
-
1
def initializers #:nodoc:
-
Bootstrap.initializers_for(self) +
-
railties_initializers(super) +
-
1
Finisher.initializers_for(self)
-
end
-
-
1
def config #:nodoc:
-
210
@config ||= Application::Configuration.new(self.class.find_root(self.class.called_from))
-
end
-
-
1
def config=(configuration) #:nodoc:
-
@config = configuration
-
end
-
-
# Returns secrets added to config/secrets.yml.
-
#
-
# Example:
-
#
-
# development:
-
# secret_key_base: 836fa3665997a860728bcb9e9a1e704d427cfc920e79d847d79c8a9a907b9e965defa4154b2b86bdec6930adbe33f21364523a6f6ce363865724549fdfc08553
-
# test:
-
# secret_key_base: 5a37811464e7d378488b0f073e2193b093682e4e21f5d6f3ae0a4e1781e61a351fdc878a843424e81c73fb484a40d23f92c8dafac4870e74ede6e5e174423010
-
# production:
-
# secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
-
# namespace: my_app_production
-
#
-
# +Rails.application.secrets.namespace+ returns +my_app_production+ in the
-
# production environment.
-
1
def secrets
-
@secrets ||= begin
-
1
secrets = ActiveSupport::OrderedOptions.new
-
1
yaml = config.paths["config/secrets"].first
-
1
if File.exist?(yaml)
-
1
require "erb"
-
1
all_secrets = YAML.load(ERB.new(IO.read(yaml)).result) || {}
-
1
env_secrets = all_secrets[Rails.env]
-
1
secrets.merge!(env_secrets.symbolize_keys) if env_secrets
-
end
-
-
# Fallback to config.secret_key_base if secrets.secret_key_base isn't set
-
1
secrets.secret_key_base ||= config.secret_key_base
-
# Fallback to config.secret_token if secrets.secret_token isn't set
-
1
secrets.secret_token ||= config.secret_token
-
-
1
secrets
-
5
end
-
end
-
-
1
def secrets=(secrets) #:nodoc:
-
@secrets = secrets
-
end
-
-
1
def to_app #:nodoc:
-
self
-
end
-
-
1
def helpers_paths #:nodoc:
-
1
config.helpers_paths
-
end
-
-
1
console do
-
require "pp"
-
end
-
-
1
console do
-
unless ::Kernel.private_method_defined?(:y)
-
if RUBY_VERSION >= '2.0'
-
require "psych/y"
-
else
-
module ::Kernel
-
def y(*objects)
-
puts ::Psych.dump_stream(*objects)
-
end
-
private :y
-
end
-
end
-
end
-
end
-
-
# Return an array of railties respecting the order they're loaded
-
# and the order specified by the +railties_order+ config.
-
#
-
# While when running initializers we need engines in reverse
-
# order here when copying migrations from railties we need then in the same
-
# order as given by +railties_order+
-
1
def migration_railties # :nodoc:
-
ordered_railties.flatten - [self]
-
end
-
-
1
protected
-
-
1
alias :build_middleware_stack :app
-
-
1
def run_tasks_blocks(app) #:nodoc:
-
railties.each { |r| r.run_tasks_blocks(app) }
-
super
-
require "rails/tasks"
-
task :environment do
-
ActiveSupport.on_load(:before_initialize) { config.eager_load = false }
-
-
require_environment!
-
end
-
end
-
-
1
def run_generators_blocks(app) #:nodoc:
-
railties.each { |r| r.run_generators_blocks(app) }
-
super
-
end
-
-
1
def run_runner_blocks(app) #:nodoc:
-
railties.each { |r| r.run_runner_blocks(app) }
-
super
-
end
-
-
1
def run_console_blocks(app) #:nodoc:
-
railties.each { |r| r.run_console_blocks(app) }
-
super
-
end
-
-
# Returns the ordered railties for this application considering railties_order.
-
1
def ordered_railties #:nodoc:
-
@ordered_railties ||= begin
-
1
order = config.railties_order.map do |railtie|
-
1
if railtie == :main_app
-
self
-
elsif railtie.respond_to?(:instance)
-
railtie.instance
-
else
-
1
railtie
-
end
-
end
-
-
1
all = (railties - order)
-
1
all.push(self) unless (all + order).include?(self)
-
1
order.push(:all) unless order.include?(:all)
-
-
1
index = order.index(:all)
-
1
order[index] = all
-
1
order
-
1
end
-
end
-
-
1
def railties_initializers(current) #:nodoc:
-
1
initializers = []
-
1
ordered_railties.reverse.flatten.each do |r|
-
21
if r == self
-
1
initializers += current
-
else
-
20
initializers += r.initializers
-
end
-
end
-
1
initializers
-
end
-
-
1
def default_middleware_stack #:nodoc:
-
1
default_stack = DefaultMiddlewareStack.new(self, config, paths)
-
1
default_stack.build_stack
-
end
-
-
1
def build_original_fullpath(env) #:nodoc:
-
66
path_info = env["PATH_INFO"]
-
66
query_string = env["QUERY_STRING"]
-
66
script_name = env["SCRIPT_NAME"]
-
-
66
if query_string.present?
-
"#{script_name}#{path_info}?#{query_string}"
-
else
-
66
"#{script_name}#{path_info}"
-
end
-
end
-
-
1
def validate_secret_key_config! #:nodoc:
-
1
if secrets.secret_key_base.blank?
-
ActiveSupport::Deprecation.warn "You didn't set `secret_key_base`. " +
-
"Read the upgrade documentation to learn more about this new config option."
-
-
if secrets.secret_token.blank?
-
raise "Missing `secret_token` and `secret_key_base` for '#{Rails.env}' environment, set these values in `config/secrets.yml`"
-
end
-
end
-
end
-
end
-
end
-
1
require "active_support/notifications"
-
1
require "active_support/dependencies"
-
1
require "active_support/deprecation"
-
1
require "active_support/descendants_tracker"
-
-
1
module Rails
-
1
class Application
-
1
module Bootstrap
-
1
include Initializable
-
-
1
initializer :load_environment_hook, group: :all do end
-
-
1
initializer :load_active_support, group: :all do
-
1
require "active_support/all" unless config.active_support.bare
-
end
-
-
1
initializer :set_eager_load, group: :all do
-
1
if config.eager_load.nil?
-
warn <<-INFO
-
config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly:
-
-
* development - set it to false
-
* test - set it to false (unless you use a tool that preloads your test environment)
-
* production - set it to true
-
-
INFO
-
config.eager_load = config.cache_classes
-
end
-
end
-
-
# Initialize the logger early in the stack in case we need to log some deprecation.
-
1
initializer :initialize_logger, group: :all do
-
1
Rails.logger ||= config.logger || begin
-
1
path = config.paths["log"].first
-
1
unless File.exist? File.dirname path
-
FileUtils.mkdir_p File.dirname path
-
end
-
-
1
f = File.open path, 'a'
-
1
f.binmode
-
1
f.sync = config.autoflush_log # if true make sure every write flushes
-
-
1
logger = ActiveSupport::Logger.new f
-
1
logger.formatter = config.log_formatter
-
1
logger = ActiveSupport::TaggedLogging.new(logger)
-
1
logger
-
rescue StandardError
-
logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR))
-
logger.level = ActiveSupport::Logger::WARN
-
logger.warn(
-
"Rails Error: Unable to access log file. Please ensure that #{path} exists and is writable " +
-
"(ie, make it writable for user and group: chmod 0664 #{path}). " +
-
"The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
-
)
-
logger
-
end
-
-
1
if Rails.env.production? && !config.has_explicit_log_level?
-
ActiveSupport::Deprecation.warn \
-
"You did not specify a `log_level` in `production.rb`. Currently, " \
-
"the default value for `log_level` is `:info` for the production " \
-
"environment and `:debug` in all other environments. In Rails 5 " \
-
"the default value will be unified to `:debug` across all " \
-
"environments. To preserve the current setting, add the following " \
-
"line to your `production.rb`:\n" \
-
"\n" \
-
" config.log_level = :info\n\n"
-
end
-
-
1
Rails.logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase)
-
end
-
-
# Initialize cache early in the stack so railties can make use of it.
-
1
initializer :initialize_cache, group: :all do
-
1
unless Rails.cache
-
1
Rails.cache = ActiveSupport::Cache.lookup_store(config.cache_store)
-
-
1
if Rails.cache.respond_to?(:middleware)
-
1
config.middleware.insert_before("Rack::Runtime", Rails.cache.middleware)
-
end
-
end
-
end
-
-
# Sets the dependency loading mechanism.
-
1
initializer :initialize_dependency_mechanism, group: :all do
-
1
ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load
-
end
-
-
1
initializer :bootstrap_hook, group: :all do |app|
-
1
ActiveSupport.run_load_hooks(:before_initialize, app)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'active_support/file_update_checker'
-
1
require 'active_support/deprecation'
-
1
require 'rails/engine/configuration'
-
1
require 'rails/source_annotation_extractor'
-
-
1
module Rails
-
1
class Application
-
1
class Configuration < ::Rails::Engine::Configuration
-
1
attr_accessor :allow_concurrency, :asset_host, :assets, :autoflush_log,
-
:cache_classes, :cache_store, :consider_all_requests_local, :console,
-
:eager_load, :exceptions_app, :file_watcher, :filter_parameters,
-
:force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags,
-
:railties_order, :relative_url_root, :secret_key_base, :secret_token,
-
:serve_static_files, :ssl_options, :static_cache_control, :session_options,
-
:time_zone, :reload_classes_only_on_change,
-
:beginning_of_week, :filter_redirect, :x
-
-
1
attr_reader :encoding
-
-
1
def initialize(*)
-
1
super
-
1
self.encoding = "utf-8"
-
1
@allow_concurrency = nil
-
1
@consider_all_requests_local = false
-
1
@filter_parameters = []
-
1
@filter_redirect = []
-
1
@helpers_paths = []
-
1
@serve_static_files = true
-
1
@static_cache_control = nil
-
1
@force_ssl = false
-
1
@ssl_options = {}
-
1
@session_store = :cookie_store
-
1
@session_options = {}
-
1
@time_zone = "UTC"
-
1
@beginning_of_week = :monday
-
1
@has_explicit_log_level = false
-
1
@log_level = nil
-
1
@middleware = app_middleware
-
1
@generators = app_generators
-
1
@cache_store = [ :file_store, "#{root}/tmp/cache/" ]
-
1
@railties_order = [:all]
-
1
@relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"]
-
1
@reload_classes_only_on_change = true
-
1
@file_watcher = ActiveSupport::FileUpdateChecker
-
1
@exceptions_app = nil
-
1
@autoflush_log = true
-
1
@log_formatter = ActiveSupport::Logger::SimpleFormatter.new
-
1
@eager_load = nil
-
1
@secret_token = nil
-
1
@secret_key_base = nil
-
1
@x = Custom.new
-
-
1
@assets = ActiveSupport::OrderedOptions.new
-
1
@assets.enabled = true
-
1
@assets.paths = []
-
1
@assets.precompile = [ Proc.new { |path, fn| fn =~ /app\/assets/ && !%w(.js .css).include?(File.extname(path)) },
-
/(?:\/|\\|\A)application\.(css|js)$/ ]
-
1
@assets.prefix = "/assets"
-
1
@assets.version = '1.0'
-
1
@assets.debug = false
-
1
@assets.compile = true
-
1
@assets.digest = false
-
1
@assets.cache_store = [ :file_store, "#{root}/tmp/cache/assets/#{Rails.env}/" ]
-
1
@assets.js_compressor = nil
-
1
@assets.css_compressor = nil
-
1
@assets.logger = nil
-
end
-
-
1
def encoding=(value)
-
1
@encoding = value
-
1
silence_warnings do
-
1
Encoding.default_external = value
-
1
Encoding.default_internal = value
-
end
-
end
-
-
1
def paths
-
@paths ||= begin
-
1
paths = super
-
1
paths.add "config/database", with: "config/database.yml"
-
1
paths.add "config/secrets", with: "config/secrets.yml"
-
1
paths.add "config/environment", with: "config/environment.rb"
-
1
paths.add "lib/templates"
-
1
paths.add "log", with: "log/#{Rails.env}.log"
-
1
paths.add "public"
-
1
paths.add "public/javascripts"
-
1
paths.add "public/stylesheets"
-
1
paths.add "tmp"
-
1
paths
-
25
end
-
end
-
-
# Loads and returns the entire raw configuration of database from
-
# values stored in `config/database.yml`.
-
1
def database_configuration
-
1
path = paths["config/database"].existent.first
-
1
yaml = Pathname.new(path) if path
-
-
1
config = if yaml && yaml.exist?
-
1
require "yaml"
-
1
require "erb"
-
1
YAML.load(ERB.new(yaml.read).result) || {}
-
elsif ENV['DATABASE_URL']
-
# Value from ENV['DATABASE_URL'] is set to default database connection
-
# by Active Record.
-
{}
-
else
-
raise "Could not load database configuration. No such file - #{paths["config/database"].instance_variable_get(:@paths)}"
-
end
-
-
1
config
-
rescue Psych::SyntaxError => e
-
raise "YAML syntax error occurred while parsing #{paths["config/database"].first}. " \
-
"Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
-
"Error: #{e.message}"
-
rescue => e
-
raise e, "Cannot load `Rails.application.database_configuration`:\n#{e.message}", e.backtrace
-
end
-
-
1
def has_explicit_log_level? # :nodoc:
-
@has_explicit_log_level
-
end
-
-
1
def log_level=(level)
-
@has_explicit_log_level = !!(level)
-
@log_level = level
-
end
-
-
1
def log_level
-
1
@log_level ||= (Rails.env.production? ? :info : :debug)
-
end
-
-
1
def colorize_logging
-
ActiveSupport::LogSubscriber.colorize_logging
-
end
-
-
1
def colorize_logging=(val)
-
ActiveSupport::LogSubscriber.colorize_logging = val
-
self.generators.colorize_logging = val
-
end
-
-
# :nodoc:
-
1
SERVE_STATIC_ASSETS_DEPRECATION_MESSAGE = <<-MSG.squish
-
The configuration option `config.serve_static_assets` has been renamed
-
to `config.serve_static_files` to clarify its role (it merely enables
-
serving everything in the `public` folder and is unrelated to the asset
-
pipeline). The `serve_static_assets` alias will be removed in Rails 5.0.
-
Please migrate your configuration files accordingly.
-
MSG
-
-
1
def serve_static_assets
-
ActiveSupport::Deprecation.warn SERVE_STATIC_ASSETS_DEPRECATION_MESSAGE
-
serve_static_files
-
end
-
-
1
def serve_static_assets=(value)
-
ActiveSupport::Deprecation.warn SERVE_STATIC_ASSETS_DEPRECATION_MESSAGE
-
self.serve_static_files = value
-
end
-
-
1
def session_store(*args)
-
3
if args.empty?
-
2
case @session_store
-
when :disabled
-
nil
-
when :active_record_store
-
begin
-
ActionDispatch::Session::ActiveRecordStore
-
rescue NameError
-
raise "`ActiveRecord::SessionStore` is extracted out of Rails into a gem. " \
-
"Please add `activerecord-session_store` to your Gemfile to use it."
-
end
-
when Symbol
-
2
ActionDispatch::Session.const_get(@session_store.to_s.camelize)
-
else
-
@session_store
-
end
-
else
-
1
@session_store = args.shift
-
1
@session_options = args.shift || {}
-
end
-
end
-
-
1
def annotations
-
SourceAnnotationExtractor::Annotation
-
end
-
-
1
private
-
1
class Custom #:nodoc:
-
1
def initialize
-
1
@configurations = Hash.new
-
end
-
-
1
def method_missing(method, *args)
-
if method =~ /=$/
-
@configurations[$`.to_sym] = args.first
-
else
-
@configurations.fetch(method) {
-
@configurations[method] = ActiveSupport::OrderedOptions.new
-
}
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
class Application
-
1
class DefaultMiddlewareStack
-
1
attr_reader :config, :paths, :app
-
-
1
def initialize(app, config, paths)
-
1
@app = app
-
1
@config = config
-
1
@paths = paths
-
end
-
-
1
def build_stack
-
1
ActionDispatch::MiddlewareStack.new.tap do |middleware|
-
1
if config.force_ssl
-
middleware.use ::ActionDispatch::SSL, config.ssl_options
-
end
-
-
1
middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
-
-
1
if config.serve_static_files
-
1
middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
-
end
-
-
1
if rack_cache = load_rack_cache
-
require "action_dispatch/http/rack_cache"
-
middleware.use ::Rack::Cache, rack_cache
-
end
-
-
1
middleware.use ::Rack::Lock unless allow_concurrency?
-
1
middleware.use ::Rack::Runtime
-
1
middleware.use ::Rack::MethodOverride
-
1
middleware.use ::ActionDispatch::RequestId
-
-
# Must come after Rack::MethodOverride to properly log overridden methods
-
1
middleware.use ::Rails::Rack::Logger, config.log_tags
-
1
middleware.use ::ActionDispatch::ShowExceptions, show_exceptions_app
-
1
middleware.use ::ActionDispatch::DebugExceptions, app
-
1
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
-
-
1
unless config.cache_classes
-
middleware.use ::ActionDispatch::Reloader, lambda { reload_dependencies? }
-
end
-
-
1
middleware.use ::ActionDispatch::Callbacks
-
1
middleware.use ::ActionDispatch::Cookies
-
-
1
if config.session_store
-
1
if config.force_ssl && !config.session_options.key?(:secure)
-
config.session_options[:secure] = true
-
end
-
1
middleware.use config.session_store, config.session_options
-
1
middleware.use ::ActionDispatch::Flash
-
end
-
-
1
middleware.use ::ActionDispatch::ParamsParser
-
1
middleware.use ::Rack::Head
-
1
middleware.use ::Rack::ConditionalGet
-
1
middleware.use ::Rack::ETag, "no-cache"
-
end
-
end
-
-
1
private
-
-
1
def reload_dependencies?
-
config.reload_classes_only_on_change != true || app.reloaders.map(&:updated?).any?
-
end
-
-
1
def allow_concurrency?
-
1
if config.allow_concurrency.nil?
-
1
config.cache_classes && config.eager_load
-
else
-
config.allow_concurrency
-
end
-
end
-
-
1
def load_rack_cache
-
1
rack_cache = config.action_dispatch.rack_cache
-
1
return unless rack_cache
-
-
begin
-
require 'rack/cache'
-
rescue LoadError => error
-
error.message << ' Be sure to add rack-cache to your Gemfile'
-
raise
-
end
-
-
if rack_cache == true
-
{
-
metastore: "rails:/",
-
entitystore: "rails:/",
-
verbose: false
-
}
-
else
-
rack_cache
-
end
-
end
-
-
1
def show_exceptions_app
-
1
config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
class Application
-
1
module Finisher
-
1
include Initializable
-
-
1
initializer :add_generator_templates do
-
1
config.generators.templates.unshift(*paths["lib/templates"].existent)
-
end
-
-
1
initializer :ensure_autoload_once_paths_as_subset do
-
1
extra = ActiveSupport::Dependencies.autoload_once_paths -
-
ActiveSupport::Dependencies.autoload_paths
-
-
1
unless extra.empty?
-
abort <<-end_error
-
autoload_once_paths must be a subset of the autoload_paths.
-
Extra items in autoload_once_paths: #{extra * ','}
-
end_error
-
end
-
end
-
-
1
initializer :add_builtin_route do |app|
-
1
if Rails.env.development?
-
app.routes.append do
-
get '/rails/info/properties' => "rails/info#properties"
-
get '/rails/info/routes' => "rails/info#routes"
-
get '/rails/info' => "rails/info#index"
-
get '/' => "rails/welcome#index"
-
end
-
end
-
end
-
-
1
initializer :build_middleware_stack do
-
1
build_middleware_stack
-
end
-
-
1
initializer :define_main_app_helper do |app|
-
1
app.routes.define_mounted_helper(:main_app)
-
end
-
-
1
initializer :add_to_prepare_blocks do
-
1
config.to_prepare_blocks.each do |block|
-
ActionDispatch::Reloader.to_prepare(&block)
-
end
-
end
-
-
# This needs to happen before eager load so it happens
-
# in exactly the same point regardless of config.cache_classes
-
1
initializer :run_prepare_callbacks do
-
1
ActionDispatch::Reloader.prepare!
-
end
-
-
1
initializer :eager_load! do
-
1
if config.eager_load
-
ActiveSupport.run_load_hooks(:before_eager_load, self)
-
config.eager_load_namespaces.each(&:eager_load!)
-
end
-
end
-
-
# All initialization is done, including eager loading in production
-
1
initializer :finisher_hook do
-
1
ActiveSupport.run_load_hooks(:after_initialize, self)
-
end
-
-
# Set routes reload after the finisher hook to ensure routes added in
-
# the hook are taken into account.
-
1
initializer :set_routes_reloader_hook do
-
1
reloader = routes_reloader
-
1
reloader.execute_if_updated
-
1
self.reloaders << reloader
-
1
ActionDispatch::Reloader.to_prepare do
-
# We configure #execute rather than #execute_if_updated because if
-
# autoloaded constants are cleared we need to reload routes also in
-
# case any was used there, as in
-
#
-
# mount MailPreview => 'mail_view'
-
#
-
# This means routes are also reloaded if i18n is updated, which
-
# might not be necessary, but in order to be more precise we need
-
# some sort of reloaders dependency support, to be added.
-
reloader.execute
-
end
-
end
-
-
# Set clearing dependencies after the finisher hook to ensure paths
-
# added in the hook are taken into account.
-
1
initializer :set_clear_dependencies_hook, group: :all do
-
1
callback = lambda do
-
ActiveSupport::DescendantsTracker.clear
-
ActiveSupport::Dependencies.clear
-
end
-
-
1
if config.reload_classes_only_on_change
-
1
reloader = config.file_watcher.new(*watchable_args, &callback)
-
1
self.reloaders << reloader
-
-
# Prepend this callback to have autoloaded constants cleared before
-
# any other possible reloading, in case they need to autoload fresh
-
# constants.
-
1
ActionDispatch::Reloader.to_prepare(prepend: true) do
-
# In addition to changes detected by the file watcher, if routes
-
# or i18n have been updated we also need to clear constants,
-
# that's why we run #execute rather than #execute_if_updated, this
-
# callback has to clear autoloaded constants after any update.
-
reloader.execute
-
end
-
else
-
ActionDispatch::Reloader.to_cleanup(&callback)
-
end
-
end
-
end
-
end
-
end
-
1
require "active_support/core_ext/module/delegation"
-
-
1
module Rails
-
1
class Application
-
1
class RoutesReloader
-
1
attr_reader :route_sets, :paths
-
1
delegate :execute_if_updated, :execute, :updated?, to: :updater
-
-
1
def initialize
-
1
@paths = []
-
1
@route_sets = []
-
end
-
-
1
def reload!
-
1
clear!
-
1
load_paths
-
1
finalize!
-
ensure
-
1
revert
-
end
-
-
1
private
-
-
1
def updater
-
@updater ||= begin
-
2
updater = ActiveSupport::FileUpdateChecker.new(paths) { reload! }
-
1
updater.execute
-
1
updater
-
1
end
-
end
-
-
1
def clear!
-
1
route_sets.each do |routes|
-
1
routes.disable_clear_and_finalize = true
-
1
routes.clear!
-
end
-
end
-
-
1
def load_paths
-
2
paths.each { |path| load(path) }
-
end
-
-
1
def finalize!
-
1
route_sets.each do |routes|
-
1
routes.finalize!
-
end
-
end
-
-
1
def revert
-
1
route_sets.each do |routes|
-
1
routes.disable_clear_and_finalize = false
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/backtrace_cleaner'
-
-
1
module Rails
-
1
class BacktraceCleaner < ActiveSupport::BacktraceCleaner
-
1
APP_DIRS_PATTERN = /^\/?(app|config|lib|test)/
-
1
RENDER_TEMPLATE_PATTERN = /:in `_render_template_\w*'/
-
1
EMPTY_STRING = ''.freeze
-
1
SLASH = '/'.freeze
-
1
DOT_SLASH = './'.freeze
-
-
1
def initialize
-
1
super
-
1
@root = "#{Rails.root}/".freeze
-
1
add_filter { |line| line.sub(@root, EMPTY_STRING) }
-
1
add_filter { |line| line.sub(RENDER_TEMPLATE_PATTERN, EMPTY_STRING) }
-
1
add_filter { |line| line.sub(DOT_SLASH, SLASH) } # for tests
-
-
1
add_gem_filters
-
1
add_silencer { |line| line !~ APP_DIRS_PATTERN }
-
end
-
-
1
private
-
1
def add_gem_filters
-
3
gems_paths = (Gem.path | [Gem.default_dir]).map { |p| Regexp.escape(p) }
-
1
return if gems_paths.empty?
-
-
1
gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w.]+)/(.*)}
-
1
gems_result = '\2 (\3) \4'.freeze
-
1
add_filter { |line| line.sub(gems_regexp, gems_result) }
-
end
-
end
-
end
-
1
require 'active_support/ordered_options'
-
1
require 'active_support/core_ext/object'
-
1
require 'rails/paths'
-
1
require 'rails/rack'
-
-
1
module Rails
-
1
module Configuration
-
# MiddlewareStackProxy is a proxy for the Rails middleware stack that allows
-
# you to configure middlewares in your application. It works basically as a
-
# command recorder, saving each command to be applied after initialization
-
# over the default middleware stack, so you can add, swap, or remove any
-
# middleware in Rails.
-
#
-
# You can add your own middlewares by using the +config.middleware.use+ method:
-
#
-
# config.middleware.use Magical::Unicorns
-
#
-
# This will put the <tt>Magical::Unicorns</tt> middleware on the end of the stack.
-
# You can use +insert_before+ if you wish to add a middleware before another:
-
#
-
# config.middleware.insert_before Rack::Head, Magical::Unicorns
-
#
-
# There's also +insert_after+ which will insert a middleware after another:
-
#
-
# config.middleware.insert_after Rack::Head, Magical::Unicorns
-
#
-
# Middlewares can also be completely swapped out and replaced with others:
-
#
-
# config.middleware.swap ActionDispatch::Flash, Magical::Unicorns
-
#
-
# And finally they can also be removed from the stack completely:
-
#
-
# config.middleware.delete ActionDispatch::Flash
-
#
-
1
class MiddlewareStackProxy
-
1
def initialize
-
1
@operations = []
-
end
-
-
1
def insert_before(*args, &block)
-
1
@operations << [__method__, args, block]
-
end
-
-
1
alias :insert :insert_before
-
-
1
def insert_after(*args, &block)
-
2
@operations << [__method__, args, block]
-
end
-
-
1
def swap(*args, &block)
-
@operations << [__method__, args, block]
-
end
-
-
1
def use(*args, &block)
-
@operations << [__method__, args, block]
-
end
-
-
1
def delete(*args, &block)
-
@operations << [__method__, args, block]
-
end
-
-
1
def unshift(*args, &block)
-
@operations << [__method__, args, block]
-
end
-
-
1
def merge_into(other) #:nodoc:
-
1
@operations.each do |operation, args, block|
-
3
other.send(operation, *args, &block)
-
end
-
1
other
-
end
-
end
-
-
1
class Generators #:nodoc:
-
1
attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging
-
1
attr_reader :hidden_namespaces
-
-
1
def initialize
-
1
@aliases = Hash.new { |h,k| h[k] = {} }
-
5
@options = Hash.new { |h,k| h[k] = {} }
-
1
@fallbacks = {}
-
1
@templates = []
-
1
@colorize_logging = true
-
1
@hidden_namespaces = []
-
end
-
-
1
def initialize_copy(source)
-
4
@aliases = @aliases.deep_dup
-
4
@options = @options.deep_dup
-
4
@fallbacks = @fallbacks.deep_dup
-
4
@templates = @templates.dup
-
end
-
-
1
def hide_namespace(namespace)
-
1
@hidden_namespaces << namespace
-
end
-
-
1
def method_missing(method, *args)
-
9
method = method.to_s.sub(/=$/, '').to_sym
-
-
9
return @options[method] if args.empty?
-
-
9
if method == :rails || args.first.is_a?(Hash)
-
namespace, configuration = method, args.shift
-
else
-
9
namespace, configuration = args.shift, args.shift
-
9
namespace = namespace.to_sym if namespace.respond_to?(:to_sym)
-
9
@options[:rails][method] = namespace
-
end
-
-
9
if configuration
-
3
aliases = configuration.delete(:aliases)
-
3
@aliases[namespace].merge!(aliases) if aliases
-
3
@options[namespace].merge!(configuration)
-
end
-
end
-
end
-
end
-
end
-
1
require 'rails/railtie'
-
1
require 'rails/engine/railties'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'pathname'
-
-
1
module Rails
-
# <tt>Rails::Engine</tt> allows you to wrap a specific Rails application or subset of
-
# functionality and share it with other applications or within a larger packaged application.
-
# Since Rails 3.0, every <tt>Rails::Application</tt> is just an engine, which allows for simple
-
# feature and application sharing.
-
#
-
# Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same
-
# methods (like <tt>rake_tasks</tt> and +generators+) and configuration
-
# options that are available in railties can also be used in engines.
-
#
-
# == Creating an Engine
-
#
-
# In Rails versions prior to 3.0, your gems automatically behaved as engines, however,
-
# this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically
-
# behave as an engine, you have to specify an +Engine+ for it somewhere inside
-
# your plugin's +lib+ folder (similar to how we specify a +Railtie+):
-
#
-
# # lib/my_engine.rb
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# end
-
# end
-
#
-
# Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt>
-
# (or in your +Gemfile+) and it will automatically load models, controllers and helpers
-
# inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at
-
# <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>.
-
#
-
# == Configuration
-
#
-
# Besides the +Railtie+ configuration which is shared across the application, in a
-
# <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt>
-
# and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to
-
# the current engine.
-
#
-
# class MyEngine < Rails::Engine
-
# # Add a load path for this specific Engine
-
# config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)
-
#
-
# initializer "my_engine.add_middleware" do |app|
-
# app.middleware.use MyEngine::Middleware
-
# end
-
# end
-
#
-
# == Generators
-
#
-
# You can set up generators for engines with <tt>config.generators</tt> method:
-
#
-
# class MyEngine < Rails::Engine
-
# config.generators do |g|
-
# g.orm :active_record
-
# g.template_engine :erb
-
# g.test_framework :test_unit
-
# end
-
# end
-
#
-
# You can also set generators for an application by using <tt>config.app_generators</tt>:
-
#
-
# class MyEngine < Rails::Engine
-
# # note that you can also pass block to app_generators in the same way you
-
# # can pass it to generators method
-
# config.app_generators.orm :datamapper
-
# end
-
#
-
# == Paths
-
#
-
# Since Rails 3.0, applications and engines have more flexible path configuration (as
-
# opposed to the previous hardcoded path configuration). This means that you are not
-
# required to place your controllers at <tt>app/controllers</tt>, but in any place
-
# which you find convenient.
-
#
-
# For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>.
-
# You can set that as an option:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app/controllers"] = "lib/controllers"
-
# end
-
#
-
# You can also have your controllers loaded from both <tt>app/controllers</tt> and
-
# <tt>lib/controllers</tt>:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app/controllers"] << "lib/controllers"
-
# end
-
#
-
# The available paths in an engine are:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app"] # => ["app"]
-
# paths["app/controllers"] # => ["app/controllers"]
-
# paths["app/helpers"] # => ["app/helpers"]
-
# paths["app/models"] # => ["app/models"]
-
# paths["app/views"] # => ["app/views"]
-
# paths["lib"] # => ["lib"]
-
# paths["lib/tasks"] # => ["lib/tasks"]
-
# paths["config"] # => ["config"]
-
# paths["config/initializers"] # => ["config/initializers"]
-
# paths["config/locales"] # => ["config/locales"]
-
# paths["config/routes.rb"] # => ["config/routes.rb"]
-
# end
-
#
-
# The <tt>Application</tt> class adds a couple more paths to this set. And as in your
-
# <tt>Application</tt>, all folders under +app+ are automatically added to the load path.
-
# If you have an <tt>app/services</tt> folder for example, it will be added by default.
-
#
-
# == Endpoint
-
#
-
# An engine can also be a rack application. It can be useful if you have a rack application that
-
# you would like to wrap with +Engine+ and provide with some of the +Engine+'s features.
-
#
-
# To do that, use the +endpoint+ method:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# endpoint MyRackApplication
-
# end
-
# end
-
#
-
# Now you can mount your engine in application's routes just like that:
-
#
-
# Rails.application.routes.draw do
-
# mount MyEngine::Engine => "/engine"
-
# end
-
#
-
# == Middleware stack
-
#
-
# As an engine can now be a rack endpoint, it can also have a middleware
-
# stack. The usage is exactly the same as in <tt>Application</tt>:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# middleware.use SomeMiddleware
-
# end
-
# end
-
#
-
# == Routes
-
#
-
# If you don't specify an endpoint, routes will be used as the default
-
# endpoint. You can use them just like you use an application's routes:
-
#
-
# # ENGINE/config/routes.rb
-
# MyEngine::Engine.routes.draw do
-
# get "/" => "posts#index"
-
# end
-
#
-
# == Mount priority
-
#
-
# Note that now there can be more than one router in your application, and it's better to avoid
-
# passing requests through many routers. Consider this situation:
-
#
-
# Rails.application.routes.draw do
-
# mount MyEngine::Engine => "/blog"
-
# get "/blog/omg" => "main#omg"
-
# end
-
#
-
# +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's
-
# controller. In such a situation, requests to <tt>/blog/omg</tt> will go through +MyEngine+,
-
# and if there is no such route in +Engine+'s routes, it will be dispatched to <tt>main#omg</tt>.
-
# It's much better to swap that:
-
#
-
# Rails.application.routes.draw do
-
# get "/blog/omg" => "main#omg"
-
# mount MyEngine::Engine => "/blog"
-
# end
-
#
-
# Now, +Engine+ will get only requests that were not handled by +Application+.
-
#
-
# == Engine name
-
#
-
# There are some places where an Engine's name is used:
-
#
-
# * routes: when you mount an Engine with <tt>mount(MyEngine::Engine => '/my_engine')</tt>,
-
# it's used as default <tt>:as</tt> option
-
# * rake task for installing migrations <tt>my_engine:install:migrations</tt>
-
#
-
# Engine name is set by default based on class name. For <tt>MyEngine::Engine</tt> it will be
-
# <tt>my_engine_engine</tt>. You can change it manually using the <tt>engine_name</tt> method:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# engine_name "my_engine"
-
# end
-
# end
-
#
-
# == Isolated Engine
-
#
-
# Normally when you create controllers, helpers and models inside an engine, they are treated
-
# as if they were created inside the application itself. This means that all helpers and
-
# named routes from the application will be available to your engine's controllers as well.
-
#
-
# However, sometimes you want to isolate your engine from the application, especially if your engine
-
# has its own router. To do that, you simply need to call +isolate_namespace+. This method requires
-
# you to pass a module where all your controllers, helpers and models should be nested to:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# isolate_namespace MyEngine
-
# end
-
# end
-
#
-
# With such an engine, everything that is inside the +MyEngine+ module will be isolated from
-
# the application.
-
#
-
# Consider such controller:
-
#
-
# module MyEngine
-
# class FooController < ActionController::Base
-
# end
-
# end
-
#
-
# If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and
-
# <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>.
-
#
-
# The next thing that changes in isolated engines is the behavior of routes. Normally, when you namespace
-
# your controllers, you also need to do namespace all your routes. With an isolated engine,
-
# the namespace is applied by default, so you can ignore it in routes:
-
#
-
# MyEngine::Engine.routes.draw do
-
# resources :articles
-
# end
-
#
-
# The routes above will automatically point to <tt>MyEngine::ArticlesController</tt>. Furthermore, you don't
-
# need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you should simply use
-
# <tt>articles_path</tt> as you would do with your application.
-
#
-
# To make that behavior consistent with other parts of the framework, an isolated engine also has influence on
-
# <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally
-
# use the prefix "my_engine". In an isolated engine, the prefix will be omitted in url helpers and
-
# form fields for convenience.
-
#
-
# polymorphic_url(MyEngine::Article.new) # => "articles_path"
-
#
-
# form_for(MyEngine::Article.new) do
-
# text_field :title # => <input type="text" name="article[title]" id="article_title" />
-
# end
-
#
-
# Additionally, an isolated engine will set its name according to namespace, so
-
# MyEngine::Engine.engine_name will be "my_engine". It will also set MyEngine.table_name_prefix
-
# to "my_engine_", changing the MyEngine::Article model to use the my_engine_articles table.
-
#
-
# == Using Engine's routes outside Engine
-
#
-
# Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s
-
# <tt>url_helpers</tt> inside +Application+. When you mount an engine in an application's routes, a special helper is
-
# created to allow you to do that. Consider such a scenario:
-
#
-
# # config/routes.rb
-
# Rails.application.routes.draw do
-
# mount MyEngine::Engine => "/my_engine", as: "my_engine"
-
# get "/foo" => "foo#index"
-
# end
-
#
-
# Now, you can use the <tt>my_engine</tt> helper inside your application:
-
#
-
# class FooController < ApplicationController
-
# def index
-
# my_engine.root_url # => /my_engine/
-
# end
-
# end
-
#
-
# There is also a <tt>main_app</tt> helper that gives you access to application's routes inside Engine:
-
#
-
# module MyEngine
-
# class BarController
-
# def index
-
# main_app.foo_path # => /foo
-
# end
-
# end
-
# end
-
#
-
# Note that the <tt>:as</tt> option given to mount takes the <tt>engine_name</tt> as default, so most of the time
-
# you can simply omit it.
-
#
-
# Finally, if you want to generate a url to an engine's route using
-
# <tt>polymorphic_url</tt>, you also need to pass the engine helper. Let's
-
# say that you want to create a form pointing to one of the engine's routes.
-
# All you need to do is pass the helper as the first element in array with
-
# attributes for url:
-
#
-
# form_for([my_engine, @user])
-
#
-
# This code will use <tt>my_engine.user_path(@user)</tt> to generate the proper route.
-
#
-
# == Isolated engine's helpers
-
#
-
# Sometimes you may want to isolate engine, but use helpers that are defined for it.
-
# If you want to share just a few specific helpers you can add them to application's
-
# helpers in ApplicationController:
-
#
-
# class ApplicationController < ActionController::Base
-
# helper MyEngine::SharedEngineHelper
-
# end
-
#
-
# If you want to include all of the engine's helpers, you can use #helper method on an engine's
-
# instance:
-
#
-
# class ApplicationController < ActionController::Base
-
# helper MyEngine::Engine.helpers
-
# end
-
#
-
# It will include all of the helpers from engine's directory. Take into account that this does
-
# not include helpers defined in controllers with helper_method or other similar solutions,
-
# only helpers defined in the helpers directory will be included.
-
#
-
# == Migrations & seed data
-
#
-
# Engines can have their own migrations. The default path for migrations is exactly the same
-
# as in application: <tt>db/migrate</tt>
-
#
-
# To use engine's migrations in application you can use rake task, which copies them to
-
# application's dir:
-
#
-
# rake ENGINE_NAME:install:migrations
-
#
-
# Note that some of the migrations may be skipped if a migration with the same name already exists
-
# in application. In such a situation you must decide whether to leave that migration or rename the
-
# migration in the application and rerun copying migrations.
-
#
-
# If your engine has migrations, you may also want to prepare data for the database in
-
# the <tt>db/seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
-
#
-
# MyEngine::Engine.load_seed
-
#
-
# == Loading priority
-
#
-
# In order to change engine's priority you can use +config.railties_order+ in main application.
-
# It will affect the priority of loading views, helpers, assets and all the other files
-
# related to engine or application.
-
#
-
# # load Blog::Engine with highest priority, followed by application and other railties
-
# config.railties_order = [Blog::Engine, :main_app, :all]
-
1
class Engine < Railtie
-
1
autoload :Configuration, "rails/engine/configuration"
-
-
1
class << self
-
1
attr_accessor :called_from, :isolated
-
-
1
alias :isolated? :isolated
-
1
alias :engine_name :railtie_name
-
-
1
delegate :eager_load!, to: :instance
-
-
1
def inherited(base)
-
5
unless base.abstract_railtie?
-
4
Rails::Railtie::Configuration.eager_load_namespaces << base
-
-
4
base.called_from = begin
-
4
call_stack = if Kernel.respond_to?(:caller_locations)
-
125
caller_locations.map { |l| l.absolute_path || l.path }
-
else
-
# Remove the line number from backtraces making sure we don't leave anything behind
-
caller.map { |p| p.sub(/:\d+.*/, '') }
-
end
-
-
9
File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] })
-
end
-
end
-
-
5
super
-
end
-
-
1
def find_root(from)
-
3
find_root_with_flag "lib", from
-
end
-
-
1
def endpoint(endpoint = nil)
-
1
@endpoint ||= nil
-
1
@endpoint = endpoint if endpoint
-
1
@endpoint
-
end
-
-
1
def isolate_namespace(mod)
-
engine_name(generate_railtie_name(mod.name))
-
-
self.routes.default_scope = { module: ActiveSupport::Inflector.underscore(mod.name) }
-
self.isolated = true
-
-
unless mod.respond_to?(:railtie_namespace)
-
name, railtie = engine_name, self
-
-
mod.singleton_class.instance_eval do
-
define_method(:railtie_namespace) { railtie }
-
-
unless mod.respond_to?(:table_name_prefix)
-
define_method(:table_name_prefix) { "#{name}_" }
-
end
-
-
unless mod.respond_to?(:use_relative_model_naming?)
-
class_eval "def use_relative_model_naming?; true; end", __FILE__, __LINE__
-
end
-
-
unless mod.respond_to?(:railtie_helpers_paths)
-
define_method(:railtie_helpers_paths) { railtie.helpers_paths }
-
end
-
-
unless mod.respond_to?(:railtie_routes_url_helpers)
-
define_method(:railtie_routes_url_helpers) {|include_path_helpers = true| railtie.routes.url_helpers(include_path_helpers) }
-
end
-
end
-
end
-
end
-
-
# Finds engine with given path
-
1
def find(path)
-
expanded_path = File.expand_path path
-
Rails::Engine.subclasses.each do |klass|
-
engine = klass.instance
-
return engine if File.expand_path(engine.root) == expanded_path
-
end
-
nil
-
end
-
end
-
-
1
delegate :middleware, :root, :paths, to: :config
-
1
delegate :engine_name, :isolated?, to: :class
-
-
1
def initialize
-
4
@_all_autoload_paths = nil
-
4
@_all_load_paths = nil
-
4
@app = nil
-
4
@config = nil
-
4
@env_config = nil
-
4
@helpers = nil
-
4
@routes = nil
-
4
super
-
end
-
-
# Load console and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.console</tt> for more info.
-
1
def load_console(app=self)
-
require "rails/console/app"
-
require "rails/console/helpers"
-
run_console_blocks(app)
-
self
-
end
-
-
# Load Rails runner and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.runner</tt> for more info.
-
1
def load_runner(app=self)
-
run_runner_blocks(app)
-
self
-
end
-
-
# Load Rake, railties tasks and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.rake_tasks</tt> for more info.
-
1
def load_tasks(app=self)
-
require "rake"
-
run_tasks_blocks(app)
-
self
-
end
-
-
# Load Rails generators and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.generators</tt> for more info.
-
1
def load_generators(app=self)
-
require "rails/generators"
-
run_generators_blocks(app)
-
Rails::Generators.configure!(app.config.generators)
-
self
-
end
-
-
# Eager load the application by loading all ruby
-
# files inside eager_load paths.
-
1
def eager_load!
-
config.eager_load_paths.each do |load_path|
-
matcher = /\A#{Regexp.escape(load_path.to_s)}\/(.*)\.rb\Z/
-
Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
-
require_dependency file.sub(matcher, '\1')
-
end
-
end
-
end
-
-
1
def railties
-
1
@railties ||= Railties.new
-
end
-
-
# Returns a module with all the helpers defined for the engine.
-
1
def helpers
-
@helpers ||= begin
-
helpers = Module.new
-
all = ActionController::Base.all_helpers_from_path(helpers_paths)
-
ActionController::Base.modules_for_helpers(all).each do |mod|
-
helpers.send(:include, mod)
-
end
-
helpers
-
end
-
end
-
-
# Returns all registered helpers paths.
-
1
def helpers_paths
-
paths["app/helpers"].existent
-
end
-
-
# Returns the underlying rack application for this engine.
-
1
def app
-
@app ||= begin
-
1
config.middleware = config.middleware.merge_into(default_middleware_stack)
-
1
config.middleware.build(endpoint)
-
67
end
-
end
-
-
# Returns the endpoint for this engine. If none is registered,
-
# defaults to an ActionDispatch::Routing::RouteSet.
-
1
def endpoint
-
1
self.class.endpoint || routes
-
end
-
-
# Define the Rack API for this engine.
-
1
def call(env)
-
66
env.merge!(env_config)
-
66
if env['SCRIPT_NAME']
-
66
env["ROUTES_#{routes.object_id}_SCRIPT_NAME"] = env['SCRIPT_NAME'].dup
-
end
-
66
app.call(env)
-
end
-
-
# Defines additional Rack env configuration that is added on each call.
-
1
def env_config
-
@env_config ||= {
-
'action_dispatch.routes' => routes
-
1
}
-
end
-
-
# Defines the routes for this engine. If a block is given to
-
# routes, it is appended to the engine.
-
1
def routes
-
79
@routes ||= ActionDispatch::Routing::RouteSet.new
-
79
@routes.append(&Proc.new) if block_given?
-
79
@routes
-
end
-
-
# Define the configuration object for the engine.
-
1
def config
-
59
@config ||= Engine::Configuration.new(self.class.find_root(self.class.called_from))
-
end
-
-
# Load data from db/seeds.rb file. It can be used in to load engines'
-
# seeds, e.g.:
-
#
-
# Blog::Engine.load_seed
-
1
def load_seed
-
seed_file = paths["db/seeds.rb"].existent.first
-
load(seed_file) if seed_file
-
end
-
-
# Add configured load paths to ruby load paths and remove duplicates.
-
1
initializer :set_load_path, before: :bootstrap_hook do
-
4
_all_load_paths.reverse_each do |path|
-
13
$LOAD_PATH.unshift(path) if File.directory?(path)
-
end
-
4
$LOAD_PATH.uniq!
-
end
-
-
# Set the paths from which Rails will automatically load source files,
-
# and the load_once paths.
-
#
-
# This needs to be an initializer, since it needs to run once
-
# per engine and get the engine as a block parameter
-
1
initializer :set_autoload_paths, before: :bootstrap_hook do
-
4
ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths)
-
4
ActiveSupport::Dependencies.autoload_once_paths.unshift(*_all_autoload_once_paths)
-
-
# Freeze so future modifications will fail rather than do nothing mysteriously
-
4
config.autoload_paths.freeze
-
4
config.eager_load_paths.freeze
-
4
config.autoload_once_paths.freeze
-
end
-
-
1
initializer :add_routing_paths do |app|
-
4
routing_paths = self.paths["config/routes.rb"].existent
-
-
4
if routes? || routing_paths.any?
-
1
app.routes_reloader.paths.unshift(*routing_paths)
-
1
app.routes_reloader.route_sets << routes
-
end
-
end
-
-
# I18n load paths are a special case since the ones added
-
# later have higher priority.
-
1
initializer :add_locales do
-
4
config.i18n.railties_load_path.concat(paths["config/locales"].existent)
-
end
-
-
1
initializer :add_view_paths do
-
4
views = paths["app/views"].existent
-
4
unless views.empty?
-
2
ActiveSupport.on_load(:action_controller){ prepend_view_path(views) if respond_to?(:prepend_view_path) }
-
2
ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) }
-
end
-
end
-
-
1
initializer :load_environment_config, before: :load_environment_hook, group: :all do
-
4
paths["config/environments"].existent.each do |environment|
-
1
require environment
-
end
-
end
-
-
1
initializer :append_assets_path, group: :all do |app|
-
4
app.config.assets.paths.unshift(*paths["vendor/assets"].existent_directories)
-
4
app.config.assets.paths.unshift(*paths["lib/assets"].existent_directories)
-
4
app.config.assets.paths.unshift(*paths["app/assets"].existent_directories)
-
end
-
-
1
initializer :prepend_helpers_path do |app|
-
4
if !isolated? || (app == self)
-
4
app.config.helpers_paths.unshift(*paths["app/helpers"].existent)
-
end
-
end
-
-
1
initializer :load_config_initializers do
-
4
config.paths["config/initializers"].existent.sort.each do |initializer|
-
8
load_config_initializer(initializer)
-
end
-
end
-
-
1
initializer :engines_blank_point do
-
# We need this initializer so all extra initializers added in engines are
-
# consistently executed after all the initializers above across all engines.
-
end
-
-
1
rake_tasks do
-
next if self.is_a?(Rails::Application)
-
next unless has_migrations?
-
-
namespace railtie_name do
-
namespace :install do
-
desc "Copy migrations from #{railtie_name} to application"
-
task :migrations do
-
ENV["FROM"] = railtie_name
-
if Rake::Task.task_defined?("railties:install:migrations")
-
Rake::Task["railties:install:migrations"].invoke
-
else
-
Rake::Task["app:railties:install:migrations"].invoke
-
end
-
end
-
end
-
end
-
end
-
-
1
def routes? #:nodoc:
-
4
@routes
-
end
-
-
1
protected
-
-
1
def load_config_initializer(initializer)
-
8
ActiveSupport::Notifications.instrument('load_config_initializer.railties', initializer: initializer) do
-
8
load(initializer)
-
end
-
end
-
-
1
def run_tasks_blocks(*) #:nodoc:
-
super
-
paths["lib/tasks"].existent.sort.each { |ext| load(ext) }
-
end
-
-
1
def has_migrations? #:nodoc:
-
paths["db/migrate"].existent.any?
-
end
-
-
1
def self.find_root_with_flag(flag, root_path, default=nil) #:nodoc:
-
-
5
while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
-
9
parent = File.dirname(root_path)
-
9
root_path = parent != root_path && parent
-
end
-
-
5
root = File.exist?("#{root_path}/#{flag}") ? root_path : default
-
5
raise "Could not find root path for #{self}" unless root
-
-
5
Pathname.new File.realpath root
-
end
-
-
1
def default_middleware_stack #:nodoc:
-
ActionDispatch::MiddlewareStack.new
-
end
-
-
1
def _all_autoload_once_paths #:nodoc:
-
4
config.autoload_once_paths
-
end
-
-
1
def _all_autoload_paths #:nodoc:
-
8
@_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq
-
end
-
-
1
def _all_load_paths #:nodoc:
-
4
@_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq
-
end
-
end
-
end
-
1
require 'rails/railtie/configuration'
-
-
1
module Rails
-
1
class Engine
-
1
class Configuration < ::Rails::Railtie::Configuration
-
1
attr_reader :root
-
1
attr_writer :middleware, :eager_load_paths, :autoload_once_paths, :autoload_paths
-
-
1
def initialize(root=nil)
-
4
super()
-
4
@root = root
-
4
@generators = app_generators.dup
-
end
-
-
# Returns the middleware stack for the engine.
-
1
def middleware
-
3
@middleware ||= Rails::Configuration::MiddlewareStackProxy.new
-
end
-
-
# Holds generators configuration:
-
#
-
# config.generators do |g|
-
# g.orm :data_mapper, migration: true
-
# g.template_engine :haml
-
# g.test_framework :rspec
-
# end
-
#
-
# If you want to disable color in console, do:
-
#
-
# config.generators.colorize_logging = false
-
#
-
1
def generators
-
2
@generators ||= Rails::Configuration::Generators.new
-
2
yield(@generators) if block_given?
-
2
@generators
-
end
-
-
1
def paths
-
@paths ||= begin
-
4
paths = Rails::Paths::Root.new(@root)
-
-
4
paths.add "app", eager_load: true, glob: "*"
-
4
paths.add "app/assets", glob: "*"
-
4
paths.add "app/controllers", eager_load: true
-
4
paths.add "app/helpers", eager_load: true
-
4
paths.add "app/models", eager_load: true
-
4
paths.add "app/mailers", eager_load: true
-
4
paths.add "app/views"
-
-
4
paths.add "app/controllers/concerns", eager_load: true
-
4
paths.add "app/models/concerns", eager_load: true
-
-
4
paths.add "lib", load_path: true
-
4
paths.add "lib/assets", glob: "*"
-
4
paths.add "lib/tasks", glob: "**/*.rake"
-
-
4
paths.add "config"
-
4
paths.add "config/environments", glob: "#{Rails.env}.rb"
-
4
paths.add "config/initializers", glob: "**/*.rb"
-
4
paths.add "config/locales", glob: "*.{rb,yml}"
-
4
paths.add "config/routes.rb"
-
-
4
paths.add "db"
-
4
paths.add "db/migrate"
-
4
paths.add "db/seeds.rb"
-
-
4
paths.add "vendor", load_path: true
-
4
paths.add "vendor/assets", glob: "*"
-
-
4
paths
-
40
end
-
end
-
-
1
def root=(value)
-
@root = paths.path = Pathname.new(value).expand_path
-
end
-
-
1
def eager_load_paths
-
8
@eager_load_paths ||= paths.eager_load
-
end
-
-
1
def autoload_once_paths
-
12
@autoload_once_paths ||= paths.autoload_once
-
end
-
-
1
def autoload_paths
-
8
@autoload_paths ||= paths.autoload_paths
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
class Engine < Railtie
-
1
class Railties
-
1
include Enumerable
-
1
attr_reader :_all
-
-
1
def initialize
-
@_all ||= ::Rails::Railtie.subclasses.map(&:instance) +
-
1
::Rails::Engine.subclasses.map(&:instance)
-
end
-
-
1
def each(*args, &block)
-
_all.each(*args, &block)
-
end
-
-
1
def -(others)
-
1
_all - others
-
end
-
end
-
end
-
end
-
1
module Rails
-
# Returns the version of the currently loaded Rails as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 2
-
1
TINY = 5
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
activesupport_path = File.expand_path('../../../../activesupport/lib', __FILE__)
-
1
$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
-
1
require 'thor/group'
-
-
1
require 'active_support'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/hash/deep_merge'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module Rails
-
1
module Generators
-
1
autoload :Actions, 'rails/generators/actions'
-
1
autoload :ActiveModel, 'rails/generators/active_model'
-
1
autoload :Base, 'rails/generators/base'
-
1
autoload :Migration, 'rails/generators/migration'
-
1
autoload :NamedBase, 'rails/generators/named_base'
-
1
autoload :ResourceHelpers, 'rails/generators/resource_helpers'
-
1
autoload :TestCase, 'rails/generators/test_case'
-
-
1
mattr_accessor :namespace
-
-
1
DEFAULT_ALIASES = {
-
rails: {
-
actions: '-a',
-
orm: '-o',
-
javascripts: '-j',
-
javascript_engine: '-je',
-
resource_controller: '-c',
-
scaffold_controller: '-c',
-
stylesheets: '-y',
-
stylesheet_engine: '-se',
-
template_engine: '-e',
-
test_framework: '-t'
-
},
-
-
test_unit: {
-
fixture_replacement: '-r',
-
}
-
}
-
-
1
DEFAULT_OPTIONS = {
-
rails: {
-
assets: true,
-
force_plural: false,
-
helper: true,
-
integration_tool: nil,
-
javascripts: true,
-
javascript_engine: :js,
-
orm: false,
-
resource_controller: :controller,
-
resource_route: true,
-
scaffold_controller: :scaffold_controller,
-
stylesheets: true,
-
stylesheet_engine: :css,
-
test_framework: false,
-
template_engine: :erb
-
}
-
}
-
-
1
def self.configure!(config) #:nodoc:
-
no_color! unless config.colorize_logging
-
aliases.deep_merge! config.aliases
-
options.deep_merge! config.options
-
fallbacks.merge! config.fallbacks
-
templates_path.concat config.templates
-
templates_path.uniq!
-
hide_namespaces(*config.hidden_namespaces)
-
end
-
-
1
def self.templates_path #:nodoc:
-
@templates_path ||= []
-
end
-
-
1
def self.aliases #:nodoc:
-
@aliases ||= DEFAULT_ALIASES.dup
-
end
-
-
1
def self.options #:nodoc:
-
@options ||= DEFAULT_OPTIONS.dup
-
end
-
-
# Hold configured generators fallbacks. If a plugin developer wants a
-
# generator group to fallback to another group in case of missing generators,
-
# they can add a fallback.
-
#
-
# For example, shoulda is considered a test_framework and is an extension
-
# of test_unit. However, most part of shoulda generators are similar to
-
# test_unit ones.
-
#
-
# Shoulda then can tell generators to search for test_unit generators when
-
# some of them are not available by adding a fallback:
-
#
-
# Rails::Generators.fallbacks[:shoulda] = :test_unit
-
1
def self.fallbacks
-
@fallbacks ||= {}
-
end
-
-
# Remove the color from output.
-
1
def self.no_color!
-
1
Thor::Base.shell = Thor::Shell::Basic
-
end
-
-
# Track all generators subclasses.
-
1
def self.subclasses
-
@subclasses ||= []
-
end
-
-
# Rails finds namespaces similar to thor, it only adds one rule:
-
#
-
# Generators names must end with "_generator.rb". This is required because Rails
-
# looks in load paths and loads the generator just before it's going to be used.
-
#
-
# find_by_namespace :webrat, :rails, :integration
-
#
-
# Will search for the following generators:
-
#
-
# "rails:webrat", "webrat:integration", "webrat"
-
#
-
# Notice that "rails:generators:webrat" could be loaded as well, what
-
# Rails looks for is the first and last parts of the namespace.
-
1
def self.find_by_namespace(name, base=nil, context=nil) #:nodoc:
-
lookups = []
-
lookups << "#{base}:#{name}" if base
-
lookups << "#{name}:#{context}" if context
-
-
unless base || context
-
unless name.to_s.include?(?:)
-
lookups << "#{name}:#{name}"
-
lookups << "rails:#{name}"
-
end
-
lookups << "#{name}"
-
end
-
-
lookup(lookups)
-
-
namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }]
-
-
lookups.each do |namespace|
-
klass = namespaces[namespace]
-
return klass if klass
-
end
-
-
invoke_fallbacks_for(name, base) || invoke_fallbacks_for(context, name)
-
end
-
-
# Receives a namespace, arguments and the behavior to invoke the generator.
-
# It's used as the default entry point for generate, destroy and update
-
# commands.
-
1
def self.invoke(namespace, args=ARGV, config={})
-
names = namespace.to_s.split(':')
-
if klass = find_by_namespace(names.pop, names.any? && names.join(':'))
-
args << "--help" if args.empty? && klass.arguments.any? { |a| a.required? }
-
klass.start(args, config)
-
else
-
options = sorted_groups.map(&:last).flatten
-
suggestions = options.sort_by {|suggested| levenshtein_distance(namespace.to_s, suggested) }.first(3)
-
msg = "Could not find generator '#{namespace}'. "
-
msg << "Maybe you meant #{ suggestions.map {|s| "'#{s}'"}.to_sentence(last_word_connector: " or ") }\n"
-
msg << "Run `rails generate --help` for more options."
-
puts msg
-
end
-
end
-
-
# Returns an array of generator namespaces that are hidden.
-
# Generator namespaces may be hidden for a variety of reasons.
-
# Some are aliased such as "rails:migration" and can be
-
# invoked with the shorter "migration", others are private to other generators
-
# such as "css:scaffold".
-
1
def self.hidden_namespaces
-
@hidden_namespaces ||= begin
-
orm = options[:rails][:orm]
-
test = options[:rails][:test_framework]
-
template = options[:rails][:template_engine]
-
css = options[:rails][:stylesheet_engine]
-
-
[
-
"rails",
-
"resource_route",
-
"#{orm}:migration",
-
"#{orm}:model",
-
"#{test}:controller",
-
"#{test}:helper",
-
"#{test}:integration",
-
"#{test}:mailer",
-
"#{test}:model",
-
"#{test}:scaffold",
-
"#{test}:view",
-
"#{template}:controller",
-
"#{template}:scaffold",
-
"#{template}:mailer",
-
"#{css}:scaffold",
-
"#{css}:assets",
-
"css:assets",
-
"css:scaffold"
-
]
-
end
-
end
-
-
1
class << self
-
1
def hide_namespaces(*namespaces)
-
hidden_namespaces.concat(namespaces)
-
end
-
1
alias hide_namespace hide_namespaces
-
end
-
-
# Show help message with available generators.
-
1
def self.help(command = 'generate')
-
puts "Usage: rails #{command} GENERATOR [args] [options]"
-
puts
-
puts "General options:"
-
puts " -h, [--help] # Print generator's options and usage"
-
puts " -p, [--pretend] # Run but do not make any changes"
-
puts " -f, [--force] # Overwrite files that already exist"
-
puts " -s, [--skip] # Skip files that already exist"
-
puts " -q, [--quiet] # Suppress status output"
-
puts
-
puts "Please choose a generator below."
-
puts
-
-
print_generators
-
end
-
-
1
def self.public_namespaces
-
lookup!
-
subclasses.map { |k| k.namespace }
-
end
-
-
1
def self.print_generators
-
sorted_groups.each { |b, n| print_list(b, n) }
-
end
-
-
1
def self.sorted_groups
-
namespaces = public_namespaces
-
namespaces.sort!
-
groups = Hash.new { |h,k| h[k] = [] }
-
namespaces.each do |namespace|
-
base = namespace.split(':').first
-
groups[base] << namespace
-
end
-
rails = groups.delete("rails")
-
rails.map! { |n| n.sub(/^rails:/, '') }
-
rails.delete("app")
-
rails.delete("plugin")
-
-
hidden_namespaces.each { |n| groups.delete(n.to_s) }
-
-
[["rails", rails]] + groups.sort.to_a
-
end
-
-
1
protected
-
-
# This code is based directly on the Text gem implementation
-
# Returns a value representing the "cost" of transforming str1 into str2
-
1
def self.levenshtein_distance str1, str2
-
s = str1
-
t = str2
-
n = s.length
-
m = t.length
-
-
return m if (0 == n)
-
return n if (0 == m)
-
-
d = (0..m).to_a
-
x = nil
-
-
str1.each_char.each_with_index do |char1,i|
-
e = i+1
-
-
str2.each_char.each_with_index do |char2,j|
-
cost = (char1 == char2) ? 0 : 1
-
x = [
-
d[j+1] + 1, # insertion
-
e + 1, # deletion
-
d[j] + cost # substitution
-
].min
-
d[j] = e
-
e = x
-
end
-
-
d[m] = x
-
end
-
-
return x
-
end
-
-
# Prints a list of generators.
-
1
def self.print_list(base, namespaces) #:nodoc:
-
namespaces = namespaces.reject do |n|
-
hidden_namespaces.include?(n)
-
end
-
-
return if namespaces.empty?
-
puts "#{base.camelize}:"
-
-
namespaces.each do |namespace|
-
puts(" #{namespace}")
-
end
-
-
puts
-
end
-
-
# Try fallbacks for the given base.
-
1
def self.invoke_fallbacks_for(name, base) #:nodoc:
-
return nil unless base && fallbacks[base.to_sym]
-
invoked_fallbacks = []
-
-
Array(fallbacks[base.to_sym]).each do |fallback|
-
next if invoked_fallbacks.include?(fallback)
-
invoked_fallbacks << fallback
-
-
klass = find_by_namespace(name, fallback)
-
return klass if klass
-
end
-
-
nil
-
end
-
-
# Receives namespaces in an array and tries to find matching generators
-
# in the load path.
-
1
def self.lookup(namespaces) #:nodoc:
-
paths = namespaces_to_paths(namespaces)
-
-
paths.each do |raw_path|
-
["rails/generators", "generators"].each do |base|
-
path = "#{base}/#{raw_path}_generator"
-
-
begin
-
require path
-
return
-
rescue LoadError => e
-
raise unless e.message =~ /#{Regexp.escape(path)}$/
-
rescue Exception => e
-
warn "[WARNING] Could not load generator #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}"
-
end
-
end
-
end
-
end
-
-
# This will try to load any generator in the load path to show in help.
-
1
def self.lookup! #:nodoc:
-
$LOAD_PATH.each do |base|
-
Dir[File.join(base, "{rails/generators,generators}", "**", "*_generator.rb")].each do |path|
-
begin
-
path = path.sub("#{base}/", "")
-
require path
-
rescue Exception
-
# No problem
-
end
-
end
-
end
-
end
-
-
# Convert namespaces to paths by replacing ":" for "/" and adding
-
# an extra lookup. For example, "rails:model" should be searched
-
# in both: "rails/model/model_generator" and "rails/model_generator".
-
1
def self.namespaces_to_paths(namespaces) #:nodoc:
-
paths = []
-
namespaces.each do |namespace|
-
pieces = namespace.split(":")
-
paths << pieces.dup.push(pieces.last).join("/")
-
paths << pieces.join("/")
-
end
-
paths.uniq!
-
paths
-
end
-
end
-
end
-
1
require 'rails/generators'
-
1
require 'rails/generators/testing/behaviour'
-
1
require 'rails/generators/testing/setup_and_teardown'
-
1
require 'rails/generators/testing/assertions'
-
1
require 'fileutils'
-
-
1
module Rails
-
1
module Generators
-
# Disable color in output. Easier to debug.
-
1
no_color!
-
-
# This class provides a TestCase for testing generators. To setup, you need
-
# just to configure the destination and set which generator is being tested:
-
#
-
# class AppGeneratorTest < Rails::Generators::TestCase
-
# tests AppGenerator
-
# destination File.expand_path("../tmp", File.dirname(__FILE__))
-
# end
-
#
-
# If you want to ensure your destination root is clean before running each test,
-
# you can set a setup callback:
-
#
-
# class AppGeneratorTest < Rails::Generators::TestCase
-
# tests AppGenerator
-
# destination File.expand_path("../tmp", File.dirname(__FILE__))
-
# setup :prepare_destination
-
# end
-
1
class TestCase < ActiveSupport::TestCase
-
1
include Rails::Generators::Testing::Behaviour
-
1
include Rails::Generators::Testing::SetupAndTeardown
-
1
include Rails::Generators::Testing::Assertions
-
1
include FileUtils
-
-
end
-
end
-
end
-
1
require 'shellwords'
-
-
1
module Rails
-
1
module Generators
-
1
module Testing
-
1
module Assertions
-
# Asserts a given file exists. You need to supply an absolute path or a path relative
-
# to the configured destination:
-
#
-
# assert_file "config/environment.rb"
-
#
-
# You can also give extra arguments. If the argument is a regexp, it will check if the
-
# regular expression matches the given file content. If it's a string, it compares the
-
# file with the given string:
-
#
-
# assert_file "config/environment.rb", /initialize/
-
#
-
# Finally, when a block is given, it yields the file content:
-
#
-
# assert_file "app/controllers/products_controller.rb" do |controller|
-
# assert_instance_method :index, controller do |index|
-
# assert_match(/Product\.all/, index)
-
# end
-
# end
-
1
def assert_file(relative, *contents)
-
absolute = File.expand_path(relative, destination_root)
-
assert File.exist?(absolute), "Expected file #{relative.inspect} to exist, but does not"
-
-
read = File.read(absolute) if block_given? || !contents.empty?
-
yield read if block_given?
-
-
contents.each do |content|
-
case content
-
when String
-
assert_equal content, read
-
when Regexp
-
assert_match content, read
-
end
-
end
-
end
-
1
alias :assert_directory :assert_file
-
-
# Asserts a given file does not exist. You need to supply an absolute path or a
-
# path relative to the configured destination:
-
#
-
# assert_no_file "config/random.rb"
-
1
def assert_no_file(relative)
-
absolute = File.expand_path(relative, destination_root)
-
assert !File.exist?(absolute), "Expected file #{relative.inspect} to not exist, but does"
-
end
-
1
alias :assert_no_directory :assert_no_file
-
-
# Asserts a given migration exists. You need to supply an absolute path or a
-
# path relative to the configured destination:
-
#
-
# assert_migration "db/migrate/create_products.rb"
-
#
-
# This method manipulates the given path and tries to find any migration which
-
# matches the migration name. For example, the call above is converted to:
-
#
-
# assert_file "db/migrate/003_create_products.rb"
-
#
-
# Consequently, assert_migration accepts the same arguments has assert_file.
-
1
def assert_migration(relative, *contents, &block)
-
file_name = migration_file_name(relative)
-
assert file_name, "Expected migration #{relative} to exist, but was not found"
-
assert_file file_name, *contents, &block
-
end
-
-
# Asserts a given migration does not exist. You need to supply an absolute path or a
-
# path relative to the configured destination:
-
#
-
# assert_no_migration "db/migrate/create_products.rb"
-
1
def assert_no_migration(relative)
-
file_name = migration_file_name(relative)
-
assert_nil file_name, "Expected migration #{relative} to not exist, but found #{file_name}"
-
end
-
-
# Asserts the given class method exists in the given content. This method does not detect
-
# class methods inside (class << self), only class methods which starts with "self.".
-
# When a block is given, it yields the content of the method.
-
#
-
# assert_migration "db/migrate/create_products.rb" do |migration|
-
# assert_class_method :up, migration do |up|
-
# assert_match(/create_table/, up)
-
# end
-
# end
-
1
def assert_class_method(method, content, &block)
-
assert_instance_method "self.#{method}", content, &block
-
end
-
-
# Asserts the given method exists in the given content. When a block is given,
-
# it yields the content of the method.
-
#
-
# assert_file "app/controllers/products_controller.rb" do |controller|
-
# assert_instance_method :index, controller do |index|
-
# assert_match(/Product\.all/, index)
-
# end
-
# end
-
1
def assert_instance_method(method, content)
-
assert content =~ /(\s+)def #{method}(\(.+\))?(.*?)\n\1end/m, "Expected to have method #{method}"
-
yield $3.strip if block_given?
-
end
-
1
alias :assert_method :assert_instance_method
-
-
# Asserts the given attribute type gets translated to a field type
-
# properly:
-
#
-
# assert_field_type :date, :date_select
-
1
def assert_field_type(attribute_type, field_type)
-
assert_equal(field_type, create_generated_attribute(attribute_type).field_type)
-
end
-
-
# Asserts the given attribute type gets a proper default value:
-
#
-
# assert_field_default_value :string, "MyString"
-
1
def assert_field_default_value(attribute_type, value)
-
assert_equal(value, create_generated_attribute(attribute_type).default)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/concern'
-
1
require 'rails/generators'
-
-
1
module Rails
-
1
module Generators
-
1
module Testing
-
1
module Behaviour
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :destination_root, :current_path, :generator_class, :default_arguments
-
-
# Generators frequently change the current path using +FileUtils.cd+.
-
# So we need to store the path at file load and revert back to it after each test.
-
1
self.current_path = File.expand_path(Dir.pwd)
-
1
self.default_arguments = []
-
end
-
-
1
module ClassMethods
-
# Sets which generator should be tested:
-
#
-
# tests AppGenerator
-
1
def tests(klass)
-
self.generator_class = klass
-
end
-
-
# Sets default arguments on generator invocation. This can be overwritten when
-
# invoking it.
-
#
-
# arguments %w(app_name --skip-active-record)
-
1
def arguments(array)
-
self.default_arguments = array
-
end
-
-
# Sets the destination of generator files:
-
#
-
# destination File.expand_path("../tmp", File.dirname(__FILE__))
-
1
def destination(path)
-
self.destination_root = path
-
end
-
end
-
-
# Runs the generator configured for this class. The first argument is an array like
-
# command line arguments:
-
#
-
# class AppGeneratorTest < Rails::Generators::TestCase
-
# tests AppGenerator
-
# destination File.expand_path("../tmp", File.dirname(__FILE__))
-
# setup :prepare_destination
-
#
-
# test "database.yml is not created when skipping Active Record" do
-
# run_generator %w(myapp --skip-active-record)
-
# assert_no_file "config/database.yml"
-
# end
-
# end
-
#
-
# You can provide a configuration hash as second argument. This method returns the output
-
# printed by the generator.
-
1
def run_generator(args=self.default_arguments, config={})
-
capture(:stdout) do
-
args += ['--skip-bundle'] unless args.include? '--dev'
-
self.generator_class.start(args, config.reverse_merge(destination_root: destination_root))
-
end
-
end
-
-
# Instantiate the generator.
-
1
def generator(args=self.default_arguments, options={}, config={})
-
@generator ||= self.generator_class.new(args, options, config.reverse_merge(destination_root: destination_root))
-
end
-
-
# Create a Rails::Generators::GeneratedAttribute by supplying the
-
# attribute type and, optionally, the attribute name:
-
#
-
# create_generated_attribute(:string, 'name')
-
1
def create_generated_attribute(attribute_type, name = 'test', index = nil)
-
Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(':'))
-
end
-
-
1
protected
-
-
1
def destination_root_is_set? # :nodoc:
-
raise "You need to configure your Rails::Generators::TestCase destination root." unless destination_root
-
end
-
-
1
def ensure_current_path # :nodoc:
-
cd current_path
-
end
-
-
1
def prepare_destination # :nodoc:
-
rm_rf(destination_root)
-
mkdir_p(destination_root)
-
end
-
-
1
def migration_file_name(relative) # :nodoc:
-
absolute = File.expand_path(relative, destination_root)
-
dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, '')
-
Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first
-
end
-
-
1
def capture(stream)
-
stream = stream.to_s
-
captured_stream = Tempfile.new(stream)
-
stream_io = eval("$#{stream}")
-
origin_stream = stream_io.dup
-
stream_io.reopen(captured_stream)
-
-
yield
-
-
stream_io.rewind
-
return captured_stream.read
-
ensure
-
captured_stream.close
-
captured_stream.unlink
-
stream_io.reopen(origin_stream)
-
end
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
module Generators
-
1
module Testing
-
1
module SetupAndTeardown
-
1
def setup # :nodoc:
-
destination_root_is_set?
-
ensure_current_path
-
super
-
end
-
-
1
def teardown # :nodoc:
-
ensure_current_path
-
super
-
end
-
end
-
end
-
end
-
end
-
1
require 'tsort'
-
-
1
module Rails
-
1
module Initializable
-
1
def self.included(base) #:nodoc:
-
3
base.extend ClassMethods
-
end
-
-
1
class Initializer
-
1
attr_reader :name, :block
-
-
1
def initialize(name, context, options, &block)
-
168
options[:group] ||= :default
-
168
@name, @context, @options, @block = name, context, options, block
-
end
-
-
1
def before
-
9801
@options[:before]
-
end
-
-
1
def after
-
9788
@options[:after]
-
end
-
-
1
def belongs_to?(group)
-
99
@options[:group] == group || @options[:group] == :all
-
end
-
-
1
def run(*args)
-
99
@context.instance_exec(*args, &block)
-
end
-
-
1
def bind(context)
-
99
return self if @context
-
99
Initializer.new(@name, context, @options, &block)
-
end
-
end
-
-
1
class Collection < Array
-
1
include TSort
-
-
1
alias :tsort_each_node :each
-
1
def tsort_each_child(initializer, &block)
-
9900
select { |i| i.before == initializer.name || i.name == initializer.after }.each(&block)
-
end
-
-
1
def +(other)
-
51
Collection.new(to_a + other.to_a)
-
end
-
end
-
-
1
def run_initializers(group=:default, *args)
-
1
return if instance_variable_defined?(:@ran)
-
1
initializers.tsort_each do |initializer|
-
99
initializer.run(*args) if initializer.belongs_to?(group)
-
end
-
1
@ran = true
-
end
-
-
1
def initializers
-
21
@initializers ||= self.class.initializers_for(self)
-
end
-
-
1
module ClassMethods
-
1
def initializers
-
288
@initializers ||= Collection.new
-
end
-
-
1
def initializers_chain
-
23
initializers = Collection.new
-
23
ancestors.reverse_each do |klass|
-
178
next unless klass.respond_to?(:initializers)
-
49
initializers = initializers + klass.initializers
-
end
-
23
initializers
-
end
-
-
1
def initializers_for(binding)
-
122
Collection.new(initializers_chain.map { |i| i.bind(binding) })
-
end
-
-
1
def initializer(name, opts = {}, &blk)
-
69
raise ArgumentError, "A block must be passed when defining an initializer" unless blk
-
259
opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
-
69
initializers << Initializer.new(name, nil, opts, &blk)
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
module Paths
-
# This object is an extended hash that behaves as root of the <tt>Rails::Paths</tt> system.
-
# It allows you to collect information about how you want to structure your application
-
# paths by a Hash like API. It requires you to give a physical path on initialization.
-
#
-
# root = Root.new "/rails"
-
# root.add "app/controllers", eager_load: true
-
#
-
# The command above creates a new root object and add "app/controllers" as a path.
-
# This means we can get a <tt>Rails::Paths::Path</tt> object back like below:
-
#
-
# path = root["app/controllers"]
-
# path.eager_load? # => true
-
# path.is_a?(Rails::Paths::Path) # => true
-
#
-
# The +Path+ object is simply an enumerable and allows you to easily add extra paths:
-
#
-
# path.is_a?(Enumerable) # => true
-
# path.to_ary.inspect # => ["app/controllers"]
-
#
-
# path << "lib/controllers"
-
# path.to_ary.inspect # => ["app/controllers", "lib/controllers"]
-
#
-
# Notice that when you add a path using +add+, the path object created already
-
# contains the path with the same path value given to +add+. In some situations,
-
# you may not want this behavior, so you can give <tt>:with</tt> as option.
-
#
-
# root.add "config/routes", with: "config/routes.rb"
-
# root["config/routes"].inspect # => ["config/routes.rb"]
-
#
-
# The +add+ method accepts the following options as arguments:
-
# eager_load, autoload, autoload_once and glob.
-
#
-
# Finally, the +Path+ object also provides a few helpers:
-
#
-
# root = Root.new "/rails"
-
# root.add "app/controllers"
-
#
-
# root["app/controllers"].expanded # => ["/rails/app/controllers"]
-
# root["app/controllers"].existent # => ["/rails/app/controllers"]
-
#
-
# Check the <tt>Rails::Paths::Path</tt> documentation for more information.
-
1
class Root
-
1
attr_accessor :path
-
-
1
def initialize(path)
-
4
@current = nil
-
4
@path = path
-
4
@root = {}
-
end
-
-
1
def []=(path, value)
-
glob = self[path] ? self[path].glob : nil
-
add(path, with: value, glob: glob)
-
end
-
-
1
def add(path, options = {})
-
97
with = Array(options.fetch(:with, path))
-
97
@root[path] = Path.new(self, path, with, options)
-
end
-
-
1
def [](path)
-
51
@root[path]
-
end
-
-
1
def values
-
16
@root.values
-
end
-
-
1
def keys
-
36
@root.keys
-
end
-
-
1
def values_at(*list)
-
36
@root.values_at(*list)
-
end
-
-
1
def all_paths
-
32
values.tap { |v| v.uniq! }
-
end
-
-
1
def autoload_once
-
101
filter_by { |p| p.autoload_once? }
-
end
-
-
1
def eager_load
-
141
filter_by { |p| p.eager_load? }
-
end
-
-
1
def autoload_paths
-
101
filter_by { |p| p.autoload? }
-
end
-
-
1
def load_paths
-
114
filter_by { |p| p.load_path? }
-
end
-
-
1
private
-
-
1
def filter_by(&block)
-
all_paths.find_all(&block).flat_map { |path|
-
36
paths = path.existent
-
89
paths - path.children.flat_map { |p| yield(p) ? [] : p.existent }
-
16
}.uniq
-
end
-
end
-
-
1
class Path
-
1
include Enumerable
-
-
1
attr_accessor :glob
-
-
1
def initialize(root, current, paths, options = {})
-
97
@paths = paths
-
97
@current = current
-
97
@root = root
-
97
@glob = options[:glob]
-
-
97
options[:autoload_once] ? autoload_once! : skip_autoload_once!
-
97
options[:eager_load] ? eager_load! : skip_eager_load!
-
97
options[:autoload] ? autoload! : skip_autoload!
-
97
options[:load_path] ? load_path! : skip_load_path!
-
end
-
-
1
def children
-
36
keys = @root.keys.find_all { |k|
-
873
k.start_with?(@current) && k != @current
-
}
-
36
@root.values_at(*keys.sort)
-
end
-
-
1
def first
-
13
expanded.first
-
end
-
-
1
def last
-
expanded.last
-
end
-
-
1
%w(autoload_once eager_load autoload load_path).each do |m|
-
4
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{m}! # def eager_load!
-
@#{m} = true # @eager_load = true
-
end # end
-
#
-
def skip_#{m}! # def skip_eager_load!
-
@#{m} = false # @eager_load = false
-
end # end
-
#
-
def #{m}? # def eager_load?
-
@#{m} # @eager_load
-
end # end
-
RUBY
-
end
-
-
1
def each(&block)
-
108
@paths.each(&block)
-
end
-
-
1
def <<(path)
-
@paths << path
-
end
-
1
alias :push :<<
-
-
1
def concat(paths)
-
@paths.concat paths
-
end
-
-
1
def unshift(*paths)
-
@paths.unshift(*paths)
-
end
-
-
1
def to_ary
-
@paths
-
end
-
-
# Expands all paths against the root and return all unique values.
-
1
def expanded
-
108
raise "You need to set a path root" unless @root.path
-
108
result = []
-
-
108
each do |p|
-
108
path = File.expand_path(p, @root.path)
-
-
108
if @glob && File.directory?(path)
-
15
Dir.chdir(path) do
-
46
result.concat(Dir.glob(@glob).map { |file| File.join path, file }.sort)
-
end
-
else
-
93
result << path
-
end
-
end
-
-
108
result.uniq!
-
108
result
-
end
-
-
# Returns all expanded paths but only if they exist in the filesystem.
-
1
def existent
-
180
expanded.select { |f| File.exist?(f) }
-
end
-
-
1
def existent_directories
-
26
expanded.select { |d| File.directory?(d) }
-
end
-
-
1
alias to_a expanded
-
end
-
end
-
end
-
1
module Rails
-
1
module Rack
-
1
autoload :Debugger, "rails/rack/debugger" if RUBY_VERSION < '2.0.0'
-
1
autoload :Logger, "rails/rack/logger"
-
1
autoload :LogTailer, "rails/rack/log_tailer"
-
end
-
end
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/log_subscriber'
-
1
require 'action_dispatch/http/request'
-
1
require 'rack/body_proxy'
-
-
1
module Rails
-
1
module Rack
-
# Sets log tags, logs the request, calls the app, and flushes the logs.
-
1
class Logger < ActiveSupport::LogSubscriber
-
1
def initialize(app, taggers = nil)
-
1
@app = app
-
1
@taggers = taggers || []
-
end
-
-
1
def call(env)
-
66
request = ActionDispatch::Request.new(env)
-
-
66
if logger.respond_to?(:tagged)
-
132
logger.tagged(compute_tags(request)) { call_app(request, env) }
-
else
-
call_app(request, env)
-
end
-
end
-
-
1
protected
-
-
1
def call_app(request, env)
-
# Put some space between requests in development logs.
-
66
if development?
-
logger.debug ''
-
logger.debug ''
-
end
-
-
66
instrumenter = ActiveSupport::Notifications.instrumenter
-
66
instrumenter.start 'request.action_dispatch', request: request
-
132
logger.info { started_request_message(request) }
-
66
resp = @app.call(env)
-
132
resp[2] = ::Rack::BodyProxy.new(resp[2]) { finish(request) }
-
66
resp
-
rescue Exception
-
finish(request)
-
raise
-
ensure
-
66
ActiveSupport::LogSubscriber.flush_all!
-
end
-
-
# Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700
-
1
def started_request_message(request)
-
'Started %s "%s" for %s at %s' % [
-
request.request_method,
-
request.filtered_path,
-
request.ip,
-
66
Time.now.to_default_s ]
-
end
-
-
1
def compute_tags(request)
-
66
@taggers.collect do |tag|
-
case tag
-
when Proc
-
tag.call(request)
-
when Symbol
-
request.send(tag)
-
else
-
tag
-
end
-
end
-
end
-
-
1
private
-
-
1
def finish(request)
-
66
instrumenter = ActiveSupport::Notifications.instrumenter
-
66
instrumenter.finish 'request.action_dispatch', request: request
-
end
-
-
1
def development?
-
66
Rails.env.development?
-
end
-
-
1
def logger
-
198
Rails.logger
-
end
-
end
-
end
-
end
-
1
require 'rails/initializable'
-
1
require 'rails/configuration'
-
1
require 'active_support/inflector'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/module/delegation'
-
-
1
module Rails
-
# Railtie is the core of the Rails framework and provides several hooks to extend
-
# Rails and/or modify the initialization process.
-
#
-
# Every major component of Rails (Action Mailer, Action Controller,
-
# Action View and Active Record) is a Railtie. Each of
-
# them is responsible for their own initialization. This makes Rails itself
-
# absent of any component hooks, allowing other components to be used in
-
# place of any of the Rails defaults.
-
#
-
# Developing a Rails extension does _not_ require any implementation of
-
# Railtie, but if you need to interact with the Rails framework during
-
# or after boot, then Railtie is needed.
-
#
-
# For example, an extension doing any of the following would require Railtie:
-
#
-
# * creating initializers
-
# * configuring a Rails framework for the application, like setting a generator
-
# * adding <tt>config.*</tt> keys to the environment
-
# * setting up a subscriber with ActiveSupport::Notifications
-
# * adding rake tasks
-
#
-
# == Creating your Railtie
-
#
-
# To extend Rails using Railtie, create a Railtie class which inherits
-
# from Rails::Railtie within your extension's namespace. This class must be
-
# loaded during the Rails boot process.
-
#
-
# The following example demonstrates an extension which can be used with or without Rails.
-
#
-
# # lib/my_gem/railtie.rb
-
# module MyGem
-
# class Railtie < Rails::Railtie
-
# end
-
# end
-
#
-
# # lib/my_gem.rb
-
# require 'my_gem/railtie' if defined?(Rails)
-
#
-
# == Initializers
-
#
-
# To add an initialization step from your Railtie to Rails boot process, you just need
-
# to create an initializer block:
-
#
-
# class MyRailtie < Rails::Railtie
-
# initializer "my_railtie.configure_rails_initialization" do
-
# # some initialization behavior
-
# end
-
# end
-
#
-
# If specified, the block can also receive the application object, in case you
-
# need to access some application specific configuration, like middleware:
-
#
-
# class MyRailtie < Rails::Railtie
-
# initializer "my_railtie.configure_rails_initialization" do |app|
-
# app.middleware.use MyRailtie::Middleware
-
# end
-
# end
-
#
-
# Finally, you can also pass <tt>:before</tt> and <tt>:after</tt> as option to initializer,
-
# in case you want to couple it with a specific step in the initialization process.
-
#
-
# == Configuration
-
#
-
# Inside the Railtie class, you can access a config object which contains configuration
-
# shared by all railties and the application:
-
#
-
# class MyRailtie < Rails::Railtie
-
# # Customize the ORM
-
# config.app_generators.orm :my_railtie_orm
-
#
-
# # Add a to_prepare block which is executed once in production
-
# # and before each request in development
-
# config.to_prepare do
-
# MyRailtie.setup!
-
# end
-
# end
-
#
-
# == Loading rake tasks and generators
-
#
-
# If your railtie has rake tasks, you can tell Rails to load them through the method
-
# rake_tasks:
-
#
-
# class MyRailtie < Rails::Railtie
-
# rake_tasks do
-
# load "path/to/my_railtie.tasks"
-
# end
-
# end
-
#
-
# By default, Rails loads generators from your load path. However, if you want to place
-
# your generators at a different location, you can specify in your Railtie a block which
-
# will load them during normal generators lookup:
-
#
-
# class MyRailtie < Rails::Railtie
-
# generators do
-
# require "path/to/my_railtie_generator"
-
# end
-
# end
-
#
-
# == Application and Engine
-
#
-
# A Rails::Engine is nothing more than a Railtie with some initializers already set.
-
# And since Rails::Application is an engine, the same configuration described here
-
# can be used in both.
-
#
-
# Be sure to look at the documentation of those specific classes for more information.
-
#
-
1
class Railtie
-
1
autoload :Configuration, "rails/railtie/configuration"
-
-
1
include Initializable
-
-
1
ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Engine Rails::Application)
-
-
1
class << self
-
1
private :new
-
1
delegate :config, to: :instance
-
-
1
def subclasses
-
23
@subclasses ||= []
-
end
-
-
1
def inherited(base)
-
23
unless base.abstract_railtie?
-
21
subclasses << base
-
end
-
end
-
-
1
def rake_tasks(&blk)
-
6
@rake_tasks ||= []
-
6
@rake_tasks << blk if blk
-
6
@rake_tasks
-
end
-
-
1
def console(&blk)
-
3
@load_console ||= []
-
3
@load_console << blk if blk
-
3
@load_console
-
end
-
-
1
def runner(&blk)
-
1
@load_runner ||= []
-
1
@load_runner << blk if blk
-
1
@load_runner
-
end
-
-
1
def generators(&blk)
-
2
@generators ||= []
-
2
@generators << blk if blk
-
2
@generators
-
end
-
-
1
def abstract_railtie?
-
49
ABSTRACT_RAILTIES.include?(name)
-
end
-
-
1
def railtie_name(name = nil)
-
1
@railtie_name = name.to_s if name
-
1
@railtie_name ||= generate_railtie_name(self.name)
-
end
-
-
# Since Rails::Railtie cannot be instantiated, any methods that call
-
# +instance+ are intended to be called only on subclasses of a Railtie.
-
1
def instance
-
117
@instance ||= new
-
end
-
-
1
def respond_to_missing?(*args)
-
instance.respond_to?(*args) || super
-
end
-
-
# Allows you to configure the railtie. This is the same method seen in
-
# Railtie::Configurable, but this module is no longer required for all
-
# subclasses of Railtie so we provide the class method here.
-
1
def configure(&block)
-
instance.configure(&block)
-
end
-
-
1
protected
-
1
def generate_railtie_name(string)
-
1
ActiveSupport::Inflector.underscore(string).tr("/", "_")
-
end
-
-
# If the class method does not have a method, then send the method call
-
# to the Railtie instance.
-
1
def method_missing(name, *args, &block)
-
1
if instance.respond_to?(name)
-
1
instance.public_send(name, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
-
1
delegate :railtie_name, to: :class
-
-
1
def initialize
-
21
if self.class.abstract_railtie?
-
raise "#{self.class.name} is abstract, you cannot instantiate it directly."
-
end
-
end
-
-
1
def configure(&block)
-
1
instance_eval(&block)
-
end
-
-
1
def config
-
104
@config ||= Railtie::Configuration.new
-
end
-
-
1
def railtie_namespace
-
@railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:railtie_namespace) }
-
end
-
-
1
protected
-
-
1
def run_console_blocks(app) #:nodoc:
-
each_registered_block(:console) { |block| block.call(app) }
-
end
-
-
1
def run_generators_blocks(app) #:nodoc:
-
each_registered_block(:generators) { |block| block.call(app) }
-
end
-
-
1
def run_runner_blocks(app) #:nodoc:
-
each_registered_block(:runner) { |block| block.call(app) }
-
end
-
-
1
def run_tasks_blocks(app) #:nodoc:
-
extend Rake::DSL
-
each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) }
-
end
-
-
1
private
-
-
1
def each_registered_block(type, &block)
-
klass = self.class
-
while klass.respond_to?(type)
-
klass.public_send(type).each(&block)
-
klass = klass.superclass
-
end
-
end
-
end
-
end
-
1
require 'rails/configuration'
-
-
1
module Rails
-
1
class Railtie
-
1
class Configuration
-
1
def initialize
-
19
@@options ||= {}
-
end
-
-
# Expose the eager_load_namespaces at "module" level for convenience.
-
1
def self.eager_load_namespaces #:nodoc:
-
4
@@eager_load_namespaces ||= []
-
end
-
-
# All namespaces that are eager loaded
-
1
def eager_load_namespaces
-
7
@@eager_load_namespaces ||= []
-
end
-
-
# Add files that should be watched for change.
-
1
def watchable_files
-
2
@@watchable_files ||= []
-
end
-
-
# Add directories that should be watched for change.
-
# The key of the hashes should be directories and the values should
-
# be an array of extensions to match in each directory.
-
1
def watchable_dirs
-
1
@@watchable_dirs ||= {}
-
end
-
-
# This allows you to modify the application's middlewares from Engines.
-
#
-
# All operations you run on the app_middleware will be replayed on the
-
# application once it is defined and the default_middlewares are
-
# created
-
1
def app_middleware
-
3
@@app_middleware ||= Rails::Configuration::MiddlewareStackProxy.new
-
end
-
-
# This allows you to modify application's generators from Railties.
-
#
-
# Values set on app_generators will become defaults for application, unless
-
# application overwrites them.
-
1
def app_generators
-
12
@@app_generators ||= Rails::Configuration::Generators.new
-
12
yield(@@app_generators) if block_given?
-
12
@@app_generators
-
end
-
-
# First configurable block to run. Called before any initializers are run.
-
1
def before_configuration(&block)
-
ActiveSupport.on_load(:before_configuration, yield: true, &block)
-
end
-
-
# Third configurable block to run. Does not run if +config.cache_classes+
-
# set to false.
-
1
def before_eager_load(&block)
-
1
ActiveSupport.on_load(:before_eager_load, yield: true, &block)
-
end
-
-
# Second configurable block to run. Called before frameworks initialize.
-
1
def before_initialize(&block)
-
ActiveSupport.on_load(:before_initialize, yield: true, &block)
-
end
-
-
# Last configurable block to run. Called after frameworks initialize.
-
1
def after_initialize(&block)
-
7
ActiveSupport.on_load(:after_initialize, yield: true, &block)
-
end
-
-
# Array of callbacks defined by #to_prepare.
-
1
def to_prepare_blocks
-
1
@@to_prepare_blocks ||= []
-
end
-
-
# Defines generic callbacks to run before #after_initialize. Useful for
-
# Rails::Railtie subclasses.
-
1
def to_prepare(&blk)
-
to_prepare_blocks << blk if blk
-
end
-
-
1
def respond_to?(name, include_private = false)
-
5
super || @@options.key?(name.to_sym)
-
end
-
-
1
private
-
-
1
def method_missing(name, *args, &blk)
-
181
if name.to_s =~ /=$/
-
12
@@options[$`.to_sym] = args.first
-
169
elsif @@options.key?(name)
-
169
@@options[name]
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
1
if RUBY_VERSION < '1.9.3'
-
desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
-
abort <<-end_message
-
-
Rails 4 prefers to run on Ruby 2.1 or newer.
-
-
You're running
-
#{desc}
-
-
Please upgrade to Ruby 1.9.3 or newer to continue.
-
-
end_message
-
end
-
# Implements the logic behind the rake tasks for annotations like
-
#
-
# rake notes
-
# rake notes:optimize
-
#
-
# and friends. See <tt>rake -T notes</tt> and <tt>railties/lib/tasks/annotations.rake</tt>.
-
#
-
# Annotation objects are triplets <tt>:line</tt>, <tt>:tag</tt>, <tt>:text</tt> that
-
# represent the line where the annotation lives, its tag, and its text. Note
-
# the filename is not stored.
-
#
-
# Annotations are looked for in comments and modulus whitespace they have to
-
# start with the tag optionally followed by a colon. Everything up to the end
-
# of the line (or closing ERB comment tag) is considered to be their text.
-
1
class SourceAnnotationExtractor
-
1
class Annotation < Struct.new(:line, :tag, :text)
-
1
def self.directories
-
@@directories ||= %w(app config db lib test) + (ENV['SOURCE_ANNOTATION_DIRECTORIES'] || '').split(',')
-
end
-
-
1
def self.extensions
-
3
@@extensions ||= {}
-
end
-
-
# Registers new Annotations File Extensions
-
# SourceAnnotationExtractor::Annotation.register_extensions("css", "scss", "sass", "less", "js") { |tag| /\/\/\s*(#{tag}):?\s*(.*)$/ }
-
1
def self.register_extensions(*exts, &block)
-
3
extensions[/\.(#{exts.join("|")})$/] = block
-
end
-
-
1
register_extensions("builder", "rb", "rake", "yml", "yaml", "ruby") { |tag| /#\s*(#{tag}):?\s*(.*)$/ }
-
1
register_extensions("css", "js") { |tag| /\/\/\s*(#{tag}):?\s*(.*)$/ }
-
1
register_extensions("erb") { |tag| /<%\s*#\s*(#{tag}):?\s*(.*?)\s*%>/ }
-
-
# Returns a representation of the annotation that looks like this:
-
#
-
# [126] [TODO] This algorithm is simple and clearly correct, make it faster.
-
#
-
# If +options+ has a flag <tt>:tag</tt> the tag is shown as in the example above.
-
# Otherwise the string contains just line and text.
-
1
def to_s(options={})
-
s = "[#{line.to_s.rjust(options[:indent])}] "
-
s << "[#{tag}] " if options[:tag]
-
s << text
-
end
-
end
-
-
# Prints all annotations with tag +tag+ under the root directories +app+,
-
# +config+, +db+, +lib+, and +test+ (recursively).
-
#
-
# Additional directories may be added using a comma-delimited list set using
-
# <tt>ENV['SOURCE_ANNOTATION_DIRECTORIES']</tt>.
-
#
-
# Directories may also be explicitly set using the <tt>:dirs</tt> key in +options+.
-
#
-
# SourceAnnotationExtractor.enumerate 'TODO|FIXME', dirs: %w(app lib), tag: true
-
#
-
# If +options+ has a <tt>:tag</tt> flag, it will be passed to each annotation's +to_s+.
-
#
-
# See <tt>#find_in</tt> for a list of file extensions that will be taken into account.
-
#
-
# This class method is the single entry point for the rake tasks.
-
1
def self.enumerate(tag, options={})
-
extractor = new(tag)
-
dirs = options.delete(:dirs) || Annotation.directories
-
extractor.display(extractor.find(dirs), options)
-
end
-
-
1
attr_reader :tag
-
-
1
def initialize(tag)
-
@tag = tag
-
end
-
-
# Returns a hash that maps filenames under +dirs+ (recursively) to arrays
-
# with their annotations.
-
1
def find(dirs)
-
dirs.inject({}) { |h, dir| h.update(find_in(dir)) }
-
end
-
-
# Returns a hash that maps filenames under +dir+ (recursively) to arrays
-
# with their annotations. Only files with annotations are included. Files
-
# with extension +.builder+, +.rb+, +.rake+, +.yml+, +.yaml+, +.ruby+,
-
# +.css+, +.js+ and +.erb+ are taken into account.
-
1
def find_in(dir)
-
results = {}
-
-
Dir.glob("#{dir}/*") do |item|
-
next if File.basename(item)[0] == ?.
-
-
if File.directory?(item)
-
results.update(find_in(item))
-
else
-
extension = Annotation.extensions.detect do |regexp, _block|
-
regexp.match(item)
-
end
-
-
if extension
-
pattern = extension.last.call(tag)
-
results.update(extract_annotations_from(item, pattern)) if pattern
-
end
-
end
-
end
-
-
results
-
end
-
-
# If +file+ is the filename of a file that contains annotations this method returns
-
# a hash with a single entry that maps +file+ to an array of its annotations.
-
# Otherwise it returns an empty hash.
-
1
def extract_annotations_from(file, pattern)
-
lineno = 0
-
result = File.readlines(file).inject([]) do |list, line|
-
lineno += 1
-
next list unless line =~ pattern
-
list << Annotation.new(lineno, $1, $2)
-
end
-
result.empty? ? {} : { file => result }
-
end
-
-
# Prints the mapping from filenames to annotations in +results+ ordered by filename.
-
# The +options+ hash is passed to each annotation's +to_s+.
-
1
def display(results, options={})
-
options[:indent] = results.flat_map { |f, a| a.map(&:line) }.max.to_s.size
-
results.keys.sort.each do |file|
-
puts "#{file}:"
-
results[file].each do |note|
-
puts " * #{note.to_s(options)}"
-
end
-
puts
-
end
-
end
-
end
-
# Make double-sure the RAILS_ENV is not set to production,
-
# so fixtures aren't loaded into that environment
-
1
abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production?
-
-
1
require 'active_support/testing/autorun'
-
1
require 'active_support/test_case'
-
1
require 'action_controller'
-
1
require 'action_controller/test_case'
-
1
require 'action_dispatch/testing/integration'
-
1
require 'rails/generators/test_case'
-
-
# Config Rails backtrace in tests.
-
1
require 'rails/backtrace_cleaner'
-
1
if ENV["BACKTRACE"].nil?
-
1
Minitest.backtrace_filter = Rails.backtrace_cleaner
-
end
-
-
1
if defined?(ActiveRecord::Base)
-
1
ActiveRecord::Migration.maintain_test_schema!
-
-
1
class ActiveSupport::TestCase
-
1
include ActiveRecord::TestFixtures
-
1
self.fixture_path = "#{Rails.root}/test/fixtures/"
-
end
-
-
1
ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
-
-
1
def create_fixtures(*fixture_set_names, &block)
-
FixtureSet.create_fixtures(ActiveSupport::TestCase.fixture_path, fixture_set_names, {}, &block)
-
end
-
end
-
-
1
class ActionController::TestCase
-
1
setup do
-
@routes = Rails.application.routes
-
end
-
end
-
-
1
class ActionDispatch::IntegrationTest
-
1
setup do
-
@routes = Rails.application.routes
-
end
-
end
-
1
if defined?(Rake.application) && Rake.application.top_level_tasks.grep(/^(default$|test(:|$))/).any?
-
ENV['RAILS_ENV'] ||= 'test'
-
end
-
-
1
module Rails
-
1
class TestUnitRailtie < Rails::Railtie
-
1
config.app_generators do |c|
-
1
c.test_framework :test_unit, fixture: true,
-
fixture_replacement: nil
-
-
1
c.integration_tool :test_unit
-
end
-
-
1
rake_tasks do
-
load "rails/test_unit/testing.rake"
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module Rails
-
# Returns the version of the currently loaded Rails as a string.
-
1
def self.version
-
42
VERSION::STRING
-
end
-
end
-
1
require 'rspec/core'
-
1
require 'rspec/version'
-
-
1
module RSpec # :nodoc:
-
1
module Version # :nodoc:
-
1
STRING = '3.3.0'
-
end
-
end
-
# rubocop:disable Style/GlobalVars
-
1
$_rspec_core_load_started_at = Time.now
-
# rubocop:enable Style/GlobalVars
-
-
1
require "rspec/support"
-
1
RSpec::Support.require_rspec_support "caller_filter"
-
-
33
RSpec::Support.define_optimized_require_for_rspec(:core) { |f| require_relative f }
-
-
%w[
-
version
-
warnings
-
-
set
-
flat_map
-
filter_manager
-
dsl
-
notifications
-
reporter
-
-
hooks
-
memoized_helpers
-
metadata
-
metadata_filter
-
pending
-
formatters
-
ordering
-
-
world
-
configuration
-
option_parser
-
configuration_options
-
runner
-
example
-
shared_example_group
-
example_group
-
24
].each { |name| RSpec::Support.require_rspec_core name }
-
-
# Namespace for all core RSpec code.
-
1
module RSpec
-
1
autoload :SharedContext, 'rspec/core/shared_context'
-
-
1
extend RSpec::Core::Warnings
-
-
1
class << self
-
# Setters for shared global objects
-
# @api private
-
1
attr_writer :configuration, :world
-
end
-
-
# Used to ensure examples get reloaded and user configuration gets reset to
-
# defaults between multiple runs in the same process.
-
#
-
# Users must invoke this if they want to have the configuration reset when
-
# they use the runner multiple times within the same process. Users must deal
-
# themselves with re-configuration of RSpec before run.
-
1
def self.reset
-
@world = nil
-
@configuration = nil
-
end
-
-
# Used to ensure examples get reloaded between multiple runs in the same
-
# process and ensures user configuration is persisted.
-
#
-
# Users must invoke this if they want to clear all examples but preserve
-
# current configuration when they use the runner multiple times within the
-
# same process.
-
1
def self.clear_examples
-
world.reset
-
configuration.reporter.reset
-
configuration.start_time = ::RSpec::Core::Time.now
-
configuration.reset_filters
-
end
-
-
# Returns the global [Configuration](RSpec/Core/Configuration) object. While
-
# you _can_ use this method to access the configuration, the more common
-
# convention is to use [RSpec.configure](RSpec#configure-class_method).
-
#
-
# @example
-
# RSpec.configuration.drb_port = 1234
-
# @see RSpec.configure
-
# @see Core::Configuration
-
1
def self.configuration
-
4
@configuration ||= RSpec::Core::Configuration.new
-
end
-
1
configuration.expose_dsl_globally = true
-
-
# Yields the global configuration to a block.
-
# @yield [Configuration] global configuration
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.add_formatter 'documentation'
-
# end
-
# @see Core::Configuration
-
1
def self.configure
-
2
yield configuration if block_given?
-
end
-
-
# The example being executed.
-
#
-
# The primary audience for this method is library authors who need access
-
# to the example currently being executed and also want to support all
-
# versions of RSpec 2 and 3.
-
#
-
# @example
-
#
-
# RSpec.configure do |c|
-
# # context.example is deprecated, but RSpec.current_example is not
-
# # available until RSpec 3.0.
-
# fetch_current_example = RSpec.respond_to?(:current_example) ?
-
# proc { RSpec.current_example } : proc { |context| context.example }
-
#
-
# c.before(:example) do
-
# example = fetch_current_example.call(self)
-
#
-
# # ...
-
# end
-
# end
-
#
-
1
def self.current_example
-
RSpec::Support.thread_local_data[:current_example]
-
end
-
-
# Set the current example being executed.
-
# @api private
-
1
def self.current_example=(example)
-
RSpec::Support.thread_local_data[:current_example] = example
-
end
-
-
# @private
-
# Internal container for global non-configuration data.
-
1
def self.world
-
3
@world ||= RSpec::Core::World.new
-
end
-
-
# Namespace for the rspec-core code.
-
1
module Core
-
1
autoload :ExampleStatusPersister, "rspec/core/example_status_persister"
-
1
autoload :Profiler, "rspec/core/profiler"
-
-
# @private
-
# This avoids issues with reporting time caused by examples that
-
# change the value/meaning of Time.now without properly restoring
-
# it.
-
1
class Time
-
1
class << self
-
1
define_method(:now, &::Time.method(:now))
-
end
-
end
-
-
# @private path to executable file.
-
1
def self.path_to_executable
-
@path_to_executable ||= File.expand_path('../../../exe/rspec', __FILE__)
-
end
-
end
-
-
# @private
-
1
MODULES_TO_AUTOLOAD = {
-
:Matchers => "rspec/expectations",
-
:Expectations => "rspec/expectations",
-
:Mocks => "rspec/mocks"
-
}
-
-
# @private
-
1
def self.const_missing(name)
-
# Load rspec-expectations when RSpec::Matchers is referenced. This allows
-
# people to define custom matchers (using `RSpec::Matchers.define`) before
-
# rspec-core has loaded rspec-expectations (since it delays the loading of
-
# it to allow users to configure a different assertion/expectation
-
# framework). `autoload` can't be used since it works with ruby's built-in
-
# require (e.g. for files that are available relative to a load path dir),
-
# but not with rubygems' extended require.
-
#
-
# As of rspec 2.14.1, we no longer require `rspec/mocks` and
-
# `rspec/expectations` when `rspec` is required, so we want
-
# to make them available as an autoload.
-
require MODULES_TO_AUTOLOAD.fetch(name) { return super }
-
::RSpec.const_get(name)
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
1
class BacktraceFormatter
-
# @private
-
1
attr_accessor :exclusion_patterns, :inclusion_patterns
-
-
1
def initialize
-
1
@full_backtrace = false
-
-
1
patterns = %w[ /lib\d*/ruby/ bin/ exe/rspec ]
-
1
patterns << "org/jruby/" if RUBY_PLATFORM == 'java'
-
4
patterns.map! { |s| Regexp.new(s.gsub("/", File::SEPARATOR)) }
-
-
1
@exclusion_patterns = [Regexp.union(RSpec::CallerFilter::IGNORE_REGEX, *patterns)]
-
1
@inclusion_patterns = []
-
-
1
return unless matches?(@exclusion_patterns, File.join(Dir.getwd, "lib", "foo.rb:13"))
-
inclusion_patterns << Regexp.new(Dir.getwd)
-
end
-
-
1
attr_writer :full_backtrace
-
-
1
def full_backtrace?
-
@full_backtrace || exclusion_patterns.empty?
-
end
-
-
1
def filter_gem(gem_name)
-
sep = File::SEPARATOR
-
exclusion_patterns << /#{sep}#{gem_name}(-[^#{sep}]+)?#{sep}/
-
end
-
-
1
def format_backtrace(backtrace, options={})
-
return backtrace if options[:full_backtrace] || backtrace.empty?
-
-
backtrace.map { |l| backtrace_line(l) }.compact.
-
tap do |filtered|
-
if filtered.empty?
-
filtered.concat backtrace
-
filtered << ""
-
filtered << " Showing full backtrace because every line was filtered out."
-
filtered << " See docs for RSpec::Configuration#backtrace_exclusion_patterns and"
-
filtered << " RSpec::Configuration#backtrace_inclusion_patterns for more information."
-
end
-
end
-
end
-
-
1
def backtrace_line(line)
-
Metadata.relative_path(line) unless exclude?(line)
-
end
-
-
1
def exclude?(line)
-
return false if @full_backtrace
-
matches?(exclusion_patterns, line) && !matches?(inclusion_patterns, line)
-
end
-
-
1
private
-
-
1
def matches?(patterns, line)
-
2
patterns.any? { |p| line =~ p }
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "backtrace_formatter"
-
1
RSpec::Support.require_rspec_core "ruby_project"
-
1
RSpec::Support.require_rspec_core "formatters/deprecation_formatter"
-
-
1
module RSpec
-
1
module Core
-
# rubocop:disable Style/ClassLength
-
-
# Stores runtime configuration information.
-
#
-
# Configuration options are loaded from `~/.rspec`, `.rspec`,
-
# `.rspec-local`, command line switches, and the `SPEC_OPTS` environment
-
# variable (listed in lowest to highest precedence; for example, an option
-
# in `~/.rspec` can be overridden by an option in `.rspec-local`).
-
#
-
# @example Standard settings
-
# RSpec.configure do |c|
-
# c.drb = true
-
# c.drb_port = 1234
-
# c.default_path = 'behavior'
-
# end
-
#
-
# @example Hooks
-
# RSpec.configure do |c|
-
# c.before(:suite) { establish_connection }
-
# c.before(:example) { log_in_as :authorized }
-
# c.around(:example) { |ex| Database.transaction(&ex) }
-
# end
-
#
-
# @see RSpec.configure
-
# @see Hooks
-
1
class Configuration
-
1
include RSpec::Core::Hooks
-
-
# Module that holds `attr_reader` declarations. It's in a separate
-
# module to allow us to override those methods and use `super`.
-
# @private
-
1
Readers = Module.new
-
1
include Readers
-
-
# @private
-
1
class MustBeConfiguredBeforeExampleGroupsError < StandardError; end
-
-
# @private
-
1
def self.define_reader(name)
-
26
Readers.class_eval do
-
26
remove_method name if method_defined?(name)
-
26
attr_reader name
-
end
-
-
26
define_method(name) { value_for(name) { super() } }
-
end
-
-
# @private
-
1
def self.define_aliases(name, alias_name)
-
alias_method alias_name, name
-
alias_method "#{alias_name}=", "#{name}="
-
define_predicate_for alias_name
-
end
-
-
# @private
-
1
def self.define_predicate_for(*names)
-
36
names.each { |name| alias_method "#{name}?", name }
-
end
-
-
# @private
-
#
-
# Invoked by the `add_setting` instance method. Use that method on a
-
# `Configuration` instance rather than this class method.
-
1
def self.add_setting(name, opts={})
-
18
raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default)
-
18
attr_writer name
-
18
add_read_only_setting name
-
-
18
Array(opts[:alias_with]).each do |alias_name|
-
define_aliases(name, alias_name)
-
end
-
end
-
-
# @private
-
#
-
# As `add_setting` but only add the reader.
-
1
def self.add_read_only_setting(name, opts={})
-
18
raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default)
-
18
define_reader name
-
18
define_predicate_for name
-
end
-
-
# @macro [attach] add_setting
-
# @!attribute [rw] $1
-
# @!method $1=(value)
-
#
-
# @macro [attach] define_reader
-
# @!attribute [r] $1
-
-
# @macro add_setting
-
# Path to use if no path is provided to the `rspec` command (default:
-
# `"spec"`). Allows you to just type `rspec` instead of `rspec spec` to
-
# run all the examples in the `spec` directory.
-
#
-
# @note Other scripts invoking `rspec` indirectly will ignore this
-
# setting.
-
1
add_setting :default_path
-
-
# @macro add_setting
-
# Run examples over DRb (default: `false`). RSpec doesn't supply the DRb
-
# server, but you can use tools like spork.
-
1
add_setting :drb
-
-
# @macro add_setting
-
# The drb_port (default: nil).
-
1
add_setting :drb_port
-
-
# @macro add_setting
-
# Default: `$stderr`.
-
1
add_setting :error_stream
-
-
# Indicates if the DSL has been exposed off of modules and `main`.
-
# Default: true
-
1
def expose_dsl_globally?
-
Core::DSL.exposed_globally?
-
end
-
-
# Use this to expose the core RSpec DSL via `Module` and the `main`
-
# object. It will be set automatically but you can override it to
-
# remove the DSL.
-
# Default: true
-
1
def expose_dsl_globally=(value)
-
1
if value
-
1
Core::DSL.expose_globally!
-
1
Core::SharedExampleGroup::TopLevelDSL.expose_globally!
-
else
-
Core::DSL.remove_globally!
-
Core::SharedExampleGroup::TopLevelDSL.remove_globally!
-
end
-
end
-
-
# Determines where deprecation warnings are printed.
-
# Defaults to `$stderr`.
-
# @return [IO, String] IO to write to or filename to write to
-
1
define_reader :deprecation_stream
-
-
# Determines where deprecation warnings are printed.
-
# @param value [IO, String] IO to write to or filename to write to
-
1
def deprecation_stream=(value)
-
if @reporter && !value.equal?(@deprecation_stream)
-
warn "RSpec's reporter has already been initialized with " \
-
"#{deprecation_stream.inspect} as the deprecation stream, so your change to "\
-
"`deprecation_stream` will be ignored. You should configure it earlier for " \
-
"it to take effect, or use the `--deprecation-out` CLI option. " \
-
"(Called from #{CallerFilter.first_non_rspec_line})"
-
else
-
@deprecation_stream = value
-
end
-
end
-
-
# @macro define_reader
-
# The file path to use for persisting example statuses. Necessary for the
-
# `--only-failures` and `--next-failures` CLI options.
-
#
-
# @overload example_status_persistence_file_path
-
# @return [String] the file path
-
# @overload example_status_persistence_file_path=(value)
-
# @param value [String] the file path
-
1
define_reader :example_status_persistence_file_path
-
-
# Sets the file path to use for persisting example statuses. Necessary for the
-
# `--only-failures` and `--next-failures` CLI options.
-
1
def example_status_persistence_file_path=(value)
-
@example_status_persistence_file_path = value
-
clear_values_derived_from_example_status_persistence_file_path
-
end
-
-
# @macro define_reader
-
# Indicates if the `--only-failures` (or `--next-failure`) flag is being used.
-
1
define_reader :only_failures
-
1
alias_method :only_failures?, :only_failures
-
-
# @private
-
1
def only_failures_but_not_configured?
-
only_failures? && !example_status_persistence_file_path
-
end
-
-
# @macro add_setting
-
# Clean up and exit after the first failure (default: `false`).
-
1
add_setting :fail_fast
-
-
# @macro add_setting
-
# Prints the formatter output of your suite without running any
-
# examples or hooks.
-
1
add_setting :dry_run
-
-
# @macro add_setting
-
# The exit code to return if there are any failures (default: 1).
-
1
add_setting :failure_exit_code
-
-
# @macro define_reader
-
# Indicates files configured to be required.
-
1
define_reader :requires
-
-
# @macro define_reader
-
# Returns dirs that have been prepended to the load path by the `-I`
-
# command line option.
-
1
define_reader :libs
-
-
# @macro add_setting
-
# Determines where RSpec will send its output.
-
# Default: `$stdout`.
-
1
define_reader :output_stream
-
-
# Set the output stream for reporter.
-
# @attr value [IO] value for output, defaults to $stdout
-
1
def output_stream=(value)
-
if @reporter && !value.equal?(@output_stream)
-
warn "RSpec's reporter has already been initialized with " \
-
"#{output_stream.inspect} as the output stream, so your change to "\
-
"`output_stream` will be ignored. You should configure it earlier for " \
-
"it to take effect. (Called from #{CallerFilter.first_non_rspec_line})"
-
else
-
@output_stream = value
-
end
-
end
-
-
# @macro define_reader
-
# Load files matching this pattern (default: `'**{,/*/**}/*_spec.rb'`).
-
1
define_reader :pattern
-
-
# Set pattern to match files to load.
-
# @attr value [String] the filename pattern to filter spec files by
-
1
def pattern=(value)
-
update_pattern_attr :pattern, value
-
end
-
-
# @macro define_reader
-
# Exclude files matching this pattern.
-
1
define_reader :exclude_pattern
-
-
# Set pattern to match files to exclude.
-
# @attr value [String] the filename pattern to exclude spec files by
-
1
def exclude_pattern=(value)
-
update_pattern_attr :exclude_pattern, value
-
end
-
-
# @macro add_setting
-
# Report the times for the slowest examples (default: `false`).
-
# Use this to specify the number of examples to include in the profile.
-
1
add_setting :profile_examples
-
-
# @macro add_setting
-
# Run all examples if none match the configured filters
-
# (default: `false`).
-
1
add_setting :run_all_when_everything_filtered
-
-
# @macro add_setting
-
# Color to use to indicate success.
-
# @param color [Symbol] defaults to `:green` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :success_color
-
-
# @macro add_setting
-
# Color to use to print pending examples.
-
# @param color [Symbol] defaults to `:yellow` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :pending_color
-
-
# @macro add_setting
-
# Color to use to indicate failure.
-
# @param color [Symbol] defaults to `:red` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :failure_color
-
-
# @macro add_setting
-
# The default output color.
-
# @param color [Symbol] defaults to `:white` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :default_color
-
-
# @macro add_setting
-
# Color used when a pending example is fixed.
-
# @param color [Symbol] defaults to `:blue` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :fixed_color
-
-
# @macro add_setting
-
# Color used to print details.
-
# @param color [Symbol] defaults to `:cyan` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :detail_color
-
-
# Deprecated. This config option was added in RSpec 2 to pave the way
-
# for this being the default behavior in RSpec 3. Now this option is
-
# a no-op.
-
1
def treat_symbols_as_metadata_keys_with_true_values=(_value)
-
RSpec.deprecate(
-
"RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values=",
-
:message => "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values= " \
-
"is deprecated, it is now set to true as default and " \
-
"setting it to false has no effect."
-
)
-
end
-
-
# Record the start time of the spec suite to measure load time.
-
1
add_setting :start_time
-
-
# @macro add_setting
-
# Use threadsafe options where available.
-
# Currently this will place a mutex around memoized values such as let blocks.
-
1
add_setting :threadsafe
-
-
# @private
-
1
add_setting :tty
-
# @private
-
1
attr_writer :files_to_run
-
# @private
-
1
attr_accessor :filter_manager
-
# @private
-
1
attr_accessor :static_config_filter_manager
-
# @private
-
1
attr_reader :backtrace_formatter, :ordering_manager, :loaded_spec_files
-
-
1
def initialize
-
# rubocop:disable Style/GlobalVars
-
1
@start_time = $_rspec_core_load_started_at || ::RSpec::Core::Time.now
-
# rubocop:enable Style/GlobalVars
-
1
@expectation_frameworks = []
-
1
@include_modules = FilterableItemRepository::QueryOptimized.new(:any?)
-
1
@extend_modules = FilterableItemRepository::QueryOptimized.new(:any?)
-
1
@prepend_modules = FilterableItemRepository::QueryOptimized.new(:any?)
-
-
1
@before_suite_hooks = []
-
1
@after_suite_hooks = []
-
-
1
@mock_framework = nil
-
1
@files_or_directories_to_run = []
-
1
@loaded_spec_files = Set.new
-
1
@color = false
-
1
@pattern = '**{,/*/**}/*_spec.rb'
-
1
@exclude_pattern = ''
-
1
@failure_exit_code = 1
-
1
@spec_files_loaded = false
-
-
1
@backtrace_formatter = BacktraceFormatter.new
-
-
1
@default_path = 'spec'
-
1
@deprecation_stream = $stderr
-
1
@output_stream = $stdout
-
1
@reporter = nil
-
1
@reporter_buffer = nil
-
1
@filter_manager = FilterManager.new
-
1
@static_config_filter_manager = FilterManager.new
-
1
@ordering_manager = Ordering::ConfigurationManager.new
-
1
@preferred_options = {}
-
1
@failure_color = :red
-
1
@success_color = :green
-
1
@pending_color = :yellow
-
1
@default_color = :white
-
1
@fixed_color = :blue
-
1
@detail_color = :cyan
-
1
@profile_examples = false
-
1
@requires = []
-
1
@libs = []
-
1
@derived_metadata_blocks = FilterableItemRepository::QueryOptimized.new(:any?)
-
1
@threadsafe = true
-
-
1
define_built_in_hooks
-
end
-
-
# @private
-
#
-
# Used to set higher priority option values from the command line.
-
1
def force(hash)
-
ordering_manager.force(hash)
-
@preferred_options.merge!(hash)
-
-
return unless hash.key?(:example_status_persistence_file_path)
-
clear_values_derived_from_example_status_persistence_file_path
-
end
-
-
# @private
-
1
def reset
-
@spec_files_loaded = false
-
@reporter = nil
-
@formatter_loader = nil
-
end
-
-
# @private
-
1
def reset_filters
-
self.filter_manager = FilterManager.new
-
filter_manager.include_only(
-
Metadata.deep_hash_dup(static_config_filter_manager.inclusions.rules)
-
)
-
filter_manager.exclude_only(
-
Metadata.deep_hash_dup(static_config_filter_manager.exclusions.rules)
-
)
-
end
-
-
# @overload add_setting(name)
-
# @overload add_setting(name, opts)
-
# @option opts [Symbol] :default
-
#
-
# Set a default value for the generated getter and predicate methods:
-
#
-
# add_setting(:foo, :default => "default value")
-
#
-
# @option opts [Symbol] :alias_with
-
#
-
# Use `:alias_with` to alias the setter, getter, and predicate to
-
# another name, or names:
-
#
-
# add_setting(:foo, :alias_with => :bar)
-
# add_setting(:foo, :alias_with => [:bar, :baz])
-
#
-
# Adds a custom setting to the RSpec.configuration object.
-
#
-
# RSpec.configuration.add_setting :foo
-
#
-
# Used internally and by extension frameworks like rspec-rails, so they
-
# can add config settings that are domain specific. For example:
-
#
-
# RSpec.configure do |c|
-
# c.add_setting :use_transactional_fixtures,
-
# :default => true,
-
# :alias_with => :use_transactional_examples
-
# end
-
#
-
# `add_setting` creates three methods on the configuration object, a
-
# setter, a getter, and a predicate:
-
#
-
# RSpec.configuration.foo=(value)
-
# RSpec.configuration.foo
-
# RSpec.configuration.foo? # Returns true if foo returns anything but nil or false.
-
1
def add_setting(name, opts={})
-
default = opts.delete(:default)
-
(class << self; self; end).class_exec do
-
add_setting(name, opts)
-
end
-
__send__("#{name}=", default) if default
-
end
-
-
# Returns the configured mock framework adapter module.
-
1
def mock_framework
-
if @mock_framework.nil?
-
begin
-
mock_with :rspec
-
rescue LoadError
-
mock_with :nothing
-
end
-
end
-
@mock_framework
-
end
-
-
# Delegates to mock_framework=(framework).
-
1
def mock_framework=(framework)
-
mock_with framework
-
end
-
-
# Regexps used to exclude lines from backtraces.
-
#
-
# Excludes lines from ruby (and jruby) source, installed gems, anything
-
# in any "bin" directory, and any of the RSpec libs (outside gem
-
# installs) by default.
-
#
-
# You can modify the list via the getter, or replace it with the setter.
-
#
-
# To override this behaviour and display a full backtrace, use
-
# `--backtrace` on the command line, in a `.rspec` file, or in the
-
# `rspec_options` attribute of RSpec's rake task.
-
1
def backtrace_exclusion_patterns
-
@backtrace_formatter.exclusion_patterns
-
end
-
-
# Set regular expressions used to exclude lines in backtrace.
-
# @param patterns [Regexp] set the backtrace exlusion pattern
-
1
def backtrace_exclusion_patterns=(patterns)
-
@backtrace_formatter.exclusion_patterns = patterns
-
end
-
-
# Regexps used to include lines in backtraces.
-
#
-
# Defaults to [Regexp.new Dir.getwd].
-
#
-
# Lines that match an exclusion _and_ an inclusion pattern
-
# will be included.
-
#
-
# You can modify the list via the getter, or replace it with the setter.
-
1
def backtrace_inclusion_patterns
-
@backtrace_formatter.inclusion_patterns
-
end
-
-
# Set regular expressions used to include lines in backtrace.
-
# @attr patterns [Regexp] set backtrace_formatter inclusion_patterns
-
1
def backtrace_inclusion_patterns=(patterns)
-
@backtrace_formatter.inclusion_patterns = patterns
-
end
-
-
# Adds {#backtrace_exclusion_patterns} that will filter lines from
-
# the named gems from backtraces.
-
#
-
# @param gem_names [Array<String>] Names of the gems to filter
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.filter_gems_from_backtrace "rack", "rake"
-
# end
-
#
-
# @note The patterns this adds will match the named gems in their common
-
# locations (e.g. system gems, vendored with bundler, installed as a
-
# :git dependency with bundler, etc) but is not guaranteed to work for
-
# all possible gem locations. For example, if you have the gem source
-
# in a directory with a completely unrelated name, and use bundler's
-
# :path option, this will not filter it.
-
1
def filter_gems_from_backtrace(*gem_names)
-
gem_names.each do |name|
-
@backtrace_formatter.filter_gem(name)
-
end
-
end
-
-
# @private
-
1
MOCKING_ADAPTERS = {
-
:rspec => :RSpec,
-
:flexmock => :Flexmock,
-
:rr => :RR,
-
:mocha => :Mocha,
-
:nothing => :Null
-
}
-
-
# Sets the mock framework adapter module.
-
#
-
# `framework` can be a Symbol or a Module.
-
#
-
# Given any of `:rspec`, `:mocha`, `:flexmock`, or `:rr`, configures the
-
# named framework.
-
#
-
# Given `:nothing`, configures no framework. Use this if you don't use
-
# any mocking framework to save a little bit of overhead.
-
#
-
# Given a Module, includes that module in every example group. The module
-
# should adhere to RSpec's mock framework adapter API:
-
#
-
# setup_mocks_for_rspec
-
# - called before each example
-
#
-
# verify_mocks_for_rspec
-
# - called after each example if the example hasn't yet failed.
-
# Framework should raise an exception when expectations fail
-
#
-
# teardown_mocks_for_rspec
-
# - called after verify_mocks_for_rspec (even if there are errors)
-
#
-
# If the module responds to `configuration` and `mock_with` receives a
-
# block, it will yield the configuration object to the block e.g.
-
#
-
# config.mock_with OtherMockFrameworkAdapter do |mod_config|
-
# mod_config.custom_setting = true
-
# end
-
1
def mock_with(framework)
-
1
framework_module =
-
if framework.is_a?(Module)
-
framework
-
else
-
1
const_name = MOCKING_ADAPTERS.fetch(framework) do
-
raise ArgumentError,
-
"Unknown mocking framework: #{framework.inspect}. " \
-
"Pass a module or one of #{MOCKING_ADAPTERS.keys.inspect}"
-
end
-
-
1
RSpec::Support.require_rspec_core "mocking_adapters/#{const_name.to_s.downcase}"
-
1
RSpec::Core::MockingAdapters.const_get(const_name)
-
end
-
-
1
new_name, old_name = [framework_module, @mock_framework].map do |mod|
-
2
mod.respond_to?(:framework_name) ? mod.framework_name : :unnamed
-
end
-
-
1
unless new_name == old_name
-
1
assert_no_example_groups_defined(:mock_framework)
-
end
-
-
1
if block_given?
-
raise "#{framework_module} must respond to `configuration` so that " \
-
1
"mock_with can yield it." unless framework_module.respond_to?(:configuration)
-
1
yield framework_module.configuration
-
end
-
-
1
@mock_framework = framework_module
-
end
-
-
# Returns the configured expectation framework adapter module(s)
-
1
def expectation_frameworks
-
if @expectation_frameworks.empty?
-
begin
-
expect_with :rspec
-
rescue LoadError
-
expect_with Module.new
-
end
-
end
-
@expectation_frameworks
-
end
-
-
# Delegates to expect_with(framework).
-
1
def expectation_framework=(framework)
-
expect_with(framework)
-
end
-
-
# Sets the expectation framework module(s) to be included in each example
-
# group.
-
#
-
# `frameworks` can be `:rspec`, `:test_unit`, `:minitest`, a custom
-
# module, or any combination thereof:
-
#
-
# config.expect_with :rspec
-
# config.expect_with :test_unit
-
# config.expect_with :minitest
-
# config.expect_with :rspec, :minitest
-
# config.expect_with OtherExpectationFramework
-
#
-
# RSpec will translate `:rspec`, `:minitest`, and `:test_unit` into the
-
# appropriate modules.
-
#
-
# ## Configuration
-
#
-
# If the module responds to `configuration`, `expect_with` will
-
# yield the `configuration` object if given a block:
-
#
-
# config.expect_with OtherExpectationFramework do |custom_config|
-
# custom_config.custom_setting = true
-
# end
-
1
def expect_with(*frameworks)
-
1
modules = frameworks.map do |framework|
-
1
case framework
-
when Module
-
framework
-
when :rspec
-
1
require 'rspec/expectations'
-
-
# Tag this exception class so our exception formatting logic knows
-
# that it satisfies the `MultipleExceptionError` interface.
-
1
::RSpec::Expectations::MultipleExpectationsNotMetError.__send__(
-
:include, MultipleExceptionError::InterfaceTag
-
)
-
-
1
::RSpec::Matchers
-
when :test_unit
-
require 'rspec/core/test_unit_assertions_adapter'
-
::RSpec::Core::TestUnitAssertionsAdapter
-
when :minitest
-
require 'rspec/core/minitest_assertions_adapter'
-
::RSpec::Core::MinitestAssertionsAdapter
-
else
-
raise ArgumentError, "#{framework.inspect} is not supported"
-
end
-
end
-
-
1
if (modules - @expectation_frameworks).any?
-
1
assert_no_example_groups_defined(:expect_with)
-
end
-
-
1
if block_given?
-
raise "expect_with only accepts a block with a single argument. " \
-
"Call expect_with #{modules.length} times, " \
-
1
"once with each argument, instead." if modules.length > 1
-
raise "#{modules.first} must respond to `configuration` so that " \
-
1
"expect_with can yield it." unless modules.first.respond_to?(:configuration)
-
1
yield modules.first.configuration
-
end
-
-
1
@expectation_frameworks.push(*modules)
-
end
-
-
# Check if full backtrace is enabled.
-
# @return [Boolean] is full backtrace enabled
-
1
def full_backtrace?
-
@backtrace_formatter.full_backtrace?
-
end
-
-
# Toggle full backtrace.
-
# @attr true_or_false [Boolean] toggle full backtrace display
-
1
def full_backtrace=(true_or_false)
-
@backtrace_formatter.full_backtrace = true_or_false
-
end
-
-
# Returns the configuration option for color, but should not
-
# be used to check if color is supported.
-
#
-
# @see color_enabled?
-
# @return [Boolean]
-
1
def color
-
value_for(:color) { @color }
-
end
-
-
# Check if color is enabled for a particular output.
-
# @param output [IO] an output stream to use, defaults to the current
-
# `output_stream`
-
# @return [Boolean]
-
1
def color_enabled?(output=output_stream)
-
output_to_tty?(output) && color
-
end
-
-
# Toggle output color.
-
# @attr true_or_false [Boolean] toggle color enabled
-
1
def color=(true_or_false)
-
return unless true_or_false
-
-
if RSpec::Support::OS.windows? && !ENV['ANSICON']
-
RSpec.warning "You must use ANSICON 1.31 or later " \
-
"(http://adoxa.3eeweb.com/ansicon/) to use colour " \
-
"on Windows"
-
@color = false
-
else
-
@color = true
-
end
-
end
-
-
# @private
-
1
def libs=(libs)
-
libs.map do |lib|
-
@libs.unshift lib
-
$LOAD_PATH.unshift lib
-
end
-
end
-
-
# Run examples matching on `description` in all files to run.
-
# @param description [String, Regexp] the pattern to filter on
-
1
def full_description=(description)
-
filter_run :full_description => Regexp.union(*Array(description).map { |d| Regexp.new(d) })
-
end
-
-
# @return [Array] full description filter
-
1
def full_description
-
filter.fetch :full_description, nil
-
end
-
-
# @overload add_formatter(formatter)
-
#
-
# Adds a formatter to the formatters collection. `formatter` can be a
-
# string representing any of the built-in formatters (see
-
# `built_in_formatter`), or a custom formatter class.
-
#
-
# ### Note
-
#
-
# For internal purposes, `add_formatter` also accepts the name of a class
-
# and paths to use for output streams, but you should consider that a
-
# private api that may change at any time without notice.
-
1
def add_formatter(formatter_to_use, *paths)
-
paths << output_stream if paths.empty?
-
formatter_loader.add formatter_to_use, *paths
-
end
-
1
alias_method :formatter=, :add_formatter
-
-
# The formatter that will be used if no formatter has been set.
-
# Defaults to 'progress'.
-
1
def default_formatter
-
formatter_loader.default_formatter
-
end
-
-
# Sets a fallback formatter to use if none other has been set.
-
#
-
# @example
-
#
-
# RSpec.configure do |rspec|
-
# rspec.default_formatter = 'doc'
-
# end
-
1
def default_formatter=(value)
-
formatter_loader.default_formatter = value
-
end
-
-
# Returns a duplicate of the formatters currently loaded in
-
# the `FormatterLoader` for introspection.
-
#
-
# Note as this is a duplicate, any mutations will be disregarded.
-
#
-
# @return [Array] the formatters currently loaded
-
1
def formatters
-
formatter_loader.formatters.dup
-
end
-
-
# @private
-
1
def formatter_loader
-
@formatter_loader ||= Formatters::Loader.new(Reporter.new(self))
-
end
-
-
# @private
-
#
-
# This buffer is used to capture all messages sent to the reporter during
-
# reporter initialization. It can then replay those messages after the
-
# formatter is correctly initialized. Otherwise, deprecation warnings
-
# during formatter initialization can cause an infinite loop.
-
1
class DeprecationReporterBuffer
-
1
def initialize
-
@calls = []
-
end
-
-
1
def deprecation(*args)
-
@calls << args
-
end
-
-
1
def play_onto(reporter)
-
@calls.each do |args|
-
reporter.deprecation(*args)
-
end
-
end
-
end
-
-
# @private
-
1
def reporter
-
# @reporter_buffer should only ever be set in this method to cover
-
# initialization of @reporter.
-
@reporter_buffer || @reporter ||=
-
begin
-
@reporter_buffer = DeprecationReporterBuffer.new
-
formatter_loader.setup_default output_stream, deprecation_stream
-
@reporter_buffer.play_onto(formatter_loader.reporter)
-
@reporter_buffer = nil
-
formatter_loader.reporter
-
end
-
end
-
-
# @api private
-
#
-
# Defaults `profile_examples` to 10 examples when `@profile_examples` is
-
# `true`.
-
1
def profile_examples
-
profile = value_for(:profile_examples) { @profile_examples }
-
if profile && !profile.is_a?(Integer)
-
10
-
else
-
profile
-
end
-
end
-
-
# @private
-
1
def files_or_directories_to_run=(*files)
-
files = files.flatten
-
-
if (command == 'rspec' || Runner.running_in_drb?) && default_path && files.empty?
-
files << default_path
-
end
-
-
@files_or_directories_to_run = files
-
@files_to_run = nil
-
end
-
-
# The spec files RSpec will run.
-
# @return [Array] specified files about to run
-
1
def files_to_run
-
@files_to_run ||= get_files_to_run(@files_or_directories_to_run)
-
end
-
-
# @private
-
1
def last_run_statuses
-
@last_run_statuses ||= Hash.new(UNKNOWN_STATUS).tap do |statuses|
-
if (path = example_status_persistence_file_path)
-
begin
-
ExampleStatusPersister.load_from(path).inject(statuses) do |hash, example|
-
hash[example.fetch(:example_id)] = example.fetch(:status)
-
hash
-
end
-
rescue SystemCallError => e
-
RSpec.warning "Could not read from #{path.inspect} (configured as " \
-
"`config.example_status_persistence_file_path`) due " \
-
"to a system error: #{e.inspect}. Please check that " \
-
"the config option is set to an accessible, valid " \
-
"file path", :call_site => nil
-
end
-
end
-
end
-
end
-
-
# @private
-
1
UNKNOWN_STATUS = "unknown".freeze
-
-
# @private
-
1
FAILED_STATUS = "failed".freeze
-
-
# @private
-
1
def spec_files_with_failures
-
@spec_files_with_failures ||= last_run_statuses.inject(Set.new) do |files, (id, status)|
-
files << id.split(ON_SQUARE_BRACKETS).first if status == FAILED_STATUS
-
files
-
end.to_a
-
end
-
-
# Creates a method that delegates to `example` including the submitted
-
# `args`. Used internally to add variants of `example` like `pending`:
-
# @param name [String] example name alias
-
# @param args [Array<Symbol>, Hash] metadata for the generated example
-
#
-
# @note The specific example alias below (`pending`) is already
-
# defined for you.
-
# @note Use with caution. This extends the language used in your
-
# specs, but does not add any additional documentation. We use this
-
# in RSpec to define methods like `focus` and `xit`, but we also add
-
# docs for those methods.
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.alias_example_to :pending, :pending => true
-
# end
-
#
-
# # This lets you do this:
-
#
-
# describe Thing do
-
# pending "does something" do
-
# thing = Thing.new
-
# end
-
# end
-
#
-
# # ... which is the equivalent of
-
#
-
# describe Thing do
-
# it "does something", :pending => true do
-
# thing = Thing.new
-
# end
-
# end
-
1
def alias_example_to(name, *args)
-
extra_options = Metadata.build_hash_from(args)
-
RSpec::Core::ExampleGroup.define_example_method(name, extra_options)
-
end
-
-
# Creates a method that defines an example group with the provided
-
# metadata. Can be used to define example group/metadata shortcuts.
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.alias_example_group_to :describe_model, :type => :model
-
# end
-
#
-
# shared_context_for "model tests", :type => :model do
-
# # define common model test helper methods, `let` declarations, etc
-
# end
-
#
-
# # This lets you do this:
-
#
-
# RSpec.describe_model User do
-
# end
-
#
-
# # ... which is the equivalent of
-
#
-
# RSpec.describe User, :type => :model do
-
# end
-
#
-
# @note The defined aliased will also be added to the top level
-
# (e.g. `main` and from within modules) if
-
# `expose_dsl_globally` is set to true.
-
# @see #alias_example_to
-
# @see #expose_dsl_globally=
-
1
def alias_example_group_to(new_name, *args)
-
extra_options = Metadata.build_hash_from(args)
-
RSpec::Core::ExampleGroup.define_example_group_method(new_name, extra_options)
-
end
-
-
# Define an alias for it_should_behave_like that allows different
-
# language (like "it_has_behavior" or "it_behaves_like") to be
-
# employed when including shared examples.
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.alias_it_behaves_like_to(:it_has_behavior, 'has behavior:')
-
# end
-
#
-
# # allows the user to include a shared example group like:
-
#
-
# describe Entity do
-
# it_has_behavior 'sortability' do
-
# let(:sortable) { Entity.new }
-
# end
-
# end
-
#
-
# # which is reported in the output as:
-
# # Entity
-
# # has behavior: sortability
-
# # ...sortability examples here
-
#
-
# @note Use with caution. This extends the language used in your
-
# specs, but does not add any additional documentation. We use this
-
# in RSpec to define `it_should_behave_like` (for backward
-
# compatibility), but we also add docs for that method.
-
1
def alias_it_behaves_like_to(new_name, report_label='')
-
RSpec::Core::ExampleGroup.define_nested_shared_group_method(new_name, report_label)
-
end
-
1
alias_method :alias_it_should_behave_like_to, :alias_it_behaves_like_to
-
-
# Adds key/value pairs to the `inclusion_filter`. If `args`
-
# includes any symbols that are not part of the hash, each symbol
-
# is treated as a key in the hash with the value `true`.
-
#
-
# ### Note
-
#
-
# Filters set using this method can be overridden from the command line
-
# or config files (e.g. `.rspec`).
-
#
-
# @example
-
# # Given this declaration.
-
# describe "something", :foo => 'bar' do
-
# # ...
-
# end
-
#
-
# # Any of the following will include that group.
-
# config.filter_run_including :foo => 'bar'
-
# config.filter_run_including :foo => /^ba/
-
# config.filter_run_including :foo => lambda {|v| v == 'bar'}
-
# config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
-
#
-
# # Given a proc with an arity of 1, the lambda is passed the value
-
# # related to the key, e.g.
-
# config.filter_run_including :foo => lambda {|v| v == 'bar'}
-
#
-
# # Given a proc with an arity of 2, the lambda is passed the value
-
# # related to the key, and the metadata itself e.g.
-
# config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
-
#
-
# filter_run_including :foo # same as filter_run_including :foo => true
-
1
def filter_run_including(*args)
-
meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
-
filter_manager.include_with_low_priority meta
-
static_config_filter_manager.include_with_low_priority Metadata.deep_hash_dup(meta)
-
end
-
-
1
alias_method :filter_run, :filter_run_including
-
-
# Clears and reassigns the `inclusion_filter`. Set to `nil` if you don't
-
# want any inclusion filter at all.
-
#
-
# ### Warning
-
#
-
# This overrides any inclusion filters/tags set on the command line or in
-
# configuration files.
-
1
def inclusion_filter=(filter)
-
meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
-
filter_manager.include_only meta
-
end
-
-
1
alias_method :filter=, :inclusion_filter=
-
-
# Returns the `inclusion_filter`. If none has been set, returns an empty
-
# hash.
-
1
def inclusion_filter
-
filter_manager.inclusions
-
end
-
-
1
alias_method :filter, :inclusion_filter
-
-
# Adds key/value pairs to the `exclusion_filter`. If `args`
-
# includes any symbols that are not part of the hash, each symbol
-
# is treated as a key in the hash with the value `true`.
-
#
-
# ### Note
-
#
-
# Filters set using this method can be overridden from the command line
-
# or config files (e.g. `.rspec`).
-
#
-
# @example
-
# # Given this declaration.
-
# describe "something", :foo => 'bar' do
-
# # ...
-
# end
-
#
-
# # Any of the following will exclude that group.
-
# config.filter_run_excluding :foo => 'bar'
-
# config.filter_run_excluding :foo => /^ba/
-
# config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
-
# config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
-
#
-
# # Given a proc with an arity of 1, the lambda is passed the value
-
# # related to the key, e.g.
-
# config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
-
#
-
# # Given a proc with an arity of 2, the lambda is passed the value
-
# # related to the key, and the metadata itself e.g.
-
# config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
-
#
-
# filter_run_excluding :foo # same as filter_run_excluding :foo => true
-
1
def filter_run_excluding(*args)
-
meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
-
filter_manager.exclude_with_low_priority meta
-
static_config_filter_manager.exclude_with_low_priority Metadata.deep_hash_dup(meta)
-
end
-
-
# Clears and reassigns the `exclusion_filter`. Set to `nil` if you don't
-
# want any exclusion filter at all.
-
#
-
# ### Warning
-
#
-
# This overrides any exclusion filters/tags set on the command line or in
-
# configuration files.
-
1
def exclusion_filter=(filter)
-
meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
-
filter_manager.exclude_only meta
-
end
-
-
# Returns the `exclusion_filter`. If none has been set, returns an empty
-
# hash.
-
1
def exclusion_filter
-
filter_manager.exclusions
-
end
-
-
# Tells RSpec to include `mod` in example groups. Methods defined in
-
# `mod` are exposed to examples (not example groups). Use `filters` to
-
# constrain the groups or examples in which to include the module.
-
#
-
# @example
-
#
-
# module AuthenticationHelpers
-
# def login_as(user)
-
# # ...
-
# end
-
# end
-
#
-
# module UserHelpers
-
# def users(username)
-
# # ...
-
# end
-
# end
-
#
-
# RSpec.configure do |config|
-
# config.include(UserHelpers) # included in all modules
-
# config.include(AuthenticationHelpers, :type => :request)
-
# end
-
#
-
# describe "edit profile", :type => :request do
-
# it "can be viewed by owning user" do
-
# login_as users(:jdoe)
-
# get "/profiles/jdoe"
-
# assert_select ".username", :text => 'jdoe'
-
# end
-
# end
-
#
-
# @note Filtered module inclusions can also be applied to
-
# individual examples that have matching metadata. Just like
-
# Ruby's object model is that every object has a singleton class
-
# which has only a single instance, RSpec's model is that every
-
# example has a singleton example group containing just the one
-
# example.
-
#
-
# @see #extend
-
# @see #prepend
-
1
def include(mod, *filters)
-
meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
-
@include_modules.append(mod, meta)
-
configure_existing_groups(mod, meta, :safe_include)
-
end
-
-
# Tells RSpec to extend example groups with `mod`. Methods defined in
-
# `mod` are exposed to example groups (not examples). Use `filters` to
-
# constrain the groups to extend.
-
#
-
# Similar to `include`, but behavior is added to example groups, which
-
# are classes, rather than the examples, which are instances of those
-
# classes.
-
#
-
# @example
-
#
-
# module UiHelpers
-
# def run_in_browser
-
# # ...
-
# end
-
# end
-
#
-
# RSpec.configure do |config|
-
# config.extend(UiHelpers, :type => :request)
-
# end
-
#
-
# describe "edit profile", :type => :request do
-
# run_in_browser
-
#
-
# it "does stuff in the client" do
-
# # ...
-
# end
-
# end
-
#
-
# @see #include
-
# @see #prepend
-
1
def extend(mod, *filters)
-
1
meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
-
1
@extend_modules.append(mod, meta)
-
1
configure_existing_groups(mod, meta, :safe_extend)
-
end
-
-
1
if RSpec::Support::RubyFeatures.module_prepends_supported?
-
# Tells RSpec to prepend example groups with `mod`. Methods defined in
-
# `mod` are exposed to examples (not example groups). Use `filters` to
-
# constrain the groups in which to prepend the module.
-
#
-
# Similar to `include`, but module is included before the example group's class
-
# in the ancestor chain.
-
#
-
# @example
-
#
-
# module OverrideMod
-
# def override_me
-
# "overridden"
-
# end
-
# end
-
#
-
# RSpec.configure do |config|
-
# config.prepend(OverrideMod, :method => :prepend)
-
# end
-
#
-
# describe "overriding example's class", :method => :prepend do
-
# it "finds the user" do
-
# self.class.class_eval do
-
# def override_me
-
# end
-
# end
-
# override_me # => "overridden"
-
# # ...
-
# end
-
# end
-
#
-
# @see #include
-
# @see #extend
-
1
def prepend(mod, *filters)
-
meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
-
@prepend_modules.append(mod, meta)
-
configure_existing_groups(mod, meta, :safe_prepend)
-
end
-
end
-
-
# @private
-
#
-
# Used internally to extend a group with modules using `include`, `prepend` and/or
-
# `extend`.
-
1
def configure_group(group)
-
configure_group_with group, @include_modules, :safe_include
-
configure_group_with group, @extend_modules, :safe_extend
-
configure_group_with group, @prepend_modules, :safe_prepend
-
end
-
-
# @private
-
1
def configure_group_with(group, module_list, application_method)
-
module_list.items_for(group.metadata).each do |mod|
-
__send__(application_method, mod, group)
-
end
-
end
-
-
# @private
-
1
def configure_existing_groups(mod, meta, application_method)
-
1
RSpec.world.all_example_groups.each do |group|
-
next unless meta.empty? || MetadataFilter.apply?(:any?, meta, group.metadata)
-
__send__(application_method, mod, group)
-
end
-
end
-
-
# @private
-
#
-
# Used internally to extend the singleton class of a single example's
-
# example group instance with modules using `include` and/or `extend`.
-
1
def configure_example(example)
-
singleton_group = example.example_group_instance.singleton_class
-
-
# We replace the metadata so that SharedExampleGroupModule#included
-
# has access to the example's metadata[:location].
-
singleton_group.with_replaced_metadata(example.metadata) do
-
modules = @include_modules.items_for(example.metadata)
-
modules.each do |mod|
-
safe_include(mod, example.example_group_instance.singleton_class)
-
end
-
-
MemoizedHelpers.define_helpers_on(singleton_group) unless modules.empty?
-
end
-
end
-
-
1
if RSpec::Support::RubyFeatures.module_prepends_supported?
-
# @private
-
1
def safe_prepend(mod, host)
-
host.__send__(:prepend, mod) unless host < mod
-
end
-
end
-
-
# @private
-
1
def requires=(paths)
-
directories = ['lib', default_path].select { |p| File.directory? p }
-
RSpec::Core::RubyProject.add_to_load_path(*directories)
-
paths.each { |path| require path }
-
@requires += paths
-
end
-
-
# @private
-
1
if RUBY_VERSION.to_f >= 1.9
-
# @private
-
1
def safe_include(mod, host)
-
host.__send__(:include, mod) unless host < mod
-
end
-
-
# @private
-
1
def safe_extend(mod, host)
-
host.extend(mod) unless host.singleton_class < mod
-
end
-
else # for 1.8.7
-
skipped
# :nocov:
-
skipped
# @private
-
skipped
def safe_include(mod, host)
-
skipped
host.__send__(:include, mod) unless host.included_modules.include?(mod)
-
skipped
end
-
skipped
-
skipped
# @private
-
skipped
def safe_extend(mod, host)
-
skipped
host.extend(mod) unless (class << host; self; end).included_modules.include?(mod)
-
skipped
end
-
skipped
# :nocov:
-
end
-
-
# @private
-
1
def configure_mock_framework
-
RSpec::Core::ExampleGroup.__send__(:include, mock_framework)
-
conditionally_disable_mocks_monkey_patching
-
end
-
-
# @private
-
1
def configure_expectation_framework
-
expectation_frameworks.each do |framework|
-
RSpec::Core::ExampleGroup.__send__(:include, framework)
-
end
-
conditionally_disable_expectations_monkey_patching
-
end
-
-
# @private
-
1
def load_spec_files
-
files_to_run.uniq.each do |f|
-
file = File.expand_path(f)
-
load file
-
loaded_spec_files << file
-
end
-
-
@spec_files_loaded = true
-
end
-
-
# @private
-
1
DEFAULT_FORMATTER = lambda { |string| string }
-
-
# Formats the docstring output using the block provided.
-
#
-
# @example
-
# # This will strip the descriptions of both examples and example
-
# # groups.
-
# RSpec.configure do |config|
-
# config.format_docstrings { |s| s.strip }
-
# end
-
1
def format_docstrings(&block)
-
@format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER
-
end
-
-
# @private
-
1
def format_docstrings_block
-
@format_docstrings_block ||= DEFAULT_FORMATTER
-
end
-
-
# @private
-
# @macro [attach] delegate_to_ordering_manager
-
# @!method $1
-
1
def self.delegate_to_ordering_manager(*methods)
-
5
methods.each do |method|
-
6
define_method method do |*args, &block|
-
ordering_manager.__send__(method, *args, &block)
-
end
-
end
-
end
-
-
# @macro delegate_to_ordering_manager
-
#
-
# Sets the seed value and sets the default global ordering to random.
-
1
delegate_to_ordering_manager :seed=
-
-
# @macro delegate_to_ordering_manager
-
# Seed for random ordering (default: generated randomly each run).
-
#
-
# When you run specs with `--order random`, RSpec generates a random seed
-
# for the randomization and prints it to the `output_stream` (assuming
-
# you're using RSpec's built-in formatters). If you discover an ordering
-
# dependency (i.e. examples fail intermittently depending on order), set
-
# this (on Configuration or on the command line with `--seed`) to run
-
# using the same seed while you debug the issue.
-
#
-
# We recommend, actually, that you use the command line approach so you
-
# don't accidentally leave the seed encoded.
-
1
delegate_to_ordering_manager :seed
-
-
# @macro delegate_to_ordering_manager
-
#
-
# Sets the default global order and, if order is `'rand:<seed>'`, also
-
# sets the seed.
-
1
delegate_to_ordering_manager :order=
-
-
# @macro delegate_to_ordering_manager
-
# Registers a named ordering strategy that can later be
-
# used to order an example group's subgroups by adding
-
# `:order => <name>` metadata to the example group.
-
#
-
# @param name [Symbol] The name of the ordering.
-
# @yield Block that will order the given examples or example groups
-
# @yieldparam list [Array<RSpec::Core::Example>,
-
# Array<RSpec::Core::ExampleGroup>] The examples or groups to order
-
# @yieldreturn [Array<RSpec::Core::Example>,
-
# Array<RSpec::Core::ExampleGroup>] The re-ordered examples or groups
-
#
-
# @example
-
# RSpec.configure do |rspec|
-
# rspec.register_ordering :reverse do |list|
-
# list.reverse
-
# end
-
# end
-
#
-
# describe MyClass, :order => :reverse do
-
# # ...
-
# end
-
#
-
# @note Pass the symbol `:global` to set the ordering strategy that
-
# will be used to order the top-level example groups and any example
-
# groups that do not have declared `:order` metadata.
-
1
delegate_to_ordering_manager :register_ordering
-
-
# @private
-
1
delegate_to_ordering_manager :seed_used?, :ordering_registry
-
-
# Set Ruby warnings on or off.
-
1
def warnings=(value)
-
$VERBOSE = !!value
-
end
-
-
# @return [Boolean] Whether or not ruby warnings are enabled.
-
1
def warnings?
-
$VERBOSE
-
end
-
-
# Exposes the current running example via the named
-
# helper method. RSpec 2.x exposed this via `example`,
-
# but in RSpec 3.0, the example is instead exposed via
-
# an arg yielded to `it`, `before`, `let`, etc. However,
-
# some extension gems (such as Capybara) depend on the
-
# RSpec 2.x's `example` method, so this config option
-
# can be used to maintain compatibility.
-
#
-
# @param method_name [Symbol] the name of the helper method
-
#
-
# @example
-
#
-
# RSpec.configure do |rspec|
-
# rspec.expose_current_running_example_as :example
-
# end
-
#
-
# describe MyClass do
-
# before do
-
# # `example` can be used here because of the above config.
-
# do_something if example.metadata[:type] == "foo"
-
# end
-
# end
-
1
def expose_current_running_example_as(method_name)
-
ExposeCurrentExample.module_exec do
-
extend RSpec::SharedContext
-
let(method_name) { |ex| ex }
-
end
-
-
include ExposeCurrentExample
-
end
-
-
# @private
-
1
module ExposeCurrentExample; end
-
-
# Turns deprecation warnings into errors, in order to surface
-
# the full backtrace of the call site. This can be useful when
-
# you need more context to address a deprecation than the
-
# single-line call site normally provided.
-
#
-
# @example
-
#
-
# RSpec.configure do |rspec|
-
# rspec.raise_errors_for_deprecations!
-
# end
-
1
def raise_errors_for_deprecations!
-
self.deprecation_stream = Formatters::DeprecationFormatter::RaiseErrorStream.new
-
end
-
-
# Enables zero monkey patching mode for RSpec. It removes monkey
-
# patching of the top-level DSL methods (`describe`,
-
# `shared_examples_for`, etc) onto `main` and `Module`, instead
-
# requiring you to prefix these methods with `RSpec.`. It enables
-
# expect-only syntax for rspec-mocks and rspec-expectations. It
-
# simply disables monkey patching on whatever pieces of RSpec
-
# the user is using.
-
#
-
# @note It configures rspec-mocks and rspec-expectations only
-
# if the user is using those (either explicitly or implicitly
-
# by not setting `mock_with` or `expect_with` to anything else).
-
#
-
# @note If the user uses this options with `mock_with :mocha`
-
# (or similiar) they will still have monkey patching active
-
# in their test environment from mocha.
-
#
-
# @example
-
#
-
# # It disables all monkey patching.
-
# RSpec.configure do |config|
-
# config.disable_monkey_patching!
-
# end
-
#
-
# # Is an equivalent to
-
# RSpec.configure do |config|
-
# config.expose_dsl_globally = false
-
#
-
# config.mock_with :rspec do |mocks|
-
# mocks.syntax = :expect
-
# mocks.patch_marshal_to_support_partial_doubles = false
-
# end
-
#
-
# config.mock_with :rspec do |expectations|
-
# expectations.syntax = :expect
-
# end
-
# end
-
1
def disable_monkey_patching!
-
self.expose_dsl_globally = false
-
self.disable_monkey_patching = true
-
conditionally_disable_mocks_monkey_patching
-
conditionally_disable_expectations_monkey_patching
-
end
-
-
# @private
-
1
attr_accessor :disable_monkey_patching
-
-
# Defines a callback that can assign derived metadata values.
-
#
-
# @param filters [Array<Symbol>, Hash] metadata filters that determine
-
# which example or group metadata hashes the callback will be triggered
-
# for. If none are given, the callback will be run against the metadata
-
# hashes of all groups and examples.
-
# @yieldparam metadata [Hash] original metadata hash from an example or
-
# group. Mutate this in your block as needed.
-
#
-
# @example
-
# RSpec.configure do |config|
-
# # Tag all groups and examples in the spec/unit directory with
-
# # :type => :unit
-
# config.define_derived_metadata(:file_path => %r{/spec/unit/}) do |metadata|
-
# metadata[:type] = :unit
-
# end
-
# end
-
1
def define_derived_metadata(*filters, &block)
-
meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
-
@derived_metadata_blocks.append(block, meta)
-
end
-
-
# @private
-
1
def apply_derived_metadata_to(metadata)
-
@derived_metadata_blocks.items_for(metadata).each do |block|
-
block.call(metadata)
-
end
-
end
-
-
# Defines a `before` hook. See {Hooks#before} for full docs.
-
#
-
# This method differs from {Hooks#before} in only one way: it supports
-
# the `:suite` scope. Hooks with the `:suite` scope will be run once before
-
# the first example of the entire suite is executed.
-
#
-
# @see #prepend_before
-
# @see #after
-
# @see #append_after
-
1
def before(*args, &block)
-
handle_suite_hook(args, @before_suite_hooks, :push,
-
Hooks::BeforeHook, block) || super(*args, &block)
-
end
-
1
alias_method :append_before, :before
-
-
# Adds `block` to the start of the list of `before` blocks in the same
-
# scope (`:example`, `:context`, or `:suite`), in contrast to {#before},
-
# which adds the hook to the end of the list.
-
#
-
# See {Hooks#before} for full `before` hook docs.
-
#
-
# This method differs from {Hooks#prepend_before} in only one way: it supports
-
# the `:suite` scope. Hooks with the `:suite` scope will be run once before
-
# the first example of the entire suite is executed.
-
#
-
# @see #before
-
# @see #after
-
# @see #append_after
-
1
def prepend_before(*args, &block)
-
handle_suite_hook(args, @before_suite_hooks, :unshift,
-
Hooks::BeforeHook, block) || super(*args, &block)
-
end
-
-
# Defines a `after` hook. See {Hooks#after} for full docs.
-
#
-
# This method differs from {Hooks#after} in only one way: it supports
-
# the `:suite` scope. Hooks with the `:suite` scope will be run once after
-
# the last example of the entire suite is executed.
-
#
-
# @see #append_after
-
# @see #before
-
# @see #prepend_before
-
1
def after(*args, &block)
-
handle_suite_hook(args, @after_suite_hooks, :unshift,
-
Hooks::AfterHook, block) || super(*args, &block)
-
end
-
1
alias_method :prepend_after, :after
-
-
# Adds `block` to the end of the list of `after` blocks in the same
-
# scope (`:example`, `:context`, or `:suite`), in contrast to {#after},
-
# which adds the hook to the start of the list.
-
#
-
# See {Hooks#after} for full `after` hook docs.
-
#
-
# This method differs from {Hooks#append_after} in only one way: it supports
-
# the `:suite` scope. Hooks with the `:suite` scope will be run once after
-
# the last example of the entire suite is executed.
-
#
-
# @see #append_after
-
# @see #before
-
# @see #prepend_before
-
1
def append_after(*args, &block)
-
handle_suite_hook(args, @after_suite_hooks, :push,
-
Hooks::AfterHook, block) || super(*args, &block)
-
end
-
-
# @private
-
1
def with_suite_hooks
-
return yield if dry_run?
-
-
hook_context = SuiteHookContext.new
-
begin
-
run_hooks_with(@before_suite_hooks, hook_context)
-
yield
-
ensure
-
run_hooks_with(@after_suite_hooks, hook_context)
-
end
-
end
-
-
# @private
-
# Holds the various registered hooks. Here we use a FilterableItemRepository
-
# implementation that is specifically optimized for the read/write patterns
-
# of the config object.
-
1
def hooks
-
1
@hooks ||= HookCollections.new(self, FilterableItemRepository::QueryOptimized)
-
end
-
-
1
private
-
-
1
def handle_suite_hook(args, collection, append_or_prepend, hook_type, block)
-
scope, meta = *args
-
return nil unless scope == :suite
-
-
if meta
-
# TODO: in RSpec 4, consider raising an error here.
-
# We warn only for backwards compatibility.
-
RSpec.warn_with "WARNING: `:suite` hooks do not support metadata since " \
-
"they apply to the suite as a whole rather than " \
-
"any individual example or example group that has metadata. " \
-
"The metadata you have provided (#{meta.inspect}) will be ignored."
-
end
-
-
collection.__send__(append_or_prepend, hook_type.new(block, {}))
-
end
-
-
1
def run_hooks_with(hooks, hook_context)
-
hooks.each { |h| h.run(hook_context) }
-
end
-
-
1
def get_files_to_run(paths)
-
files = FlatMap.flat_map(paths_to_check(paths)) do |path|
-
path = path.gsub(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
-
File.directory?(path) ? gather_directories(path) : extract_location(path)
-
end.sort.uniq
-
-
return files unless only_failures?
-
relative_files = files.map { |f| Metadata.relative_path(File.expand_path f) }
-
intersection = (relative_files & spec_files_with_failures.to_a)
-
intersection.empty? ? files : intersection
-
end
-
-
1
def paths_to_check(paths)
-
return paths if pattern_might_load_specs_from_vendored_dirs?
-
paths + [Dir.getwd]
-
end
-
-
1
def pattern_might_load_specs_from_vendored_dirs?
-
pattern.split(File::SEPARATOR).first.include?('**')
-
end
-
-
1
def gather_directories(path)
-
include_files = get_matching_files(path, pattern)
-
exclude_files = get_matching_files(path, exclude_pattern)
-
(include_files - exclude_files).sort.uniq
-
end
-
-
1
def get_matching_files(path, pattern)
-
Dir[file_glob_from(path, pattern)].map { |file| File.expand_path(file) }
-
end
-
-
1
def file_glob_from(path, pattern)
-
stripped = "{#{pattern.gsub(/\s*,\s*/, ',')}}"
-
return stripped if pattern =~ /^(\.\/)?#{Regexp.escape path}/ || absolute_pattern?(pattern)
-
File.join(path, stripped)
-
end
-
-
1
if RSpec::Support::OS.windows?
-
skipped
# :nocov:
-
skipped
def absolute_pattern?(pattern)
-
skipped
pattern =~ /\A[A-Z]:\\/ || windows_absolute_network_path?(pattern)
-
skipped
end
-
skipped
-
skipped
def windows_absolute_network_path?(pattern)
-
skipped
return false unless ::File::ALT_SEPARATOR
-
skipped
pattern.start_with?(::File::ALT_SEPARATOR + ::File::ALT_SEPARATOR)
-
skipped
end
-
skipped
# :nocov:
-
else
-
1
def absolute_pattern?(pattern)
-
pattern.start_with?(File::Separator)
-
end
-
end
-
-
# @private
-
1
ON_SQUARE_BRACKETS = /[\[\]]/
-
-
1
def extract_location(path)
-
match = /^(.*?)((?:\:\d+)+)$/.match(path)
-
-
if match
-
captures = match.captures
-
path, lines = captures[0], captures[1][1..-1].split(":").map { |n| n.to_i }
-
filter_manager.add_location path, lines
-
else
-
path, scoped_ids = path.split(ON_SQUARE_BRACKETS)
-
filter_manager.add_ids(path, scoped_ids.split(/\s*,\s*/)) if scoped_ids
-
end
-
-
return [] if path == default_path
-
path
-
end
-
-
1
def command
-
$0.split(File::SEPARATOR).last
-
end
-
-
1
def value_for(key)
-
@preferred_options.fetch(key) { yield }
-
end
-
-
1
def define_built_in_hooks
-
1
around(:example, :aggregate_failures => true) do |procsy|
-
begin
-
aggregate_failures(nil, :hide_backtrace => true, &procsy)
-
rescue Exception => exception
-
procsy.example.set_aggregate_failures_exception(exception)
-
end
-
end
-
end
-
-
1
def assert_no_example_groups_defined(config_option)
-
2
return unless RSpec.world.example_groups.any?
-
-
raise MustBeConfiguredBeforeExampleGroupsError.new(
-
"RSpec's #{config_option} configuration option must be configured before " \
-
"any example groups are defined, but you have already defined a group."
-
)
-
end
-
-
1
def output_to_tty?(output=output_stream)
-
tty? || (output.respond_to?(:tty?) && output.tty?)
-
end
-
-
1
def conditionally_disable_mocks_monkey_patching
-
return unless disable_monkey_patching && rspec_mocks_loaded?
-
-
RSpec::Mocks.configuration.tap do |config|
-
config.syntax = :expect
-
config.patch_marshal_to_support_partial_doubles = false
-
end
-
end
-
-
1
def conditionally_disable_expectations_monkey_patching
-
return unless disable_monkey_patching && rspec_expectations_loaded?
-
-
RSpec::Expectations.configuration.syntax = :expect
-
end
-
-
1
def rspec_mocks_loaded?
-
defined?(RSpec::Mocks.configuration)
-
end
-
-
1
def rspec_expectations_loaded?
-
defined?(RSpec::Expectations.configuration)
-
end
-
-
1
def update_pattern_attr(name, value)
-
if @spec_files_loaded
-
RSpec.warning "Configuring `#{name}` to #{value} has no effect since " \
-
"RSpec has already loaded the spec files."
-
end
-
-
instance_variable_set(:"@#{name}", value)
-
@files_to_run = nil
-
end
-
-
1
def clear_values_derived_from_example_status_persistence_file_path
-
@last_run_statuses = nil
-
@spec_files_with_failures = nil
-
end
-
end
-
# rubocop:enable Style/ClassLength
-
end
-
end
-
1
require 'erb'
-
1
require 'shellwords'
-
-
1
module RSpec
-
1
module Core
-
# Responsible for utilizing externally provided configuration options,
-
# whether via the command line, `.rspec`, `~/.rspec`, `.rspec-local`
-
# or a custom options file.
-
1
class ConfigurationOptions
-
# @param args [Array<String>] command line arguments
-
1
def initialize(args)
-
@args = args.dup
-
organize_options
-
end
-
-
# Updates the provided {Configuration} instance based on the provided
-
# external configuration options.
-
#
-
# @param config [Configuration] the configuration instance to update
-
1
def configure(config)
-
process_options_into config
-
configure_filter_manager config.filter_manager
-
load_formatters_into config
-
end
-
-
# @api private
-
# Updates the provided {FilterManager} based on the filter options.
-
# @param filter_manager [FilterManager] instance to update
-
1
def configure_filter_manager(filter_manager)
-
@filter_manager_options.each do |command, value|
-
filter_manager.__send__ command, value
-
end
-
end
-
-
# @return [Hash] the final merged options, drawn from all external sources
-
1
attr_reader :options
-
-
1
private
-
-
1
def organize_options
-
@filter_manager_options = []
-
-
@options = (file_options << command_line_options << env_options).each do |opts|
-
@filter_manager_options << [:include, opts.delete(:inclusion_filter)] if opts.key?(:inclusion_filter)
-
@filter_manager_options << [:exclude, opts.delete(:exclusion_filter)] if opts.key?(:exclusion_filter)
-
end
-
-
@options = @options.inject(:libs => [], :requires => []) do |hash, opts|
-
hash.merge(opts) do |key, oldval, newval|
-
[:libs, :requires].include?(key) ? oldval + newval : newval
-
end
-
end
-
end
-
-
1
UNFORCED_OPTIONS = Set.new([
-
:requires, :profile, :drb, :libs, :files_or_directories_to_run,
-
:full_description, :full_backtrace, :tty
-
])
-
-
1
UNPROCESSABLE_OPTIONS = Set.new([:formatters])
-
-
1
def force?(key)
-
!UNFORCED_OPTIONS.include?(key)
-
end
-
-
1
def order(keys)
-
OPTIONS_ORDER.reverse.each do |key|
-
keys.unshift(key) if keys.delete(key)
-
end
-
keys
-
end
-
-
1
OPTIONS_ORDER = [
-
# It's important to set this before anything that might issue a
-
# deprecation (or otherwise access the reporter).
-
:deprecation_stream,
-
-
# load paths depend on nothing, but must be set before `requires`
-
# to support load-path-relative requires.
-
:libs,
-
-
# `files_or_directories_to_run` uses `default_path` so it must be
-
# set before it.
-
:default_path, :only_failures,
-
-
# These must be set before `requires` to support checking
-
# `config.files_to_run` from within `spec_helper.rb` when a
-
# `-rspec_helper` option is used.
-
:files_or_directories_to_run, :pattern, :exclude_pattern,
-
-
# Necessary so that the `--seed` option is applied before requires,
-
# in case required files do something with the provided seed.
-
# (such as seed global randomization with it).
-
:order,
-
-
# In general, we want to require the specified files as early as
-
# possible. The `--require` option is specifically intended to allow
-
# early requires. For later requires, they can just put the require in
-
# their spec files, but `--require` provides a unique opportunity for
-
# users to instruct RSpec to load an extension file early for maximum
-
# flexibility.
-
:requires
-
]
-
-
1
def process_options_into(config)
-
opts = options.reject { |k, _| UNPROCESSABLE_OPTIONS.include? k }
-
-
order(opts.keys).each do |key|
-
force?(key) ? config.force(key => opts[key]) : config.__send__("#{key}=", opts[key])
-
end
-
end
-
-
1
def load_formatters_into(config)
-
options[:formatters].each { |pair| config.add_formatter(*pair) } if options[:formatters]
-
end
-
-
1
def file_options
-
custom_options_file ? [custom_options] : [global_options, project_options, local_options]
-
end
-
-
1
def env_options
-
return {} unless ENV['SPEC_OPTS']
-
-
parse_args_ignoring_files_or_dirs_to_run(
-
Shellwords.split(ENV["SPEC_OPTS"]),
-
"ENV['SPEC_OPTS']"
-
)
-
end
-
-
1
def command_line_options
-
@command_line_options ||= Parser.parse(@args)
-
end
-
-
1
def custom_options
-
options_from(custom_options_file)
-
end
-
-
1
def local_options
-
@local_options ||= options_from(local_options_file)
-
end
-
-
1
def project_options
-
@project_options ||= options_from(project_options_file)
-
end
-
-
1
def global_options
-
@global_options ||= options_from(global_options_file)
-
end
-
-
1
def options_from(path)
-
args = args_from_options_file(path)
-
parse_args_ignoring_files_or_dirs_to_run(args, path)
-
end
-
-
1
def parse_args_ignoring_files_or_dirs_to_run(args, source)
-
options = Parser.parse(args, source)
-
options.delete(:files_or_directories_to_run)
-
options
-
end
-
-
1
def args_from_options_file(path)
-
return [] unless path && File.exist?(path)
-
config_string = options_file_as_erb_string(path)
-
FlatMap.flat_map(config_string.split(/\n+/), &:shellsplit)
-
end
-
-
1
def options_file_as_erb_string(path)
-
ERB.new(File.read(path), nil, '-').result(binding)
-
end
-
-
1
def custom_options_file
-
command_line_options[:custom_options_file]
-
end
-
-
1
def project_options_file
-
"./.rspec"
-
end
-
-
1
def local_options_file
-
"./.rspec-local"
-
end
-
-
1
def global_options_file
-
File.join(File.expand_path("~"), ".rspec")
-
rescue ArgumentError
-
RSpec.warning "Unable to find ~/.rspec because the HOME environment variable is not set"
-
nil
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# DSL defines methods to group examples, most notably `describe`,
-
# and exposes them as class methods of {RSpec}. They can also be
-
# exposed globally (on `main` and instances of `Module`) through
-
# the {Configuration} option `expose_dsl_globally`.
-
#
-
# By default the methods `describe`, `context` and `example_group`
-
# are exposed. These methods define a named context for one or
-
# more examples. The given block is evaluated in the context of
-
# a generated subclass of {RSpec::Core::ExampleGroup}.
-
#
-
# ## Examples:
-
#
-
# RSpec.describe "something" do
-
# context "when something is a certain way" do
-
# it "does something" do
-
# # example code goes here
-
# end
-
# end
-
# end
-
#
-
# @see ExampleGroup
-
# @see ExampleGroup.example_group
-
1
module DSL
-
# @private
-
1
def self.example_group_aliases
-
15
@example_group_aliases ||= []
-
end
-
-
# @private
-
1
def self.exposed_globally?
-
8
@exposed_globally ||= false
-
end
-
-
# @private
-
1
def self.expose_example_group_alias(name)
-
7
return if example_group_aliases.include?(name)
-
-
7
example_group_aliases << name
-
-
14
(class << RSpec; self; end).__send__(:define_method, name) do |*args, &example_group_block|
-
RSpec.world.register RSpec::Core::ExampleGroup.__send__(name, *args, &example_group_block)
-
end
-
-
7
expose_example_group_alias_globally(name) if exposed_globally?
-
end
-
-
1
class << self
-
# @private
-
1
attr_accessor :top_level
-
end
-
-
# Adds the describe method to Module and the top level binding.
-
# @api private
-
1
def self.expose_globally!
-
1
return if exposed_globally?
-
-
1
example_group_aliases.each do |method_name|
-
7
expose_example_group_alias_globally(method_name)
-
end
-
-
1
@exposed_globally = true
-
end
-
-
# Removes the describe method from Module and the top level binding.
-
# @api private
-
1
def self.remove_globally!
-
return unless exposed_globally?
-
-
example_group_aliases.each do |method_name|
-
change_global_dsl { undef_method method_name }
-
end
-
-
@exposed_globally = false
-
end
-
-
# @private
-
1
def self.expose_example_group_alias_globally(method_name)
-
7
change_global_dsl do
-
14
remove_method(method_name) if method_defined?(method_name)
-
14
define_method(method_name) { |*a, &b| ::RSpec.__send__(method_name, *a, &b) }
-
end
-
end
-
-
# @private
-
1
def self.change_global_dsl(&changes)
-
16
(class << top_level; self; end).class_exec(&changes)
-
8
Module.class_exec(&changes)
-
end
-
end
-
end
-
end
-
-
# Capture main without an eval.
-
1
::RSpec::Core::DSL.top_level = self
-
1
module RSpec
-
1
module Core
-
# Wrapper for an instance of a subclass of {ExampleGroup}. An instance of
-
# `RSpec::Core::Example` is returned by example definition methods
-
# such as {ExampleGroup.it it} and is yielded to the {ExampleGroup.it it},
-
# {Hooks#before before}, {Hooks#after after}, {Hooks#around around},
-
# {MemoizedHelpers::ClassMethods#let let} and
-
# {MemoizedHelpers::ClassMethods#subject subject} blocks.
-
#
-
# This allows us to provide rich metadata about each individual
-
# example without adding tons of methods directly to the ExampleGroup
-
# that users may inadvertantly redefine.
-
#
-
# Useful for configuring logging and/or taking some action based
-
# on the state of an example's metadata.
-
#
-
# @example
-
#
-
# RSpec.configure do |config|
-
# config.before do |example|
-
# log example.description
-
# end
-
#
-
# config.after do |example|
-
# log example.description
-
# end
-
#
-
# config.around do |example|
-
# log example.description
-
# example.run
-
# end
-
# end
-
#
-
# shared_examples "auditable" do
-
# it "does something" do
-
# log "#{example.full_description}: #{auditable.inspect}"
-
# auditable.should do_something
-
# end
-
# end
-
#
-
# @see ExampleGroup
-
# @note Example blocks are evaluated in the context of an instance
-
# of an `ExampleGroup`, not in the context of an instance of `Example`.
-
1
class Example
-
# @private
-
#
-
# Used to define methods that delegate to this example's metadata.
-
1
def self.delegate_to_metadata(key)
-
6
define_method(key) { @metadata[key] }
-
end
-
-
# @return [ExecutionResult] represents the result of running this example.
-
1
delegate_to_metadata :execution_result
-
# @return [String] the relative path to the file where this example was
-
# defined.
-
1
delegate_to_metadata :file_path
-
# @return [String] the full description (including the docstrings of
-
# all parent example groups).
-
1
delegate_to_metadata :full_description
-
# @return [String] the exact source location of this example in a form
-
# like `./path/to/spec.rb:17`
-
1
delegate_to_metadata :location
-
# @return [Boolean] flag that indicates that the example is not expected
-
# to pass. It will be run and will either have a pending result (if a
-
# failure occurs) or a failed result (if no failure occurs).
-
1
delegate_to_metadata :pending
-
# @return [Boolean] flag that will cause the example to not run.
-
# The {ExecutionResult} status will be `:pending`.
-
1
delegate_to_metadata :skip
-
-
# Returns the string submitted to `example` or its aliases (e.g.
-
# `specify`, `it`, etc). If no string is submitted (e.g.
-
# `it { is_expected.to do_something }`) it returns the message generated
-
# by the matcher if there is one, otherwise returns a message including
-
# the location of the example.
-
1
def description
-
description = if metadata[:description].to_s.empty?
-
location_description
-
else
-
metadata[:description]
-
end
-
-
RSpec.configuration.format_docstrings_block.call(description)
-
end
-
-
# Returns a description of the example that always includes the location.
-
1
def inspect_output
-
inspect_output = "\"#{description}\""
-
unless metadata[:description].to_s.empty?
-
inspect_output << " (#{location})"
-
end
-
inspect_output
-
end
-
-
# Returns the location-based argument that can be passed to the `rspec` command to rerun this example.
-
1
def location_rerun_argument
-
@location_rerun_argument ||= begin
-
loaded_spec_files = RSpec.configuration.loaded_spec_files
-
-
Metadata.ascending(metadata) do |meta|
-
return meta[:location] if loaded_spec_files.include?(meta[:absolute_file_path])
-
end
-
end
-
end
-
-
# Returns the location-based argument that can be passed to the `rspec` command to rerun this example.
-
#
-
# @deprecated Use {#location_rerun_argument} instead.
-
# @note If there are multiple examples identified by this location, they will use {#id}
-
# to rerun instead, but this method will still return the location (that's why it is deprecated!).
-
1
def rerun_argument
-
location_rerun_argument
-
end
-
-
# @return [String] the unique id of this example. Pass
-
# this at the command line to re-run this exact example.
-
1
def id
-
@id ||= Metadata.id_from(metadata)
-
end
-
-
# @attr_reader
-
#
-
# Returns the first exception raised in the context of running this
-
# example (nil if no exception is raised).
-
1
attr_reader :exception
-
-
# @attr_reader
-
#
-
# Returns the metadata object associated with this example.
-
1
attr_reader :metadata
-
-
# @attr_reader
-
# @private
-
#
-
# Returns the example_group_instance that provides the context for
-
# running this example.
-
1
attr_reader :example_group_instance
-
-
# @attr
-
# @private
-
1
attr_accessor :clock
-
-
# Creates a new instance of Example.
-
# @param example_group_class [Class] the subclass of ExampleGroup in which
-
# this Example is declared
-
# @param description [String] the String passed to the `it` method (or
-
# alias)
-
# @param user_metadata [Hash] additional args passed to `it` to be used as
-
# metadata
-
# @param example_block [Proc] the block of code that represents the
-
# example
-
# @api private
-
1
def initialize(example_group_class, description, user_metadata, example_block=nil)
-
@example_group_class = example_group_class
-
@example_block = example_block
-
-
@metadata = Metadata::ExampleHash.create(
-
@example_group_class.metadata, user_metadata,
-
example_group_class.method(:next_runnable_index_for),
-
description, example_block
-
)
-
-
# This should perhaps be done in `Metadata::ExampleHash.create`,
-
# but the logic there has no knowledge of `RSpec.world` and we
-
# want to keep it that way. It's easier to just assign it here.
-
@metadata[:last_run_status] = RSpec.configuration.last_run_statuses[id]
-
-
@example_group_instance = @exception = nil
-
@clock = RSpec::Core::Time
-
@reporter = RSpec::Core::NullReporter
-
end
-
-
# @return [RSpec::Core::Reporter] the current reporter for the example
-
1
attr_reader :reporter
-
-
# Returns the example group class that provides the context for running
-
# this example.
-
1
def example_group
-
@example_group_class
-
end
-
-
1
alias_method :pending?, :pending
-
1
alias_method :skipped?, :skip
-
-
# @api private
-
# instance_execs the block passed to the constructor in the context of
-
# the instance of {ExampleGroup}.
-
# @param example_group_instance the instance of an ExampleGroup subclass
-
1
def run(example_group_instance, reporter)
-
@example_group_instance = example_group_instance
-
@reporter = reporter
-
hooks.register_global_singleton_context_hooks(self, RSpec.configuration.hooks)
-
RSpec.configuration.configure_example(self)
-
RSpec.current_example = self
-
-
start(reporter)
-
Pending.mark_pending!(self, pending) if pending?
-
-
begin
-
if skipped?
-
Pending.mark_pending! self, skip
-
elsif !RSpec.configuration.dry_run?
-
with_around_and_singleton_context_hooks do
-
begin
-
run_before_example
-
@example_group_instance.instance_exec(self, &@example_block)
-
-
if pending?
-
Pending.mark_fixed! self
-
-
raise Pending::PendingExampleFixedError,
-
'Expected example to fail since it is pending, but it passed.',
-
[location]
-
end
-
rescue Pending::SkipDeclaredInExample
-
# no-op, required metadata has already been set by the `skip`
-
# method.
-
rescue Exception => e
-
set_exception(e)
-
ensure
-
run_after_example
-
end
-
end
-
end
-
rescue Exception => e
-
set_exception(e)
-
ensure
-
@example_group_instance = nil # if you love something... let it go
-
end
-
-
finish(reporter)
-
ensure
-
RSpec.current_example = nil
-
end
-
-
# Wraps both a `Proc` and an {Example} for use in {Hooks#around
-
# around} hooks. In around hooks we need to yield this special
-
# kind of object (rather than the raw {Example}) because when
-
# there are multiple `around` hooks we have to wrap them recursively.
-
#
-
# @example
-
#
-
# RSpec.configure do |c|
-
# c.around do |ex| # Procsy which wraps the example
-
# if ex.metadata[:key] == :some_value && some_global_condition
-
# raise "some message"
-
# end
-
# ex.run # run delegates to ex.call.
-
# end
-
# end
-
#
-
# @note This class also exposes the instance methods of {Example},
-
# proxying them through to the wrapped {Example} instance.
-
1
class Procsy
-
# The {Example} instance.
-
1
attr_reader :example
-
-
1
Example.public_instance_methods(false).each do |name|
-
21
next if name.to_sym == :run || name.to_sym == :inspect
-
-
20
define_method(name) { |*a, &b| @example.__send__(name, *a, &b) }
-
end
-
-
1
Proc.public_instance_methods(false).each do |name|
-
16
next if name.to_sym == :call || name.to_sym == :inspect || name.to_sym == :to_proc
-
-
13
define_method(name) { |*a, &b| @proc.__send__(name, *a, &b) }
-
end
-
-
# Calls the proc and notes that the example has been executed.
-
1
def call(*args, &block)
-
@executed = true
-
@proc.call(*args, &block)
-
end
-
1
alias run call
-
-
# Provides a wrapped proc that will update our `executed?` state when
-
# executed.
-
1
def to_proc
-
method(:call).to_proc
-
end
-
-
1
def initialize(example, &block)
-
@example = example
-
@proc = block
-
@executed = false
-
end
-
-
# @private
-
1
def wrap(&block)
-
self.class.new(example, &block)
-
end
-
-
# Indicates whether or not the around hook has executed the example.
-
1
def executed?
-
@executed
-
end
-
-
# @private
-
1
def inspect
-
@example.inspect.gsub('Example', 'ExampleProcsy')
-
end
-
end
-
-
# @private
-
#
-
# The exception that will be displayed to the user -- either the failure of
-
# the example or the `pending_exception` if the example is pending.
-
1
def display_exception
-
@exception || execution_result.pending_exception
-
end
-
-
# @private
-
#
-
# Assigns the exception that will be displayed to the user -- either the failure of
-
# the example or the `pending_exception` if the example is pending.
-
1
def display_exception=(ex)
-
if pending? && !(Pending::PendingExampleFixedError === ex)
-
@exception = nil
-
execution_result.pending_fixed = false
-
execution_result.pending_exception = ex
-
else
-
@exception = ex
-
end
-
end
-
-
# rubocop:disable Style/AccessorMethodName
-
-
# @private
-
#
-
# Used internally to set an exception in an after hook, which
-
# captures the exception but doesn't raise it.
-
1
def set_exception(exception)
-
return self.display_exception = exception unless display_exception
-
-
unless RSpec::Core::MultipleExceptionError === display_exception
-
self.display_exception = RSpec::Core::MultipleExceptionError.new(display_exception)
-
end
-
-
display_exception.add exception
-
end
-
-
# @private
-
#
-
# Used to set the exception when `aggregate_failures` fails.
-
1
def set_aggregate_failures_exception(exception)
-
return set_exception(exception) unless display_exception
-
-
exception = RSpec::Core::MultipleExceptionError::InterfaceTag.for(exception)
-
exception.add display_exception
-
self.display_exception = exception
-
end
-
-
# rubocop:enable Style/AccessorMethodName
-
-
# @private
-
#
-
# Used internally to set an exception and fail without actually executing
-
# the example when an exception is raised in before(:context).
-
1
def fail_with_exception(reporter, exception)
-
start(reporter)
-
set_exception(exception)
-
finish(reporter)
-
end
-
-
# @private
-
#
-
# Used internally to skip without actually executing the example when
-
# skip is used in before(:context).
-
1
def skip_with_exception(reporter, exception)
-
start(reporter)
-
Pending.mark_skipped! self, exception.argument
-
finish(reporter)
-
end
-
-
# @private
-
1
def instance_exec(*args, &block)
-
@example_group_instance.instance_exec(*args, &block)
-
end
-
-
1
private
-
-
1
def hooks
-
example_group_instance.singleton_class.hooks
-
end
-
-
1
def with_around_example_hooks
-
hooks.run(:around, :example, self) { yield }
-
rescue Exception => e
-
set_exception(e)
-
end
-
-
1
def start(reporter)
-
reporter.example_started(self)
-
execution_result.started_at = clock.now
-
end
-
-
1
def finish(reporter)
-
pending_message = execution_result.pending_message
-
-
if @exception
-
record_finished :failed
-
execution_result.exception = @exception
-
reporter.example_failed self
-
false
-
elsif pending_message
-
record_finished :pending
-
execution_result.pending_message = pending_message
-
reporter.example_pending self
-
true
-
else
-
record_finished :passed
-
reporter.example_passed self
-
true
-
end
-
end
-
-
1
def record_finished(status)
-
execution_result.record_finished(status, clock.now)
-
end
-
-
1
def run_before_example
-
@example_group_instance.setup_mocks_for_rspec
-
hooks.run(:before, :example, self)
-
end
-
-
1
def with_around_and_singleton_context_hooks
-
singleton_context_hooks_host = example_group_instance.singleton_class
-
singleton_context_hooks_host.run_before_context_hooks(example_group_instance)
-
with_around_example_hooks { yield }
-
ensure
-
singleton_context_hooks_host.run_after_context_hooks(example_group_instance)
-
end
-
-
1
def run_after_example
-
assign_generated_description if defined?(::RSpec::Matchers)
-
hooks.run(:after, :example, self)
-
verify_mocks
-
ensure
-
@example_group_instance.teardown_mocks_for_rspec
-
end
-
-
1
def verify_mocks
-
@example_group_instance.verify_mocks_for_rspec if mocks_need_verification?
-
rescue Exception => e
-
set_exception(e)
-
end
-
-
1
def mocks_need_verification?
-
exception.nil? || execution_result.pending_fixed?
-
end
-
-
1
def assign_generated_description
-
if metadata[:description].empty? && (description = generate_description)
-
metadata[:description] = description
-
metadata[:full_description] << description
-
end
-
ensure
-
RSpec::Matchers.clear_generated_description
-
end
-
-
1
def generate_description
-
RSpec::Matchers.generated_description
-
rescue Exception => e
-
location_description + " (Got an error when generating description " \
-
"from matcher: #{e.class}: #{e.message} -- #{e.backtrace.first})"
-
end
-
-
1
def location_description
-
"example at #{location}"
-
end
-
-
# Represents the result of executing an example.
-
# Behaves like a hash for backwards compatibility.
-
1
class ExecutionResult
-
1
include HashImitatable
-
-
# @return [Symbol] `:passed`, `:failed` or `:pending`.
-
1
attr_accessor :status
-
-
# @return [Exception, nil] The failure, if there was one.
-
1
attr_accessor :exception
-
-
# @return [Time] When the example started.
-
1
attr_accessor :started_at
-
-
# @return [Time] When the example finished.
-
1
attr_accessor :finished_at
-
-
# @return [Float] How long the example took in seconds.
-
1
attr_accessor :run_time
-
-
# @return [String, nil] The reason the example was pending,
-
# or nil if the example was not pending.
-
1
attr_accessor :pending_message
-
-
# @return [Exception, nil] The exception triggered while
-
# executing the pending example. If no exception was triggered
-
# it would no longer get a status of `:pending` unless it was
-
# tagged with `:skip`.
-
1
attr_accessor :pending_exception
-
-
# @return [Boolean] For examples tagged with `:pending`,
-
# this indicates whether or not it now passes.
-
1
attr_accessor :pending_fixed
-
-
1
alias pending_fixed? pending_fixed
-
-
# @return [Boolean] Indicates if the example was completely skipped
-
# (typically done via `:skip` metadata or the `skip` method). Skipped examples
-
# will have a `:pending` result. A `:pending` result can also come from examples
-
# that were marked as `:pending`, which causes them to be run, and produces a
-
# `:failed` result if the example passes.
-
1
def example_skipped?
-
status == :pending && !pending_exception
-
end
-
-
# @api private
-
# Records the finished status of the example.
-
1
def record_finished(status, finished_at)
-
self.status = status
-
self.finished_at = finished_at
-
self.run_time = (finished_at - started_at).to_f
-
end
-
-
1
private
-
-
# For backwards compatibility we present `status` as a string
-
# when presenting the legacy hash interface.
-
1
def hash_for_delegation
-
super.tap do |hash|
-
hash[:status] &&= status.to_s
-
end
-
end
-
-
1
def set_value(name, value)
-
value &&= value.to_sym if name == :status
-
super(name, value)
-
end
-
-
1
def get_value(name)
-
if name == :status
-
status.to_s if status
-
else
-
super
-
end
-
end
-
-
1
def issue_deprecation(_method_name, *_args)
-
RSpec.deprecate("Treating `metadata[:execution_result]` as a hash",
-
:replacement => "the attributes methods to access the data")
-
end
-
end
-
end
-
-
# @private
-
# Provides an execution context for before/after :suite hooks.
-
1
class SuiteHookContext < Example
-
1
def initialize
-
super(AnonymousExampleGroup, "", {})
-
@example_group_instance = AnonymousExampleGroup.new
-
end
-
-
# rubocop:disable Style/AccessorMethodName
-
-
# To ensure we don't silence errors.
-
1
def set_exception(exception)
-
raise exception
-
end
-
# rubocop:enable Style/AccessorMethodName
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'recursive_const_methods'
-
-
1
module RSpec
-
1
module Core
-
# ExampleGroup and {Example} are the main structural elements of
-
# rspec-core. Consider this example:
-
#
-
# describe Thing do
-
# it "does something" do
-
# end
-
# end
-
#
-
# The object returned by `describe Thing` is a subclass of ExampleGroup.
-
# The object returned by `it "does something"` is an instance of Example,
-
# which serves as a wrapper for an instance of the ExampleGroup in which it
-
# is declared.
-
#
-
# Example group bodies (e.g. `describe` or `context` blocks) are evaluated
-
# in the context of a new subclass of ExampleGroup. Individual examples are
-
# evaluated in the context of an instance of the specific ExampleGroup
-
# subclass to which they belong.
-
#
-
# Besides the class methods defined here, there are other interesting macros
-
# defined in {Hooks}, {MemoizedHelpers::ClassMethods} and
-
# {SharedExampleGroup}. There are additional instance methods available to
-
# your examples defined in {MemoizedHelpers} and {Pending}.
-
1
class ExampleGroup
-
1
extend Hooks
-
-
1
include MemoizedHelpers
-
1
extend MemoizedHelpers::ClassMethods
-
1
include Pending
-
1
extend SharedExampleGroup
-
-
# @private
-
1
def self.idempotently_define_singleton_method(name, &definition)
-
48
(class << self; self; end).module_exec do
-
24
remove_method(name) if method_defined?(name) && instance_method(name).owner == self
-
24
define_method(name, &definition)
-
end
-
end
-
-
# @!group Metadata
-
-
# The [Metadata](Metadata) object associated with this group.
-
# @see Metadata
-
1
def self.metadata
-
@metadata ||= nil
-
end
-
-
# Temporarily replace the provided metadata.
-
# Intended primarily to allow an example group's singleton class
-
# to return the metadata of the example that it exists for. This
-
# is necessary for shared example group inclusion to work properly
-
# with singleton example groups.
-
# @private
-
1
def self.with_replaced_metadata(meta)
-
orig_metadata = metadata
-
@metadata = meta
-
yield
-
ensure
-
@metadata = orig_metadata
-
end
-
-
# @private
-
# @return [Metadata] belonging to the parent of a nested {ExampleGroup}
-
1
def self.superclass_metadata
-
@superclass_metadata ||= superclass.respond_to?(:metadata) ? superclass.metadata : nil
-
end
-
-
# @private
-
1
def self.delegate_to_metadata(*names)
-
1
names.each do |name|
-
3
idempotently_define_singleton_method(name) { metadata.fetch(name) }
-
end
-
end
-
-
1
delegate_to_metadata :described_class, :file_path, :location
-
-
# @return [String] the current example group description
-
1
def self.description
-
description = metadata[:description]
-
RSpec.configuration.format_docstrings_block.call(description)
-
end
-
-
# Returns the class or module passed to the `describe` method (or alias).
-
# Returns nil if the subject is not a class or module.
-
# @example
-
# describe Thing do
-
# it "does something" do
-
# described_class == Thing
-
# end
-
# end
-
#
-
1
def described_class
-
self.class.described_class
-
end
-
-
# @!endgroup
-
-
# @!group Defining Examples
-
-
# @private
-
# @macro [attach] define_example_method
-
# @!scope class
-
# @overload $1
-
# @overload $1(&example_implementation)
-
# @param example_implementation [Block] The implementation of the example.
-
# @overload $1(doc_string, *metadata_keys, metadata={})
-
# @param doc_string [String] The example's doc string.
-
# @param metadata [Hash] Metadata for the example.
-
# @param metadata_keys [Array<Symbol>] Metadata tags for the example.
-
# Will be transformed into hash entries with `true` values.
-
# @overload $1(doc_string, *metadata_keys, metadata={}, &example_implementation)
-
# @param doc_string [String] The example's doc string.
-
# @param metadata [Hash] Metadata for the example.
-
# @param metadata_keys [Array<Symbol>] Metadata tags for the example.
-
# Will be transformed into hash entries with `true` values.
-
# @param example_implementation [Block] The implementation of the example.
-
# @yield [Example] the example object
-
# @example
-
# $1 do
-
# end
-
#
-
# $1 "does something" do
-
# end
-
#
-
# $1 "does something", :slow, :uses_js do
-
# end
-
#
-
# $1 "does something", :with => 'additional metadata' do
-
# end
-
#
-
# $1 "does something" do |ex|
-
# # ex is the Example object that contains metadata about the example
-
# end
-
1
def self.define_example_method(name, extra_options={})
-
12
idempotently_define_singleton_method(name) do |*all_args, &block|
-
desc, *args = *all_args
-
-
options = Metadata.build_hash_from(args)
-
options.update(:skip => RSpec::Core::Pending::NOT_YET_IMPLEMENTED) unless block
-
options.update(extra_options)
-
-
example = RSpec::Core::Example.new(self, desc, options, block)
-
examples << example
-
example
-
end
-
end
-
-
# Defines an example within a group.
-
1
define_example_method :example
-
# Defines an example within a group.
-
# This is the primary API to define a code example.
-
1
define_example_method :it
-
# Defines an example within a group.
-
# Useful for when your docstring does not read well off of `it`.
-
# @example
-
# RSpec.describe MyClass do
-
# specify "#do_something is deprecated" do
-
# # ...
-
# end
-
# end
-
1
define_example_method :specify
-
-
# Shortcut to define an example with `:focus => true`.
-
# @see example
-
1
define_example_method :focus, :focus => true
-
# Shortcut to define an example with `:focus => true`.
-
# @see example
-
1
define_example_method :fexample, :focus => true
-
# Shortcut to define an example with `:focus => true`.
-
# @see example
-
1
define_example_method :fit, :focus => true
-
# Shortcut to define an example with `:focus => true`.
-
# @see example
-
1
define_example_method :fspecify, :focus => true
-
# Shortcut to define an example with `:skip => 'Temporarily skipped with xexample'`.
-
# @see example
-
1
define_example_method :xexample, :skip => 'Temporarily skipped with xexample'
-
# Shortcut to define an example with `:skip => 'Temporarily skipped with xit'`.
-
# @see example
-
1
define_example_method :xit, :skip => 'Temporarily skipped with xit'
-
# Shortcut to define an example with `:skip => 'Temporarily skipped with xspecify'`.
-
# @see example
-
1
define_example_method :xspecify, :skip => 'Temporarily skipped with xspecify'
-
# Shortcut to define an example with `:skip => true`
-
# @see example
-
1
define_example_method :skip, :skip => true
-
# Shortcut to define an example with `:pending => true`
-
# @see example
-
1
define_example_method :pending, :pending => true
-
-
# @!endgroup
-
-
# @!group Defining Example Groups
-
-
# @private
-
# @macro [attach] define_example_group_method
-
# @!scope class
-
# @overload $1
-
# @overload $1(&example_group_definition)
-
# @param example_group_definition [Block] The definition of the example group.
-
# @overload $1(doc_string, *metadata_keys, metadata={}, &example_implementation)
-
# @param doc_string [String] The group's doc string.
-
# @param metadata [Hash] Metadata for the group.
-
# @param metadata_keys [Array<Symbol>] Metadata tags for the group.
-
# Will be transformed into hash entries with `true` values.
-
# @param example_group_definition [Block] The definition of the example group.
-
#
-
# Generates a subclass of this example group which inherits
-
# everything except the examples themselves.
-
#
-
# @example
-
#
-
# RSpec.describe "something" do # << This describe method is defined in
-
# # << RSpec::Core::DSL, included in the
-
# # << global namespace (optional)
-
# before do
-
# do_something_before
-
# end
-
#
-
# let(:thing) { Thing.new }
-
#
-
# $1 "attribute (of something)" do
-
# # examples in the group get the before hook
-
# # declared above, and can access `thing`
-
# end
-
# end
-
#
-
# @see DSL#describe
-
1
def self.define_example_group_method(name, metadata={})
-
7
idempotently_define_singleton_method(name) do |*args, &example_group_block|
-
thread_data = RSpec::Support.thread_local_data
-
top_level = self == ExampleGroup
-
-
if top_level
-
if thread_data[:in_example_group]
-
raise "Creating an isolated context from within a context is " \
-
"not allowed. Change `RSpec.#{name}` to `#{name}` or " \
-
"move this to a top-level scope."
-
end
-
-
thread_data[:in_example_group] = true
-
end
-
-
begin
-
-
description = args.shift
-
combined_metadata = metadata.dup
-
combined_metadata.merge!(args.pop) if args.last.is_a? Hash
-
args << combined_metadata
-
-
subclass(self, description, args, &example_group_block).tap do |child|
-
children << child
-
end
-
-
ensure
-
thread_data.delete(:in_example_group) if top_level
-
end
-
end
-
-
7
RSpec::Core::DSL.expose_example_group_alias(name)
-
end
-
-
1
define_example_group_method :example_group
-
-
# An alias of `example_group`. Generally used when grouping examples by a
-
# thing you are describing (e.g. an object, class or method).
-
# @see example_group
-
1
define_example_group_method :describe
-
-
# An alias of `example_group`. Generally used when grouping examples
-
# contextually (e.g. "with xyz", "when xyz" or "if xyz").
-
# @see example_group
-
1
define_example_group_method :context
-
-
# Shortcut to temporarily make an example group skipped.
-
# @see example_group
-
1
define_example_group_method :xdescribe, :skip => "Temporarily skipped with xdescribe"
-
-
# Shortcut to temporarily make an example group skipped.
-
# @see example_group
-
1
define_example_group_method :xcontext, :skip => "Temporarily skipped with xcontext"
-
-
# Shortcut to define an example group with `:focus => true`.
-
# @see example_group
-
1
define_example_group_method :fdescribe, :focus => true
-
-
# Shortcut to define an example group with `:focus => true`.
-
# @see example_group
-
1
define_example_group_method :fcontext, :focus => true
-
-
# @!endgroup
-
-
# @!group Including Shared Example Groups
-
-
# @private
-
# @macro [attach] define_nested_shared_group_method
-
# @!scope class
-
#
-
# @see SharedExampleGroup
-
1
def self.define_nested_shared_group_method(new_name, report_label="it should behave like")
-
2
idempotently_define_singleton_method(new_name) do |name, *args, &customization_block|
-
# Pass :caller so the :location metadata is set properly.
-
# Otherwise, it'll be set to the next line because that's
-
# the block's source_location.
-
group = example_group("#{report_label} #{name}", :caller => (the_caller = caller)) do
-
find_and_eval_shared("examples", name, the_caller.first, *args, &customization_block)
-
end
-
group.metadata[:shared_group_name] = name
-
group
-
end
-
end
-
-
# Generates a nested example group and includes the shared content
-
# mapped to `name` in the nested group.
-
1
define_nested_shared_group_method :it_behaves_like, "behaves like"
-
# Generates a nested example group and includes the shared content
-
# mapped to `name` in the nested group.
-
1
define_nested_shared_group_method :it_should_behave_like
-
-
# Includes shared content mapped to `name` directly in the group in which
-
# it is declared, as opposed to `it_behaves_like`, which creates a nested
-
# group. If given a block, that block is also eval'd in the current
-
# context.
-
#
-
# @see SharedExampleGroup
-
1
def self.include_context(name, *args, &block)
-
find_and_eval_shared("context", name, caller.first, *args, &block)
-
end
-
-
# Includes shared content mapped to `name` directly in the group in which
-
# it is declared, as opposed to `it_behaves_like`, which creates a nested
-
# group. If given a block, that block is also eval'd in the current
-
# context.
-
#
-
# @see SharedExampleGroup
-
1
def self.include_examples(name, *args, &block)
-
find_and_eval_shared("examples", name, caller.first, *args, &block)
-
end
-
-
# @private
-
1
def self.find_and_eval_shared(label, name, inclusion_location, *args, &customization_block)
-
shared_block = RSpec.world.shared_example_group_registry.find(parent_groups, name)
-
-
unless shared_block
-
raise ArgumentError, "Could not find shared #{label} #{name.inspect}"
-
end
-
-
SharedExampleGroupInclusionStackFrame.with_frame(name, Metadata.relative_path(inclusion_location)) do
-
module_exec(*args, &shared_block)
-
module_exec(&customization_block) if customization_block
-
end
-
end
-
-
# @!endgroup
-
-
# @private
-
1
def self.subclass(parent, description, args, &example_group_block)
-
subclass = Class.new(parent)
-
subclass.set_it_up(description, *args, &example_group_block)
-
subclass.module_exec(&example_group_block) if example_group_block
-
-
# The LetDefinitions module must be included _after_ other modules
-
# to ensure that it takes precedence when there are name collisions.
-
# Thus, we delay including it until after the example group block
-
# has been eval'd.
-
MemoizedHelpers.define_helpers_on(subclass)
-
-
subclass
-
end
-
-
# @private
-
1
def self.set_it_up(description, *args, &example_group_block)
-
# Ruby 1.9 has a bug that can lead to infinite recursion and a
-
# SystemStackError if you include a module in a superclass after
-
# including it in a subclass: https://gist.github.com/845896
-
# To prevent this, we must include any modules in
-
# RSpec::Core::ExampleGroup before users create example groups and have
-
# a chance to include the same module in a subclass of
-
# RSpec::Core::ExampleGroup. So we need to configure example groups
-
# here.
-
ensure_example_groups_are_configured
-
-
user_metadata = Metadata.build_hash_from(args)
-
-
@metadata = Metadata::ExampleGroupHash.create(
-
superclass_metadata, user_metadata,
-
superclass.method(:next_runnable_index_for),
-
description, *args, &example_group_block
-
)
-
ExampleGroups.assign_const(self)
-
-
hooks.register_globals(self, RSpec.configuration.hooks)
-
RSpec.configuration.configure_group(self)
-
end
-
-
# @private
-
1
def self.examples
-
@examples ||= []
-
end
-
-
# @private
-
1
def self.filtered_examples
-
RSpec.world.filtered_examples[self]
-
end
-
-
# @private
-
1
def self.descendant_filtered_examples
-
@descendant_filtered_examples ||= filtered_examples +
-
FlatMap.flat_map(children, &:descendant_filtered_examples)
-
end
-
-
# @private
-
1
def self.children
-
@children ||= []
-
end
-
-
# @private
-
1
def self.next_runnable_index_for(file)
-
if self == ExampleGroup
-
RSpec.world.num_example_groups_defined_in(file)
-
else
-
children.count + examples.count
-
end + 1
-
end
-
-
# @private
-
1
def self.descendants
-
@_descendants ||= [self] + FlatMap.flat_map(children, &:descendants)
-
end
-
-
## @private
-
1
def self.parent_groups
-
@parent_groups ||= ancestors.select { |a| a < RSpec::Core::ExampleGroup }
-
end
-
-
# @private
-
1
def self.top_level?
-
superclass == ExampleGroup
-
end
-
-
# @private
-
1
def self.ensure_example_groups_are_configured
-
unless defined?(@@example_groups_configured)
-
RSpec.configuration.configure_mock_framework
-
RSpec.configuration.configure_expectation_framework
-
# rubocop:disable Style/ClassVars
-
@@example_groups_configured = true
-
# rubocop:enable Style/ClassVars
-
end
-
end
-
-
# @private
-
1
def self.before_context_ivars
-
@before_context_ivars ||= {}
-
end
-
-
# @private
-
1
def self.store_before_context_ivars(example_group_instance)
-
each_instance_variable_for_example(example_group_instance) do |ivar|
-
before_context_ivars[ivar] = example_group_instance.instance_variable_get(ivar)
-
end
-
end
-
-
# @private
-
1
def self.run_before_context_hooks(example_group_instance)
-
set_ivars(example_group_instance, superclass_before_context_ivars)
-
-
ContextHookMemoized::Before.isolate_for_context_hook(example_group_instance) do
-
hooks.run(:before, :context, example_group_instance)
-
end
-
ensure
-
store_before_context_ivars(example_group_instance)
-
end
-
-
1
if RUBY_VERSION.to_f >= 1.9
-
# @private
-
1
def self.superclass_before_context_ivars
-
superclass.before_context_ivars
-
end
-
else # 1.8.7
-
skipped
# :nocov:
-
skipped
# @private
-
skipped
def self.superclass_before_context_ivars
-
skipped
if superclass.respond_to?(:before_context_ivars)
-
skipped
superclass.before_context_ivars
-
skipped
else
-
skipped
# `self` must be the singleton class of an ExampleGroup instance.
-
skipped
# On 1.8.7, the superclass of a singleton class of an instance of A
-
skipped
# is A's singleton class. On 1.9+, it's A. On 1.8.7, the first ancestor
-
skipped
# is A, so we can mirror 1.8.7's behavior here. Note that we have to
-
skipped
# search for the first that responds to `before_context_ivars`
-
skipped
# in case a module has been included in the singleton class.
-
skipped
ancestors.find { |a| a.respond_to?(:before_context_ivars) }.before_context_ivars
-
skipped
end
-
skipped
end
-
skipped
# :nocov:
-
end
-
-
# @private
-
1
def self.run_after_context_hooks(example_group_instance)
-
set_ivars(example_group_instance, before_context_ivars)
-
-
ContextHookMemoized::After.isolate_for_context_hook(example_group_instance) do
-
hooks.run(:after, :context, example_group_instance)
-
end
-
ensure
-
before_context_ivars.clear
-
end
-
-
# Runs all the examples in this group.
-
1
def self.run(reporter=RSpec::Core::NullReporter)
-
return if RSpec.world.wants_to_quit
-
reporter.example_group_started(self)
-
-
should_run_context_hooks = descendant_filtered_examples.any?
-
begin
-
run_before_context_hooks(new('before(:context) hook')) if should_run_context_hooks
-
result_for_this_group = run_examples(reporter)
-
results_for_descendants = ordering_strategy.order(children).map { |child| child.run(reporter) }.all?
-
result_for_this_group && results_for_descendants
-
rescue Pending::SkipDeclaredInExample => ex
-
for_filtered_examples(reporter) { |example| example.skip_with_exception(reporter, ex) }
-
true
-
rescue Exception => ex
-
RSpec.world.wants_to_quit = true if fail_fast?
-
for_filtered_examples(reporter) { |example| example.fail_with_exception(reporter, ex) }
-
false
-
ensure
-
run_after_context_hooks(new('after(:context) hook')) if should_run_context_hooks
-
reporter.example_group_finished(self)
-
end
-
end
-
-
# @private
-
1
def self.ordering_strategy
-
order = metadata.fetch(:order, :global)
-
registry = RSpec.configuration.ordering_registry
-
-
registry.fetch(order) do
-
warn <<-WARNING.gsub(/^ +\|/, '')
-
|WARNING: Ignoring unknown ordering specified using `:order => #{order.inspect}` metadata.
-
| Falling back to configured global ordering.
-
| Unrecognized ordering specified at: #{location}
-
WARNING
-
-
registry.fetch(:global)
-
end
-
end
-
-
# @private
-
1
def self.run_examples(reporter)
-
ordering_strategy.order(filtered_examples).map do |example|
-
next if RSpec.world.wants_to_quit
-
instance = new(example.inspect_output)
-
set_ivars(instance, before_context_ivars)
-
succeeded = example.run(instance, reporter)
-
RSpec.world.wants_to_quit = true if fail_fast? && !succeeded
-
succeeded
-
end.all?
-
end
-
-
# @private
-
1
def self.for_filtered_examples(reporter, &block)
-
filtered_examples.each(&block)
-
-
children.each do |child|
-
reporter.example_group_started(child)
-
child.for_filtered_examples(reporter, &block)
-
reporter.example_group_finished(child)
-
end
-
false
-
end
-
-
# @private
-
1
def self.fail_fast?
-
RSpec.configuration.fail_fast?
-
end
-
-
# @private
-
1
def self.declaration_line_numbers
-
@declaration_line_numbers ||= [metadata[:line_number]] +
-
examples.map { |e| e.metadata[:line_number] } +
-
FlatMap.flat_map(children, &:declaration_line_numbers)
-
end
-
-
# @return [String] the unique id of this example group. Pass
-
# this at the command line to re-run this exact example group.
-
1
def self.id
-
Metadata.id_from(metadata)
-
end
-
-
# @private
-
1
def self.top_level_description
-
parent_groups.last.description
-
end
-
-
# @private
-
1
def self.set_ivars(instance, ivars)
-
ivars.each { |name, value| instance.instance_variable_set(name, value) }
-
end
-
-
1
if RUBY_VERSION.to_f < 1.9
-
skipped
# :nocov:
-
skipped
# @private
-
skipped
INSTANCE_VARIABLE_TO_IGNORE = '@__inspect_output'.freeze
-
skipped
# :nocov:
-
else
-
# @private
-
1
INSTANCE_VARIABLE_TO_IGNORE = :@__inspect_output
-
end
-
-
# @private
-
1
def self.each_instance_variable_for_example(group)
-
group.instance_variables.each do |ivar|
-
yield ivar unless ivar == INSTANCE_VARIABLE_TO_IGNORE
-
end
-
end
-
-
1
def initialize(inspect_output=nil)
-
@__inspect_output = inspect_output || '(no description provided)'
-
super() # no args get passed
-
end
-
-
# @private
-
1
def inspect
-
"#<#{self.class} #{@__inspect_output}>"
-
end
-
-
1
unless method_defined?(:singleton_class) # for 1.8.7
-
skipped
# :nocov:
-
skipped
# @private
-
skipped
def singleton_class
-
skipped
class << self; self; end
-
skipped
end
-
skipped
# :nocov:
-
end
-
-
# Raised when an RSpec API is called in the wrong scope, such as `before`
-
# being called from within an example rather than from within an example
-
# group block.
-
1
WrongScopeError = Class.new(NoMethodError)
-
-
1
def self.method_missing(name, *args)
-
if method_defined?(name)
-
raise WrongScopeError,
-
"`#{name}` is not available on an example group (e.g. a " \
-
"`describe` or `context` block). It is only available from " \
-
"within individual examples (e.g. `it` blocks) or from " \
-
"constructs that run in the scope of an example (e.g. " \
-
"`before`, `let`, etc)."
-
end
-
-
super
-
end
-
1
private_class_method :method_missing
-
-
1
private
-
-
1
def method_missing(name, *args)
-
if self.class.respond_to?(name)
-
raise WrongScopeError,
-
"`#{name}` is not available from within an example (e.g. an " \
-
"`it` block) or from constructs that run in the scope of an " \
-
"example (e.g. `before`, `let`, etc). It is only available " \
-
"on an example group (e.g. a `describe` or `context` block)."
-
end
-
-
super
-
end
-
end
-
-
# @private
-
# Unnamed example group used by `SuiteHookContext`.
-
1
class AnonymousExampleGroup < ExampleGroup
-
1
def self.metadata
-
{}
-
end
-
end
-
-
# Contains information about the inclusion site of a shared example group.
-
1
class SharedExampleGroupInclusionStackFrame
-
# @return [String] the name of the shared example group
-
1
attr_reader :shared_group_name
-
# @return [String] the location where the shared example was included
-
1
attr_reader :inclusion_location
-
-
1
def initialize(shared_group_name, inclusion_location)
-
@shared_group_name = shared_group_name
-
@inclusion_location = inclusion_location
-
end
-
-
# @return [String] The {#inclusion_location}, formatted for display by a formatter.
-
1
def formatted_inclusion_location
-
@formatted_inclusion_location ||= begin
-
RSpec.configuration.backtrace_formatter.backtrace_line(
-
inclusion_location.sub(/(:\d+):in .+$/, '\1')
-
)
-
end
-
end
-
-
# @return [String] Description of this stack frame, in the form used by
-
# RSpec's built-in formatters.
-
1
def description
-
@description ||= "Shared Example Group: #{shared_group_name.inspect} " \
-
"called from #{formatted_inclusion_location}"
-
end
-
-
# @private
-
1
def self.current_backtrace
-
shared_example_group_inclusions.reverse
-
end
-
-
# @private
-
1
def self.with_frame(name, location)
-
current_stack = shared_example_group_inclusions
-
current_stack << new(name, location)
-
yield
-
ensure
-
current_stack.pop
-
end
-
-
# @private
-
1
def self.shared_example_group_inclusions
-
RSpec::Support.thread_local_data[:shared_example_group_inclusions] ||= []
-
end
-
end
-
end
-
-
# @private
-
#
-
# Namespace for the example group subclasses generated by top-level
-
# `describe`.
-
1
module ExampleGroups
-
1
extend Support::RecursiveConstMethods
-
-
1
def self.assign_const(group)
-
base_name = base_name_for(group)
-
const_scope = constant_scope_for(group)
-
name = disambiguate(base_name, const_scope)
-
-
const_scope.const_set(name, group)
-
end
-
-
1
def self.constant_scope_for(group)
-
const_scope = group.superclass
-
const_scope = self if const_scope == ::RSpec::Core::ExampleGroup
-
const_scope
-
end
-
-
1
def self.base_name_for(group)
-
return "Anonymous" if group.description.empty?
-
-
# Convert to CamelCase.
-
name = ' ' << group.description
-
name.gsub!(/[^0-9a-zA-Z]+([0-9a-zA-Z])/) do
-
match = ::Regexp.last_match[1]
-
match.upcase!
-
match
-
end
-
-
name.lstrip! # Remove leading whitespace
-
name.gsub!(/\W/, ''.freeze) # JRuby, RBX and others don't like non-ascii in const names
-
-
# Ruby requires first const letter to be A-Z. Use `Nested`
-
# as necessary to enforce that.
-
name.gsub!(/\A([^A-Z]|\z)/, 'Nested\1'.freeze)
-
-
name
-
end
-
-
1
if RUBY_VERSION == '1.9.2'
-
skipped
# :nocov:
-
skipped
class << self
-
skipped
alias _base_name_for base_name_for
-
skipped
def base_name_for(group)
-
skipped
_base_name_for(group) + '_'
-
skipped
end
-
skipped
end
-
skipped
private_class_method :_base_name_for
-
skipped
# :nocov:
-
end
-
-
1
def self.disambiguate(name, const_scope)
-
return name unless const_defined_on?(const_scope, name)
-
-
# Add a trailing number if needed to disambiguate from an existing
-
# constant.
-
name << "_2"
-
name.next! while const_defined_on?(const_scope, name)
-
name
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
1
class FilterManager
-
1
attr_reader :exclusions, :inclusions
-
-
1
def initialize
-
2
@exclusions, @inclusions = FilterRules.build
-
end
-
-
# @api private
-
#
-
# @param file_path [String]
-
# @param line_numbers [Array]
-
1
def add_location(file_path, line_numbers)
-
# locations is a hash of expanded paths to arrays of line
-
# numbers to match against. e.g.
-
# { "path/to/file.rb" => [37, 42] }
-
add_path_to_arrays_filter(:locations, File.expand_path(file_path), line_numbers)
-
end
-
-
1
def add_ids(rerun_path, scoped_ids)
-
# ids is a hash of relative paths to arrays of ids
-
# to match against. e.g.
-
# { "./path/to/file.rb" => ["1:1", "2:4"] }
-
rerun_path = Metadata.relative_path(File.expand_path rerun_path)
-
add_path_to_arrays_filter(:ids, rerun_path, scoped_ids)
-
end
-
-
1
def empty?
-
inclusions.empty? && exclusions.empty?
-
end
-
-
1
def prune(examples)
-
# Semantically, this is unnecessary (the filtering below will return the empty
-
# array unmodified), but for perf reasons it's worth exiting early here. Users
-
# commonly have top-level examples groups that do not have any direct examples
-
# and instead have nested groups with examples. In that kind of situation,
-
# `examples` will be empty.
-
return examples if examples.empty?
-
-
examples = prune_conditionally_filtered_examples(examples)
-
-
if inclusions.standalone?
-
examples.select { |e| inclusions.include_example?(e) }
-
else
-
locations, ids, non_scoped_inclusions = inclusions.split_file_scoped_rules
-
-
examples.select do |ex|
-
file_scoped_include?(ex.metadata, ids, locations) do
-
!exclusions.include_example?(ex) && non_scoped_inclusions.include_example?(ex)
-
end
-
end
-
end
-
end
-
-
1
def exclude(*args)
-
exclusions.add(args.last)
-
end
-
-
1
def exclude_only(*args)
-
exclusions.use_only(args.last)
-
end
-
-
1
def exclude_with_low_priority(*args)
-
exclusions.add_with_low_priority(args.last)
-
end
-
-
1
def include(*args)
-
inclusions.add(args.last)
-
end
-
-
1
def include_only(*args)
-
inclusions.use_only(args.last)
-
end
-
-
1
def include_with_low_priority(*args)
-
inclusions.add_with_low_priority(args.last)
-
end
-
-
1
private
-
-
1
def add_path_to_arrays_filter(filter_key, path, values)
-
filter = inclusions.delete(filter_key) || Hash.new { |h, k| h[k] = [] }
-
filter[path].concat(values)
-
inclusions.add(filter_key => filter)
-
end
-
-
1
def prune_conditionally_filtered_examples(examples)
-
examples.reject do |ex|
-
meta = ex.metadata
-
!meta.fetch(:if, true) || meta[:unless]
-
end
-
end
-
-
# When a user specifies a particular spec location, that takes priority
-
# over any exclusion filters (such as if the spec is tagged with `:slow`
-
# and there is a `:slow => true` exclusion filter), but only for specs
-
# defined in the same file as the location filters. Excluded specs in
-
# other files should still be excluded.
-
1
def file_scoped_include?(ex_metadata, ids, locations)
-
no_id_filters = ids[ex_metadata[:rerun_file_path]].empty?
-
no_location_filters = locations[
-
File.expand_path(ex_metadata[:rerun_file_path])
-
].empty?
-
-
return yield if no_location_filters && no_id_filters
-
-
MetadataFilter.filter_applies?(:ids, ids, ex_metadata) ||
-
MetadataFilter.filter_applies?(:locations, locations, ex_metadata)
-
end
-
end
-
-
# @private
-
1
class FilterRules
-
1
PROC_HEX_NUMBER = /0x[0-9a-f]+@/
-
1
PROJECT_DIR = File.expand_path('.')
-
-
1
attr_accessor :opposite
-
1
attr_reader :rules
-
-
1
def self.build
-
2
exclusions = ExclusionRules.new
-
2
inclusions = InclusionRules.new
-
2
exclusions.opposite = inclusions
-
2
inclusions.opposite = exclusions
-
2
[exclusions, inclusions]
-
end
-
-
1
def initialize(rules={})
-
4
@rules = rules
-
end
-
-
1
def add(updated)
-
@rules.merge!(updated).each_key { |k| opposite.delete(k) }
-
end
-
-
1
def add_with_low_priority(updated)
-
updated = updated.merge(@rules)
-
opposite.each_pair { |k, v| updated.delete(k) if updated[k] == v }
-
@rules.replace(updated)
-
end
-
-
1
def use_only(updated)
-
updated.each_key { |k| opposite.delete(k) }
-
@rules.replace(updated)
-
end
-
-
1
def clear
-
@rules.clear
-
end
-
-
1
def delete(key)
-
@rules.delete(key)
-
end
-
-
1
def fetch(*args, &block)
-
@rules.fetch(*args, &block)
-
end
-
-
1
def [](key)
-
@rules[key]
-
end
-
-
1
def empty?
-
rules.empty?
-
end
-
-
1
def each_pair(&block)
-
@rules.each_pair(&block)
-
end
-
-
1
def description
-
rules.inspect.gsub(PROC_HEX_NUMBER, '').gsub(PROJECT_DIR, '.').gsub(' (lambda)', '')
-
end
-
-
1
def include_example?(example)
-
MetadataFilter.apply?(:any?, @rules, example.metadata)
-
end
-
end
-
-
# @private
-
1
ExclusionRules = FilterRules
-
-
# @private
-
1
class InclusionRules < FilterRules
-
1
def add(*args)
-
apply_standalone_filter(*args) || super
-
end
-
-
1
def add_with_low_priority(*args)
-
apply_standalone_filter(*args) || super
-
end
-
-
1
def include_example?(example)
-
@rules.empty? || super
-
end
-
-
1
def standalone?
-
is_standalone_filter?(@rules)
-
end
-
-
1
def split_file_scoped_rules
-
rules_dup = @rules.dup
-
locations = rules_dup.delete(:locations) { Hash.new([]) }
-
ids = rules_dup.delete(:ids) { Hash.new([]) }
-
-
return locations, ids, self.class.new(rules_dup)
-
end
-
-
1
private
-
-
1
def apply_standalone_filter(updated)
-
return true if standalone?
-
return nil unless is_standalone_filter?(updated)
-
-
replace_filters(updated)
-
true
-
end
-
-
1
def replace_filters(new_rules)
-
@rules.replace(new_rules)
-
opposite.clear
-
end
-
-
1
def is_standalone_filter?(rules)
-
rules.key?(:full_description)
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
1
module FlatMap
-
1
if [].respond_to?(:flat_map)
-
1
def flat_map(array, &block)
-
1
array.flat_map(&block)
-
end
-
else # for 1.8.7
-
skipped
# :nocov:
-
skipped
def flat_map(array, &block)
-
skipped
array.map(&block).flatten(1)
-
skipped
end
-
skipped
# :nocov:
-
end
-
-
1
module_function :flat_map
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support "directory_maker"
-
# ## Built-in Formatters
-
#
-
# * progress (default) - Prints dots for passing examples, `F` for failures, `*`
-
# for pending.
-
# * documentation - Prints the docstrings passed to `describe` and `it` methods
-
# (and their aliases).
-
# * html
-
# * json - Useful for archiving data for subsequent analysis.
-
#
-
# The progress formatter is the default, but you can choose any one or more of
-
# the other formatters by passing with the `--format` (or `-f` for short)
-
# command-line option, e.g.
-
#
-
# rspec --format documentation
-
#
-
# You can also send the output of multiple formatters to different streams, e.g.
-
#
-
# rspec --format documentation --format html --out results.html
-
#
-
# This example sends the output of the documentation formatter to `$stdout`, and
-
# the output of the html formatter to results.html.
-
#
-
# ## Custom Formatters
-
#
-
# You can tell RSpec to use a custom formatter by passing its path and name to
-
# the `rspec` commmand. For example, if you define MyCustomFormatter in
-
# path/to/my_custom_formatter.rb, you would type this command:
-
#
-
# rspec --require path/to/my_custom_formatter.rb --format MyCustomFormatter
-
#
-
# The reporter calls every formatter with this protocol:
-
#
-
# * To start
-
# * `start(StartNotification)`
-
# * Once per example group
-
# * `example_group_started(GroupNotification)`
-
# * Once per example
-
# * `example_started(ExampleNotification)`
-
# * One of these per example, depending on outcome
-
# * `example_passed(ExampleNotification)`
-
# * `example_failed(FailedExampleNotification)`
-
# * `example_pending(ExampleNotification)`
-
# * Optionally at any time
-
# * `message(MessageNotification)`
-
# * At the end of the suite
-
# * `stop(ExamplesNotification)`
-
# * `start_dump(NullNotification)`
-
# * `dump_pending(ExamplesNotification)`
-
# * `dump_failures(ExamplesNotification)`
-
# * `dump_summary(SummaryNotification)`
-
# * `seed(SeedNotification)`
-
# * `close(NullNotification)`
-
#
-
# Only the notifications to which you subscribe your formatter will be called
-
# on your formatter. To subscribe your formatter use:
-
# `RSpec::Core::Formatters#register` e.g.
-
#
-
# `RSpec::Core::Formatters.register FormatterClassName, :example_passed, :example_failed`
-
#
-
# We recommend you implement the methods yourself; for simplicity we provide the
-
# default formatter output via our notification objects but if you prefer you
-
# can subclass `RSpec::Core::Formatters::BaseTextFormatter` and override the
-
# methods you wish to enhance.
-
#
-
# @see RSpec::Core::Formatters::BaseTextFormatter
-
# @see RSpec::Core::Reporter
-
1
module RSpec::Core::Formatters
-
1
autoload :DocumentationFormatter, 'rspec/core/formatters/documentation_formatter'
-
1
autoload :HtmlFormatter, 'rspec/core/formatters/html_formatter'
-
1
autoload :FallbackMessageFormatter, 'rspec/core/formatters/fallback_message_formatter'
-
1
autoload :ProgressFormatter, 'rspec/core/formatters/progress_formatter'
-
1
autoload :ProfileFormatter, 'rspec/core/formatters/profile_formatter'
-
1
autoload :JsonFormatter, 'rspec/core/formatters/json_formatter'
-
1
autoload :BisectFormatter, 'rspec/core/formatters/bisect_formatter'
-
-
# Register the formatter class
-
# @param formatter_class [Class] formatter class to register
-
# @param notifications [Symbol, ...] one or more notifications to be
-
# registered to the specified formatter
-
#
-
# @see RSpec::Core::Formatters::BaseFormatter
-
1
def self.register(formatter_class, *notifications)
-
1
Loader.formatters[formatter_class] = notifications
-
end
-
-
# @api private
-
#
-
# `RSpec::Core::Formatters::Loader` is an internal class for
-
# managing formatters used by a particular configuration. It is
-
# not expected to be used directly, but only through the configuration
-
# interface.
-
1
class Loader
-
# @api private
-
#
-
# Internal formatters are stored here when loaded.
-
1
def self.formatters
-
1
@formatters ||= {}
-
end
-
-
# @api private
-
1
def initialize(reporter)
-
@formatters = []
-
@reporter = reporter
-
self.default_formatter = 'progress'
-
end
-
-
# @return [Array] the loaded formatters
-
1
attr_reader :formatters
-
-
# @return [Reporter] the reporter
-
1
attr_reader :reporter
-
-
# @return [String] the default formatter to setup, defaults to `progress`
-
1
attr_accessor :default_formatter
-
-
# @private
-
1
def setup_default(output_stream, deprecation_stream)
-
add default_formatter, output_stream if @formatters.empty?
-
-
unless @formatters.any? { |formatter| DeprecationFormatter === formatter }
-
add DeprecationFormatter, deprecation_stream, output_stream
-
end
-
-
unless existing_formatter_implements?(:message)
-
add FallbackMessageFormatter, output_stream
-
end
-
-
return unless RSpec.configuration.profile_examples?
-
-
@reporter.setup_profiler
-
-
return if existing_formatter_implements?(:dump_profile)
-
-
add RSpec::Core::Formatters::ProfileFormatter, output_stream
-
end
-
-
# @private
-
1
def add(formatter_to_use, *paths)
-
formatter_class = find_formatter(formatter_to_use)
-
-
args = paths.map { |p| p.respond_to?(:puts) ? p : file_at(p) }
-
-
if !Loader.formatters[formatter_class].nil?
-
formatter = formatter_class.new(*args)
-
register formatter, notifications_for(formatter_class)
-
elsif defined?(RSpec::LegacyFormatters)
-
formatter = RSpec::LegacyFormatters.load_formatter formatter_class, *args
-
register formatter, formatter.notifications
-
else
-
call_site = "Formatter added at: #{::RSpec::CallerFilter.first_non_rspec_line}"
-
-
RSpec.warn_deprecation <<-WARNING.gsub(/\s*\|/, ' ')
-
|The #{formatter_class} formatter uses the deprecated formatter
-
|interface not supported directly by RSpec 3.
-
|
-
|To continue to use this formatter you must install the
-
|`rspec-legacy_formatters` gem, which provides support
-
|for legacy formatters or upgrade the formatter to a
-
|compatible version.
-
|
-
|#{call_site}
-
WARNING
-
end
-
end
-
-
1
private
-
-
1
def find_formatter(formatter_to_use)
-
built_in_formatter(formatter_to_use) ||
-
custom_formatter(formatter_to_use) ||
-
(raise ArgumentError, "Formatter '#{formatter_to_use}' unknown - " \
-
"maybe you meant 'documentation' or 'progress'?.")
-
end
-
-
1
def register(formatter, notifications)
-
return if duplicate_formatter_exists?(formatter)
-
@reporter.register_listener formatter, *notifications
-
@formatters << formatter
-
formatter
-
end
-
-
1
def duplicate_formatter_exists?(new_formatter)
-
@formatters.any? do |formatter|
-
formatter.class == new_formatter.class && formatter.output == new_formatter.output
-
end
-
end
-
-
1
def existing_formatter_implements?(notification)
-
@reporter.registered_listeners(notification).any?
-
end
-
-
1
def built_in_formatter(key)
-
case key.to_s
-
when 'd', 'doc', 'documentation'
-
DocumentationFormatter
-
when 'h', 'html'
-
HtmlFormatter
-
when 'p', 'progress'
-
ProgressFormatter
-
when 'j', 'json'
-
JsonFormatter
-
when 'bisect'
-
BisectFormatter
-
end
-
end
-
-
1
def notifications_for(formatter_class)
-
formatter_class.ancestors.inject(::RSpec::Core::Set.new) do |notifications, klass|
-
notifications.merge Loader.formatters.fetch(klass) { ::RSpec::Core::Set.new }
-
end
-
end
-
-
1
def custom_formatter(formatter_ref)
-
if Class === formatter_ref
-
formatter_ref
-
elsif string_const?(formatter_ref)
-
begin
-
formatter_ref.gsub(/^::/, '').split('::').inject(Object) { |a, e| a.const_get e }
-
rescue NameError
-
require(path_for(formatter_ref)) ? retry : raise
-
end
-
end
-
end
-
-
1
def string_const?(str)
-
str.is_a?(String) && /\A[A-Z][a-zA-Z0-9_:]*\z/ =~ str
-
end
-
-
1
def path_for(const_ref)
-
underscore_with_fix_for_non_standard_rspec_naming(const_ref)
-
end
-
-
1
def underscore_with_fix_for_non_standard_rspec_naming(string)
-
underscore(string).sub(%r{(^|/)r_spec($|/)}, '\\1rspec\\2')
-
end
-
-
# activesupport/lib/active_support/inflector/methods.rb, line 48
-
1
def underscore(camel_cased_word)
-
word = camel_cased_word.to_s.dup
-
word.gsub!(/::/, '/')
-
word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
-
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
-
word.tr!("-", "_")
-
word.downcase!
-
word
-
end
-
-
1
def file_at(path)
-
RSpec::Support::DirectoryMaker.mkdir_p(File.dirname(path))
-
File.new(path, 'w')
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "formatters/helpers"
-
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# @private
-
1
class DeprecationFormatter
-
1
Formatters.register self, :deprecation, :deprecation_summary
-
-
1
attr_reader :count, :deprecation_stream, :summary_stream
-
-
1
def initialize(deprecation_stream, summary_stream)
-
@deprecation_stream = deprecation_stream
-
@summary_stream = summary_stream
-
@seen_deprecations = Set.new
-
@count = 0
-
end
-
1
alias :output :deprecation_stream
-
-
1
def printer
-
@printer ||= case deprecation_stream
-
when File
-
ImmediatePrinter.new(FileStream.new(deprecation_stream),
-
summary_stream, self)
-
when RaiseErrorStream
-
ImmediatePrinter.new(deprecation_stream, summary_stream, self)
-
else
-
DelayedPrinter.new(deprecation_stream, summary_stream, self)
-
end
-
end
-
-
1
def deprecation(notification)
-
return if @seen_deprecations.include? notification
-
-
@count += 1
-
printer.print_deprecation_message notification
-
@seen_deprecations << notification
-
end
-
-
1
def deprecation_summary(_notification)
-
printer.deprecation_summary
-
end
-
-
1
def deprecation_message_for(data)
-
if data.message
-
SpecifiedDeprecationMessage.new(data)
-
else
-
GeneratedDeprecationMessage.new(data)
-
end
-
end
-
-
1
RAISE_ERROR_CONFIG_NOTICE = <<-EOS.gsub(/^\s+\|/, '')
-
|
-
|If you need more of the backtrace for any of these deprecations to
-
|identify where to make the necessary changes, you can configure
-
|`config.raise_errors_for_deprecations!`, and it will turn the
-
|deprecation warnings into errors, giving you the full backtrace.
-
EOS
-
-
1
DEPRECATION_STREAM_NOTICE = "Pass `--deprecation-out` or set " \
-
"`config.deprecation_stream` to a file for full output."
-
-
1
SpecifiedDeprecationMessage = Struct.new(:type) do
-
1
def initialize(data)
-
@message = data.message
-
super deprecation_type_for(data)
-
end
-
-
1
def to_s
-
output_formatted @message
-
end
-
-
1
def too_many_warnings_message
-
msg = "Too many similar deprecation messages reported, disregarding further reports. "
-
msg << DEPRECATION_STREAM_NOTICE
-
msg
-
end
-
-
1
private
-
-
1
def output_formatted(str)
-
return str unless str.lines.count > 1
-
separator = "#{'-' * 80}"
-
"#{separator}\n#{str.chomp}\n#{separator}"
-
end
-
-
1
def deprecation_type_for(data)
-
data.message.gsub(/(\w+\/)+\w+\.rb:\d+/, '')
-
end
-
end
-
-
1
GeneratedDeprecationMessage = Struct.new(:type) do
-
1
def initialize(data)
-
@data = data
-
super data.deprecated
-
end
-
-
1
def to_s
-
msg = "#{@data.deprecated} is deprecated."
-
msg << " Use #{@data.replacement} instead." if @data.replacement
-
msg << " Called from #{@data.call_site}." if @data.call_site
-
msg
-
end
-
-
1
def too_many_warnings_message
-
msg = "Too many uses of deprecated '#{type}'. "
-
msg << DEPRECATION_STREAM_NOTICE
-
msg
-
end
-
end
-
-
# @private
-
1
class ImmediatePrinter
-
1
attr_reader :deprecation_stream, :summary_stream, :deprecation_formatter
-
-
1
def initialize(deprecation_stream, summary_stream, deprecation_formatter)
-
@deprecation_stream = deprecation_stream
-
-
@summary_stream = summary_stream
-
@deprecation_formatter = deprecation_formatter
-
end
-
-
1
def print_deprecation_message(data)
-
deprecation_message = deprecation_formatter.deprecation_message_for(data)
-
deprecation_stream.puts deprecation_message.to_s
-
end
-
-
1
def deprecation_summary
-
return if deprecation_formatter.count.zero?
-
deprecation_stream.summarize(summary_stream, deprecation_formatter.count)
-
end
-
end
-
-
# @private
-
1
class DelayedPrinter
-
1
TOO_MANY_USES_LIMIT = 4
-
-
1
attr_reader :deprecation_stream, :summary_stream, :deprecation_formatter
-
-
1
def initialize(deprecation_stream, summary_stream, deprecation_formatter)
-
@deprecation_stream = deprecation_stream
-
@summary_stream = summary_stream
-
@deprecation_formatter = deprecation_formatter
-
@seen_deprecations = Hash.new { 0 }
-
@deprecation_messages = Hash.new { |h, k| h[k] = [] }
-
end
-
-
1
def print_deprecation_message(data)
-
deprecation_message = deprecation_formatter.deprecation_message_for(data)
-
@seen_deprecations[deprecation_message] += 1
-
-
stash_deprecation_message(deprecation_message)
-
end
-
-
1
def stash_deprecation_message(deprecation_message)
-
if @seen_deprecations[deprecation_message] < TOO_MANY_USES_LIMIT
-
@deprecation_messages[deprecation_message] << deprecation_message.to_s
-
elsif @seen_deprecations[deprecation_message] == TOO_MANY_USES_LIMIT
-
@deprecation_messages[deprecation_message] << deprecation_message.too_many_warnings_message
-
end
-
end
-
-
1
def deprecation_summary
-
return unless @deprecation_messages.any?
-
-
print_deferred_deprecation_warnings
-
deprecation_stream.puts RAISE_ERROR_CONFIG_NOTICE
-
-
summary_stream.puts "\n#{Helpers.pluralize(deprecation_formatter.count, 'deprecation warning')} total"
-
end
-
-
1
def print_deferred_deprecation_warnings
-
deprecation_stream.puts "\nDeprecation Warnings:\n\n"
-
@deprecation_messages.keys.sort_by(&:type).each do |deprecation|
-
messages = @deprecation_messages[deprecation]
-
messages.each { |msg| deprecation_stream.puts msg }
-
deprecation_stream.puts
-
end
-
end
-
end
-
-
# @private
-
# Not really a stream, but is usable in place of one.
-
1
class RaiseErrorStream
-
1
def puts(message)
-
raise DeprecationError, message
-
end
-
-
1
def summarize(summary_stream, deprecation_count)
-
summary_stream.puts "\n#{Helpers.pluralize(deprecation_count, 'deprecation')} found."
-
end
-
end
-
-
# @private
-
# Wraps a File object and provides file-specific operations.
-
1
class FileStream
-
1
def initialize(file)
-
@file = file
-
-
# In one of my test suites, I got lots of duplicate output in the
-
# deprecation file (e.g. 200 of the same deprecation, even though
-
# the `puts` below was only called 6 times). Setting `sync = true`
-
# fixes this (but we really have no idea why!).
-
@file.sync = true
-
end
-
-
1
def puts(*args)
-
@file.puts(*args)
-
end
-
-
1
def summarize(summary_stream, deprecation_count)
-
path = @file.respond_to?(:path) ? @file.path : @file.inspect
-
summary_stream.puts "\n#{Helpers.pluralize(deprecation_count, 'deprecation')} logged to #{path}"
-
puts RAISE_ERROR_CONFIG_NOTICE
-
end
-
end
-
end
-
end
-
-
# Deprecation Error.
-
1
DeprecationError = Class.new(StandardError)
-
end
-
end
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# @private
-
1
class ExceptionPresenter
-
1
attr_reader :exception, :example, :description, :message_color,
-
:detail_formatter, :extra_detail_formatter, :backtrace_formatter
-
1
private :message_color, :detail_formatter, :extra_detail_formatter, :backtrace_formatter
-
-
1
def initialize(exception, example, options={})
-
@exception = exception
-
@example = example
-
@message_color = options.fetch(:message_color) { RSpec.configuration.failure_color }
-
@description = options.fetch(:description_formatter) { Proc.new { example.full_description } }.call(self)
-
@detail_formatter = options.fetch(:detail_formatter) { Proc.new {} }
-
@extra_detail_formatter = options.fetch(:extra_detail_formatter) { Proc.new {} }
-
@backtrace_formatter = options.fetch(:backtrace_formatter) { RSpec.configuration.backtrace_formatter }
-
@indentation = options.fetch(:indentation, 2)
-
@skip_shared_group_trace = options.fetch(:skip_shared_group_trace, false)
-
@failure_lines = options[:failure_lines]
-
end
-
-
1
def message_lines
-
add_shared_group_lines(failure_lines, Notifications::NullColorizer)
-
end
-
-
1
def colorized_message_lines(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
add_shared_group_lines(failure_lines, colorizer).map do |line|
-
colorizer.wrap line, message_color
-
end
-
end
-
-
1
def formatted_backtrace
-
backtrace_formatter.format_backtrace(exception_backtrace, example.metadata)
-
end
-
-
1
def colorized_formatted_backtrace(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
formatted_backtrace.map do |backtrace_info|
-
colorizer.wrap "# #{backtrace_info}", RSpec.configuration.detail_color
-
end
-
end
-
-
1
def fully_formatted(failure_number, colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
alignment_basis = "#{' ' * @indentation}#{failure_number}) "
-
indentation = ' ' * alignment_basis.length
-
-
"\n#{alignment_basis}#{description_and_detail(colorizer, indentation)}" \
-
"\n#{formatted_message_and_backtrace(colorizer, indentation)}" \
-
"#{extra_detail_formatter.call(failure_number, colorizer, indentation)}"
-
end
-
-
1
def failure_slash_error_line
-
@failure_slash_error_line ||= "Failure/Error: #{read_failed_line.strip}"
-
end
-
-
1
private
-
-
1
def description_and_detail(colorizer, indentation)
-
detail = detail_formatter.call(example, colorizer, indentation)
-
return (description || detail) unless description && detail
-
"#{description}\n#{indentation}#{detail}"
-
end
-
-
1
if String.method_defined?(:encoding)
-
1
def encoding_of(string)
-
string.encoding
-
end
-
-
1
def encoded_string(string)
-
RSpec::Support::EncodedString.new(string, Encoding.default_external)
-
end
-
else # for 1.8.7
-
skipped
# :nocov:
-
skipped
def encoding_of(_string)
-
skipped
end
-
skipped
-
skipped
def encoded_string(string)
-
skipped
RSpec::Support::EncodedString.new(string)
-
skipped
end
-
skipped
# :nocov:
-
end
-
-
1
def exception_class_name
-
name = exception.class.name.to_s
-
name = "(anonymous error class)" if name == ''
-
name
-
end
-
-
1
def failure_lines
-
@failure_lines ||=
-
begin
-
lines = []
-
lines << failure_slash_error_line unless (description == failure_slash_error_line)
-
lines << "#{exception_class_name}:" unless exception_class_name =~ /RSpec/
-
encoded_string(exception.message.to_s).split("\n").each do |line|
-
lines << " #{line}"
-
end
-
lines
-
end
-
end
-
-
1
def add_shared_group_lines(lines, colorizer)
-
return lines if @skip_shared_group_trace
-
-
example.metadata[:shared_group_inclusion_backtrace].each do |frame|
-
lines << colorizer.wrap(frame.description, RSpec.configuration.default_color)
-
end
-
-
lines
-
end
-
-
1
def read_failed_line
-
matching_line = find_failed_line
-
unless matching_line
-
return "Unable to find matching line from backtrace"
-
end
-
-
file_path, line_number = matching_line.match(/(.+?):(\d+)(|:\d+)/)[1..2]
-
-
if File.exist?(file_path)
-
File.readlines(file_path)[line_number.to_i - 1] ||
-
"Unable to find matching line in #{file_path}"
-
else
-
"Unable to find #{file_path} to read failed line"
-
end
-
rescue SecurityError
-
"Unable to read failed line"
-
end
-
-
1
def find_failed_line
-
example_path = example.metadata[:absolute_file_path].downcase
-
exception_backtrace.find do |line|
-
next unless (line_path = line[/(.+?):(\d+)(|:\d+)/, 1])
-
File.expand_path(line_path).downcase == example_path
-
end
-
end
-
-
1
def formatted_message_and_backtrace(colorizer, indentation)
-
lines = colorized_message_lines(colorizer) + colorized_formatted_backtrace(colorizer)
-
-
formatted = ""
-
-
lines.each do |line|
-
formatted << RSpec::Support::EncodedString.new("#{indentation}#{line}\n", encoding_of(formatted))
-
end
-
-
formatted
-
end
-
-
1
def exception_backtrace
-
exception.backtrace || []
-
end
-
-
# @private
-
# Configuring the `ExceptionPresenter` with the right set of options to handle
-
# pending vs failed vs skipped and aggregated (or not) failures is not simple.
-
# This class takes care of building an appropriate `ExceptionPresenter` for the
-
# provided example.
-
1
class Factory
-
1
def build
-
ExceptionPresenter.new(@exception, @example, options)
-
end
-
-
1
private
-
-
1
def initialize(example)
-
@example = example
-
@execution_result = example.execution_result
-
@exception = if @execution_result.status == :pending
-
@execution_result.pending_exception
-
else
-
@execution_result.exception
-
end
-
end
-
-
1
def options
-
with_multiple_error_options_as_needed(@exception, pending_options || {})
-
end
-
-
1
def pending_options
-
if @execution_result.pending_fixed?
-
{
-
:description_formatter => Proc.new { "#{@example.full_description} FIXED" },
-
:message_color => RSpec.configuration.fixed_color,
-
:failure_lines => [
-
"Expected pending '#{@execution_result.pending_message}' to fail. No Error was raised."
-
]
-
}
-
elsif @execution_result.status == :pending
-
{
-
:message_color => RSpec.configuration.pending_color,
-
:detail_formatter => PENDING_DETAIL_FORMATTER
-
}
-
end
-
end
-
-
1
def with_multiple_error_options_as_needed(exception, options)
-
return options unless multiple_exceptions_error?(exception)
-
-
options = options.merge(
-
:failure_lines => [],
-
:extra_detail_formatter => sub_failure_list_formatter(exception, options[:message_color]),
-
:detail_formatter => multiple_exception_summarizer(exception,
-
options[:detail_formatter],
-
options[:message_color])
-
)
-
-
options[:description_formatter] &&= Proc.new {}
-
-
return options unless exception.aggregation_metadata[:hide_backtrace]
-
options[:backtrace_formatter] = EmptyBacktraceFormatter
-
options
-
end
-
-
1
def multiple_exceptions_error?(exception)
-
MultipleExceptionError::InterfaceTag === exception
-
end
-
-
1
def multiple_exception_summarizer(exception, prior_detail_formatter, color)
-
lambda do |example, colorizer, indentation|
-
summary = if exception.aggregation_metadata[:hide_backtrace]
-
# Since the backtrace is hidden, the subfailures will come
-
# immediately after this, and using `:` will read well.
-
"Got #{exception.exception_count_description}:"
-
else
-
# The backtrace comes after this, so using a `:` doesn't make sense
-
# since the failures may be many lines below.
-
"#{exception.summary}."
-
end
-
-
summary = colorizer.wrap(summary, color || RSpec.configuration.failure_color)
-
return summary unless prior_detail_formatter
-
"#{prior_detail_formatter.call(example, colorizer, indentation)}\n#{indentation}#{summary}"
-
end
-
end
-
-
1
def sub_failure_list_formatter(exception, message_color)
-
common_backtrace_truncater = CommonBacktraceTruncater.new(exception)
-
-
lambda do |failure_number, colorizer, indentation|
-
exception.all_exceptions.each_with_index.map do |failure, index|
-
options = with_multiple_error_options_as_needed(
-
failure,
-
:description_formatter => :failure_slash_error_line.to_proc,
-
:indentation => indentation.length,
-
:message_color => message_color || RSpec.configuration.failure_color,
-
:skip_shared_group_trace => true
-
)
-
-
failure = common_backtrace_truncater.with_truncated_backtrace(failure)
-
presenter = ExceptionPresenter.new(failure, @example, options)
-
presenter.fully_formatted("#{failure_number}.#{index + 1}", colorizer)
-
end.join
-
end
-
end
-
-
# @private
-
# Used to prevent a confusing backtrace from showing up from the `aggregate_failures`
-
# block declared for `:aggregate_failures` metadata.
-
1
module EmptyBacktraceFormatter
-
1
def self.format_backtrace(*)
-
[]
-
end
-
end
-
-
# @private
-
1
class CommonBacktraceTruncater
-
1
def initialize(parent)
-
@parent = parent
-
end
-
-
1
def with_truncated_backtrace(child)
-
child_bt = child.backtrace
-
parent_bt = @parent.backtrace
-
return child if child_bt.nil? || child_bt.empty? || parent_bt.nil?
-
-
index_before_first_common_frame = -1.downto(-child_bt.size).find do |index|
-
parent_bt[index] != child_bt[index]
-
end
-
-
return child if index_before_first_common_frame == -1
-
-
child = child.dup
-
child.set_backtrace(child_bt[0..index_before_first_common_frame])
-
child
-
end
-
end
-
end
-
-
# @private
-
1
PENDING_DETAIL_FORMATTER = Proc.new do |example, colorizer|
-
colorizer.wrap("# #{example.execution_result.pending_message}", :detail)
-
end
-
end
-
end
-
-
# Provides a single exception instance that provides access to
-
# multiple sub-exceptions. This is used in situations where a single
-
# individual spec has multiple exceptions, such as one in the `it` block
-
# and one in an `after` block.
-
1
class MultipleExceptionError < StandardError
-
# @private
-
# Used so there is a common module in the ancestor chain of this class
-
# and `RSpec::Expectations::MultipleExpectationsNotMetError`, which allows
-
# code to detect exceptions that are instances of either, without first
-
# checking to see if rspec-expectations is loaded.
-
1
module InterfaceTag
-
# Appends the provided exception to the list.
-
# @param exception [Exception] Exception to append to the list.
-
# @private
-
1
def add(exception)
-
# `PendingExampleFixedError` can be assigned to an example that initially has no
-
# failures, but when the `aggregate_failures` around hook completes, it notifies of
-
# a failure. If we do not ignore `PendingExampleFixedError` it would be surfaced to
-
# the user as part of a multiple exception error, which is undesirable. While it's
-
# pretty weird we handle this here, it's the best solution I've been able to come
-
# up with, and `PendingExampleFixedError` always represents the _lack_ of any exception
-
# so clearly when we are transitioning to a `MultipleExceptionError`, it makes sense to
-
# ignore it.
-
return if Pending::PendingExampleFixedError === exception
-
-
all_exceptions << exception
-
-
if exception.class.name =~ /RSpec/
-
failures << exception
-
else
-
other_errors << exception
-
end
-
end
-
-
# Provides a way to force `ex` to be something that satisfies the multiple
-
# exception error interface. If it already satisfies it, it will be returned;
-
# otherwise it will wrap it in a `MultipleExceptionError`.
-
# @private
-
1
def self.for(ex)
-
return ex if self === ex
-
MultipleExceptionError.new(ex)
-
end
-
end
-
-
1
include InterfaceTag
-
-
# @return [Array<Exception>] The list of failures.
-
1
attr_reader :failures
-
-
# @return [Array<Exception>] The list of other errors.
-
1
attr_reader :other_errors
-
-
# @return [Array<Exception>] The list of failures and other exceptions, combined.
-
1
attr_reader :all_exceptions
-
-
# @return [Hash] Metadata used by RSpec for formatting purposes.
-
1
attr_reader :aggregation_metadata
-
-
# @return [nil] Provided only for interface compatibility with
-
# `RSpec::Expectations::MultipleExpectationsNotMetError`.
-
1
attr_reader :aggregation_block_label
-
-
# @param exceptions [Array<Exception>] The initial list of exceptions.
-
1
def initialize(*exceptions)
-
super()
-
-
@failures = []
-
@other_errors = []
-
@all_exceptions = []
-
@aggregation_metadata = { :hide_backtrace => true }
-
@aggregation_block_label = nil
-
-
exceptions.each { |e| add e }
-
end
-
-
# @return [String] Combines all the exception messages into a single string.
-
# @note RSpec does not actually use this -- instead it formats each exception
-
# individually.
-
1
def message
-
all_exceptions.map(&:message).join("\n\n")
-
end
-
-
# @return [String] A summary of the failure, including the block label and a count of failures.
-
1
def summary
-
"Got #{exception_count_description}"
-
end
-
-
# return [String] A description of the failure/error counts.
-
1
def exception_count_description
-
failure_count = Formatters::Helpers.pluralize(failures.size, "failure")
-
return failure_count if other_errors.empty?
-
error_count = Formatters::Helpers.pluralize(other_errors.size, "other error")
-
"#{failure_count} and #{error_count}"
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "shell_escape"
-
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# Formatters helpers.
-
1
module Helpers
-
# @private
-
1
SUB_SECOND_PRECISION = 5
-
-
# @private
-
1
DEFAULT_PRECISION = 2
-
-
# @api private
-
#
-
# Formats seconds into a human-readable string.
-
#
-
# @param duration [Float, Fixnum] in seconds
-
# @return [String] human-readable time
-
#
-
# @example
-
# format_duration(1) #=> "1 minute 1 second"
-
# format_duration(135.14) #=> "2 minutes 15.14 seconds"
-
1
def self.format_duration(duration)
-
precision = case
-
when duration < 1 then SUB_SECOND_PRECISION
-
when duration < 120 then DEFAULT_PRECISION
-
when duration < 300 then 1
-
else 0
-
end
-
-
if duration > 60
-
minutes = (duration.to_i / 60).to_i
-
seconds = duration - minutes * 60
-
-
"#{pluralize(minutes, 'minute')} #{pluralize(format_seconds(seconds, precision), 'second')}"
-
else
-
pluralize(format_seconds(duration, precision), 'second')
-
end
-
end
-
-
# @api private
-
#
-
# Formats seconds to have 5 digits of precision with trailing zeros
-
# removed if the number is less than 1 or with 2 digits of precision if
-
# the number is greater than zero.
-
#
-
# @param float [Float]
-
# @return [String] formatted float
-
#
-
# @example
-
# format_seconds(0.000006) #=> "0.00001"
-
# format_seconds(0.020000) #=> "0.02"
-
# format_seconds(1.00000000001) #=> "1"
-
#
-
# The precision used is set in {Helpers::SUB_SECOND_PRECISION} and
-
# {Helpers::DEFAULT_PRECISION}.
-
#
-
# @see #strip_trailing_zeroes
-
1
def self.format_seconds(float, precision=nil)
-
precision ||= (float < 1) ? SUB_SECOND_PRECISION : DEFAULT_PRECISION
-
formatted = "%.#{precision}f" % float
-
strip_trailing_zeroes(formatted)
-
end
-
-
# @api private
-
#
-
# Remove trailing zeros from a string.
-
#
-
# Only remove trailing zeros after a decimal place.
-
# see: http://rubular.com/r/ojtTydOgpn
-
#
-
# @param string [String] string with trailing zeros
-
# @return [String] string with trailing zeros removed
-
1
def self.strip_trailing_zeroes(string)
-
string.sub(/(?:(\..*[^0])0+|\.0+)$/, '\1')
-
end
-
1
private_class_method :strip_trailing_zeroes
-
-
# @api private
-
#
-
# Pluralize a word based on a count.
-
#
-
# @param count [Fixnum] number of objects
-
# @param string [String] word to be pluralized
-
# @return [String] pluralized word
-
1
def self.pluralize(count, string)
-
"#{count} #{string}#{'s' unless count.to_f == 1}"
-
end
-
-
# @api private
-
# Given a list of example ids, organizes them into a compact, ordered list.
-
1
def self.organize_ids(ids)
-
grouped = ids.inject(Hash.new { |h, k| h[k] = [] }) do |hash, id|
-
file, id = id.split(Configuration::ON_SQUARE_BRACKETS)
-
hash[file] << id
-
hash
-
end
-
-
grouped.sort_by(&:first).map do |file, grouped_ids|
-
grouped_ids = grouped_ids.sort_by { |id| id.split(':').map(&:to_i) }
-
id = Metadata.id_from(:rerun_file_path => file, :scoped_id => grouped_ids.join(','))
-
ShellEscape.conditionally_quote(id)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Provides `before`, `after` and `around` hooks as a means of
-
# supporting common setup and teardown. This module is extended
-
# onto {ExampleGroup}, making the methods available from any `describe`
-
# or `context` block and included in {Configuration}, making them
-
# available off of the configuration object to define global setup
-
# or teardown logic.
-
1
module Hooks
-
# @api public
-
#
-
# @overload before(&block)
-
# @overload before(scope, &block)
-
# @param scope [Symbol] `:example`, `:context`, or `:suite`
-
# (defaults to `:example`)
-
# @overload before(scope, conditions, &block)
-
# @param scope [Symbol] `:example`, `:context`, or `:suite`
-
# (defaults to `:example`)
-
# @param conditions [Hash]
-
# constrains this hook to examples matching these conditions e.g.
-
# `before(:example, :ui => true) { ... }` will only run with examples
-
# or groups declared with `:ui => true`.
-
# @overload before(conditions, &block)
-
# @param conditions [Hash]
-
# constrains this hook to examples matching these conditions e.g.
-
# `before(:example, :ui => true) { ... }` will only run with examples
-
# or groups declared with `:ui => true`.
-
#
-
# @see #after
-
# @see #around
-
# @see ExampleGroup
-
# @see SharedContext
-
# @see SharedExampleGroup
-
# @see Configuration
-
#
-
# Declare a block of code to be run before each example (using `:example`)
-
# or once before any example (using `:context`). These are usually
-
# declared directly in the {ExampleGroup} to which they apply, but they
-
# can also be shared across multiple groups.
-
#
-
# You can also use `before(:suite)` to run a block of code before any
-
# example groups are run. This should be declared in {RSpec.configure}.
-
#
-
# Instance variables declared in `before(:example)` or `before(:context)`
-
# are accessible within each example.
-
#
-
# ### Order
-
#
-
# `before` hooks are stored in three scopes, which are run in order:
-
# `:suite`, `:context`, and `:example`. They can also be declared in
-
# several different places: `RSpec.configure`, a parent group, the current
-
# group. They are run in the following order:
-
#
-
# before(:suite) # Declared in RSpec.configure.
-
# before(:context) # Declared in RSpec.configure.
-
# before(:context) # Declared in a parent group.
-
# before(:context) # Declared in the current group.
-
# before(:example) # Declared in RSpec.configure.
-
# before(:example) # Declared in a parent group.
-
# before(:example) # Declared in the current group.
-
#
-
# If more than one `before` is declared within any one scope, they are run
-
# in the order in which they are declared.
-
#
-
# ### Conditions
-
#
-
# When you add a conditions hash to `before(:example)` or
-
# `before(:context)`, RSpec will only apply that hook to groups or
-
# examples that match the conditions. e.g.
-
#
-
# RSpec.configure do |config|
-
# config.before(:example, :authorized => true) do
-
# log_in_as :authorized_user
-
# end
-
# end
-
#
-
# describe Something, :authorized => true do
-
# # The before hook will run in before each example in this group.
-
# end
-
#
-
# describe SomethingElse do
-
# it "does something", :authorized => true do
-
# # The before hook will run before this example.
-
# end
-
#
-
# it "does something else" do
-
# # The hook will not run before this example.
-
# end
-
# end
-
#
-
# Note that filtered config `:context` hooks can still be applied
-
# to individual examples that have matching metadata. Just like
-
# Ruby's object model is that every object has a singleton class
-
# which has only a single instance, RSpec's model is that every
-
# example has a singleton example group containing just the one
-
# example.
-
#
-
# ### Warning: `before(:suite, :with => :conditions)`
-
#
-
# The conditions hash is used to match against specific examples. Since
-
# `before(:suite)` is not run in relation to any specific example or
-
# group, conditions passed along with `:suite` are effectively ignored.
-
#
-
# ### Exceptions
-
#
-
# When an exception is raised in a `before` block, RSpec skips any
-
# subsequent `before` blocks and the example, but runs all of the
-
# `after(:example)` and `after(:context)` hooks.
-
#
-
# ### Warning: implicit before blocks
-
#
-
# `before` hooks can also be declared in shared contexts which get
-
# included implicitly either by you or by extension libraries. Since
-
# RSpec runs these in the order in which they are declared within each
-
# scope, load order matters, and can lead to confusing results when one
-
# before block depends on state that is prepared in another before block
-
# that gets run later.
-
#
-
# ### Warning: `before(:context)`
-
#
-
# It is very tempting to use `before(:context)` to speed things up, but we
-
# recommend that you avoid this as there are a number of gotchas, as well
-
# as things that simply don't work.
-
#
-
# #### Context
-
#
-
# `before(:context)` is run in an example that is generated to provide
-
# group context for the block.
-
#
-
# #### Instance variables
-
#
-
# Instance variables declared in `before(:context)` are shared across all
-
# the examples in the group. This means that each example can change the
-
# state of a shared object, resulting in an ordering dependency that can
-
# make it difficult to reason about failures.
-
#
-
# #### Unsupported RSpec constructs
-
#
-
# RSpec has several constructs that reset state between each example
-
# automatically. These are not intended for use from within
-
# `before(:context)`:
-
#
-
# * `let` declarations
-
# * `subject` declarations
-
# * Any mocking, stubbing or test double declaration
-
#
-
# ### other frameworks
-
#
-
# Mock object frameworks and database transaction managers (like
-
# ActiveRecord) are typically designed around the idea of setting up
-
# before an example, running that one example, and then tearing down. This
-
# means that mocks and stubs can (sometimes) be declared in
-
# `before(:context)`, but get torn down before the first real example is
-
# ever run.
-
#
-
# You _can_ create database-backed model objects in a `before(:context)`
-
# in rspec-rails, but it will not be wrapped in a transaction for you, so
-
# you are on your own to clean up in an `after(:context)` block.
-
#
-
# @example before(:example) declared in an {ExampleGroup}
-
#
-
# describe Thing do
-
# before(:example) do
-
# @thing = Thing.new
-
# end
-
#
-
# it "does something" do
-
# # Here you can access @thing.
-
# end
-
# end
-
#
-
# @example before(:context) declared in an {ExampleGroup}
-
#
-
# describe Parser do
-
# before(:context) do
-
# File.open(file_to_parse, 'w') do |f|
-
# f.write <<-CONTENT
-
# stuff in the file
-
# CONTENT
-
# end
-
# end
-
#
-
# it "parses the file" do
-
# Parser.parse(file_to_parse)
-
# end
-
#
-
# after(:context) do
-
# File.delete(file_to_parse)
-
# end
-
# end
-
#
-
# @note The `:example` and `:context` scopes are also available as
-
# `:each` and `:all`, respectively. Use whichever you prefer.
-
# @note The `:scope` alias is only supported for hooks registered on
-
# `RSpec.configuration` since they exist independently of any
-
# example or example group.
-
1
def before(*args, &block)
-
hooks.register :append, :before, *args, &block
-
end
-
-
1
alias_method :append_before, :before
-
-
# Adds `block` to the front of the list of `before` blocks in the same
-
# scope (`:example`, `:context`, or `:suite`).
-
#
-
# See {#before} for scoping semantics.
-
1
def prepend_before(*args, &block)
-
hooks.register :prepend, :before, *args, &block
-
end
-
-
# @api public
-
# @overload after(&block)
-
# @overload after(scope, &block)
-
# @param scope [Symbol] `:example`, `:context`, or `:suite` (defaults to
-
# `:example`)
-
# @overload after(scope, conditions, &block)
-
# @param scope [Symbol] `:example`, `:context`, or `:suite` (defaults to
-
# `:example`)
-
# @param conditions [Hash]
-
# constrains this hook to examples matching these conditions e.g.
-
# `after(:example, :ui => true) { ... }` will only run with examples
-
# or groups declared with `:ui => true`.
-
# @overload after(conditions, &block)
-
# @param conditions [Hash]
-
# constrains this hook to examples matching these conditions e.g.
-
# `after(:example, :ui => true) { ... }` will only run with examples
-
# or groups declared with `:ui => true`.
-
#
-
# @see #before
-
# @see #around
-
# @see ExampleGroup
-
# @see SharedContext
-
# @see SharedExampleGroup
-
# @see Configuration
-
#
-
# Declare a block of code to be run after each example (using `:example`)
-
# or once after all examples n the context (using `:context`). See
-
# {#before} for more information about ordering.
-
#
-
# ### Exceptions
-
#
-
# `after` hooks are guaranteed to run even when there are exceptions in
-
# `before` hooks or examples. When an exception is raised in an after
-
# block, the exception is captured for later reporting, and subsequent
-
# `after` blocks are run.
-
#
-
# ### Order
-
#
-
# `after` hooks are stored in three scopes, which are run in order:
-
# `:example`, `:context`, and `:suite`. They can also be declared in
-
# several different places: `RSpec.configure`, a parent group, the current
-
# group. They are run in the following order:
-
#
-
# after(:example) # Declared in the current group.
-
# after(:example) # Declared in a parent group.
-
# after(:example) # Declared in RSpec.configure.
-
# after(:context) # Declared in the current group.
-
# after(:context) # Declared in a parent group.
-
# after(:context) # Declared in RSpec.configure.
-
# after(:suite) # Declared in RSpec.configure.
-
#
-
# This is the reverse of the order in which `before` hooks are run.
-
# Similarly, if more than one `after` is declared within any one scope,
-
# they are run in reverse order of that in which they are declared.
-
#
-
# @note The `:example` and `:context` scopes are also available as
-
# `:each` and `:all`, respectively. Use whichever you prefer.
-
# @note The `:scope` alias is only supported for hooks registered on
-
# `RSpec.configuration` since they exist independently of any
-
# example or example group.
-
1
def after(*args, &block)
-
hooks.register :prepend, :after, *args, &block
-
end
-
-
1
alias_method :prepend_after, :after
-
-
# Adds `block` to the back of the list of `after` blocks in the same
-
# scope (`:example`, `:context`, or `:suite`).
-
#
-
# See {#after} for scoping semantics.
-
1
def append_after(*args, &block)
-
hooks.register :append, :after, *args, &block
-
end
-
-
# @api public
-
# @overload around(&block)
-
# @overload around(scope, &block)
-
# @param scope [Symbol] `:example` (defaults to `:example`)
-
# present for syntax parity with `before` and `after`, but
-
# `:example`/`:each` is the only supported value.
-
# @overload around(scope, conditions, &block)
-
# @param scope [Symbol] `:example` (defaults to `:example`)
-
# present for syntax parity with `before` and `after`, but
-
# `:example`/`:each` is the only supported value.
-
# @param conditions [Hash] constrains this hook to examples matching
-
# these conditions e.g. `around(:example, :ui => true) { ... }` will
-
# only run with examples or groups declared with `:ui => true`.
-
# @overload around(conditions, &block)
-
# @param conditions [Hash] constrains this hook to examples matching
-
# these conditions e.g. `around(:example, :ui => true) { ... }` will
-
# only run with examples or groups declared with `:ui => true`.
-
#
-
# @yield [Example] the example to run
-
#
-
# @note the syntax of `around` is similar to that of `before` and `after`
-
# but the semantics are quite different. `before` and `after` hooks are
-
# run in the context of of the examples with which they are associated,
-
# whereas `around` hooks are actually responsible for running the
-
# examples. Consequently, `around` hooks do not have direct access to
-
# resources that are made available within the examples and their
-
# associated `before` and `after` hooks.
-
#
-
# @note `:example`/`:each` is the only supported scope.
-
#
-
# Declare a block of code, parts of which will be run before and parts
-
# after the example. It is your responsibility to run the example:
-
#
-
# around(:example) do |ex|
-
# # Do some stuff before.
-
# ex.run
-
# # Do some stuff after.
-
# end
-
#
-
# The yielded example aliases `run` with `call`, which lets you treat it
-
# like a `Proc`. This is especially handy when working with libaries
-
# that manage their own setup and teardown using a block or proc syntax,
-
# e.g.
-
#
-
# around(:example) {|ex| Database.transaction(&ex)}
-
# around(:example) {|ex| FakeFS(&ex)}
-
#
-
1
def around(*args, &block)
-
1
hooks.register :prepend, :around, *args, &block
-
end
-
-
# @private
-
# Holds the various registered hooks.
-
1
def hooks
-
@hooks ||= HookCollections.new(self, FilterableItemRepository::UpdateOptimized)
-
end
-
-
1
private
-
-
# @private
-
1
class Hook
-
1
attr_reader :block, :options
-
-
1
def initialize(block, options)
-
1
@block = block
-
1
@options = options
-
end
-
end
-
-
# @private
-
1
class BeforeHook < Hook
-
1
def run(example)
-
example.instance_exec(example, &block)
-
end
-
end
-
-
# @private
-
1
class AfterHook < Hook
-
1
def run(example)
-
example.instance_exec(example, &block)
-
rescue Exception => ex
-
example.set_exception(ex)
-
end
-
end
-
-
# @private
-
1
class AfterContextHook < Hook
-
1
def run(example)
-
example.instance_exec(example, &block)
-
rescue Exception => e
-
# TODO: Come up with a better solution for this.
-
RSpec.configuration.reporter.message <<-EOS
-
-
An error occurred in an `after(:context)` hook.
-
#{e.class}: #{e.message}
-
occurred at #{e.backtrace.first}
-
-
EOS
-
end
-
end
-
-
# @private
-
1
class AroundHook < Hook
-
1
def execute_with(example, procsy)
-
example.instance_exec(procsy, &block)
-
return if procsy.executed?
-
Pending.mark_skipped!(example,
-
"#{hook_description} did not execute the example")
-
end
-
-
1
if Proc.method_defined?(:source_location)
-
1
def hook_description
-
"around hook at #{Metadata.relative_path(block.source_location.join(':'))}"
-
end
-
else # for 1.8.7
-
skipped
# :nocov:
-
skipped
def hook_description
-
skipped
"around hook"
-
skipped
end
-
skipped
# :nocov:
-
end
-
end
-
-
# @private
-
#
-
# This provides the primary API used by other parts of rspec-core. By hiding all
-
# implementation details behind this facade, it's allowed us to heavily optimize
-
# this, so that, for example, hook collection objects are only instantiated when
-
# a hook is added. This allows us to avoid many object allocations for the common
-
# case of a group having no hooks.
-
#
-
# This is only possible because this interface provides a "tell, don't ask"-style
-
# API, so that callers _tell_ this class what to do with the hooks, rather than
-
# asking this class for a list of hooks, and then doing something with them.
-
1
class HookCollections
-
1
def initialize(owner, filterable_item_repo_class)
-
1
@owner = owner
-
1
@filterable_item_repo_class = filterable_item_repo_class
-
1
@before_example_hooks = nil
-
1
@after_example_hooks = nil
-
1
@before_context_hooks = nil
-
1
@after_context_hooks = nil
-
1
@around_example_hooks = nil
-
end
-
-
1
def register_globals(host, globals)
-
parent_groups = host.parent_groups
-
-
process(host, parent_groups, globals, :before, :example, &:options)
-
process(host, parent_groups, globals, :after, :example, &:options)
-
process(host, parent_groups, globals, :around, :example, &:options)
-
-
process(host, parent_groups, globals, :before, :context, &:options)
-
process(host, parent_groups, globals, :after, :context, &:options)
-
end
-
-
1
def register_global_singleton_context_hooks(example, globals)
-
parent_groups = example.example_group.parent_groups
-
-
process(example, parent_groups, globals, :before, :context) { {} }
-
process(example, parent_groups, globals, :after, :context) { {} }
-
end
-
-
1
def register(prepend_or_append, position, *args, &block)
-
1
scope, options = scope_and_options_from(*args)
-
-
1
if scope == :suite
-
# TODO: consider making this an error in RSpec 4. For SemVer reasons,
-
# we are only warning in RSpec 3.
-
RSpec.warn_with "WARNING: `#{position}(:suite)` hooks are only supported on " \
-
"the RSpec configuration object. This " \
-
"`#{position}(:suite)` hook, registered on an example " \
-
"group, will be ignored."
-
return
-
end
-
-
1
hook = HOOK_TYPES[position][scope].new(block, options)
-
1
ensure_hooks_initialized_for(position, scope).__send__(prepend_or_append, hook, options)
-
end
-
-
# @private
-
#
-
# Runs all of the blocks stored with the hook in the context of the
-
# example. If no example is provided, just calls the hook directly.
-
1
def run(position, scope, example_or_group)
-
return if RSpec.configuration.dry_run?
-
-
if scope == :context
-
run_owned_hooks_for(position, :context, example_or_group)
-
else
-
case position
-
when :before then run_example_hooks_for(example_or_group, :before, :reverse_each)
-
when :after then run_example_hooks_for(example_or_group, :after, :each)
-
when :around then run_around_example_hooks_for(example_or_group) { yield }
-
end
-
end
-
end
-
-
1
SCOPES = [:example, :context]
-
-
1
SCOPE_ALIASES = { :each => :example, :all => :context }
-
-
1
HOOK_TYPES = {
-
:before => Hash.new { BeforeHook },
-
:after => Hash.new { AfterHook },
-
1
:around => Hash.new { AroundHook }
-
}
-
-
1
HOOK_TYPES[:after][:context] = AfterContextHook
-
-
1
protected
-
-
1
EMPTY_HOOK_ARRAY = [].freeze
-
-
1
def matching_hooks_for(position, scope, example_or_group)
-
repository = hooks_for(position, scope) { return EMPTY_HOOK_ARRAY }
-
-
# It would be nice to not have to switch on type here, but
-
# we don't want to define `ExampleGroup#metadata` because then
-
# `metadata` from within an individual example would return the
-
# group's metadata but the user would probably expect it to be
-
# the example's metadata.
-
metadata = case example_or_group
-
when ExampleGroup then example_or_group.class.metadata
-
else example_or_group.metadata
-
end
-
-
repository.items_for(metadata)
-
end
-
-
1
def all_hooks_for(position, scope)
-
hooks_for(position, scope) { return EMPTY_HOOK_ARRAY }.items_and_filters.map(&:first)
-
end
-
-
1
def run_owned_hooks_for(position, scope, example_or_group)
-
matching_hooks_for(position, scope, example_or_group).each do |hook|
-
hook.run(example_or_group)
-
end
-
end
-
-
1
def processable_hooks_for(position, scope, host)
-
if scope == :example
-
all_hooks_for(position, scope)
-
else
-
matching_hooks_for(position, scope, host)
-
end
-
end
-
-
1
private
-
-
1
def hooks_for(position, scope)
-
if position == :before
-
scope == :example ? @before_example_hooks : @before_context_hooks
-
elsif position == :after
-
scope == :example ? @after_example_hooks : @after_context_hooks
-
else # around
-
@around_example_hooks
-
end || yield
-
end
-
-
1
def ensure_hooks_initialized_for(position, scope)
-
1
if position == :before
-
if scope == :example
-
@before_example_hooks ||= @filterable_item_repo_class.new(:all?)
-
else
-
@before_context_hooks ||= @filterable_item_repo_class.new(:all?)
-
end
-
1
elsif position == :after
-
if scope == :example
-
@after_example_hooks ||= @filterable_item_repo_class.new(:all?)
-
else
-
@after_context_hooks ||= @filterable_item_repo_class.new(:all?)
-
end
-
else # around
-
1
@around_example_hooks ||= @filterable_item_repo_class.new(:all?)
-
end
-
end
-
-
1
def process(host, parent_groups, globals, position, scope)
-
hooks_to_process = globals.processable_hooks_for(position, scope, host)
-
return if hooks_to_process.empty?
-
-
hooks_to_process -= FlatMap.flat_map(parent_groups) do |group|
-
group.hooks.all_hooks_for(position, scope)
-
end
-
return if hooks_to_process.empty?
-
-
repository = ensure_hooks_initialized_for(position, scope)
-
hooks_to_process.each { |hook| repository.append hook, (yield hook) }
-
end
-
-
1
def scope_and_options_from(*args)
-
1
return :suite if args.first == :suite
-
1
scope = extract_scope_from(args)
-
1
meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
-
1
return scope, meta
-
end
-
-
1
def extract_scope_from(args)
-
1
if known_scope?(args.first)
-
1
normalized_scope_for(args.shift)
-
elsif args.any? { |a| a.is_a?(Symbol) }
-
error_message = "You must explicitly give a scope " \
-
"(#{SCOPES.join(", ")}) or scope alias " \
-
"(#{SCOPE_ALIASES.keys.join(", ")}) when using symbols as " \
-
"metadata for a hook."
-
raise ArgumentError.new error_message
-
else
-
:example
-
end
-
end
-
-
1
def known_scope?(scope)
-
1
SCOPES.include?(scope) || SCOPE_ALIASES.keys.include?(scope)
-
end
-
-
1
def normalized_scope_for(scope)
-
1
SCOPE_ALIASES[scope] || scope
-
end
-
-
1
def run_example_hooks_for(example, position, each_method)
-
owner_parent_groups.__send__(each_method) do |group|
-
group.hooks.run_owned_hooks_for(position, :example, example)
-
end
-
end
-
-
1
def run_around_example_hooks_for(example)
-
hooks = FlatMap.flat_map(owner_parent_groups) do |group|
-
group.hooks.matching_hooks_for(:around, :example, example)
-
end
-
-
return yield if hooks.empty? # exit early to avoid the extra allocation cost of `Example::Procsy`
-
-
initial_procsy = Example::Procsy.new(example) { yield }
-
hooks.inject(initial_procsy) do |procsy, around_hook|
-
procsy.wrap { around_hook.execute_with(example, procsy) }
-
end.call
-
end
-
-
1
if respond_to?(:singleton_class) && singleton_class.ancestors.include?(singleton_class)
-
1
def owner_parent_groups
-
@owner.parent_groups
-
end
-
else # Ruby < 2.1 (see https://bugs.ruby-lang.org/issues/8035)
-
skipped
# :nocov:
-
skipped
def owner_parent_groups
-
skipped
@owner_parent_groups ||= [@owner] + @owner.parent_groups
-
skipped
end
-
skipped
# :nocov:
-
end
-
end
-
end
-
end
-
end
-
1
require 'rspec/core/reentrant_mutex'
-
-
1
module RSpec
-
1
module Core
-
# This module is included in {ExampleGroup}, making the methods
-
# available to be called from within example blocks.
-
#
-
# @see ClassMethods
-
1
module MemoizedHelpers
-
# @note `subject` was contributed by Joe Ferris to support the one-liner
-
# syntax embraced by shoulda matchers:
-
#
-
# describe Widget do
-
# it { is_expected.to validate_presence_of(:name) }
-
# # or
-
# it { should validate_presence_of(:name) }
-
# end
-
#
-
# While the examples below demonstrate how to use `subject`
-
# explicitly in examples, we recommend that you define a method with
-
# an intention revealing name instead.
-
#
-
# @example
-
#
-
# # Explicit declaration of subject.
-
# describe Person do
-
# subject { Person.new(:birthdate => 19.years.ago) }
-
# it "should be eligible to vote" do
-
# subject.should be_eligible_to_vote
-
# # ^ ^ explicit reference to subject not recommended
-
# end
-
# end
-
#
-
# # Implicit subject => { Person.new }.
-
# describe Person do
-
# it "should be eligible to vote" do
-
# subject.should be_eligible_to_vote
-
# # ^ ^ explicit reference to subject not recommended
-
# end
-
# end
-
#
-
# # One-liner syntax - expectation is set on the subject.
-
# describe Person do
-
# it { is_expected.to be_eligible_to_vote }
-
# # or
-
# it { should be_eligible_to_vote }
-
# end
-
#
-
# @note Because `subject` is designed to create state that is reset
-
# between each example, and `before(:context)` is designed to setup
-
# state that is shared across _all_ examples in an example group,
-
# `subject` is _not_ intended to be used in a `before(:context)` hook.
-
#
-
# @see #should
-
# @see #should_not
-
# @see #is_expected
-
1
def subject
-
__memoized.fetch_or_store(:subject) do
-
described = described_class || self.class.metadata.fetch(:description_args).first
-
Class === described ? described.new : described
-
end
-
end
-
-
# When `should` is called with no explicit receiver, the call is
-
# delegated to the object returned by `subject`. Combined with an
-
# implicit subject this supports very concise expressions.
-
#
-
# @example
-
#
-
# describe Person do
-
# it { should be_eligible_to_vote }
-
# end
-
#
-
# @see #subject
-
# @see #is_expected
-
#
-
# @note This only works if you are using rspec-expectations.
-
# @note If you are using RSpec's newer expect-based syntax you may
-
# want to use `is_expected.to` instead of `should`.
-
1
def should(matcher=nil, message=nil)
-
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(subject, matcher, message)
-
end
-
-
# Just like `should`, `should_not` delegates to the subject (implicit or
-
# explicit) of the example group.
-
#
-
# @example
-
#
-
# describe Person do
-
# it { should_not be_eligible_to_vote }
-
# end
-
#
-
# @see #subject
-
# @see #is_expected
-
#
-
# @note This only works if you are using rspec-expectations.
-
# @note If you are using RSpec's newer expect-based syntax you may
-
# want to use `is_expected.to_not` instead of `should_not`.
-
1
def should_not(matcher=nil, message=nil)
-
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(subject, matcher, message)
-
end
-
-
# Wraps the `subject` in `expect` to make it the target of an expectation.
-
# Designed to read nicely for one-liners.
-
#
-
# @example
-
#
-
# describe [1, 2, 3] do
-
# it { is_expected.to be_an Array }
-
# it { is_expected.not_to include 4 }
-
# end
-
#
-
# @see #subject
-
# @see #should
-
# @see #should_not
-
#
-
# @note This only works if you are using rspec-expectations.
-
1
def is_expected
-
expect(subject)
-
end
-
-
# @private
-
# should just be placed in private section,
-
# but Ruby issues warnings on private attributes.
-
# and expanding it to the equivalent method upsets Rubocop,
-
# b/c it should obviously be a reader
-
1
attr_reader :__memoized
-
1
private :__memoized
-
-
1
private
-
-
# @private
-
1
def initialize(*)
-
__init_memoized
-
super
-
end
-
-
# @private
-
1
def __init_memoized
-
@__memoized = if RSpec.configuration.threadsafe?
-
ThreadsafeMemoized.new
-
else
-
NonThreadSafeMemoized.new
-
end
-
end
-
-
# @private
-
1
class ThreadsafeMemoized
-
1
def initialize
-
@memoized = {}
-
@mutex = ReentrantMutex.new
-
end
-
-
1
def fetch_or_store(key)
-
@memoized.fetch(key) do # only first access pays for synchronization
-
@mutex.synchronize do
-
@memoized.fetch(key) { @memoized[key] = yield }
-
end
-
end
-
end
-
end
-
-
# @private
-
1
class NonThreadSafeMemoized
-
1
def initialize
-
@memoized = {}
-
end
-
-
1
def fetch_or_store(key)
-
@memoized.fetch(key) { @memoized[key] = yield }
-
end
-
end
-
-
# Used internally to customize the behavior of the
-
# memoized hash when used in a `before(:context)` hook.
-
#
-
# @private
-
1
class ContextHookMemoized
-
1
def self.isolate_for_context_hook(example_group_instance)
-
exploding_memoized = self
-
-
example_group_instance.instance_exec do
-
@__memoized = exploding_memoized
-
-
begin
-
yield
-
ensure
-
# This is doing a reset instead of just isolating for context hook.
-
# Really, this should set the old @__memoized back into place.
-
#
-
# Caller is the before and after context hooks
-
# which are both called from self.run
-
# I didn't look at why it made tests fail, maybe an object was getting reused in RSpec tests,
-
# if so, then that probably already works, and its the tests that are wrong.
-
__init_memoized
-
end
-
end
-
end
-
-
1
def self.fetch_or_store(key, &_block)
-
description = if key == :subject
-
"subject"
-
else
-
"let declaration `#{key}`"
-
end
-
-
raise <<-EOS
-
#{description} accessed in #{article} #{hook_expression} hook at:
-
#{CallerFilter.first_non_rspec_line}
-
-
`let` and `subject` declarations are not intended to be called
-
in #{article} #{hook_expression} hook, as they exist to define state that
-
is reset between each example, while #{hook_expression} exists to
-
#{hook_intention}.
-
EOS
-
end
-
-
# @private
-
1
class Before < self
-
1
def self.hook_expression
-
"`before(:context)`"
-
end
-
-
1
def self.article
-
"a"
-
end
-
-
1
def self.hook_intention
-
"define state that is shared across examples in an example group"
-
end
-
end
-
-
# @private
-
1
class After < self
-
1
def self.hook_expression
-
"`after(:context)`"
-
end
-
-
1
def self.article
-
"an"
-
end
-
-
1
def self.hook_intention
-
"cleanup state that is shared across examples in an example group"
-
end
-
end
-
end
-
-
# This module is extended onto {ExampleGroup}, making the methods
-
# available to be called from within example group blocks.
-
# You can think of them as being analagous to class macros.
-
1
module ClassMethods
-
# Generates a method whose return value is memoized after the first
-
# call. Useful for reducing duplication between examples that assign
-
# values to the same local variable.
-
#
-
# @note `let` _can_ enhance readability when used sparingly (1,2, or
-
# maybe 3 declarations) in any given example group, but that can
-
# quickly degrade with overuse. YMMV.
-
#
-
# @note `let` can be configured to be threadsafe or not.
-
# If it is threadsafe, it will take longer to access the value.
-
# If it is not threadsafe, it may behave in surprising ways in examples
-
# that spawn separate threads. Specify this on `RSpec.configure`
-
#
-
# @note Because `let` is designed to create state that is reset between
-
# each example, and `before(:context)` is designed to setup state that
-
# is shared across _all_ examples in an example group, `let` is _not_
-
# intended to be used in a `before(:context)` hook.
-
#
-
# @example
-
#
-
# describe Thing do
-
# let(:thing) { Thing.new }
-
#
-
# it "does something" do
-
# # First invocation, executes block, memoizes and returns result.
-
# thing.do_something
-
#
-
# # Second invocation, returns the memoized value.
-
# thing.should be_something
-
# end
-
# end
-
1
def let(name, &block)
-
# We have to pass the block directly to `define_method` to
-
# allow it to use method constructs like `super` and `return`.
-
raise "#let or #subject called without a block" if block.nil?
-
MemoizedHelpers.module_for(self).__send__(:define_method, name, &block)
-
-
# Apply the memoization. The method has been defined in an ancestor
-
# module so we can use `super` here to get the value.
-
if block.arity == 1
-
define_method(name) { __memoized.fetch_or_store(name) { super(RSpec.current_example, &nil) } }
-
else
-
define_method(name) { __memoized.fetch_or_store(name) { super(&nil) } }
-
end
-
end
-
-
# Just like `let`, except the block is invoked by an implicit `before`
-
# hook. This serves a dual purpose of setting up state and providing a
-
# memoized reference to that state.
-
#
-
# @example
-
#
-
# class Thing
-
# def self.count
-
# @count ||= 0
-
# end
-
#
-
# def self.count=(val)
-
# @count += val
-
# end
-
#
-
# def self.reset_count
-
# @count = 0
-
# end
-
#
-
# def initialize
-
# self.class.count += 1
-
# end
-
# end
-
#
-
# describe Thing do
-
# after(:example) { Thing.reset_count }
-
#
-
# context "using let" do
-
# let(:thing) { Thing.new }
-
#
-
# it "is not invoked implicitly" do
-
# Thing.count.should eq(0)
-
# end
-
#
-
# it "can be invoked explicitly" do
-
# thing
-
# Thing.count.should eq(1)
-
# end
-
# end
-
#
-
# context "using let!" do
-
# let!(:thing) { Thing.new }
-
#
-
# it "is invoked implicitly" do
-
# Thing.count.should eq(1)
-
# end
-
#
-
# it "returns memoized version on first invocation" do
-
# thing
-
# Thing.count.should eq(1)
-
# end
-
# end
-
# end
-
1
def let!(name, &block)
-
let(name, &block)
-
before { __send__(name) }
-
end
-
-
# Declares a `subject` for an example group which can then be wrapped
-
# with `expect` using `is_expected` to make it the target of an
-
# expectation in a concise, one-line example.
-
#
-
# Given a `name`, defines a method with that name which returns the
-
# `subject`. This lets you declare the subject once and access it
-
# implicitly in one-liners and explicitly using an intention revealing
-
# name.
-
#
-
# When given a `name`, calling `super` in the block is not supported.
-
#
-
# @note `subject` can be configured to be threadsafe or not.
-
# If it is threadsafe, it will take longer to access the value.
-
# If it is not threadsafe, it may behave in surprising ways in examples
-
# that spawn separate threads. Specify this on `RSpec.configure`
-
#
-
# @param name [String,Symbol] used to define an accessor with an
-
# intention revealing name
-
# @param block defines the value to be returned by `subject` in examples
-
#
-
# @example
-
#
-
# describe CheckingAccount, "with $50" do
-
# subject { CheckingAccount.new(Money.new(50, :USD)) }
-
# it { is_expected.to have_a_balance_of(Money.new(50, :USD)) }
-
# it { is_expected.not_to be_overdrawn }
-
# end
-
#
-
# describe CheckingAccount, "with a non-zero starting balance" do
-
# subject(:account) { CheckingAccount.new(Money.new(50, :USD)) }
-
# it { is_expected.not_to be_overdrawn }
-
# it "has a balance equal to the starting balance" do
-
# account.balance.should eq(Money.new(50, :USD))
-
# end
-
# end
-
#
-
# @see MemoizedHelpers#should
-
# @see MemoizedHelpers#should_not
-
# @see MemoizedHelpers#is_expected
-
1
def subject(name=nil, &block)
-
if name
-
let(name, &block)
-
alias_method :subject, name
-
-
self::NamedSubjectPreventSuper.__send__(:define_method, name) do
-
raise NotImplementedError, "`super` in named subjects is not supported"
-
end
-
else
-
let(:subject, &block)
-
end
-
end
-
-
# Just like `subject`, except the block is invoked by an implicit
-
# `before` hook. This serves a dual purpose of setting up state and
-
# providing a memoized reference to that state.
-
#
-
# @example
-
#
-
# class Thing
-
# def self.count
-
# @count ||= 0
-
# end
-
#
-
# def self.count=(val)
-
# @count += val
-
# end
-
#
-
# def self.reset_count
-
# @count = 0
-
# end
-
#
-
# def initialize
-
# self.class.count += 1
-
# end
-
# end
-
#
-
# describe Thing do
-
# after(:example) { Thing.reset_count }
-
#
-
# context "using subject" do
-
# subject { Thing.new }
-
#
-
# it "is not invoked implicitly" do
-
# Thing.count.should eq(0)
-
# end
-
#
-
# it "can be invoked explicitly" do
-
# subject
-
# Thing.count.should eq(1)
-
# end
-
# end
-
#
-
# context "using subject!" do
-
# subject!(:thing) { Thing.new }
-
#
-
# it "is invoked implicitly" do
-
# Thing.count.should eq(1)
-
# end
-
#
-
# it "returns memoized version on first invocation" do
-
# subject
-
# Thing.count.should eq(1)
-
# end
-
# end
-
# end
-
1
def subject!(name=nil, &block)
-
subject(name, &block)
-
before { subject }
-
end
-
end
-
-
# @private
-
#
-
# Gets the LetDefinitions module. The module is mixed into
-
# the example group and is used to hold all let definitions.
-
# This is done so that the block passed to `let` can be
-
# forwarded directly on to `define_method`, so that all method
-
# constructs (including `super` and `return`) can be used in
-
# a `let` block.
-
#
-
# The memoization is provided by a method definition on the
-
# example group that supers to the LetDefinitions definition
-
# in order to get the value to memoize.
-
1
def self.module_for(example_group)
-
get_constant_or_yield(example_group, :LetDefinitions) do
-
mod = Module.new do
-
include Module.new {
-
example_group.const_set(:NamedSubjectPreventSuper, self)
-
}
-
end
-
-
example_group.const_set(:LetDefinitions, mod)
-
mod
-
end
-
end
-
-
# @private
-
1
def self.define_helpers_on(example_group)
-
example_group.__send__(:include, module_for(example_group))
-
end
-
-
1
if Module.method(:const_defined?).arity == 1 # for 1.8
-
# @private
-
#
-
# Gets the named constant or yields.
-
# On 1.8, const_defined? / const_get do not take into
-
# account the inheritance hierarchy.
-
skipped
# :nocov:
-
skipped
def self.get_constant_or_yield(example_group, name)
-
skipped
if example_group.const_defined?(name)
-
skipped
example_group.const_get(name)
-
skipped
else
-
skipped
yield
-
skipped
end
-
skipped
end
-
skipped
# :nocov:
-
else
-
# @private
-
#
-
# Gets the named constant or yields.
-
# On 1.9, const_defined? / const_get take into account the
-
# the inheritance by default, and accept an argument to
-
# disable this behavior. It's important that we don't
-
# consider inheritance here; each example group level that
-
# uses a `let` should get its own `LetDefinitions` module.
-
1
def self.get_constant_or_yield(example_group, name)
-
if example_group.const_defined?(name, (check_ancestors = false))
-
example_group.const_get(name, check_ancestors)
-
else
-
yield
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Each ExampleGroup class and Example instance owns an instance of
-
# Metadata, which is Hash extended to support lazy evaluation of values
-
# associated with keys that may or may not be used by any example or group.
-
#
-
# In addition to metadata that is used internally, this also stores
-
# user-supplied metadata, e.g.
-
#
-
# describe Something, :type => :ui do
-
# it "does something", :slow => true do
-
# # ...
-
# end
-
# end
-
#
-
# `:type => :ui` is stored in the Metadata owned by the example group, and
-
# `:slow => true` is stored in the Metadata owned by the example. These can
-
# then be used to select which examples are run using the `--tag` option on
-
# the command line, or several methods on `Configuration` used to filter a
-
# run (e.g. `filter_run_including`, `filter_run_excluding`, etc).
-
#
-
# @see Example#metadata
-
# @see ExampleGroup.metadata
-
# @see FilterManager
-
# @see Configuration#filter_run_including
-
# @see Configuration#filter_run_excluding
-
1
module Metadata
-
# Matches strings either at the beginning of the input or prefixed with a
-
# whitespace, containing the current path, either postfixed with the
-
# separator, or at the end of the string. Match groups are the character
-
# before and the character after the string if any.
-
#
-
# http://rubular.com/r/fT0gmX6VJX
-
# http://rubular.com/r/duOrD4i3wb
-
# http://rubular.com/r/sbAMHFrOx1
-
1
def self.relative_path_regex
-
@relative_path_regex ||= /(\A|\s)#{File.expand_path('.')}(#{File::SEPARATOR}|\s|\Z)/
-
end
-
-
# @api private
-
#
-
# @param line [String] current code line
-
# @return [String] relative path to line
-
1
def self.relative_path(line)
-
line = line.sub(relative_path_regex, "\\1.\\2".freeze)
-
line = line.sub(/\A([^:]+:\d+)$/, '\\1'.freeze)
-
return nil if line == '-e:1'.freeze
-
line
-
rescue SecurityError
-
nil
-
end
-
-
# @private
-
# Iteratively walks up from the given metadata through all
-
# example group ancestors, yielding each metadata hash along the way.
-
1
def self.ascending(metadata)
-
yield metadata
-
return unless (group_metadata = metadata.fetch(:example_group) { metadata[:parent_example_group] })
-
-
loop do
-
yield group_metadata
-
break unless (group_metadata = group_metadata[:parent_example_group])
-
end
-
end
-
-
# @private
-
# Returns an enumerator that iteratively walks up the given metadata through all
-
# example group ancestors, yielding each metadata hash along the way.
-
1
def self.ascend(metadata)
-
enum_for(:ascending, metadata)
-
end
-
-
# @private
-
# Used internally to build a hash from an args array.
-
# Symbols are converted into hash keys with a value of `true`.
-
# This is done to support simple tagging using a symbol, rather
-
# than needing to do `:symbol => true`.
-
1
def self.build_hash_from(args, warn_about_example_group_filtering=false)
-
2
hash = args.last.is_a?(Hash) ? args.pop : {}
-
-
2
hash[args.pop] = true while args.last.is_a?(Symbol)
-
-
2
if warn_about_example_group_filtering && hash.key?(:example_group)
-
RSpec.deprecate("Filtering by an `:example_group` subhash",
-
:replacement => "the subhash to filter directly")
-
end
-
-
2
hash
-
end
-
-
# @private
-
1
def self.deep_hash_dup(object)
-
return object.dup if Array === object
-
return object unless Hash === object
-
-
object.inject(object.dup) do |duplicate, (key, value)|
-
duplicate[key] = deep_hash_dup(value)
-
duplicate
-
end
-
end
-
-
# @private
-
1
def self.id_from(metadata)
-
"#{metadata[:rerun_file_path]}[#{metadata[:scoped_id]}]"
-
end
-
-
# @private
-
# Used internally to populate metadata hashes with computed keys
-
# managed by RSpec.
-
1
class HashPopulator
-
1
attr_reader :metadata, :user_metadata, :description_args, :block
-
-
1
def initialize(metadata, user_metadata, index_provider, description_args, block)
-
@metadata = metadata
-
@user_metadata = user_metadata
-
@index_provider = index_provider
-
@description_args = description_args
-
@block = block
-
end
-
-
1
def populate
-
ensure_valid_user_keys
-
-
metadata[:execution_result] = Example::ExecutionResult.new
-
metadata[:block] = block
-
metadata[:description_args] = description_args
-
metadata[:description] = build_description_from(*metadata[:description_args])
-
metadata[:full_description] = full_description
-
metadata[:described_class] = described_class
-
-
populate_location_attributes
-
metadata.update(user_metadata)
-
RSpec.configuration.apply_derived_metadata_to(metadata)
-
end
-
-
1
private
-
-
1
def populate_location_attributes
-
backtrace = user_metadata.delete(:caller)
-
-
file_path, line_number = if backtrace
-
file_path_and_line_number_from(backtrace)
-
elsif block.respond_to?(:source_location)
-
block.source_location
-
else
-
file_path_and_line_number_from(caller)
-
end
-
-
relative_file_path = Metadata.relative_path(file_path)
-
metadata[:file_path] = relative_file_path
-
metadata[:line_number] = line_number.to_i
-
metadata[:location] = "#{relative_file_path}:#{line_number}"
-
metadata[:absolute_file_path] = File.expand_path(relative_file_path)
-
metadata[:rerun_file_path] ||= relative_file_path
-
metadata[:scoped_id] = build_scoped_id_for(relative_file_path)
-
end
-
-
1
def file_path_and_line_number_from(backtrace)
-
first_caller_from_outside_rspec = backtrace.find { |l| l !~ CallerFilter::LIB_REGEX }
-
first_caller_from_outside_rspec ||= backtrace.first
-
/(.+?):(\d+)(?:|:\d+)/.match(first_caller_from_outside_rspec).captures
-
end
-
-
1
def description_separator(parent_part, child_part)
-
if parent_part.is_a?(Module) && child_part =~ /^(#|::|\.)/
-
''.freeze
-
else
-
' '.freeze
-
end
-
end
-
-
1
def build_description_from(parent_description=nil, my_description=nil)
-
return parent_description.to_s unless my_description
-
separator = description_separator(parent_description, my_description)
-
(parent_description.to_s + separator) << my_description.to_s
-
end
-
-
1
def build_scoped_id_for(file_path)
-
index = @index_provider.call(file_path).to_s
-
parent_scoped_id = metadata.fetch(:scoped_id) { return index }
-
"#{parent_scoped_id}:#{index}"
-
end
-
-
1
def ensure_valid_user_keys
-
RESERVED_KEYS.each do |key|
-
next unless user_metadata.key?(key)
-
raise <<-EOM.gsub(/^\s+\|/, '')
-
|#{"*" * 50}
-
|:#{key} is not allowed
-
|
-
|RSpec reserves some hash keys for its own internal use,
-
|including :#{key}, which is used on:
-
|
-
| #{CallerFilter.first_non_rspec_line}.
-
|
-
|Here are all of RSpec's reserved hash keys:
-
|
-
| #{RESERVED_KEYS.join("\n ")}
-
|#{"*" * 50}
-
EOM
-
end
-
end
-
end
-
-
# @private
-
1
class ExampleHash < HashPopulator
-
1
def self.create(group_metadata, user_metadata, index_provider, description, block)
-
example_metadata = group_metadata.dup
-
group_metadata = Hash.new(&ExampleGroupHash.backwards_compatibility_default_proc do |hash|
-
hash[:parent_example_group]
-
end)
-
group_metadata.update(example_metadata)
-
-
example_metadata[:example_group] = group_metadata
-
example_metadata[:shared_group_inclusion_backtrace] = SharedExampleGroupInclusionStackFrame.current_backtrace
-
example_metadata.delete(:parent_example_group)
-
-
description_args = description.nil? ? [] : [description]
-
hash = new(example_metadata, user_metadata, index_provider, description_args, block)
-
hash.populate
-
hash.metadata
-
end
-
-
1
private
-
-
1
def described_class
-
metadata[:example_group][:described_class]
-
end
-
-
1
def full_description
-
build_description_from(
-
metadata[:example_group][:full_description],
-
metadata[:description]
-
)
-
end
-
end
-
-
# @private
-
1
class ExampleGroupHash < HashPopulator
-
1
def self.create(parent_group_metadata, user_metadata, example_group_index, *args, &block)
-
group_metadata = hash_with_backwards_compatibility_default_proc
-
-
if parent_group_metadata
-
group_metadata.update(parent_group_metadata)
-
group_metadata[:parent_example_group] = parent_group_metadata
-
end
-
-
hash = new(group_metadata, user_metadata, example_group_index, args, block)
-
hash.populate
-
hash.metadata
-
end
-
-
1
def self.hash_with_backwards_compatibility_default_proc
-
Hash.new(&backwards_compatibility_default_proc { |hash| hash })
-
end
-
-
1
def self.backwards_compatibility_default_proc(&example_group_selector)
-
Proc.new do |hash, key|
-
case key
-
when :example_group
-
# We commonly get here when rspec-core is applying a previously
-
# configured filter rule, such as when a gem configures:
-
#
-
# RSpec.configure do |c|
-
# c.include MyGemHelpers, :example_group => { :file_path => /spec\/my_gem_specs/ }
-
# end
-
#
-
# It's confusing for a user to get a deprecation at this point in
-
# the code, so instead we issue a deprecation from the config APIs
-
# that take a metadata hash, and MetadataFilter sets this thread
-
# local to silence the warning here since it would be so
-
# confusing.
-
unless RSpec::Support.thread_local_data[:silence_metadata_example_group_deprecations]
-
RSpec.deprecate("The `:example_group` key in an example group's metadata hash",
-
:replacement => "the example group's hash directly for the " \
-
"computed keys and `:parent_example_group` to access the parent " \
-
"example group metadata")
-
end
-
-
group_hash = example_group_selector.call(hash)
-
LegacyExampleGroupHash.new(group_hash) if group_hash
-
when :example_group_block
-
RSpec.deprecate("`metadata[:example_group_block]`",
-
:replacement => "`metadata[:block]`")
-
hash[:block]
-
when :describes
-
RSpec.deprecate("`metadata[:describes]`",
-
:replacement => "`metadata[:described_class]`")
-
hash[:described_class]
-
end
-
end
-
end
-
-
1
private
-
-
1
def described_class
-
candidate = metadata[:description_args].first
-
return candidate unless NilClass === candidate || String === candidate
-
parent_group = metadata[:parent_example_group]
-
parent_group && parent_group[:described_class]
-
end
-
-
1
def full_description
-
description = metadata[:description]
-
parent_example_group = metadata[:parent_example_group]
-
return description unless parent_example_group
-
-
parent_description = parent_example_group[:full_description]
-
separator = description_separator(parent_example_group[:description_args].last,
-
metadata[:description_args].first)
-
-
parent_description + separator + description
-
end
-
end
-
-
# @private
-
1
RESERVED_KEYS = [
-
:description,
-
:description_args,
-
:described_class,
-
:example_group,
-
:parent_example_group,
-
:execution_result,
-
:last_run_status,
-
:file_path,
-
:absolute_file_path,
-
:rerun_file_path,
-
:full_description,
-
:line_number,
-
:location,
-
:scoped_id,
-
:block,
-
:shared_group_inclusion_backtrace
-
]
-
end
-
-
# Mixin that makes the including class imitate a hash for backwards
-
# compatibility. The including class should use `attr_accessor` to
-
# declare attributes.
-
# @private
-
1
module HashImitatable
-
1
def self.included(klass)
-
2
klass.extend ClassMethods
-
end
-
-
1
def to_h
-
hash = extra_hash_attributes.dup
-
-
self.class.hash_attribute_names.each do |name|
-
hash[name] = __send__(name)
-
end
-
-
hash
-
end
-
-
1
(Hash.public_instance_methods - Object.public_instance_methods).each do |method_name|
-
137
next if [:[], :[]=, :to_h].include?(method_name.to_sym)
-
-
134
define_method(method_name) do |*args, &block|
-
issue_deprecation(method_name, *args)
-
-
hash = hash_for_delegation
-
self.class.hash_attribute_names.each do |name|
-
hash.delete(name) unless instance_variable_defined?(:"@#{name}")
-
end
-
-
hash.__send__(method_name, *args, &block).tap do
-
# apply mutations back to the object
-
hash.each do |name, value|
-
if directly_supports_attribute?(name)
-
set_value(name, value)
-
else
-
extra_hash_attributes[name] = value
-
end
-
end
-
end
-
end
-
end
-
-
1
def [](key)
-
issue_deprecation(:[], key)
-
-
if directly_supports_attribute?(key)
-
get_value(key)
-
else
-
extra_hash_attributes[key]
-
end
-
end
-
-
1
def []=(key, value)
-
issue_deprecation(:[]=, key, value)
-
-
if directly_supports_attribute?(key)
-
set_value(key, value)
-
else
-
extra_hash_attributes[key] = value
-
end
-
end
-
-
1
private
-
-
1
def extra_hash_attributes
-
@extra_hash_attributes ||= {}
-
end
-
-
1
def directly_supports_attribute?(name)
-
self.class.hash_attribute_names.include?(name)
-
end
-
-
1
def get_value(name)
-
__send__(name)
-
end
-
-
1
def set_value(name, value)
-
__send__(:"#{name}=", value)
-
end
-
-
1
def hash_for_delegation
-
to_h
-
end
-
-
1
def issue_deprecation(_method_name, *_args)
-
# no-op by default: subclasses can override
-
end
-
-
# @private
-
1
module ClassMethods
-
1
def hash_attribute_names
-
8
@hash_attribute_names ||= []
-
end
-
-
1
def attr_accessor(*names)
-
8
hash_attribute_names.concat(names)
-
8
super
-
end
-
end
-
end
-
-
# @private
-
# Together with the example group metadata hash default block,
-
# provides backwards compatibility for the old `:example_group`
-
# key. In RSpec 2.x, the computed keys of a group's metadata
-
# were exposed from a nested subhash keyed by `[:example_group]`, and
-
# then the parent group's metadata was exposed by sub-subhash
-
# keyed by `[:example_group][:example_group]`.
-
#
-
# In RSpec 3, we reorganized this to that the computed keys are
-
# exposed directly of the group metadata hash (no nesting), and
-
# `:parent_example_group` returns the parent group's metadata.
-
#
-
# Maintaining backwards compatibility was difficult: we wanted
-
# `:example_group` to return an object that:
-
#
-
# * Exposes the top-level metadata keys that used to be nested
-
# under `:example_group`.
-
# * Supports mutation (rspec-rails, for example, assigns
-
# `metadata[:example_group][:described_class]` when you use
-
# anonymous controller specs) such that changes are written
-
# back to the top-level metadata hash.
-
# * Exposes the parent group metadata as
-
# `[:example_group][:example_group]`.
-
1
class LegacyExampleGroupHash
-
1
include HashImitatable
-
-
1
def initialize(metadata)
-
@metadata = metadata
-
parent_group_metadata = metadata.fetch(:parent_example_group) { {} }[:example_group]
-
self[:example_group] = parent_group_metadata if parent_group_metadata
-
end
-
-
1
def to_h
-
super.merge(@metadata)
-
end
-
-
1
private
-
-
1
def directly_supports_attribute?(name)
-
name != :example_group
-
end
-
-
1
def get_value(name)
-
@metadata[name]
-
end
-
-
1
def set_value(name, value)
-
@metadata[name] = value
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Contains metadata filtering logic. This has been extracted from
-
# the metadata classes because it operates ON a metadata hash but
-
# does not manage any of the state in the hash. We're moving towards
-
# having metadata be a raw hash (not a custom subclass), so externalizing
-
# this filtering logic helps us move in that direction.
-
1
module MetadataFilter
-
1
class << self
-
# @private
-
1
def apply?(predicate, filters, metadata)
-
filters.__send__(predicate) { |k, v| filter_applies?(k, v, metadata) }
-
end
-
-
# @private
-
1
def filter_applies?(key, value, metadata)
-
silence_metadata_example_group_deprecations do
-
return filter_applies_to_any_value?(key, value, metadata) if Array === metadata[key] && !(Proc === value)
-
return location_filter_applies?(value, metadata) if key == :locations
-
return id_filter_applies?(value, metadata) if key == :ids
-
return filters_apply?(key, value, metadata) if Hash === value
-
-
return false unless metadata.key?(key)
-
-
case value
-
when Regexp
-
metadata[key] =~ value
-
when Proc
-
case value.arity
-
when 0 then value.call
-
when 2 then value.call(metadata[key], metadata)
-
else value.call(metadata[key])
-
end
-
else
-
metadata[key].to_s == value.to_s
-
end
-
end
-
end
-
-
1
private
-
-
1
def filter_applies_to_any_value?(key, value, metadata)
-
metadata[key].any? { |v| filter_applies?(key, v, key => value) }
-
end
-
-
1
def id_filter_applies?(rerun_paths_to_scoped_ids, metadata)
-
scoped_ids = rerun_paths_to_scoped_ids.fetch(metadata[:rerun_file_path]) { return false }
-
-
Metadata.ascend(metadata).any? do |meta|
-
scoped_ids.include?(meta[:scoped_id])
-
end
-
end
-
-
1
def location_filter_applies?(locations, metadata)
-
line_numbers = example_group_declaration_lines(locations, metadata)
-
line_number_filter_applies?(line_numbers, metadata)
-
end
-
-
1
def line_number_filter_applies?(line_numbers, metadata)
-
preceding_declaration_lines = line_numbers.map { |n| RSpec.world.preceding_declaration_line(n) }
-
!(relevant_line_numbers(metadata) & preceding_declaration_lines).empty?
-
end
-
-
1
def relevant_line_numbers(metadata)
-
Metadata.ascend(metadata).map { |meta| meta[:line_number] }
-
end
-
-
1
def example_group_declaration_lines(locations, metadata)
-
FlatMap.flat_map(Metadata.ascend(metadata)) do |meta|
-
locations[meta[:absolute_file_path]]
-
end.uniq
-
end
-
-
1
def filters_apply?(key, value, metadata)
-
subhash = metadata[key]
-
return false unless Hash === subhash || HashImitatable === subhash
-
value.all? { |k, v| filter_applies?(k, v, subhash) }
-
end
-
-
1
def silence_metadata_example_group_deprecations
-
RSpec::Support.thread_local_data[:silence_metadata_example_group_deprecations] = true
-
yield
-
ensure
-
RSpec::Support.thread_local_data.delete(:silence_metadata_example_group_deprecations)
-
end
-
end
-
end
-
-
# Tracks a collection of filterable items (e.g. modules, hooks, etc)
-
# and provides an optimized API to get the applicable items for the
-
# metadata of an example or example group.
-
#
-
# There are two implementations, optimized for different uses.
-
# @private
-
1
module FilterableItemRepository
-
# This implementation is simple, and is optimized for frequent
-
# updates but rare queries. `append` and `prepend` do no extra
-
# processing, and no internal memoization is done, since this
-
# is not optimized for queries.
-
#
-
# This is ideal for use by a example or example group, which may
-
# be updated multiple times with globally configured hooks, etc,
-
# but will not be queried frequently by other examples or examle
-
# groups.
-
# @private
-
1
class UpdateOptimized
-
1
attr_reader :items_and_filters
-
-
1
def initialize(applies_predicate)
-
5
@applies_predicate = applies_predicate
-
5
@items_and_filters = []
-
end
-
-
1
def append(item, metadata)
-
1
@items_and_filters << [item, metadata]
-
end
-
-
1
def prepend(item, metadata)
-
1
@items_and_filters.unshift [item, metadata]
-
end
-
-
1
def items_for(request_meta)
-
@items_and_filters.each_with_object([]) do |(item, item_meta), to_return|
-
to_return << item if item_meta.empty? ||
-
MetadataFilter.apply?(@applies_predicate, item_meta, request_meta)
-
end
-
end
-
-
1
unless [].respond_to?(:each_with_object) # For 1.8.7
-
skipped
# :nocov:
-
skipped
undef items_for
-
skipped
def items_for(request_meta)
-
skipped
@items_and_filters.inject([]) do |to_return, (item, item_meta)|
-
skipped
to_return << item if item_meta.empty? ||
-
skipped
MetadataFilter.apply?(@applies_predicate, item_meta, request_meta)
-
skipped
to_return
-
skipped
end
-
skipped
end
-
skipped
# :nocov:
-
end
-
end
-
-
# This implementation is much more complex, and is optimized for
-
# rare (or hopefully no) updates once the queries start. Updates
-
# incur a cost as it has to clear the memoization and keep track
-
# of applicable keys. Queries will be O(N) the first time an item
-
# is provided with a given set of applicable metadata; subsequent
-
# queries with items with the same set of applicable metadata will
-
# be O(1) due to internal memoization.
-
#
-
# This is ideal for use by config, where filterable items (e.g. hooks)
-
# are typically added at the start of the process (e.g. in `spec_helper`)
-
# and then repeatedly queried as example groups and examples are defined.
-
# @private
-
1
class QueryOptimized < UpdateOptimized
-
1
alias find_items_for items_for
-
1
private :find_items_for
-
-
1
def initialize(applies_predicate)
-
5
super
-
5
@applicable_keys = Set.new
-
5
@proc_keys = Set.new
-
5
@memoized_lookups = Hash.new do |hash, applicable_metadata|
-
hash[applicable_metadata] = find_items_for(applicable_metadata)
-
end
-
end
-
-
1
def append(item, metadata)
-
1
super
-
1
handle_mutation(metadata)
-
end
-
-
1
def prepend(item, metadata)
-
1
super
-
1
handle_mutation(metadata)
-
end
-
-
1
def items_for(metadata)
-
# The filtering of `metadata` to `applicable_metadata` is the key thing
-
# that makes the memoization actually useful in practice, since each
-
# example and example group have different metadata (e.g. location and
-
# description). By filtering to the metadata keys our items care about,
-
# we can ignore extra metadata keys that differ for each example/group.
-
# For example, given `config.include DBHelpers, :db`, example groups
-
# can be split into these two sets: those that are tagged with `:db` and those
-
# that are not. For each set, this method for the first group in the set is
-
# still an `O(N)` calculation, but all subsequent groups in the set will be
-
# constant time lookups when they call this method.
-
applicable_metadata = applicable_metadata_from(metadata)
-
-
if applicable_metadata.any? { |k, _| @proc_keys.include?(k) }
-
# It's unsafe to memoize lookups involving procs (since they can
-
# be non-deterministic), so we skip the memoization in this case.
-
find_items_for(applicable_metadata)
-
else
-
@memoized_lookups[applicable_metadata]
-
end
-
end
-
-
1
private
-
-
1
def handle_mutation(metadata)
-
2
@applicable_keys.merge(metadata.keys)
-
2
@proc_keys.merge(proc_keys_from metadata)
-
2
@memoized_lookups.clear
-
end
-
-
1
def applicable_metadata_from(metadata)
-
@applicable_keys.inject({}) do |hash, key|
-
hash[key] = metadata[key] if metadata.key?(key)
-
hash
-
end
-
end
-
-
1
def proc_keys_from(metadata)
-
2
metadata.each_with_object([]) do |(key, value), to_return|
-
1
to_return << key if Proc === value
-
end
-
end
-
-
1
unless [].respond_to?(:each_with_object) # For 1.8.7
-
skipped
# :nocov:
-
skipped
undef proc_keys_from
-
skipped
def proc_keys_from(metadata)
-
skipped
metadata.inject([]) do |to_return, (key, value)|
-
skipped
to_return << key if Proc === value
-
skipped
to_return
-
skipped
end
-
skipped
end
-
skipped
# :nocov:
-
end
-
end
-
end
-
end
-
end
-
1
require 'rspec/mocks'
-
-
1
module RSpec
-
1
module Core
-
1
module MockingAdapters
-
# @private
-
1
module RSpec
-
1
include ::RSpec::Mocks::ExampleMethods
-
-
1
def self.framework_name
-
1
:rspec
-
end
-
-
1
def self.configuration
-
1
::RSpec::Mocks.configuration
-
end
-
-
1
def setup_mocks_for_rspec
-
::RSpec::Mocks.setup
-
end
-
-
1
def verify_mocks_for_rspec
-
::RSpec::Mocks.verify
-
end
-
-
1
def teardown_mocks_for_rspec
-
::RSpec::Mocks.teardown
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "formatters/exception_presenter"
-
1
RSpec::Support.require_rspec_core "formatters/helpers"
-
1
RSpec::Support.require_rspec_core "shell_escape"
-
1
RSpec::Support.require_rspec_support "encoded_string"
-
-
1
module RSpec::Core
-
# Notifications are value objects passed to formatters to provide them
-
# with information about a particular event of interest.
-
1
module Notifications
-
# @private
-
1
module NullColorizer
-
1
module_function
-
1
def wrap(line, _code_or_symbol)
-
line
-
end
-
end
-
-
# The `StartNotification` represents a notification sent by the reporter
-
# when the suite is started. It contains the expected amount of examples
-
# to be executed, and the load time of RSpec.
-
#
-
# @attr count [Fixnum] the number counted
-
# @attr load_time [Float] the number of seconds taken to boot RSpec
-
# and load the spec files
-
1
StartNotification = Struct.new(:count, :load_time)
-
-
# The `ExampleNotification` represents notifications sent by the reporter
-
# which contain information about the current (or soon to be) example.
-
# It is used by formatters to access information about that example.
-
#
-
# @example
-
# def example_started(notification)
-
# puts "Hey I started #{notification.example.description}"
-
# end
-
#
-
# @attr example [RSpec::Core::Example] the current example
-
1
ExampleNotification = Struct.new(:example)
-
1
class ExampleNotification
-
# @private
-
1
def self.for(example)
-
execution_result = example.execution_result
-
-
return SkippedExampleNotification.new(example) if execution_result.example_skipped?
-
return new(example) unless execution_result.status == :pending || execution_result.status == :failed
-
-
klass = if execution_result.pending_fixed?
-
PendingExampleFixedNotification
-
elsif execution_result.status == :pending
-
PendingExampleFailedAsExpectedNotification
-
else
-
FailedExampleNotification
-
end
-
-
exception_presenter = Formatters::ExceptionPresenter::Factory.new(example).build
-
klass.new(example, exception_presenter)
-
end
-
-
1
private_class_method :new
-
end
-
-
# The `ExamplesNotification` represents notifications sent by the reporter
-
# which contain information about the suites examples.
-
#
-
# @example
-
# def stop(notification)
-
# puts "Hey I ran #{notification.examples.size}"
-
# end
-
#
-
1
class ExamplesNotification
-
1
def initialize(reporter)
-
@reporter = reporter
-
end
-
-
# @return [Array<RSpec::Core::Example>] list of examples
-
1
def examples
-
@reporter.examples
-
end
-
-
# @return [Array<RSpec::Core::Example>] list of failed examples
-
1
def failed_examples
-
@reporter.failed_examples
-
end
-
-
# @return [Array<RSpec::Core::Example>] list of pending examples
-
1
def pending_examples
-
@reporter.pending_examples
-
end
-
-
# @return [Array<RSpec::Core::Notifications::ExampleNotification>]
-
# returns examples as notifications
-
1
def notifications
-
@notifications ||= format_examples(examples)
-
end
-
-
# @return [Array<RSpec::Core::Notifications::FailedExampleNotification>]
-
# returns failed examples as notifications
-
1
def failure_notifications
-
@failed_notifications ||= format_examples(failed_examples)
-
end
-
-
# @return [Array<RSpec::Core::Notifications::SkippedExampleNotification,
-
# RSpec::Core::Notifications::PendingExampleFailedAsExpectedNotification>]
-
# returns pending examples as notifications
-
1
def pending_notifications
-
@pending_notifications ||= format_examples(pending_examples)
-
end
-
-
# @return [String] The list of failed examples, fully formatted in the way
-
# that RSpec's built-in formatters emit.
-
1
def fully_formatted_failed_examples(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
formatted = "\nFailures:\n"
-
-
failure_notifications.each_with_index do |failure, index|
-
formatted << failure.fully_formatted(index.next, colorizer)
-
end
-
-
formatted
-
end
-
-
# @return [String] The list of pending examples, fully formatted in the
-
# way that RSpec's built-in formatters emit.
-
1
def fully_formatted_pending_examples(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
formatted = "\nPending: (Failures listed here are expected and do not affect your suite's status)\n"
-
-
pending_notifications.each_with_index do |notification, index|
-
formatted << notification.fully_formatted(index.next, colorizer)
-
end
-
-
formatted
-
end
-
-
1
private
-
-
1
def format_examples(examples)
-
examples.map do |example|
-
ExampleNotification.for(example)
-
end
-
end
-
end
-
-
# The `FailedExampleNotification` extends `ExampleNotification` with
-
# things useful for examples that have failure info -- typically a
-
# failed or pending spec.
-
#
-
# @example
-
# def example_failed(notification)
-
# puts "Hey I failed :("
-
# puts "Here's my stack trace"
-
# puts notification.exception.backtrace.join("\n")
-
# end
-
#
-
# @attr [RSpec::Core::Example] example the current example
-
# @see ExampleNotification
-
1
class FailedExampleNotification < ExampleNotification
-
1
public_class_method :new
-
-
# @return [Exception] The example failure
-
1
def exception
-
@exception_presenter.exception
-
end
-
-
# @return [String] The example description
-
1
def description
-
@exception_presenter.description
-
end
-
-
# Returns the message generated for this failure line by line.
-
#
-
# @return [Array<String>] The example failure message
-
1
def message_lines
-
@exception_presenter.message_lines
-
end
-
-
# Returns the message generated for this failure colorized line by line.
-
#
-
# @param colorizer [#wrap] An object to colorize the message_lines by
-
# @return [Array<String>] The example failure message colorized
-
1
def colorized_message_lines(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
@exception_presenter.colorized_message_lines(colorizer)
-
end
-
-
# Returns the failures formatted backtrace.
-
#
-
# @return [Array<String>] the examples backtrace lines
-
1
def formatted_backtrace
-
@exception_presenter.formatted_backtrace
-
end
-
-
# Returns the failures colorized formatted backtrace.
-
#
-
# @param colorizer [#wrap] An object to colorize the message_lines by
-
# @return [Array<String>] the examples colorized backtrace lines
-
1
def colorized_formatted_backtrace(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
@exception_presenter.colorized_formatted_backtrace(colorizer)
-
end
-
-
# @return [String] The failure information fully formatted in the way that
-
# RSpec's built-in formatters emit.
-
1
def fully_formatted(failure_number, colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
@exception_presenter.fully_formatted(failure_number, colorizer)
-
end
-
-
1
private
-
-
1
def initialize(example, exception_presenter=Formatters::ExceptionPresenter.new(example.execution_result.exception, example))
-
@exception_presenter = exception_presenter
-
super(example)
-
end
-
end
-
-
# @deprecated Use {FailedExampleNotification} instead.
-
1
class PendingExampleFixedNotification < FailedExampleNotification; end
-
-
# @deprecated Use {FailedExampleNotification} instead.
-
1
class PendingExampleFailedAsExpectedNotification < FailedExampleNotification; end
-
-
# The `SkippedExampleNotification` extends `ExampleNotification` with
-
# things useful for specs that are skipped.
-
#
-
# @attr [RSpec::Core::Example] example the current example
-
# @see ExampleNotification
-
1
class SkippedExampleNotification < ExampleNotification
-
1
public_class_method :new
-
-
# @return [String] The pending detail fully formatted in the way that
-
# RSpec's built-in formatters emit.
-
1
def fully_formatted(pending_number, colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
formatted_caller = RSpec.configuration.backtrace_formatter.backtrace_line(example.location)
-
colorizer.wrap("\n #{pending_number}) #{example.full_description}", :pending) << "\n " <<
-
Formatters::ExceptionPresenter::PENDING_DETAIL_FORMATTER.call(example, colorizer) <<
-
"\n" << colorizer.wrap(" # #{formatted_caller}\n", :detail)
-
end
-
end
-
-
# The `GroupNotification` represents notifications sent by the reporter
-
# which contain information about the currently running (or soon to be)
-
# example group. It is used by formatters to access information about that
-
# group.
-
#
-
# @example
-
# def example_group_started(notification)
-
# puts "Hey I started #{notification.group.description}"
-
# end
-
# @attr group [RSpec::Core::ExampleGroup] the current group
-
1
GroupNotification = Struct.new(:group)
-
-
# The `MessageNotification` encapsulates generic messages that the reporter
-
# sends to formatters.
-
#
-
# @attr message [String] the message
-
1
MessageNotification = Struct.new(:message)
-
-
# The `SeedNotification` holds the seed used to randomize examples and
-
# whether that seed has been used or not.
-
#
-
# @attr seed [Fixnum] the seed used to randomize ordering
-
# @attr used [Boolean] whether the seed has been used or not
-
1
SeedNotification = Struct.new(:seed, :used)
-
1
class SeedNotification
-
# @api
-
# @return [Boolean] has the seed been used?
-
1
def seed_used?
-
!!used
-
end
-
1
private :used
-
-
# @return [String] The seed information fully formatted in the way that
-
# RSpec's built-in formatters emit.
-
1
def fully_formatted
-
"\nRandomized with seed #{seed}\n"
-
end
-
end
-
-
# The `SummaryNotification` holds information about the results of running
-
# a test suite. It is used by formatters to provide information at the end
-
# of the test run.
-
#
-
# @attr duration [Float] the time taken (in seconds) to run the suite
-
# @attr examples [Array<RSpec::Core::Example>] the examples run
-
# @attr failed_examples [Array<RSpec::Core::Example>] the failed examples
-
# @attr pending_examples [Array<RSpec::Core::Example>] the pending examples
-
# @attr load_time [Float] the number of seconds taken to boot RSpec
-
# and load the spec files
-
1
SummaryNotification = Struct.new(:duration, :examples, :failed_examples, :pending_examples, :load_time)
-
1
class SummaryNotification
-
# @api
-
# @return [Fixnum] the number of examples run
-
1
def example_count
-
@example_count ||= examples.size
-
end
-
-
# @api
-
# @return [Fixnum] the number of failed examples
-
1
def failure_count
-
@failure_count ||= failed_examples.size
-
end
-
-
# @api
-
# @return [Fixnum] the number of pending examples
-
1
def pending_count
-
@pending_count ||= pending_examples.size
-
end
-
-
# @api
-
# @return [String] A line summarising the result totals of the spec run.
-
1
def totals_line
-
summary = Formatters::Helpers.pluralize(example_count, "example")
-
summary << ", " << Formatters::Helpers.pluralize(failure_count, "failure")
-
summary << ", #{pending_count} pending" if pending_count > 0
-
summary
-
end
-
-
# @api public
-
#
-
# Wraps the results line with colors based on the configured
-
# colors for failure, pending, and success. Defaults to red,
-
# yellow, green accordingly.
-
#
-
# @param colorizer [#wrap] An object which supports wrapping text with
-
# specific colors.
-
# @return [String] A colorized results line.
-
1
def colorized_totals_line(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
if failure_count > 0
-
colorizer.wrap(totals_line, RSpec.configuration.failure_color)
-
elsif pending_count > 0
-
colorizer.wrap(totals_line, RSpec.configuration.pending_color)
-
else
-
colorizer.wrap(totals_line, RSpec.configuration.success_color)
-
end
-
end
-
-
# @api public
-
#
-
# Formats failures into a rerunable command format.
-
#
-
# @param colorizer [#wrap] An object which supports wrapping text with
-
# specific colors.
-
# @return [String] A colorized summary line.
-
1
def colorized_rerun_commands(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
"\nFailed examples:\n\n" +
-
failed_examples.map do |example|
-
colorizer.wrap("rspec #{rerun_argument_for(example)}", RSpec.configuration.failure_color) + " " +
-
colorizer.wrap("# #{example.full_description}", RSpec.configuration.detail_color)
-
end.join("\n")
-
end
-
-
# @return [String] a formatted version of the time it took to run the
-
# suite
-
1
def formatted_duration
-
Formatters::Helpers.format_duration(duration)
-
end
-
-
# @return [String] a formatted version of the time it took to boot RSpec
-
# and load the spec files
-
1
def formatted_load_time
-
Formatters::Helpers.format_duration(load_time)
-
end
-
-
# @return [String] The summary information fully formatted in the way that
-
# RSpec's built-in formatters emit.
-
1
def fully_formatted(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
formatted = "\nFinished in #{formatted_duration} " \
-
"(files took #{formatted_load_time} to load)\n" \
-
"#{colorized_totals_line(colorizer)}\n"
-
-
unless failed_examples.empty?
-
formatted << colorized_rerun_commands(colorizer) << "\n"
-
end
-
-
formatted
-
end
-
-
1
private
-
-
1
include RSpec::Core::ShellEscape
-
-
1
def rerun_argument_for(example)
-
location = example.location_rerun_argument
-
return location unless duplicate_rerun_locations.include?(location)
-
conditionally_quote(example.id)
-
end
-
-
1
def duplicate_rerun_locations
-
@duplicate_rerun_locations ||= begin
-
locations = RSpec.world.all_examples.map(&:location_rerun_argument)
-
-
Set.new.tap do |s|
-
locations.group_by { |l| l }.each do |l, ls|
-
s << l if ls.count > 1
-
end
-
end
-
end
-
end
-
end
-
-
# The `ProfileNotification` holds information about the results of running a
-
# test suite when profiling is enabled. It is used by formatters to provide
-
# information at the end of the test run for profiling information.
-
#
-
# @attr duration [Float] the time taken (in seconds) to run the suite
-
# @attr examples [Array<RSpec::Core::Example>] the examples run
-
# @attr number_of_examples [Fixnum] the number of examples to profile
-
# @attr example_groups [Array<RSpec::Core::Profiler>] example groups run
-
1
class ProfileNotification
-
1
def initialize(duration, examples, number_of_examples, example_groups)
-
@duration = duration
-
@examples = examples
-
@number_of_examples = number_of_examples
-
@example_groups = example_groups
-
end
-
1
attr_reader :duration, :examples, :number_of_examples
-
-
# @return [Array<RSpec::Core::Example>] the slowest examples
-
1
def slowest_examples
-
@slowest_examples ||=
-
examples.sort_by do |example|
-
-example.execution_result.run_time
-
end.first(number_of_examples)
-
end
-
-
# @return [Float] the time taken (in seconds) to run the slowest examples
-
1
def slow_duration
-
@slow_duration ||=
-
slowest_examples.inject(0.0) do |i, e|
-
i + e.execution_result.run_time
-
end
-
end
-
-
# @return [String] the percentage of total time taken
-
1
def percentage
-
@percentage ||=
-
begin
-
time_taken = slow_duration / duration
-
'%.1f' % ((time_taken.nan? ? 0.0 : time_taken) * 100)
-
end
-
end
-
-
# @return [Array<RSpec::Core::Example>] the slowest example groups
-
1
def slowest_groups
-
@slowest_groups ||= calculate_slowest_groups
-
end
-
-
1
private
-
-
1
def calculate_slowest_groups
-
# stop if we've only one example group
-
return {} if @example_groups.keys.length <= 1
-
-
@example_groups.each_value do |hash|
-
hash[:average] = hash[:total_time].to_f / hash[:count]
-
end
-
-
groups = @example_groups.sort_by { |_, hash| -hash[:average] }.first(number_of_examples)
-
groups.map { |group, data| [group.location, data] }
-
end
-
end
-
-
# The `DeprecationNotification` is issued by the reporter when a deprecated
-
# part of RSpec is encountered. It represents information about the
-
# deprecated call site.
-
#
-
# @attr message [String] A custom message about the deprecation
-
# @attr deprecated [String] A custom message about the deprecation (alias of
-
# message)
-
# @attr replacement [String] An optional replacement for the deprecation
-
# @attr call_site [String] An optional call site from which the deprecation
-
# was issued
-
1
DeprecationNotification = Struct.new(:deprecated, :message, :replacement, :call_site)
-
1
class DeprecationNotification
-
1
private_class_method :new
-
-
# @api
-
# Convenience way to initialize the notification
-
1
def self.from_hash(data)
-
new data[:deprecated], data[:message], data[:replacement], data[:call_site]
-
end
-
end
-
-
# `NullNotification` represents a placeholder value for notifications that
-
# currently require no information, but we may wish to extend in future.
-
1
class NullNotification
-
end
-
-
# `CustomNotification` is used when sending custom events to formatters /
-
# other registered listeners, it creates attributes based on supplied hash
-
# of options.
-
1
class CustomNotification < Struct
-
# @param options [Hash] A hash of method / value pairs to create on this notification
-
# @return [CustomNotification]
-
#
-
# Build a custom notification based on the supplied option key / values.
-
1
def self.for(options={})
-
return NullNotification if options.keys.empty?
-
new(*options.keys).new(*options.values)
-
end
-
end
-
end
-
end
-
# http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html
-
1
require 'optparse'
-
-
1
module RSpec::Core
-
# @private
-
1
class Parser
-
1
def self.parse(args, source=nil)
-
new(args).parse(source)
-
end
-
-
1
attr_reader :original_args
-
-
1
def initialize(original_args)
-
@original_args = original_args
-
end
-
-
1
def parse(source=nil)
-
return { :files_or_directories_to_run => [] } if original_args.empty?
-
args = original_args.dup
-
-
options = args.delete('--tty') ? { :tty => true } : {}
-
begin
-
parser(options).parse!(args)
-
rescue OptionParser::InvalidOption => e
-
failure = e.message
-
failure << " (defined in #{source})" if source
-
abort "#{failure}\n\nPlease use --help for a listing of valid options"
-
end
-
-
options[:files_or_directories_to_run] = args
-
options
-
end
-
-
1
private
-
-
# rubocop:disable MethodLength
-
1
def parser(options)
-
OptionParser.new do |parser|
-
parser.banner = "Usage: rspec [options] [files or directories]\n\n"
-
-
parser.on('-I PATH', 'Specify PATH to add to $LOAD_PATH (may be used more than once).') do |dirs|
-
options[:libs] ||= []
-
options[:libs].concat(dirs.split(File::PATH_SEPARATOR))
-
end
-
-
parser.on('-r', '--require PATH', 'Require a file.') do |path|
-
options[:requires] ||= []
-
options[:requires] << path
-
end
-
-
parser.on('-O', '--options PATH', 'Specify the path to a custom options file.') do |path|
-
options[:custom_options_file] = path
-
end
-
-
parser.on('--order TYPE[:SEED]', 'Run examples by the specified order type.',
-
' [defined] examples and groups are run in the order they are defined',
-
' [rand] randomize the order of groups and examples',
-
' [random] alias for rand',
-
' [random:SEED] e.g. --order random:123') do |o|
-
options[:order] = o
-
end
-
-
parser.on('--seed SEED', Integer, 'Equivalent of --order rand:SEED.') do |seed|
-
options[:order] = "rand:#{seed}"
-
end
-
-
parser.on('--bisect[=verbose]', 'Repeatedly runs the suite in order to isolate the failures to the ',
-
' smallest reproducible case.') do |argument|
-
bisect_and_exit(argument)
-
end
-
-
parser.on('--[no-]fail-fast', 'Abort the run on first failure.') do |value|
-
set_fail_fast(options, value)
-
end
-
-
parser.on('--failure-exit-code CODE', Integer,
-
'Override the exit code used when there are failing specs.') do |code|
-
options[:failure_exit_code] = code
-
end
-
-
parser.on('--dry-run', 'Print the formatter output of your suite without',
-
' running any examples or hooks') do |_o|
-
options[:dry_run] = true
-
end
-
-
parser.on('-X', '--[no-]drb', 'Run examples via DRb.') do |o|
-
options[:drb] = o
-
end
-
-
parser.on('--drb-port PORT', 'Port to connect to the DRb server.') do |o|
-
options[:drb_port] = o.to_i
-
end
-
-
parser.on('--init', 'Initialize your project with RSpec.') do |_cmd|
-
initialize_project_and_exit
-
end
-
-
parser.separator("\n **** Output ****\n\n")
-
-
parser.on('-f', '--format FORMATTER', 'Choose a formatter.',
-
' [p]rogress (default - dots)',
-
' [d]ocumentation (group and example names)',
-
' [h]tml',
-
' [j]son',
-
' custom formatter class name') do |o|
-
options[:formatters] ||= []
-
options[:formatters] << [o]
-
end
-
-
parser.on('-o', '--out FILE',
-
'Write output to a file instead of $stdout. This option applies',
-
' to the previously specified --format, or the default format',
-
' if no format is specified.'
-
) do |o|
-
options[:formatters] ||= [['progress']]
-
options[:formatters].last << o
-
end
-
-
parser.on('--deprecation-out FILE', 'Write deprecation warnings to a file instead of $stderr.') do |file|
-
options[:deprecation_stream] = file
-
end
-
-
parser.on('-b', '--backtrace', 'Enable full backtrace.') do |_o|
-
options[:full_backtrace] = true
-
end
-
-
parser.on('-c', '--[no-]color', '--[no-]colour', 'Enable color in the output.') do |o|
-
options[:color] = o
-
end
-
-
parser.on('-p', '--[no-]profile [COUNT]',
-
'Enable profiling of examples and list the slowest examples (default: 10).') do |argument|
-
options[:profile_examples] = if argument.nil?
-
true
-
elsif argument == false
-
false
-
else
-
begin
-
Integer(argument)
-
rescue ArgumentError
-
RSpec.warning "Non integer specified as profile count, seperate " \
-
"your path from options with -- e.g. " \
-
"`rspec --profile -- #{argument}`",
-
:call_site => nil
-
true
-
end
-
end
-
end
-
-
parser.on('-w', '--warnings', 'Enable ruby warnings') do
-
$VERBOSE = true
-
end
-
-
parser.separator <<-FILTERING
-
-
**** Filtering/tags ****
-
-
In addition to the following options for selecting specific files, groups, or
-
examples, you can select individual examples by appending the line number(s) to
-
the filename:
-
-
rspec path/to/a_spec.rb:37:87
-
-
You can also pass example ids enclosed in square brackets:
-
-
rspec path/to/a_spec.rb[1:5,1:6] # run the 5th and 6th examples/groups defined in the 1st group
-
-
FILTERING
-
-
parser.on('--only-failures', "Filter to just the examples that failed the last time they ran.") do
-
configure_only_failures(options)
-
end
-
-
parser.on("--next-failure", "Apply `--only-failures` and abort after one failure.",
-
" (Equivalent to `--only-failures --fail-fast --order defined`)") do
-
configure_only_failures(options)
-
set_fail_fast(options, true)
-
options[:order] ||= 'defined'
-
end
-
-
parser.on('-P', '--pattern PATTERN', 'Load files matching pattern (default: "spec/**/*_spec.rb").') do |o|
-
options[:pattern] = o
-
end
-
-
parser.on('--exclude-pattern PATTERN',
-
'Load files except those matching pattern. Opposite effect of --pattern.') do |o|
-
options[:exclude_pattern] = o
-
end
-
-
parser.on('-e', '--example STRING', "Run examples whose full nested names include STRING (may be",
-
" used more than once)") do |o|
-
(options[:full_description] ||= []) << Regexp.compile(Regexp.escape(o))
-
end
-
-
parser.on('-t', '--tag TAG[:VALUE]',
-
'Run examples with the specified tag, or exclude examples',
-
'by adding ~ before the tag.',
-
' - e.g. ~slow',
-
' - TAG is always converted to a symbol') do |tag|
-
filter_type = tag =~ /^~/ ? :exclusion_filter : :inclusion_filter
-
-
name, value = tag.gsub(/^(~@|~|@)/, '').split(':', 2)
-
name = name.to_sym
-
-
parsed_value = case value
-
when nil then true # The default value for tags is true
-
when 'true' then true
-
when 'false' then false
-
when 'nil' then nil
-
when /^:/ then value[1..-1].to_sym
-
when /^\d+$/ then Integer(value)
-
when /^\d+.\d+$/ then Float(value)
-
else
-
value
-
end
-
-
add_tag_filter(options, filter_type, name, parsed_value)
-
end
-
-
parser.on('--default-path PATH', 'Set the default path where RSpec looks for examples (can',
-
' be a path to a file or a directory).') do |path|
-
options[:default_path] = path
-
end
-
-
parser.separator("\n **** Utility ****\n\n")
-
-
parser.on('-v', '--version', 'Display the version.') do
-
print_version_and_exit
-
end
-
-
# These options would otherwise be confusing to users, so we forcibly
-
# prevent them from executing.
-
#
-
# * --I is too similar to -I.
-
# * -d was a shorthand for --debugger, which is removed, but now would
-
# trigger --default-path.
-
invalid_options = %w[-d --I]
-
-
parser.on_tail('-h', '--help', "You're looking at it.") do
-
print_help_and_exit(parser, invalid_options)
-
end
-
-
# This prevents usage of the invalid_options.
-
invalid_options.each do |option|
-
parser.on(option) do
-
raise OptionParser::InvalidOption.new
-
end
-
end
-
-
end
-
end
-
# rubocop:enable MethodLength
-
-
1
def add_tag_filter(options, filter_type, tag_name, value=true)
-
(options[filter_type] ||= {})[tag_name] = value
-
end
-
-
1
def set_fail_fast(options, value)
-
options[:fail_fast] = value
-
end
-
-
1
def configure_only_failures(options)
-
options[:only_failures] = true
-
add_tag_filter(options, :inclusion_filter, :last_run_status, 'failed')
-
end
-
-
1
def initialize_project_and_exit
-
RSpec::Support.require_rspec_core "project_initializer"
-
ProjectInitializer.new.run
-
exit
-
end
-
-
1
def bisect_and_exit(argument)
-
RSpec::Support.require_rspec_core "bisect/coordinator"
-
-
success = Bisect::Coordinator.bisect_with(
-
original_args,
-
RSpec.configuration,
-
bisect_formatter_for(argument)
-
)
-
-
exit(success ? 0 : 1)
-
end
-
-
1
def bisect_formatter_for(argument)
-
return Formatters::BisectDebugFormatter if argument == "verbose"
-
Formatters::BisectProgressFormatter
-
end
-
-
1
def print_version_and_exit
-
puts RSpec::Core::Version::STRING
-
exit
-
end
-
-
1
def print_help_and_exit(parser, invalid_options)
-
# Removing the blank invalid options from the output.
-
puts parser.to_s.gsub(/^\s+(#{invalid_options.join('|')})\s*$\n/, '')
-
exit
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
1
module Ordering
-
# @private
-
# The default global ordering (defined order).
-
1
class Identity
-
1
def order(items)
-
items
-
end
-
end
-
-
# @private
-
# Orders items randomly.
-
1
class Random
-
1
def initialize(configuration)
-
1
@configuration = configuration
-
1
@used = false
-
end
-
-
1
def used?
-
@used
-
end
-
-
1
def order(items)
-
@used = true
-
-
seed = @configuration.seed.to_s
-
items.sort_by { |item| jenkins_hash_digest(seed + item.id) }
-
end
-
-
1
private
-
-
# http://en.wikipedia.org/wiki/Jenkins_hash_function
-
# Jenkins provides a good distribution and is simpler than MD5.
-
# It's a bit slower than MD5 (primarily because `Digest::MD5` is
-
# implemented in C) but has the advantage of not requiring us
-
# to load another part of stdlib, which we try to minimize.
-
1
def jenkins_hash_digest(string)
-
hash = 0
-
-
string.each_byte do |byte|
-
hash += byte
-
hash &= MAX_32_BIT
-
hash += ((hash << 10) & MAX_32_BIT)
-
hash &= MAX_32_BIT
-
hash ^= hash >> 6
-
end
-
-
hash += ((hash << 3) & MAX_32_BIT)
-
hash &= MAX_32_BIT
-
hash ^= hash >> 11
-
hash += ((hash << 15) & MAX_32_BIT)
-
hash &= MAX_32_BIT
-
hash
-
end
-
-
1
MAX_32_BIT = 4_294_967_295
-
end
-
-
# @private
-
# Orders items based on a custom block.
-
1
class Custom
-
1
def initialize(callable)
-
@callable = callable
-
end
-
-
1
def order(list)
-
@callable.call(list)
-
end
-
end
-
-
# @private
-
# Stores the different ordering strategies.
-
1
class Registry
-
1
def initialize(configuration)
-
1
@configuration = configuration
-
1
@strategies = {}
-
-
1
register(:random, Random.new(configuration))
-
-
1
identity = Identity.new
-
1
register(:defined, identity)
-
-
# The default global ordering is --defined.
-
1
register(:global, identity)
-
end
-
-
1
def fetch(name, &fallback)
-
@strategies.fetch(name, &fallback)
-
end
-
-
1
def register(sym, strategy)
-
3
@strategies[sym] = strategy
-
end
-
-
1
def used_random_seed?
-
@strategies[:random].used?
-
end
-
end
-
-
# @private
-
# Manages ordering configuration.
-
#
-
# @note This is not intended to be used externally. Use
-
# the APIs provided by `RSpec::Core::Configuration` instead.
-
1
class ConfigurationManager
-
1
attr_reader :seed, :ordering_registry
-
-
1
def initialize
-
1
@ordering_registry = Registry.new(self)
-
1
@seed = rand(0xFFFF)
-
1
@seed_forced = false
-
1
@order_forced = false
-
end
-
-
1
def seed_used?
-
ordering_registry.used_random_seed?
-
end
-
-
1
def seed=(seed)
-
return if @seed_forced
-
register_ordering(:global, ordering_registry.fetch(:random))
-
@seed = seed.to_i
-
end
-
-
1
def order=(type)
-
order, seed = type.to_s.split(':')
-
@seed = seed.to_i if seed
-
-
ordering_name = if order.include?('rand')
-
:random
-
elsif order == 'defined'
-
:defined
-
end
-
-
register_ordering(:global, ordering_registry.fetch(ordering_name)) if ordering_name
-
end
-
-
1
def force(hash)
-
if hash.key?(:seed)
-
self.seed = hash[:seed]
-
@seed_forced = true
-
@order_forced = true
-
elsif hash.key?(:order)
-
self.order = hash[:order]
-
@order_forced = true
-
end
-
end
-
-
1
def register_ordering(name, strategy=Custom.new(Proc.new { |l| yield l }))
-
return if @order_forced && name == :global
-
ordering_registry.register(name, strategy)
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Provides methods to mark examples as pending. These methods are available
-
# to be called from within any example or hook.
-
1
module Pending
-
# Raised in the middle of an example to indicate that it should be marked
-
# as skipped.
-
1
class SkipDeclaredInExample < StandardError
-
1
attr_reader :argument
-
-
1
def initialize(argument)
-
@argument = argument
-
end
-
end
-
-
# If Test::Unit is loaded, we'll use its error as baseclass, so that
-
# Test::Unit will report unmet RSpec expectations as failures rather than
-
# errors.
-
1
begin
-
1
class PendingExampleFixedError < Test::Unit::AssertionFailedError; end
-
rescue
-
1
class PendingExampleFixedError < StandardError; end
-
end
-
-
# @private
-
1
NO_REASON_GIVEN = 'No reason given'
-
-
# @private
-
1
NOT_YET_IMPLEMENTED = 'Not yet implemented'
-
-
# @overload pending()
-
# @overload pending(message)
-
#
-
# Marks an example as pending. The rest of the example will still be
-
# executed, and if it passes the example will fail to indicate that the
-
# pending can be removed.
-
#
-
# @param message [String] optional message to add to the summary report.
-
#
-
# @example
-
# describe "an example" do
-
# # reported as "Pending: no reason given"
-
# it "is pending with no message" do
-
# pending
-
# raise "broken"
-
# end
-
#
-
# # reported as "Pending: something else getting finished"
-
# it "is pending with a custom message" do
-
# pending("something else getting finished")
-
# raise "broken"
-
# end
-
# end
-
#
-
# @note `before(:example)` hooks are eval'd when you use the `pending`
-
# method within an example. If you want to declare an example `pending`
-
# and bypass the `before` hooks as well, you can pass `:pending => true`
-
# to the `it` method:
-
#
-
# it "does something", :pending => true do
-
# # ...
-
# end
-
#
-
# or pass `:pending => "something else getting finished"` to add a
-
# message to the summary report:
-
#
-
# it "does something", :pending => "something else getting finished" do
-
# # ...
-
# end
-
1
def pending(message=nil)
-
current_example = RSpec.current_example
-
-
if block_given?
-
raise ArgumentError, <<-EOS.gsub(/^\s+\|/, '')
-
|The semantics of `RSpec::Core::Pending#pending` have changed in
-
|RSpec 3. In RSpec 2.x, it caused the example to be skipped. In
-
|RSpec 3, the rest of the example is still run but is expected to
-
|fail, and will be marked as a failure (rather than as pending) if
-
|the example passes.
-
|
-
|Passing a block within an example is now deprecated. Marking the
-
|example as pending provides the same behavior in RSpec 3 which was
-
|provided only by the block in RSpec 2.x.
-
|
-
|Move the code in the block provided to `pending` into the rest of
-
|the example body.
-
|
-
|Called from #{CallerFilter.first_non_rspec_line}.
-
|
-
EOS
-
elsif current_example
-
Pending.mark_pending! current_example, message
-
else
-
raise "`pending` may not be used outside of examples, such as in " \
-
"before(:context). Maybe you want `skip`?"
-
end
-
end
-
-
# @overload skip()
-
# @overload skip(message)
-
#
-
# Marks an example as pending and skips execution.
-
#
-
# @param message [String] optional message to add to the summary report.
-
#
-
# @example
-
# describe "an example" do
-
# # reported as "Pending: no reason given"
-
# it "is skipped with no message" do
-
# skip
-
# end
-
#
-
# # reported as "Pending: something else getting finished"
-
# it "is skipped with a custom message" do
-
# skip "something else getting finished"
-
# end
-
# end
-
1
def skip(message=nil)
-
current_example = RSpec.current_example
-
-
Pending.mark_skipped!(current_example, message) if current_example
-
-
raise SkipDeclaredInExample.new(message)
-
end
-
-
# @private
-
#
-
# Mark example as skipped.
-
#
-
# @param example [RSpec::Core::Example] the example to mark as skipped
-
# @param message_or_bool [Boolean, String] the message to use, or true
-
1
def self.mark_skipped!(example, message_or_bool)
-
Pending.mark_pending! example, message_or_bool
-
example.metadata[:skip] = true
-
end
-
-
# @private
-
#
-
# Mark example as pending.
-
#
-
# @param example [RSpec::Core::Example] the example to mark as pending
-
# @param message_or_bool [Boolean, String] the message to use, or true
-
1
def self.mark_pending!(example, message_or_bool)
-
message = if !message_or_bool || !(String === message_or_bool)
-
NO_REASON_GIVEN
-
else
-
message_or_bool
-
end
-
-
example.metadata[:pending] = true
-
example.execution_result.pending_message = message
-
example.execution_result.pending_fixed = false
-
end
-
-
# @private
-
#
-
# Mark example as fixed.
-
#
-
# @param example [RSpec::Core::Example] the example to mark as fixed
-
1
def self.mark_fixed!(example)
-
example.execution_result.pending_fixed = true
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Allows a thread to lock out other threads from a critical section of code,
-
# while allowing the thread with the lock to reenter that section.
-
#
-
# Based on Monitor as of 2.2 - https://github.com/ruby/ruby/blob/eb7ddaa3a47bf48045d26c72eb0f263a53524ebc/lib/monitor.rb#L9
-
#
-
# Depends on Mutex, but Mutex is only available as part of core since 1.9.1:
-
# exists - http://ruby-doc.org/core-1.9.1/Mutex.html
-
# dne - http://ruby-doc.org/core-1.9.0/Mutex.html
-
#
-
# @private
-
1
class ReentrantMutex
-
1
def initialize
-
@owner = nil
-
@count = 0
-
@mutex = Mutex.new
-
end
-
-
1
def synchronize
-
enter
-
yield
-
ensure
-
exit
-
end
-
-
1
private
-
-
1
def enter
-
@mutex.lock if @owner != Thread.current
-
@owner = Thread.current
-
@count += 1
-
end
-
-
1
def exit
-
@count -= 1
-
return unless @count == 0
-
@owner = nil
-
@mutex.unlock
-
end
-
end
-
-
1
if defined? ::Mutex
-
# On 1.9 and up, this is in core, so we just use the real one
-
1
Mutex = ::Mutex
-
else # For 1.8.7
-
skipped
# :nocov:
-
skipped
RSpec::Support.require_rspec_core "mutex"
-
skipped
# :nocov:
-
end
-
end
-
end
-
1
module RSpec::Core
-
# A reporter will send notifications to listeners, usually formatters for the
-
# spec suite run.
-
1
class Reporter
-
# @private
-
1
RSPEC_NOTIFICATIONS = Set.new(
-
[
-
:close, :deprecation, :deprecation_summary, :dump_failures, :dump_pending,
-
:dump_profile, :dump_summary, :example_failed, :example_group_finished,
-
:example_group_started, :example_passed, :example_pending, :example_started,
-
:message, :seed, :start, :start_dump, :stop
-
])
-
-
1
def initialize(configuration)
-
@configuration = configuration
-
@listeners = Hash.new { |h, k| h[k] = Set.new }
-
@examples = []
-
@failed_examples = []
-
@pending_examples = []
-
@duration = @start = @load_time = nil
-
end
-
-
# @private
-
1
attr_reader :examples, :failed_examples, :pending_examples
-
-
# @private
-
1
def reset
-
@examples = []
-
@failed_examples = []
-
@pending_examples = []
-
@profiler = Profiler.new if defined?(@profiler)
-
end
-
-
# @private
-
1
def setup_profiler
-
@profiler = Profiler.new
-
register_listener @profiler, *Profiler::NOTIFICATIONS
-
end
-
-
# Registers a listener to a list of notifications. The reporter will send
-
# notification of events to all registered listeners.
-
#
-
# @param listener [Object] An obect that wishes to be notified of reporter
-
# events
-
# @param notifications [Array] Array of symbols represents the events a
-
# listener wishes to subscribe too
-
1
def register_listener(listener, *notifications)
-
notifications.each do |notification|
-
@listeners[notification.to_sym] << listener
-
end
-
true
-
end
-
-
# @private
-
1
def registered_listeners(notification)
-
@listeners[notification].to_a
-
end
-
-
# @overload report(count, &block)
-
# @overload report(count, &block)
-
# @param expected_example_count [Integer] the number of examples being run
-
# @yield [Block] block yields itself for further reporting.
-
#
-
# Initializes the report run and yields itself for further reporting. The
-
# block is required, so that the reporter can manage cleaning up after the
-
# run.
-
#
-
# @example
-
#
-
# reporter.report(group.examples.size) do |r|
-
# example_groups.map {|g| g.run(r) }
-
# end
-
#
-
1
def report(expected_example_count)
-
start(expected_example_count)
-
begin
-
yield self
-
ensure
-
finish
-
end
-
end
-
-
# @private
-
1
def start(expected_example_count, time=RSpec::Core::Time.now)
-
@start = time
-
@load_time = (@start - @configuration.start_time).to_f
-
notify :seed, Notifications::SeedNotification.new(@configuration.seed, seed_used?)
-
notify :start, Notifications::StartNotification.new(expected_example_count, @load_time)
-
end
-
-
# @param message [#to_s] A message object to send to formatters
-
#
-
# Send a custom message to supporting formatters.
-
1
def message(message)
-
notify :message, Notifications::MessageNotification.new(message)
-
end
-
-
# @param event [Symbol] Name of the custom event to trigger on formatters
-
# @param options [Hash] Hash of arguments to provide via `CustomNotification`
-
#
-
# Publish a custom event to supporting registered formatters.
-
# @see RSpec::Core::Notifications::CustomNotification
-
1
def publish(event, options={})
-
if RSPEC_NOTIFICATIONS.include? event
-
raise "RSpec::Core::Reporter#publish is intended for sending custom " \
-
"events not internal RSpec ones, please rename your custom event."
-
end
-
notify event, Notifications::CustomNotification.for(options)
-
end
-
-
# @private
-
1
def example_group_started(group)
-
notify :example_group_started, Notifications::GroupNotification.new(group) unless group.descendant_filtered_examples.empty?
-
end
-
-
# @private
-
1
def example_group_finished(group)
-
notify :example_group_finished, Notifications::GroupNotification.new(group) unless group.descendant_filtered_examples.empty?
-
end
-
-
# @private
-
1
def example_started(example)
-
@examples << example
-
notify :example_started, Notifications::ExampleNotification.for(example)
-
end
-
-
# @private
-
1
def example_passed(example)
-
notify :example_passed, Notifications::ExampleNotification.for(example)
-
end
-
-
# @private
-
1
def example_failed(example)
-
@failed_examples << example
-
notify :example_failed, Notifications::ExampleNotification.for(example)
-
end
-
-
# @private
-
1
def example_pending(example)
-
@pending_examples << example
-
notify :example_pending, Notifications::ExampleNotification.for(example)
-
end
-
-
# @private
-
1
def deprecation(hash)
-
notify :deprecation, Notifications::DeprecationNotification.from_hash(hash)
-
end
-
-
# @private
-
1
def finish
-
close_after do
-
stop
-
notify :start_dump, Notifications::NullNotification
-
notify :dump_pending, Notifications::ExamplesNotification.new(self)
-
notify :dump_failures, Notifications::ExamplesNotification.new(self)
-
notify :deprecation_summary, Notifications::NullNotification
-
unless mute_profile_output?
-
notify :dump_profile, Notifications::ProfileNotification.new(@duration, @examples,
-
@configuration.profile_examples,
-
@profiler.example_groups)
-
end
-
notify :dump_summary, Notifications::SummaryNotification.new(@duration, @examples, @failed_examples,
-
@pending_examples, @load_time)
-
notify :seed, Notifications::SeedNotification.new(@configuration.seed, seed_used?)
-
end
-
end
-
-
# @private
-
1
def close_after
-
yield
-
ensure
-
close
-
end
-
-
# @private
-
1
def stop
-
@duration = (RSpec::Core::Time.now - @start).to_f if @start
-
notify :stop, Notifications::ExamplesNotification.new(self)
-
end
-
-
# @private
-
1
def notify(event, notification)
-
registered_listeners(event).each do |formatter|
-
formatter.__send__(event, notification)
-
end
-
end
-
-
# @private
-
1
def abort_with(msg, exit_status)
-
message(msg)
-
close
-
exit!(exit_status)
-
end
-
-
1
private
-
-
1
def close
-
notify :close, Notifications::NullNotification
-
end
-
-
1
def mute_profile_output?
-
# Don't print out profiled info if there are failures and `--fail-fast` is
-
# used, it just clutters the output.
-
!@configuration.profile_examples? || (@configuration.fail_fast? && @failed_examples.size > 0)
-
end
-
-
1
def seed_used?
-
@configuration.seed && @configuration.seed_used?
-
end
-
end
-
-
# @private
-
# # Used in place of a {Reporter} for situations where we don't want reporting output.
-
1
class NullReporter
-
1
def self.method_missing(*)
-
# ignore
-
end
-
1
private_class_method :method_missing
-
end
-
end
-
# This is borrowed (slightly modified) from Scott Taylor's
-
# project_path project:
-
# http://github.com/smtlaissezfaire/project_path
-
1
module RSpec
-
1
module Core
-
# @private
-
1
module RubyProject
-
1
def add_to_load_path(*dirs)
-
dirs.map { |dir| add_dir_to_load_path(File.join(root, dir)) }
-
end
-
-
1
def add_dir_to_load_path(dir)
-
$LOAD_PATH.unshift(dir) unless $LOAD_PATH.include?(dir)
-
end
-
-
1
def root
-
@project_root ||= determine_root
-
end
-
-
1
def determine_root
-
find_first_parent_containing('spec') || '.'
-
end
-
-
1
def find_first_parent_containing(dir)
-
ascend_until { |path| File.exist?(File.join(path, dir)) }
-
end
-
-
1
def ascend_until
-
fs = File::SEPARATOR
-
escaped_slash = "\\#{fs}"
-
special = "_RSPEC_ESCAPED_SLASH_"
-
project_path = File.expand_path(".")
-
parts = project_path.gsub(escaped_slash, special).squeeze(fs).split(fs).map do |x|
-
x.gsub(special, escaped_slash)
-
end
-
-
until parts.empty?
-
path = parts.join(fs)
-
path = fs if path == ""
-
return path if yield(path)
-
parts.pop
-
end
-
end
-
-
1
module_function :add_to_load_path
-
1
module_function :add_dir_to_load_path
-
1
module_function :root
-
1
module_function :determine_root
-
1
module_function :find_first_parent_containing
-
1
module_function :ascend_until
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Provides the main entry point to run a suite of RSpec examples.
-
1
class Runner
-
# Register an `at_exit` hook that runs the suite when the process exits.
-
#
-
# @note This is not generally needed. The `rspec` command takes care
-
# of running examples for you without involving an `at_exit`
-
# hook. This is only needed if you are running specs using
-
# the `ruby` command, and even then, the normal way to invoke
-
# this is by requiring `rspec/autorun`.
-
1
def self.autorun
-
if autorun_disabled?
-
RSpec.deprecate("Requiring `rspec/autorun` when running RSpec via the `rspec` command")
-
return
-
elsif installed_at_exit? || running_in_drb?
-
return
-
end
-
-
at_exit { perform_at_exit }
-
@installed_at_exit = true
-
end
-
-
# @private
-
1
def self.perform_at_exit
-
# Don't bother running any specs and just let the program terminate
-
# if we got here due to an unrescued exception (anything other than
-
# SystemExit, which is raised when somebody calls Kernel#exit).
-
return unless $!.nil? || $!.is_a?(SystemExit)
-
-
# We got here because either the end of the program was reached or
-
# somebody called Kernel#exit. Run the specs and then override any
-
# existing exit status with RSpec's exit status if any specs failed.
-
invoke
-
end
-
-
# Runs the suite of specs and exits the process with an appropriate exit
-
# code.
-
1
def self.invoke
-
disable_autorun!
-
status = run(ARGV, $stderr, $stdout).to_i
-
exit(status) if status != 0
-
end
-
-
# Run a suite of RSpec examples. Does not exit.
-
#
-
# This is used internally by RSpec to run a suite, but is available
-
# for use by any other automation tool.
-
#
-
# If you want to run this multiple times in the same process, and you
-
# want files like `spec_helper.rb` to be reloaded, be sure to load `load`
-
# instead of `require`.
-
#
-
# @param args [Array] command-line-supported arguments
-
# @param err [IO] error stream
-
# @param out [IO] output stream
-
# @return [Fixnum] exit status code. 0 if all specs passed,
-
# or the configured failure exit code (1 by default) if specs
-
# failed.
-
1
def self.run(args, err=$stderr, out=$stdout)
-
trap_interrupt
-
options = ConfigurationOptions.new(args)
-
-
if options.options[:drb]
-
require 'rspec/core/drb'
-
begin
-
DRbRunner.new(options).run(err, out)
-
rescue DRb::DRbConnError
-
err.puts "No DRb server is running. Running in local process instead ..."
-
new(options).run(err, out)
-
end
-
else
-
new(options).run(err, out)
-
end
-
end
-
-
1
def initialize(options, configuration=RSpec.configuration, world=RSpec.world)
-
@options = options
-
@configuration = configuration
-
@world = world
-
end
-
-
# Configures and runs a spec suite.
-
#
-
# @param err [IO] error stream
-
# @param out [IO] output stream
-
1
def run(err, out)
-
setup(err, out)
-
run_specs(@world.ordered_example_groups).tap do
-
persist_example_statuses
-
end
-
end
-
-
# Wires together the various configuration objects and state holders.
-
#
-
# @param err [IO] error stream
-
# @param out [IO] output stream
-
1
def setup(err, out)
-
@configuration.error_stream = err
-
@configuration.output_stream = out if @configuration.output_stream == $stdout
-
@options.configure(@configuration)
-
@configuration.load_spec_files
-
@world.announce_filters
-
end
-
-
# Runs the provided example groups.
-
#
-
# @param example_groups [Array<RSpec::Core::ExampleGroup>] groups to run
-
# @return [Fixnum] exit status code. 0 if all specs passed,
-
# or the configured failure exit code (1 by default) if specs
-
# failed.
-
1
def run_specs(example_groups)
-
@configuration.reporter.report(@world.example_count(example_groups)) do |reporter|
-
@configuration.with_suite_hooks do
-
example_groups.map { |g| g.run(reporter) }.all? ? 0 : @configuration.failure_exit_code
-
end
-
end
-
end
-
-
1
private
-
-
1
def persist_example_statuses
-
return unless (path = @configuration.example_status_persistence_file_path)
-
-
ExampleStatusPersister.persist(@world.all_examples, path)
-
rescue SystemCallError => e
-
RSpec.warning "Could not write example statuses to #{path} (configured as " \
-
"`config.example_status_persistence_file_path`) due to a " \
-
"system error: #{e.inspect}. Please check that the config " \
-
"option is set to an accessible, valid file path", :call_site => nil
-
end
-
-
# @private
-
1
def self.disable_autorun!
-
@autorun_disabled = true
-
end
-
-
# @private
-
1
def self.autorun_disabled?
-
@autorun_disabled ||= false
-
end
-
-
# @private
-
1
def self.installed_at_exit?
-
@installed_at_exit ||= false
-
end
-
-
# @private
-
# rubocop:disable Lint/EnsureReturn
-
1
def self.running_in_drb?
-
if defined?(DRb) && DRb.current_server
-
require 'socket'
-
require 'uri'
-
local_ipv4 = IPSocket.getaddress(Socket.gethostname)
-
local_drb = ["127.0.0.1", "localhost", local_ipv4].any? { |addr| addr == URI(DRb.current_server.uri).host }
-
end
-
rescue DRb::DRbServerNotFound
-
ensure
-
return local_drb || false
-
end
-
# rubocop:enable Lint/EnsureReturn
-
-
# @private
-
1
def self.trap_interrupt
-
trap('INT') { handle_interrupt }
-
end
-
-
# @private
-
1
def self.handle_interrupt
-
if RSpec.world.wants_to_quit
-
exit!(1)
-
else
-
RSpec.world.wants_to_quit = true
-
STDERR.puts "\nRSpec is shutting down and will print the summary report... Interrupt again to force quit."
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
#
-
# We use this to replace `::Set` so we can have the advantage of
-
# constant time key lookups for unique arrays but without the
-
# potential to pollute a developers environment with an extra
-
# piece of the stdlib. This helps to prevent false positive
-
# builds.
-
#
-
1
class Set
-
1
include Enumerable
-
-
1
def initialize(array=[])
-
14
@values = {}
-
14
merge(array)
-
end
-
-
1
def empty?
-
@values.empty?
-
end
-
-
1
def <<(key)
-
@values[key] = true
-
self
-
end
-
-
1
def delete(key)
-
@values.delete(key)
-
end
-
-
1
def each(&block)
-
@values.keys.each(&block)
-
self
-
end
-
-
1
def include?(key)
-
@values.key?(key)
-
end
-
-
1
def merge(values)
-
18
values.each do |key|
-
28
@values[key] = true
-
end
-
18
self
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Represents some functionality that is shared with multiple example groups.
-
# The functionality is defined by the provided block, which is lazily
-
# eval'd when the `SharedExampleGroupModule` instance is included in an example
-
# group.
-
1
class SharedExampleGroupModule < Module
-
1
def initialize(description, definition)
-
@description = description
-
@definition = definition
-
end
-
-
# Provides a human-readable representation of this module.
-
1
def inspect
-
"#<#{self.class.name} #{@description.inspect}>"
-
end
-
1
alias to_s inspect
-
-
# Ruby callback for when a module is included in another module is class.
-
# Our definition evaluates the shared group block in the context of the
-
# including example group.
-
1
def included(klass)
-
inclusion_line = klass.metadata[:location]
-
SharedExampleGroupInclusionStackFrame.with_frame(@description, inclusion_line) do
-
klass.class_exec(&@definition)
-
end
-
end
-
end
-
-
# Shared example groups let you define common context and/or common
-
# examples that you wish to use in multiple example groups.
-
#
-
# When defined, the shared group block is stored for later evaluation.
-
# It can later be included in an example group either explicitly
-
# (using `include_examples`, `include_context` or `it_behaves_like`)
-
# or implicitly (via matching metadata).
-
#
-
# Named shared example groups are scoped based on where they are
-
# defined. Shared groups defined in an example group are available
-
# for inclusion in that example group or any child example groups,
-
# but not in any parent or sibling example groups. Shared example
-
# groups defined at the top level can be included from any example group.
-
1
module SharedExampleGroup
-
# @overload shared_examples(name, &block)
-
# @param name [String, Symbol, Module] identifer to use when looking up
-
# this shared group
-
# @param block The block to be eval'd
-
# @overload shared_examples(name, metadata, &block)
-
# @param name [String, Symbol, Module] identifer to use when looking up
-
# this shared group
-
# @param metadata [Array<Symbol>, Hash] metadata to attach to this
-
# group; any example group or example with matching metadata will
-
# automatically include this shared example group.
-
# @param block The block to be eval'd
-
# @overload shared_examples(metadata, &block)
-
# @param metadata [Array<Symbol>, Hash] metadata to attach to this
-
# group; any example group or example with matching metadata will
-
# automatically include this shared example group.
-
# @param block The block to be eval'd
-
#
-
# Stores the block for later use. The block will be evaluated
-
# in the context of an example group via `include_examples`,
-
# `include_context`, or `it_behaves_like`.
-
#
-
# @example
-
# shared_examples "auditable" do
-
# it "stores an audit record on save!" do
-
# expect { auditable.save! }.to change(Audit, :count).by(1)
-
# end
-
# end
-
#
-
# describe Account do
-
# it_behaves_like "auditable" do
-
# let(:auditable) { Account.new }
-
# end
-
# end
-
#
-
# @see ExampleGroup.it_behaves_like
-
# @see ExampleGroup.include_examples
-
# @see ExampleGroup.include_context
-
1
def shared_examples(name, *args, &block)
-
top_level = self == ExampleGroup
-
if top_level && RSpec::Support.thread_local_data[:in_example_group]
-
raise "Creating isolated shared examples from within a context is " \
-
"not allowed. Remove `RSpec.` prefix or move this to a " \
-
"top-level scope."
-
end
-
-
RSpec.world.shared_example_group_registry.add(self, name, *args, &block)
-
end
-
1
alias shared_context shared_examples
-
1
alias shared_examples_for shared_examples
-
-
# @api private
-
#
-
# Shared examples top level DSL.
-
1
module TopLevelDSL
-
# @private
-
1
def self.definitions
-
2
proc do
-
3
def shared_examples(name, *args, &block)
-
RSpec.world.shared_example_group_registry.add(:main, name, *args, &block)
-
end
-
3
alias shared_context shared_examples
-
3
alias shared_examples_for shared_examples
-
end
-
end
-
-
# @private
-
1
def self.exposed_globally?
-
1
@exposed_globally ||= false
-
end
-
-
# @api private
-
#
-
# Adds the top level DSL methods to Module and the top level binding.
-
1
def self.expose_globally!
-
1
return if exposed_globally?
-
1
Core::DSL.change_global_dsl(&definitions)
-
1
@exposed_globally = true
-
end
-
-
# @api private
-
#
-
# Removes the top level DSL methods to Module and the top level binding.
-
1
def self.remove_globally!
-
return unless exposed_globally?
-
-
Core::DSL.change_global_dsl do
-
undef shared_examples
-
undef shared_context
-
undef shared_examples_for
-
end
-
-
@exposed_globally = false
-
end
-
end
-
-
# @private
-
1
class Registry
-
1
def add(context, name, *metadata_args, &block)
-
ensure_block_has_source_location(block) { CallerFilter.first_non_rspec_line }
-
-
if valid_name?(name)
-
warn_if_key_taken context, name, block
-
shared_example_groups[context][name] = block
-
else
-
metadata_args.unshift name
-
end
-
-
return if metadata_args.empty?
-
RSpec.configuration.include SharedExampleGroupModule.new(name, block), *metadata_args
-
end
-
-
1
def find(lookup_contexts, name)
-
lookup_contexts.each do |context|
-
found = shared_example_groups[context][name]
-
return found if found
-
end
-
-
shared_example_groups[:main][name]
-
end
-
-
1
private
-
-
1
def shared_example_groups
-
@shared_example_groups ||= Hash.new { |hash, context| hash[context] = {} }
-
end
-
-
1
def valid_name?(candidate)
-
case candidate
-
when String, Symbol, Module then true
-
else false
-
end
-
end
-
-
1
def warn_if_key_taken(context, key, new_block)
-
existing_block = shared_example_groups[context][key]
-
-
return unless existing_block
-
-
RSpec.warn_with <<-WARNING.gsub(/^ +\|/, ''), :call_site => nil
-
|WARNING: Shared example group '#{key}' has been previously defined at:
-
| #{formatted_location existing_block}
-
|...and you are now defining it at:
-
| #{formatted_location new_block}
-
|The new definition will overwrite the original one.
-
WARNING
-
end
-
-
1
def formatted_location(block)
-
block.source_location.join ":"
-
end
-
-
1
if Proc.method_defined?(:source_location)
-
1
def ensure_block_has_source_location(_block); end
-
else # for 1.8.7
-
skipped
# :nocov:
-
skipped
def ensure_block_has_source_location(block)
-
skipped
source_location = yield.split(':')
-
skipped
block.extend Module.new { define_method(:source_location) { source_location } }
-
skipped
end
-
skipped
# :nocov:
-
end
-
end
-
end
-
end
-
-
1
instance_exec(&Core::SharedExampleGroup::TopLevelDSL.definitions)
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
# Deals with the fact that `shellwords` only works on POSIX systems.
-
1
module ShellEscape
-
1
module_function
-
-
1
def quote(argument)
-
"'#{argument.gsub("'", "\\\\'")}'"
-
end
-
-
1
if RSpec::Support::OS.windows?
-
skipped
# :nocov:
-
skipped
alias escape quote
-
skipped
# :nocov:
-
else
-
1
require 'shellwords'
-
-
1
def escape(shell_command)
-
shell_command.shellescape
-
end
-
end
-
-
# Known shells that require quoting: zsh, csh, tcsh.
-
#
-
# Feel free to add other shells to this list that are known to
-
# allow `rspec ./some_spec.rb[1:1]` syntax without quoting the id.
-
#
-
# @private
-
1
SHELLS_ALLOWING_UNQUOTED_IDS = %w[ bash ksh fish ]
-
-
1
def conditionally_quote(id)
-
return id if shell_allows_unquoted_ids?
-
quote(id)
-
end
-
-
1
def shell_allows_unquoted_ids?
-
# Note: ENV['SHELL'] isn't necessarily the shell the user is currently running.
-
# According to http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html:
-
# "This variable shall represent a pathname of the user's preferred command language interpreter."
-
#
-
# It's the best we can easily do, though. We err on the side of safety (quoting
-
# the id when not actually needed) so it's not a big deal if the user is actually
-
# using a different shell.
-
SHELLS_ALLOWING_UNQUOTED_IDS.include?(ENV['SHELL'].to_s.split('/').last)
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Version information for RSpec Core.
-
1
module Version
-
# Current version of RSpec Core, in semantic versioning format.
-
1
STRING = '3.3.2'
-
end
-
end
-
end
-
1
require "rspec/support/warnings"
-
-
1
module RSpec
-
1
module Core
-
# @private
-
1
module Warnings
-
# @private
-
#
-
# Used internally to print deprecation warnings.
-
1
def deprecate(deprecated, data={})
-
RSpec.configuration.reporter.deprecation(
-
{
-
:deprecated => deprecated,
-
:call_site => CallerFilter.first_non_rspec_line
-
}.merge(data)
-
)
-
end
-
-
# @private
-
#
-
# Used internally to print deprecation warnings.
-
1
def warn_deprecation(message, opts={})
-
RSpec.configuration.reporter.deprecation opts.merge(:message => message)
-
end
-
-
# @private
-
1
def warn_with(message, options={})
-
if options[:use_spec_location_as_call_site]
-
message += "." unless message.end_with?(".")
-
-
if RSpec.current_example
-
message += " Warning generated from spec at `#{RSpec.current_example.location}`."
-
end
-
end
-
-
super(message, options)
-
end
-
end
-
end
-
end
-
1
require 'rspec/support'
-
1
RSpec::Support.require_rspec_support "caller_filter"
-
1
RSpec::Support.require_rspec_support "warnings"
-
1
RSpec::Support.require_rspec_support "object_formatter"
-
-
1
require 'rspec/matchers'
-
-
7
RSpec::Support.define_optimized_require_for_rspec(:expectations) { |f| require_relative(f) }
-
-
%w[
-
expectation_target
-
configuration
-
fail_with
-
handler
-
version
-
6
].each { |file| RSpec::Support.require_rspec_expectations(file) }
-
-
1
module RSpec
-
# RSpec::Expectations provides a simple, readable API to express
-
# the expected outcomes in a code example. To express an expected
-
# outcome, wrap an object or block in `expect`, call `to` or `to_not`
-
# (aliased as `not_to`) and pass it a matcher object:
-
#
-
# expect(order.total).to eq(Money.new(5.55, :USD))
-
# expect(list).to include(user)
-
# expect(message).not_to match(/foo/)
-
# expect { do_something }.to raise_error
-
#
-
# The last form (the block form) is needed to match against ruby constructs
-
# that are not objects, but can only be observed when executing a block
-
# of code. This includes raising errors, throwing symbols, yielding,
-
# and changing values.
-
#
-
# When `expect(...).to` is invoked with a matcher, it turns around
-
# and calls `matcher.matches?(<object wrapped by expect>)`. For example,
-
# in the expression:
-
#
-
# expect(order.total).to eq(Money.new(5.55, :USD))
-
#
-
# ...`eq(Money.new(5.55, :USD))` returns a matcher object, and it results
-
# in the equivalent of `eq.matches?(order.total)`. If `matches?` returns
-
# `true`, the expectation is met and execution continues. If `false`, then
-
# the spec fails with the message returned by `eq.failure_message`.
-
#
-
# Given the expression:
-
#
-
# expect(order.entries).not_to include(entry)
-
#
-
# ...the `not_to` method (also available as `to_not`) invokes the equivalent of
-
# `include.matches?(order.entries)`, but it interprets `false` as success, and
-
# `true` as a failure, using the message generated by
-
# `include.failure_message_when_negated`.
-
#
-
# rspec-expectations ships with a standard set of useful matchers, and writing
-
# your own matchers is quite simple.
-
#
-
# See [RSpec::Matchers](../RSpec/Matchers) for more information about the
-
# built-in matchers that ship with rspec-expectations, and how to write your
-
# own custom matchers.
-
1
module Expectations
-
# Exception raised when an expectation fails.
-
#
-
# @note We subclass Exception so that in a stub implementation if
-
# the user sets an expectation, it can't be caught in their
-
# code by a bare `rescue`.
-
# @api public
-
1
class ExpectationNotMetError < Exception
-
end
-
-
# Exception raised from `aggregate_failures` when multiple expectations fail.
-
#
-
# @note The constant is defined here but the extensive logic of this class
-
# is lazily defined when `FailureAggregator` is autoloaded, since we do
-
# not need to waste time defining that functionality unless
-
# `aggregate_failures` is used.
-
1
class MultipleExpectationsNotMetError < ExpectationNotMetError
-
end
-
-
1
autoload :FailureAggregator, "rspec/expectations/failure_aggregator"
-
end
-
end
-
1
module RSpec
-
1
module Expectations
-
# Wraps the target of an expectation.
-
#
-
# @example
-
# expect(something) # => ExpectationTarget wrapping something
-
# expect { do_something } # => ExpectationTarget wrapping the block
-
#
-
# # used with `to`
-
# expect(actual).to eq(3)
-
#
-
# # with `not_to`
-
# expect(actual).not_to eq(3)
-
#
-
# @note `ExpectationTarget` is not intended to be instantiated
-
# directly by users. Use `expect` instead.
-
1
class ExpectationTarget
-
# @private
-
# Used as a sentinel value to be able to tell when the user
-
# did not pass an argument. We can't use `nil` for that because
-
# `nil` is a valid value to pass.
-
1
UndefinedValue = Module.new
-
-
# @api private
-
1
def initialize(value)
-
@target = value
-
end
-
-
# @private
-
1
def self.for(value, block)
-
if UndefinedValue.equal?(value)
-
unless block
-
raise ArgumentError, "You must pass either an argument or a block to `expect`."
-
end
-
BlockExpectationTarget.new(block)
-
elsif block
-
raise ArgumentError, "You cannot pass both an argument and a block to `expect`."
-
else
-
new(value)
-
end
-
end
-
-
# Runs the given expectation, passing if `matcher` returns true.
-
# @example
-
# expect(value).to eq(5)
-
# expect { perform }.to raise_error
-
# @param [Matcher]
-
# matcher
-
# @param [String or Proc] message optional message to display when the expectation fails
-
# @return [Boolean] true if the expectation succeeds (else raises)
-
# @see RSpec::Matchers
-
1
def to(matcher=nil, message=nil, &block)
-
prevent_operator_matchers(:to) unless matcher
-
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(@target, matcher, message, &block)
-
end
-
-
# Runs the given expectation, passing if `matcher` returns false.
-
# @example
-
# expect(value).not_to eq(5)
-
# @param [Matcher]
-
# matcher
-
# @param [String or Proc] message optional message to display when the expectation fails
-
# @return [Boolean] false if the negative expectation succeeds (else raises)
-
# @see RSpec::Matchers
-
1
def not_to(matcher=nil, message=nil, &block)
-
prevent_operator_matchers(:not_to) unless matcher
-
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(@target, matcher, message, &block)
-
end
-
1
alias to_not not_to
-
-
1
private
-
-
1
def prevent_operator_matchers(verb)
-
raise ArgumentError, "The expect syntax does not support operator matchers, " \
-
"so you must pass a matcher to `##{verb}`."
-
end
-
end
-
-
# @private
-
# Validates the provided matcher to ensure it supports block
-
# expectations, in order to avoid user confusion when they
-
# use a block thinking the expectation will be on the return
-
# value of the block rather than the block itself.
-
1
class BlockExpectationTarget < ExpectationTarget
-
1
def to(matcher, message=nil, &block)
-
enforce_block_expectation(matcher)
-
super
-
end
-
-
1
def not_to(matcher, message=nil, &block)
-
enforce_block_expectation(matcher)
-
super
-
end
-
1
alias to_not not_to
-
-
1
private
-
-
1
def enforce_block_expectation(matcher)
-
return if supports_block_expectations?(matcher)
-
-
raise ExpectationNotMetError, "You must pass an argument rather than a block to use the provided " \
-
"matcher (#{RSpec::Support::ObjectFormatter.format(matcher)}), or the matcher must implement " \
-
"`supports_block_expectations?`."
-
end
-
-
1
def supports_block_expectations?(matcher)
-
matcher.supports_block_expectations?
-
rescue NoMethodError
-
false
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Expectations
-
1
class << self
-
# @private
-
1
def differ
-
RSpec::Support::Differ.new(
-
:object_preparer => lambda { |object| RSpec::Matchers::Composable.surface_descriptions_in(object) },
-
:color => RSpec::Matchers.configuration.color?
-
)
-
end
-
-
# Raises an RSpec::Expectations::ExpectationNotMetError with message.
-
# @param [String] message
-
# @param [Object] expected
-
# @param [Object] actual
-
#
-
# Adds a diff to the failure message when `expected` and `actual` are
-
# both present.
-
1
def fail_with(message, expected=nil, actual=nil)
-
unless message
-
raise ArgumentError, "Failure message is nil. Does your matcher define the " \
-
"appropriate failure_message[_when_negated] method to return a string?"
-
end
-
-
message = ::RSpec::Matchers::ExpectedsForMultipleDiffs.from(expected).message_with_diff(message, differ, actual)
-
-
RSpec::Support.notify_failure(RSpec::Expectations::ExpectationNotMetError.new message)
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Expectations
-
# @private
-
1
module ExpectationHelper
-
1
def self.check_message(msg)
-
18
unless msg.nil? || msg.respond_to?(:to_str) || msg.respond_to?(:call)
-
::Kernel.warn [
-
"WARNING: ignoring the provided expectation message argument (",
-
msg.inspect,
-
") since it is not a string or a proc."
-
].join
-
end
-
end
-
-
# Returns an RSpec-3+ compatible matcher, wrapping a legacy one
-
# in an adapter if necessary.
-
#
-
# @private
-
1
def self.modern_matcher_from(matcher)
-
LegacyMatcherAdapter::RSpec2.wrap(matcher) ||
-
18
LegacyMatcherAdapter::RSpec1.wrap(matcher) || matcher
-
end
-
-
1
def self.with_matcher(handler, matcher, message)
-
18
check_message(message)
-
18
matcher = modern_matcher_from(matcher)
-
18
yield matcher
-
ensure
-
18
::RSpec::Matchers.last_expectation_handler = handler
-
18
::RSpec::Matchers.last_matcher = matcher
-
end
-
-
1
def self.handle_failure(matcher, message, failure_message_method)
-
message = message.call if message.respond_to?(:call)
-
message ||= matcher.__send__(failure_message_method)
-
-
if matcher.respond_to?(:diffable?) && matcher.diffable?
-
::RSpec::Expectations.fail_with message, matcher.expected, matcher.actual
-
else
-
::RSpec::Expectations.fail_with message
-
end
-
end
-
end
-
-
# @private
-
1
class PositiveExpectationHandler
-
1
def self.handle_matcher(actual, initial_matcher, message=nil, &block)
-
18
ExpectationHelper.with_matcher(self, initial_matcher, message) do |matcher|
-
18
return ::RSpec::Matchers::BuiltIn::PositiveOperatorMatcher.new(actual) unless initial_matcher
-
14
matcher.matches?(actual, &block) || ExpectationHelper.handle_failure(matcher, message, :failure_message)
-
end
-
end
-
-
1
def self.verb
-
"should"
-
end
-
-
1
def self.should_method
-
:should
-
end
-
-
1
def self.opposite_should_method
-
:should_not
-
end
-
end
-
-
# @private
-
1
class NegativeExpectationHandler
-
1
def self.handle_matcher(actual, initial_matcher, message=nil, &block)
-
ExpectationHelper.with_matcher(self, initial_matcher, message) do |matcher|
-
return ::RSpec::Matchers::BuiltIn::NegativeOperatorMatcher.new(actual) unless initial_matcher
-
!(does_not_match?(matcher, actual, &block) || ExpectationHelper.handle_failure(matcher, message, :failure_message_when_negated))
-
end
-
end
-
-
1
def self.does_not_match?(matcher, actual, &block)
-
if matcher.respond_to?(:does_not_match?)
-
matcher.does_not_match?(actual, &block)
-
else
-
!matcher.matches?(actual, &block)
-
end
-
end
-
-
1
def self.verb
-
"should not"
-
end
-
-
1
def self.should_method
-
:should_not
-
end
-
-
1
def self.opposite_should_method
-
:should
-
end
-
end
-
-
# Wraps a matcher written against one of the legacy protocols in
-
# order to present the current protocol.
-
#
-
# @private
-
1
class LegacyMatcherAdapter < Matchers::MatcherDelegator
-
1
def initialize(matcher)
-
super
-
::RSpec.warn_deprecation(<<-EOS.gsub(/^\s+\|/, ''), :type => "legacy_matcher")
-
|#{matcher.class.name || matcher.inspect} implements a legacy RSpec matcher
-
|protocol. For the current protocol you should expose the failure messages
-
|via the `failure_message` and `failure_message_when_negated` methods.
-
|(Used from #{CallerFilter.first_non_rspec_line})
-
EOS
-
end
-
-
1
def self.wrap(matcher)
-
36
new(matcher) if interface_matches?(matcher)
-
end
-
-
# Starting in RSpec 1.2 (and continuing through all 2.x releases),
-
# the failure message protocol was:
-
# * `failure_message_for_should`
-
# * `failure_message_for_should_not`
-
# @private
-
1
class RSpec2 < self
-
1
def failure_message
-
base_matcher.failure_message_for_should
-
end
-
-
1
def failure_message_when_negated
-
base_matcher.failure_message_for_should_not
-
end
-
-
1
def self.interface_matches?(matcher)
-
(
-
!matcher.respond_to?(:failure_message) &&
-
18
matcher.respond_to?(:failure_message_for_should)
-
) || (
-
!matcher.respond_to?(:failure_message_when_negated) &&
-
18
matcher.respond_to?(:failure_message_for_should_not)
-
18
)
-
end
-
end
-
-
# Before RSpec 1.2, the failure message protocol was:
-
# * `failure_message`
-
# * `negative_failure_message`
-
# @private
-
1
class RSpec1 < self
-
1
def failure_message
-
base_matcher.failure_message
-
end
-
-
1
def failure_message_when_negated
-
base_matcher.negative_failure_message
-
end
-
-
# Note: `failure_message` is part of the RSpec 3 protocol
-
# (paired with `failure_message_when_negated`), so we don't check
-
# for `failure_message` here.
-
1
def self.interface_matches?(matcher)
-
!matcher.respond_to?(:failure_message_when_negated) &&
-
18
matcher.respond_to?(:negative_failure_message)
-
end
-
end
-
end
-
-
# RSpec 3.0 was released with the class name misspelled. For SemVer compatibility,
-
# we will provide this misspelled alias until 4.0.
-
# @deprecated Use LegacyMatcherAdapter instead.
-
# @private
-
1
LegacyMacherAdapter = LegacyMatcherAdapter
-
end
-
end
-
1
module RSpec
-
1
module Expectations
-
# @api private
-
# Provides methods for enabling and disabling the available
-
# syntaxes provided by rspec-expectations.
-
1
module Syntax
-
1
module_function
-
-
# @api private
-
# Determines where we add `should` and `should_not`.
-
1
def default_should_host
-
4
@default_should_host ||= ::Object.ancestors.last
-
end
-
-
# @api private
-
# Instructs rspec-expectations to warn on first usage of `should` or `should_not`.
-
# Enabled by default. This is largely here to facilitate testing.
-
1
def warn_about_should!
-
1
@warn_about_should = true
-
end
-
-
# @api private
-
# Generates a deprecation warning for the given method if no warning
-
# has already been issued.
-
1
def warn_about_should_unless_configured(method_name)
-
18
return unless @warn_about_should
-
-
RSpec.deprecate(
-
"Using `#{method_name}` from rspec-expectations' old `:should` syntax without explicitly enabling the syntax",
-
:replacement => "the new `:expect` syntax or explicitly enable `:should` with `config.expect_with(:rspec) { |c| c.syntax = :should }`"
-
)
-
-
@warn_about_should = false
-
end
-
-
# @api private
-
# Enables the `should` syntax.
-
1
def enable_should(syntax_host=default_should_host)
-
2
@warn_about_should = false if syntax_host == default_should_host
-
2
return if should_enabled?(syntax_host)
-
-
1
syntax_host.module_exec do
-
1
def should(matcher=nil, message=nil, &block)
-
18
::RSpec::Expectations::Syntax.warn_about_should_unless_configured(__method__)
-
18
::RSpec::Expectations::PositiveExpectationHandler.handle_matcher(self, matcher, message, &block)
-
end
-
-
1
def should_not(matcher=nil, message=nil, &block)
-
::RSpec::Expectations::Syntax.warn_about_should_unless_configured(__method__)
-
::RSpec::Expectations::NegativeExpectationHandler.handle_matcher(self, matcher, message, &block)
-
end
-
end
-
end
-
-
# @api private
-
# Disables the `should` syntax.
-
1
def disable_should(syntax_host=default_should_host)
-
return unless should_enabled?(syntax_host)
-
-
syntax_host.module_exec do
-
undef should
-
undef should_not
-
end
-
end
-
-
# @api private
-
# Enables the `expect` syntax.
-
1
def enable_expect(syntax_host=::RSpec::Matchers)
-
2
return if expect_enabled?(syntax_host)
-
-
1
syntax_host.module_exec do
-
1
def expect(value=::RSpec::Expectations::ExpectationTarget::UndefinedValue, &block)
-
::RSpec::Expectations::ExpectationTarget.for(value, block)
-
end
-
end
-
end
-
-
# @api private
-
# Disables the `expect` syntax.
-
1
def disable_expect(syntax_host=::RSpec::Matchers)
-
return unless expect_enabled?(syntax_host)
-
-
syntax_host.module_exec do
-
undef expect
-
end
-
end
-
-
# @api private
-
# Indicates whether or not the `should` syntax is enabled.
-
1
def should_enabled?(syntax_host=default_should_host)
-
2
syntax_host.method_defined?(:should)
-
end
-
-
# @api private
-
# Indicates whether or not the `expect` syntax is enabled.
-
1
def expect_enabled?(syntax_host=::RSpec::Matchers)
-
2
syntax_host.method_defined?(:expect)
-
end
-
end
-
end
-
end
-
-
1
if defined?(BasicObject)
-
# The legacy `:should` syntax adds the following methods directly to
-
# `BasicObject` so that they are available off of any object. Note, however,
-
# that this syntax does not always play nice with delegate/proxy objects.
-
# We recommend you use the non-monkeypatching `:expect` syntax instead.
-
1
class BasicObject
-
# @method should
-
# Passes if `matcher` returns true. Available on every `Object`.
-
# @example
-
# actual.should eq expected
-
# actual.should match /expression/
-
# @param [Matcher]
-
# matcher
-
# @param [String] message optional message to display when the expectation fails
-
# @return [Boolean] true if the expectation succeeds (else raises)
-
# @note This is only available when you have enabled the `:should` syntax.
-
# @see RSpec::Matchers
-
-
# @method should_not
-
# Passes if `matcher` returns false. Available on every `Object`.
-
# @example
-
# actual.should_not eq expected
-
# @param [Matcher]
-
# matcher
-
# @param [String] message optional message to display when the expectation fails
-
# @return [Boolean] false if the negative expectation succeeds (else raises)
-
# @note This is only available when you have enabled the `:should` syntax.
-
# @see RSpec::Matchers
-
end
-
end
-
1
module RSpec
-
1
module Expectations
-
# @private
-
1
module Version
-
1
STRING = '3.3.1'
-
end
-
end
-
end
-
1
require 'rspec/support'
-
1
RSpec::Support.require_rspec_support 'matcher_definition'
-
10
RSpec::Support.define_optimized_require_for_rspec(:matchers) { |f| require_relative(f) }
-
-
%w[
-
english_phrasing
-
composable
-
built_in
-
generated_descriptions
-
dsl
-
matcher_delegator
-
aliased_matcher
-
expecteds_for_multiple_diffs
-
9
].each { |file| RSpec::Support.require_rspec_matchers(file) }
-
-
# RSpec's top level namespace. All of rspec-expectations is contained
-
# in the `RSpec::Expectations` and `RSpec::Matchers` namespaces.
-
1
module RSpec
-
# RSpec::Matchers provides a number of useful matchers we use to define
-
# expectations. Any object that implements the [matcher protocol](Matchers/MatcherProtocol)
-
# can be used as a matcher.
-
#
-
# ## Predicates
-
#
-
# In addition to matchers that are defined explicitly, RSpec will create
-
# custom matchers on the fly for any arbitrary predicate, giving your specs a
-
# much more natural language feel.
-
#
-
# A Ruby predicate is a method that ends with a "?" and returns true or false.
-
# Common examples are `empty?`, `nil?`, and `instance_of?`.
-
#
-
# All you need to do is write `expect(..).to be_` followed by the predicate
-
# without the question mark, and RSpec will figure it out from there.
-
# For example:
-
#
-
# expect([]).to be_empty # => [].empty?() | passes
-
# expect([]).not_to be_empty # => [].empty?() | fails
-
#
-
# In addtion to prefixing the predicate matchers with "be_", you can also use "be_a_"
-
# and "be_an_", making your specs read much more naturally:
-
#
-
# expect("a string").to be_an_instance_of(String) # =>"a string".instance_of?(String) # passes
-
#
-
# expect(3).to be_a_kind_of(Fixnum) # => 3.kind_of?(Numeric) | passes
-
# expect(3).to be_a_kind_of(Numeric) # => 3.kind_of?(Numeric) | passes
-
# expect(3).to be_an_instance_of(Fixnum) # => 3.instance_of?(Fixnum) | passes
-
# expect(3).not_to be_an_instance_of(Numeric) # => 3.instance_of?(Numeric) | fails
-
#
-
# RSpec will also create custom matchers for predicates like `has_key?`. To
-
# use this feature, just state that the object should have_key(:key) and RSpec will
-
# call has_key?(:key) on the target. For example:
-
#
-
# expect(:a => "A").to have_key(:a)
-
# expect(:a => "A").to have_key(:b) # fails
-
#
-
# You can use this feature to invoke any predicate that begins with "has_", whether it is
-
# part of the Ruby libraries (like `Hash#has_key?`) or a method you wrote on your own class.
-
#
-
# Note that RSpec does not provide composable aliases for these dynamic predicate
-
# matchers. You can easily define your own aliases, though:
-
#
-
# RSpec::Matchers.alias_matcher :a_user_who_is_an_admin, :be_an_admin
-
# expect(user_list).to include(a_user_who_is_an_admin)
-
#
-
# ## Custom Matchers
-
#
-
# When you find that none of the stock matchers provide a natural feeling
-
# expectation, you can very easily write your own using RSpec's matcher DSL
-
# or writing one from scratch.
-
#
-
# ### Matcher DSL
-
#
-
# Imagine that you are writing a game in which players can be in various
-
# zones on a virtual board. To specify that bob should be in zone 4, you
-
# could say:
-
#
-
# expect(bob.current_zone).to eql(Zone.new("4"))
-
#
-
# But you might find it more expressive to say:
-
#
-
# expect(bob).to be_in_zone("4")
-
#
-
# and/or
-
#
-
# expect(bob).not_to be_in_zone("3")
-
#
-
# You can create such a matcher like so:
-
#
-
# RSpec::Matchers.define :be_in_zone do |zone|
-
# match do |player|
-
# player.in_zone?(zone)
-
# end
-
# end
-
#
-
# This will generate a <tt>be_in_zone</tt> method that returns a matcher
-
# with logical default messages for failures. You can override the failure
-
# messages and the generated description as follows:
-
#
-
# RSpec::Matchers.define :be_in_zone do |zone|
-
# match do |player|
-
# player.in_zone?(zone)
-
# end
-
#
-
# failure_message do |player|
-
# # generate and return the appropriate string.
-
# end
-
#
-
# failure_message_when_negated do |player|
-
# # generate and return the appropriate string.
-
# end
-
#
-
# description do
-
# # generate and return the appropriate string.
-
# end
-
# end
-
#
-
# Each of the message-generation methods has access to the block arguments
-
# passed to the <tt>create</tt> method (in this case, <tt>zone</tt>). The
-
# failure message methods (<tt>failure_message</tt> and
-
# <tt>failure_message_when_negated</tt>) are passed the actual value (the
-
# receiver of <tt>expect(..)</tt> or <tt>expect(..).not_to</tt>).
-
#
-
# ### Custom Matcher from scratch
-
#
-
# You could also write a custom matcher from scratch, as follows:
-
#
-
# class BeInZone
-
# def initialize(expected)
-
# @expected = expected
-
# end
-
#
-
# def matches?(target)
-
# @target = target
-
# @target.current_zone.eql?(Zone.new(@expected))
-
# end
-
#
-
# def failure_message
-
# "expected #{@target.inspect} to be in Zone #{@expected}"
-
# end
-
#
-
# def failure_message_when_negated
-
# "expected #{@target.inspect} not to be in Zone #{@expected}"
-
# end
-
# end
-
#
-
# ... and a method like this:
-
#
-
# def be_in_zone(expected)
-
# BeInZone.new(expected)
-
# end
-
#
-
# And then expose the method to your specs. This is normally done
-
# by including the method and the class in a module, which is then
-
# included in your spec:
-
#
-
# module CustomGameMatchers
-
# class BeInZone
-
# # ...
-
# end
-
#
-
# def be_in_zone(expected)
-
# # ...
-
# end
-
# end
-
#
-
# describe "Player behaviour" do
-
# include CustomGameMatchers
-
# # ...
-
# end
-
#
-
# or you can include in globally in a spec_helper.rb file <tt>require</tt>d
-
# from your spec file(s):
-
#
-
# RSpec::configure do |config|
-
# config.include(CustomGameMatchers)
-
# end
-
#
-
# ### Making custom matchers composable
-
#
-
# RSpec's built-in matchers are designed to be composed, in expressions like:
-
#
-
# expect(["barn", 2.45]).to contain_exactly(
-
# a_value_within(0.1).of(2.5),
-
# a_string_starting_with("bar")
-
# )
-
#
-
# Custom matchers can easily participate in composed matcher expressions like these.
-
# Include {RSpec::Matchers::Composable} in your custom matcher to make it support
-
# being composed (matchers defined using the DSL have this included automatically).
-
# Within your matcher's `matches?` method (or the `match` block, if using the DSL),
-
# use `values_match?(expected, actual)` rather than `expected == actual`.
-
# Under the covers, `values_match?` is able to match arbitrary
-
# nested data structures containing a mix of both matchers and non-matcher objects.
-
# It uses `===` and `==` to perform the matching, considering the values to
-
# match if either returns `true`. The `Composable` mixin also provides some helper
-
# methods for surfacing the matcher descriptions within your matcher's description
-
# or failure messages.
-
#
-
# RSpec's built-in matchers each have a number of aliases that rephrase the matcher
-
# from a verb phrase (such as `be_within`) to a noun phrase (such as `a_value_within`),
-
# which reads better when the matcher is passed as an argument in a composed matcher
-
# expressions, and also uses the noun-phrase wording in the matcher's `description`,
-
# for readable failure messages. You can alias your custom matchers in similar fashion
-
# using {RSpec::Matchers.alias_matcher}.
-
1
module Matchers
-
# @method expect
-
# Supports `expect(actual).to matcher` syntax by wrapping `actual` in an
-
# `ExpectationTarget`.
-
# @example
-
# expect(actual).to eq(expected)
-
# expect(actual).not_to eq(expected)
-
# @return [ExpectationTarget]
-
# @see ExpectationTarget#to
-
# @see ExpectationTarget#not_to
-
-
# Defines a matcher alias. The returned matcher's `description` will be overriden
-
# to reflect the phrasing of the new name, which will be used in failure messages
-
# when passed as an argument to another matcher in a composed matcher expression.
-
#
-
# @param new_name [Symbol] the new name for the matcher
-
# @param old_name [Symbol] the original name for the matcher
-
# @param options [Hash] options for the aliased matcher
-
# @option options [Class] :klass the ruby class to use as the decorator. (Not normally used).
-
# @yield [String] optional block that, when given, is used to define the overriden
-
# logic. The yielded arg is the original description or failure message. If no
-
# block is provided, a default override is used based on the old and new names.
-
#
-
# @example
-
# RSpec::Matchers.alias_matcher :a_list_that_sums_to, :sum_to
-
# sum_to(3).description # => "sum to 3"
-
# a_list_that_sums_to(3).description # => "a list that sums to 3"
-
#
-
# @example
-
# RSpec::Matchers.alias_matcher :a_list_sorted_by, :be_sorted_by do |description|
-
# description.sub("be sorted by", "a list sorted by")
-
# end
-
#
-
# be_sorted_by(:age).description # => "be sorted by age"
-
# a_list_sorted_by(:age).description # => "a list sorted by age"
-
#
-
# @!macro [attach] alias_matcher
-
# @!parse
-
# alias $1 $2
-
1
def self.alias_matcher(new_name, old_name, options={}, &description_override)
-
description_override ||= lambda do |old_desc|
-
old_desc.gsub(EnglishPhrasing.split_words(old_name), EnglishPhrasing.split_words(new_name))
-
57
end
-
113
klass = options.fetch(:klass) { AliasedMatcher }
-
-
57
define_method(new_name) do |*args, &block|
-
matcher = __send__(old_name, *args, &block)
-
klass.new(matcher, description_override)
-
end
-
end
-
-
# Defines a negated matcher. The returned matcher's `description` and `failure_message`
-
# will be overriden to reflect the phrasing of the new name, and the match logic will
-
# be based on the original matcher but negated.
-
#
-
# @param negated_name [Symbol] the name for the negated matcher
-
# @param base_name [Symbol] the name of the original matcher that will be negated
-
# @yield [String] optional block that, when given, is used to define the overriden
-
# logic. The yielded arg is the original description or failure message. If no
-
# block is provided, a default override is used based on the old and new names.
-
#
-
# @example
-
# RSpec::Matchers.define_negated_matcher :exclude, :include
-
# include(1, 2).description # => "include 1 and 2"
-
# exclude(1, 2).description # => "exclude 1 and 2"
-
#
-
# @note While the most obvious negated form may be to add a `not_` prefix,
-
# the failure messages you get with that form can be confusing (e.g.
-
# "expected [actual] to not [verb], but did not"). We've found it works
-
# best to find a more positive name for the negated form, such as
-
# `avoid_changing` rather than `not_change`.
-
1
def self.define_negated_matcher(negated_name, base_name, &description_override)
-
alias_matcher(negated_name, base_name, :klass => AliasedNegatedMatcher, &description_override)
-
end
-
-
# Allows multiple expectations in the provided block to fail, and then
-
# aggregates them into a single exception, rather than aborting on the
-
# first expectation failure like normal. This allows you to see all
-
# failures from an entire set of expectations without splitting each
-
# off into its own example (which may slow things down if the example
-
# setup is expensive).
-
#
-
# @param label [String] label for this aggregation block, which will be
-
# included in the aggregated exception message.
-
# @param metadata [Hash] additional metadata about this failure aggregation
-
# block. If multiple expectations fail, it will be exposed from the
-
# {Expectations::MultipleExpectationsNotMetError} exception. Mostly
-
# intended for internal RSpec use but you can use it as well.
-
# @yield Block containing as many expectation as you want. The block is
-
# simply yielded to, so you can trust that anything that works outside
-
# the block should work within it.
-
# @raise [Expectations::MultipleExpectationsNotMetError] raised when
-
# multiple expectations fail.
-
# @raise [Expectations::ExpectationNotMetError] raised when a single
-
# expectation fails.
-
# @raise [Exception] other sorts of exceptions will be raised as normal.
-
#
-
# @example
-
# aggregate_failures("verifying response") do
-
# expect(response.status).to eq(200)
-
# expect(response.headers).to include("Content-Type" => "text/plain")
-
# expect(response.body).to include("Success")
-
# end
-
#
-
# @note The implementation of this feature uses a thread-local variable,
-
# which means that if you have an expectation failure in another thread,
-
# it'll abort like normal.
-
1
def aggregate_failures(label=nil, metadata={}, &block)
-
Expectations::FailureAggregator.new(label, metadata).aggregate(&block)
-
end
-
-
# Passes if actual is truthy (anything but false or nil)
-
1
def be_truthy
-
BuiltIn::BeTruthy.new
-
end
-
1
alias_matcher :a_truthy_value, :be_truthy
-
-
# Passes if actual is falsey (false or nil)
-
1
def be_falsey
-
BuiltIn::BeFalsey.new
-
end
-
1
alias_matcher :be_falsy, :be_falsey
-
1
alias_matcher :a_falsey_value, :be_falsey
-
1
alias_matcher :a_falsy_value, :be_falsey
-
-
# Passes if actual is nil
-
1
def be_nil
-
BuiltIn::BeNil.new
-
end
-
1
alias_matcher :a_nil_value, :be_nil
-
-
# @example
-
# expect(actual).to be_truthy
-
# expect(actual).to be_falsey
-
# expect(actual).to be_nil
-
# expect(actual).to be_[arbitrary_predicate](*args)
-
# expect(actual).not_to be_nil
-
# expect(actual).not_to be_[arbitrary_predicate](*args)
-
#
-
# Given true, false, or nil, will pass if actual value is true, false or
-
# nil (respectively). Given no args means the caller should satisfy an if
-
# condition (to be or not to be).
-
#
-
# Predicates are any Ruby method that ends in a "?" and returns true or
-
# false. Given be_ followed by arbitrary_predicate (without the "?"),
-
# RSpec will match convert that into a query against the target object.
-
#
-
# The arbitrary_predicate feature will handle any predicate prefixed with
-
# "be_an_" (e.g. be_an_instance_of), "be_a_" (e.g. be_a_kind_of) or "be_"
-
# (e.g. be_empty), letting you choose the prefix that best suits the
-
# predicate.
-
1
def be(*args)
-
args.empty? ? Matchers::BuiltIn::Be.new : equal(*args)
-
end
-
1
alias_matcher :a_value, :be, :klass => AliasedMatcherWithOperatorSupport
-
-
# passes if target.kind_of?(klass)
-
1
def be_a(klass)
-
be_a_kind_of(klass)
-
end
-
1
alias_method :be_an, :be_a
-
-
# Passes if actual.instance_of?(expected)
-
#
-
# @example
-
# expect(5).to be_an_instance_of(Fixnum)
-
# expect(5).not_to be_an_instance_of(Numeric)
-
# expect(5).not_to be_an_instance_of(Float)
-
1
def be_an_instance_of(expected)
-
BuiltIn::BeAnInstanceOf.new(expected)
-
end
-
1
alias_method :be_instance_of, :be_an_instance_of
-
1
alias_matcher :an_instance_of, :be_an_instance_of
-
-
# Passes if actual.kind_of?(expected)
-
#
-
# @example
-
# expect(5).to be_a_kind_of(Fixnum)
-
# expect(5).to be_a_kind_of(Numeric)
-
# expect(5).not_to be_a_kind_of(Float)
-
1
def be_a_kind_of(expected)
-
BuiltIn::BeAKindOf.new(expected)
-
end
-
1
alias_method :be_kind_of, :be_a_kind_of
-
1
alias_matcher :a_kind_of, :be_a_kind_of
-
-
# Passes if actual.between?(min, max). Works with any Comparable object,
-
# including String, Symbol, Time, or Numeric (Fixnum, Bignum, Integer,
-
# Float, Complex, and Rational).
-
#
-
# By default, `be_between` is inclusive (i.e. passes when given either the max or min value),
-
# but you can make it `exclusive` by chaining that off the matcher.
-
#
-
# @example
-
# expect(5).to be_between(1, 10)
-
# expect(11).not_to be_between(1, 10)
-
# expect(10).not_to be_between(1, 10).exclusive
-
1
def be_between(min, max)
-
BuiltIn::BeBetween.new(min, max)
-
end
-
1
alias_matcher :a_value_between, :be_between
-
-
# Passes if actual == expected +/- delta
-
#
-
# @example
-
# expect(result).to be_within(0.5).of(3.0)
-
# expect(result).not_to be_within(0.5).of(3.0)
-
1
def be_within(delta)
-
BuiltIn::BeWithin.new(delta)
-
end
-
1
alias_matcher :a_value_within, :be_within
-
1
alias_matcher :within, :be_within
-
-
# Applied to a proc, specifies that its execution will cause some value to
-
# change.
-
#
-
# @param [Object] receiver
-
# @param [Symbol] message the message to send the receiver
-
#
-
# You can either pass <tt>receiver</tt> and <tt>message</tt>, or a block,
-
# but not both.
-
#
-
# When passing a block, it must use the `{ ... }` format, not
-
# do/end, as `{ ... }` binds to the `change` method, whereas do/end
-
# would errantly bind to the `expect(..).to` or `expect(...).not_to` method.
-
#
-
# You can chain any of the following off of the end to specify details
-
# about the change:
-
#
-
# * `from`
-
# * `to`
-
#
-
# or any one of:
-
#
-
# * `by`
-
# * `by_at_least`
-
# * `by_at_most`
-
#
-
# @example
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count)
-
#
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count).by(1)
-
#
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count).by_at_least(1)
-
#
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count).by_at_most(1)
-
#
-
# string = "string"
-
# expect {
-
# string.reverse!
-
# }.to change { string }.from("string").to("gnirts")
-
#
-
# string = "string"
-
# expect {
-
# string
-
# }.not_to change { string }.from("string")
-
#
-
# expect {
-
# person.happy_birthday
-
# }.to change(person, :birthday).from(32).to(33)
-
#
-
# expect {
-
# employee.develop_great_new_social_networking_app
-
# }.to change(employee, :title).from("Mail Clerk").to("CEO")
-
#
-
# expect {
-
# doctor.leave_office
-
# }.to change(doctor, :sign).from(/is in/).to(/is out/)
-
#
-
# user = User.new(:type => "admin")
-
# expect {
-
# user.symbolize_type
-
# }.to change(user, :type).from(String).to(Symbol)
-
#
-
# == Notes
-
#
-
# Evaluates `receiver.message` or `block` before and after it
-
# evaluates the block passed to `expect`.
-
#
-
# `expect( ... ).not_to change` supports the form that specifies `from`
-
# (which specifies what you expect the starting, unchanged value to be)
-
# but does not support forms with subsequent calls to `by`, `by_at_least`,
-
# `by_at_most` or `to`.
-
1
def change(receiver=nil, message=nil, &block)
-
BuiltIn::Change.new(receiver, message, &block)
-
end
-
1
alias_matcher :a_block_changing, :change
-
1
alias_matcher :changing, :change
-
-
# Passes if actual contains all of the expected regardless of order.
-
# This works for collections. Pass in multiple args and it will only
-
# pass if all args are found in collection.
-
#
-
# @note This is also available using the `=~` operator with `should`,
-
# but `=~` is not supported with `expect`.
-
#
-
# @example
-
# expect([1, 2, 3]).to contain_exactly(1, 2, 3)
-
# expect([1, 2, 3]).to contain_exactly(1, 3, 2)
-
#
-
# @see #match_array
-
1
def contain_exactly(*items)
-
BuiltIn::ContainExactly.new(items)
-
end
-
1
alias_matcher :a_collection_containing_exactly, :contain_exactly
-
1
alias_matcher :containing_exactly, :contain_exactly
-
-
# Passes if actual covers expected. This works for
-
# Ranges. You can also pass in multiple args
-
# and it will only pass if all args are found in Range.
-
#
-
# @example
-
# expect(1..10).to cover(5)
-
# expect(1..10).to cover(4, 6)
-
# expect(1..10).to cover(4, 6, 11) # fails
-
# expect(1..10).not_to cover(11)
-
# expect(1..10).not_to cover(5) # fails
-
#
-
# ### Warning:: Ruby >= 1.9 only
-
1
def cover(*values)
-
BuiltIn::Cover.new(*values)
-
end
-
1
alias_matcher :a_range_covering, :cover
-
1
alias_matcher :covering, :cover
-
-
# Matches if the actual value ends with the expected value(s). In the case
-
# of a string, matches against the last `expected.length` characters of the
-
# actual string. In the case of an array, matches against the last
-
# `expected.length` elements of the actual array.
-
#
-
# @example
-
# expect("this string").to end_with "string"
-
# expect([0, 1, 2, 3, 4]).to end_with 4
-
# expect([0, 2, 3, 4, 4]).to end_with 3, 4
-
1
def end_with(*expected)
-
BuiltIn::EndWith.new(*expected)
-
end
-
1
alias_matcher :a_collection_ending_with, :end_with
-
1
alias_matcher :a_string_ending_with, :end_with
-
1
alias_matcher :ending_with, :end_with
-
-
# Passes if <tt>actual == expected</tt>.
-
#
-
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more
-
# information about equality in Ruby.
-
#
-
# @example
-
# expect(5).to eq(5)
-
# expect(5).not_to eq(3)
-
1
def eq(expected)
-
BuiltIn::Eq.new(expected)
-
end
-
1
alias_matcher :an_object_eq_to, :eq
-
1
alias_matcher :eq_to, :eq
-
-
# Passes if `actual.eql?(expected)`
-
#
-
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more
-
# information about equality in Ruby.
-
#
-
# @example
-
# expect(5).to eql(5)
-
# expect(5).not_to eql(3)
-
1
def eql(expected)
-
BuiltIn::Eql.new(expected)
-
end
-
1
alias_matcher :an_object_eql_to, :eql
-
1
alias_matcher :eql_to, :eql
-
-
# Passes if <tt>actual.equal?(expected)</tt> (object identity).
-
#
-
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more
-
# information about equality in Ruby.
-
#
-
# @example
-
# expect(5).to equal(5) # Fixnums are equal
-
# expect("5").not_to equal("5") # Strings that look the same are not the same object
-
1
def equal(expected)
-
BuiltIn::Equal.new(expected)
-
end
-
1
alias_matcher :an_object_equal_to, :equal
-
1
alias_matcher :equal_to, :equal
-
-
# Passes if `actual.exist?` or `actual.exists?`
-
#
-
# @example
-
# expect(File).to exist("path/to/file")
-
1
def exist(*args)
-
BuiltIn::Exist.new(*args)
-
end
-
1
alias_matcher :an_object_existing, :exist
-
1
alias_matcher :existing, :exist
-
-
# Passes if actual's attribute values match the expected attributes hash.
-
# This works no matter how you define your attribute readers.
-
#
-
# @example
-
# Person = Struct.new(:name, :age)
-
# person = Person.new("Bob", 32)
-
#
-
# expect(person).to have_attributes(:name => "Bob", :age => 32)
-
# expect(person).to have_attributes(:name => a_string_starting_with("B"), :age => (a_value > 30) )
-
#
-
# @note It will fail if actual doesn't respond to any of the expected attributes.
-
#
-
# @example
-
# expect(person).to have_attributes(:color => "red")
-
1
def have_attributes(expected)
-
BuiltIn::HaveAttributes.new(expected)
-
end
-
1
alias_matcher :an_object_having_attributes, :have_attributes
-
-
# Passes if actual includes expected. This works for
-
# collections and Strings. You can also pass in multiple args
-
# and it will only pass if all args are found in collection.
-
#
-
# @example
-
# expect([1,2,3]).to include(3)
-
# expect([1,2,3]).to include(2,3)
-
# expect([1,2,3]).to include(2,3,4) # fails
-
# expect([1,2,3]).not_to include(4)
-
# expect("spread").to include("read")
-
# expect("spread").not_to include("red")
-
# expect(:a => 1, :b => 2).to include(:a)
-
# expect(:a => 1, :b => 2).to include(:a, :b)
-
# expect(:a => 1, :b => 2).to include(:a => 1)
-
# expect(:a => 1, :b => 2).to include(:b => 2, :a => 1)
-
# expect(:a => 1, :b => 2).to include(:c) # fails
-
# expect(:a => 1, :b => 2).not_to include(:a => 2)
-
1
def include(*expected)
-
BuiltIn::Include.new(*expected)
-
end
-
1
alias_matcher :a_collection_including, :include
-
1
alias_matcher :a_string_including, :include
-
1
alias_matcher :a_hash_including, :include
-
1
alias_matcher :including, :include
-
-
# Passes if the provided matcher passes when checked against all
-
# elements of the collection.
-
#
-
# @example
-
# expect([1, 3, 5]).to all be_odd
-
# expect([1, 3, 6]).to all be_odd # fails
-
#
-
# @note The negative form `not_to all` is not supported. Instead
-
# use `not_to include` or pass a negative form of a matcher
-
# as the argument (e.g. `all exclude(:foo)`).
-
#
-
# @note You can also use this with compound matchers as well.
-
#
-
# @example
-
# expect([1, 3, 5]).to all( be_odd.and be_an(Integer) )
-
1
def all(expected)
-
BuiltIn::All.new(expected)
-
end
-
-
# Given a `Regexp` or `String`, passes if `actual.match(pattern)`
-
# Given an arbitrary nested data structure (e.g. arrays and hashes),
-
# matches if `expected === actual` || `actual == expected` for each
-
# pair of elements.
-
#
-
# @example
-
# expect(email).to match(/^([^\s]+)((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
-
# expect(email).to match("@example.com")
-
#
-
# @example
-
# hash = {
-
# :a => {
-
# :b => ["foo", 5],
-
# :c => { :d => 2.05 }
-
# }
-
# }
-
#
-
# expect(hash).to match(
-
# :a => {
-
# :b => a_collection_containing_exactly(
-
# a_string_starting_with("f"),
-
# an_instance_of(Fixnum)
-
# ),
-
# :c => { :d => (a_value < 3) }
-
# }
-
# )
-
#
-
# @note The `match_regex` alias is deprecated and is not recommended for use.
-
# It was added in 2.12.1 to facilitate its use from within custom
-
# matchers (due to how the custom matcher DSL was evaluated in 2.x,
-
# `match` could not be used there), but is no longer needed in 3.x.
-
1
def match(expected)
-
BuiltIn::Match.new(expected)
-
end
-
1
alias_matcher :match_regex, :match
-
1
alias_matcher :an_object_matching, :match
-
1
alias_matcher :a_string_matching, :match
-
1
alias_matcher :matching, :match
-
-
# An alternate form of `contain_exactly` that accepts
-
# the expected contents as a single array arg rather
-
# that splatted out as individual items.
-
#
-
# @example
-
# expect(results).to contain_exactly(1, 2)
-
# # is identical to:
-
# expect(results).to match_array([1, 2])
-
#
-
# @see #contain_exactly
-
1
def match_array(items)
-
contain_exactly(*items)
-
end
-
-
# With no arg, passes if the block outputs `to_stdout` or `to_stderr`.
-
# With a string, passes if the block outputs that specific string `to_stdout` or `to_stderr`.
-
# With a regexp or matcher, passes if the block outputs a string `to_stdout` or `to_stderr` that matches.
-
#
-
# To capture output from any spawned subprocess as well, use `to_stdout_from_any_process` or
-
# `to_stderr_from_any_process`. Output from any process that inherits the main process's corresponding
-
# standard stream will be captured.
-
#
-
# @example
-
# expect { print 'foo' }.to output.to_stdout
-
# expect { print 'foo' }.to output('foo').to_stdout
-
# expect { print 'foo' }.to output(/foo/).to_stdout
-
#
-
# expect { do_something }.to_not output.to_stdout
-
#
-
# expect { warn('foo') }.to output.to_stderr
-
# expect { warn('foo') }.to output('foo').to_stderr
-
# expect { warn('foo') }.to output(/foo/).to_stderr
-
#
-
# expect { do_something }.to_not output.to_stderr
-
#
-
# expect { system('echo foo') }.to output("foo\n").to_stdout_from_any_process
-
# expect { system('echo foo', out: :err) }.to output("foo\n").to_stderr_from_any_process
-
#
-
# @note `to_stdout` and `to_stderr` work by temporarily replacing `$stdout` or `$stderr`,
-
# so they're not able to intercept stream output that explicitly uses `STDOUT`/`STDERR`
-
# or that uses a reference to `$stdout`/`$stderr` that was stored before the
-
# matcher was used.
-
# @note `to_stdout_from_any_process` and `to_stderr_from_any_process` use Tempfiles, and
-
# are thus significantly (~30x) slower than `to_stdout` and `to_stderr`.
-
1
def output(expected=nil)
-
BuiltIn::Output.new(expected)
-
end
-
1
alias_matcher :a_block_outputting, :output
-
-
# With no args, matches if any error is raised.
-
# With a named error, matches only if that specific error is raised.
-
# With a named error and messsage specified as a String, matches only if both match.
-
# With a named error and messsage specified as a Regexp, matches only if both match.
-
# Pass an optional block to perform extra verifications on the exception matched
-
#
-
# @example
-
# expect { do_something_risky }.to raise_error
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError)
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError) { |error| expect(error.data).to eq 42 }
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError, "that was too risky")
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError, /oo ri/)
-
#
-
# expect { do_something_risky }.not_to raise_error
-
1
def raise_error(error=nil, message=nil, &block)
-
BuiltIn::RaiseError.new(error, message, &block)
-
end
-
1
alias_method :raise_exception, :raise_error
-
-
1
alias_matcher :a_block_raising, :raise_error do |desc|
-
desc.sub("raise", "a block raising")
-
end
-
-
1
alias_matcher :raising, :raise_error do |desc|
-
desc.sub("raise", "raising")
-
end
-
-
# Matches if the target object responds to all of the names
-
# provided. Names can be Strings or Symbols.
-
#
-
# @example
-
# expect("string").to respond_to(:length)
-
#
-
1
def respond_to(*names)
-
BuiltIn::RespondTo.new(*names)
-
end
-
1
alias_matcher :an_object_responding_to, :respond_to
-
1
alias_matcher :responding_to, :respond_to
-
-
# Passes if the submitted block returns true. Yields target to the
-
# block.
-
#
-
# Generally speaking, this should be thought of as a last resort when
-
# you can't find any other way to specify the behaviour you wish to
-
# specify.
-
#
-
# If you do find yourself in such a situation, you could always write
-
# a custom matcher, which would likely make your specs more expressive.
-
#
-
# @param description [String] optional description to be used for this matcher.
-
#
-
# @example
-
# expect(5).to satisfy { |n| n > 3 }
-
# expect(5).to satisfy("be greater than 3") { |n| n > 3 }
-
1
def satisfy(description="satisfy block", &block)
-
BuiltIn::Satisfy.new(description, &block)
-
end
-
1
alias_matcher :an_object_satisfying, :satisfy
-
1
alias_matcher :satisfying, :satisfy
-
-
# Matches if the actual value starts with the expected value(s). In the
-
# case of a string, matches against the first `expected.length` characters
-
# of the actual string. In the case of an array, matches against the first
-
# `expected.length` elements of the actual array.
-
#
-
# @example
-
# expect("this string").to start_with "this s"
-
# expect([0, 1, 2, 3, 4]).to start_with 0
-
# expect([0, 2, 3, 4, 4]).to start_with 0, 1
-
1
def start_with(*expected)
-
BuiltIn::StartWith.new(*expected)
-
end
-
1
alias_matcher :a_collection_starting_with, :start_with
-
1
alias_matcher :a_string_starting_with, :start_with
-
1
alias_matcher :starting_with, :start_with
-
-
# Given no argument, matches if a proc throws any Symbol.
-
#
-
# Given a Symbol, matches if the given proc throws the specified Symbol.
-
#
-
# Given a Symbol and an arg, matches if the given proc throws the
-
# specified Symbol with the specified arg.
-
#
-
# @example
-
# expect { do_something_risky }.to throw_symbol
-
# expect { do_something_risky }.to throw_symbol(:that_was_risky)
-
# expect { do_something_risky }.to throw_symbol(:that_was_risky, 'culprit')
-
#
-
# expect { do_something_risky }.not_to throw_symbol
-
# expect { do_something_risky }.not_to throw_symbol(:that_was_risky)
-
# expect { do_something_risky }.not_to throw_symbol(:that_was_risky, 'culprit')
-
1
def throw_symbol(expected_symbol=nil, expected_arg=nil)
-
BuiltIn::ThrowSymbol.new(expected_symbol, expected_arg)
-
end
-
-
1
alias_matcher :a_block_throwing, :throw_symbol do |desc|
-
desc.sub("throw", "a block throwing")
-
end
-
-
1
alias_matcher :throwing, :throw_symbol do |desc|
-
desc.sub("throw", "throwing")
-
end
-
-
# Passes if the method called in the expect block yields, regardless
-
# of whether or not arguments are yielded.
-
#
-
# @example
-
# expect { |b| 5.tap(&b) }.to yield_control
-
# expect { |b| "a".to_sym(&b) }.not_to yield_control
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
1
def yield_control
-
BuiltIn::YieldControl.new
-
end
-
1
alias_matcher :a_block_yielding_control, :yield_control
-
1
alias_matcher :yielding_control, :yield_control
-
-
# Passes if the method called in the expect block yields with
-
# no arguments. Fails if it does not yield, or yields with arguments.
-
#
-
# @example
-
# expect { |b| User.transaction(&b) }.to yield_with_no_args
-
# expect { |b| 5.tap(&b) }.not_to yield_with_no_args # because it yields with `5`
-
# expect { |b| "a".to_sym(&b) }.not_to yield_with_no_args # because it does not yield
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
# @note This matcher is not designed for use with methods that yield
-
# multiple times.
-
1
def yield_with_no_args
-
BuiltIn::YieldWithNoArgs.new
-
end
-
1
alias_matcher :a_block_yielding_with_no_args, :yield_with_no_args
-
1
alias_matcher :yielding_with_no_args, :yield_with_no_args
-
-
# Given no arguments, matches if the method called in the expect
-
# block yields with arguments (regardless of what they are or how
-
# many there are).
-
#
-
# Given arguments, matches if the method called in the expect block
-
# yields with arguments that match the given arguments.
-
#
-
# Argument matching is done using `===` (the case match operator)
-
# and `==`. If the expected and actual arguments match with either
-
# operator, the matcher will pass.
-
#
-
# @example
-
# expect { |b| 5.tap(&b) }.to yield_with_args # because #tap yields an arg
-
# expect { |b| 5.tap(&b) }.to yield_with_args(5) # because 5 == 5
-
# expect { |b| 5.tap(&b) }.to yield_with_args(Fixnum) # because Fixnum === 5
-
# expect { |b| File.open("f.txt", &b) }.to yield_with_args(/txt/) # because /txt/ === "f.txt"
-
#
-
# expect { |b| User.transaction(&b) }.not_to yield_with_args # because it yields no args
-
# expect { |b| 5.tap(&b) }.not_to yield_with_args(1, 2, 3)
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
# @note This matcher is not designed for use with methods that yield
-
# multiple times.
-
1
def yield_with_args(*args)
-
BuiltIn::YieldWithArgs.new(*args)
-
end
-
1
alias_matcher :a_block_yielding_with_args, :yield_with_args
-
1
alias_matcher :yielding_with_args, :yield_with_args
-
-
# Designed for use with methods that repeatedly yield (such as
-
# iterators). Passes if the method called in the expect block yields
-
# multiple times with arguments matching those given.
-
#
-
# Argument matching is done using `===` (the case match operator)
-
# and `==`. If the expected and actual arguments match with either
-
# operator, the matcher will pass.
-
#
-
# @example
-
# expect { |b| [1, 2, 3].each(&b) }.to yield_successive_args(1, 2, 3)
-
# expect { |b| { :a => 1, :b => 2 }.each(&b) }.to yield_successive_args([:a, 1], [:b, 2])
-
# expect { |b| [1, 2, 3].each(&b) }.not_to yield_successive_args(1, 2)
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
1
def yield_successive_args(*args)
-
BuiltIn::YieldSuccessiveArgs.new(*args)
-
end
-
1
alias_matcher :a_block_yielding_successive_args, :yield_successive_args
-
1
alias_matcher :yielding_successive_args, :yield_successive_args
-
-
# Delegates to {RSpec::Expectations.configuration}.
-
# This is here because rspec-core's `expect_with` option
-
# looks for a `configuration` method on the mixin
-
# (`RSpec::Matchers`) to yield to a block.
-
# @return [RSpec::Expectations::Configuration] the configuration object
-
1
def self.configuration
-
1
Expectations.configuration
-
end
-
-
1
private
-
-
1
BE_PREDICATE_REGEX = /^(be_(?:an?_)?)(.*)/
-
1
HAS_REGEX = /^(?:have_)(.*)/
-
1
DYNAMIC_MATCHER_REGEX = Regexp.union(BE_PREDICATE_REGEX, HAS_REGEX)
-
-
1
def method_missing(method, *args, &block)
-
4
case method.to_s
-
when BE_PREDICATE_REGEX
-
BuiltIn::BePredicate.new(method, *args, &block)
-
when HAS_REGEX
-
3
BuiltIn::Has.new(method, *args, &block)
-
else
-
1
super
-
end
-
end
-
-
1
if RUBY_VERSION.to_f >= 1.9
-
1
def respond_to_missing?(method, *)
-
method =~ DYNAMIC_MATCHER_REGEX || super
-
end
-
else # for 1.8.7
-
skipped
# :nocov:
-
skipped
def respond_to?(method, *)
-
skipped
method = method.to_s
-
skipped
method =~ DYNAMIC_MATCHER_REGEX || super
-
skipped
end
-
skipped
public :respond_to?
-
skipped
# :nocov:
-
end
-
-
# @api private
-
1
def self.is_a_matcher?(obj)
-
return true if ::RSpec::Matchers::BuiltIn::BaseMatcher === obj
-
begin
-
return false if obj.respond_to?(:i_respond_to_everything_so_im_not_really_a_matcher)
-
rescue NoMethodError
-
# Some objects, like BasicObject, don't implemented standard
-
# reflection methods.
-
return false
-
end
-
return false unless obj.respond_to?(:matches?)
-
-
obj.respond_to?(:failure_message) ||
-
obj.respond_to?(:failure_message_for_should) # support legacy matchers
-
end
-
-
1
::RSpec::Support.register_matcher_definition do |obj|
-
is_a_matcher?(obj)
-
end
-
-
# @api private
-
1
def self.is_a_describable_matcher?(obj)
-
is_a_matcher?(obj) && obj.respond_to?(:description)
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
# Decorator that wraps a matcher and overrides `description`
-
# using the provided block in order to support an alias
-
# of a matcher. This is intended for use when composing
-
# matchers, so that you can use an expression like
-
# `include( a_value_within(0.1).of(3) )` rather than
-
# `include( be_within(0.1).of(3) )`, and have the corresponding
-
# description read naturally.
-
#
-
# @api private
-
1
class AliasedMatcher < MatcherDelegator
-
1
def initialize(base_matcher, description_block)
-
@description_block = description_block
-
super(base_matcher)
-
end
-
-
# Forward messages on to the wrapped matcher.
-
# Since many matchers provide a fluent interface
-
# (e.g. `a_value_within(0.1).of(3)`), we need to wrap
-
# the returned value if it responds to `description`,
-
# so that our override can be applied when it is eventually
-
# used.
-
1
def method_missing(*)
-
return_val = super
-
return return_val unless RSpec::Matchers.is_a_matcher?(return_val)
-
self.class.new(return_val, @description_block)
-
end
-
-
# Provides the description of the aliased matcher. Aliased matchers
-
# are designed to behave identically to the original matcher except
-
# for the description and failure messages. The description is different
-
# to reflect the aliased name.
-
#
-
# @api private
-
1
def description
-
@description_block.call(super)
-
end
-
-
# Provides the failure_message of the aliased matcher. Aliased matchers
-
# are designed to behave identically to the original matcher except
-
# for the description and failure messages. The failure_message is different
-
# to reflect the aliased name.
-
#
-
# @api private
-
1
def failure_message
-
@description_block.call(super)
-
end
-
-
# Provides the failure_message_when_negated of the aliased matcher. Aliased matchers
-
# are designed to behave identically to the original matcher except
-
# for the description and failure messages. The failure_message_when_negated is different
-
# to reflect the aliased name.
-
#
-
# @api private
-
1
def failure_message_when_negated
-
@description_block.call(super)
-
end
-
end
-
-
# Decorator used for matchers that have special implementations of
-
# operators like `==` and `===`.
-
# @private
-
1
class AliasedMatcherWithOperatorSupport < AliasedMatcher
-
# We undef these so that they get delegated via `method_missing`.
-
1
undef ==
-
1
undef ===
-
end
-
-
# @private
-
1
class AliasedNegatedMatcher < AliasedMatcher
-
1
def matches?(*args, &block)
-
if @base_matcher.respond_to?(:does_not_match?)
-
@base_matcher.does_not_match?(*args, &block)
-
else
-
!super
-
end
-
end
-
-
1
def does_not_match?(*args, &block)
-
@base_matcher.matches?(*args, &block)
-
end
-
-
1
def failure_message
-
optimal_failure_message(__method__, :failure_message_when_negated)
-
end
-
-
1
def failure_message_when_negated
-
optimal_failure_message(__method__, :failure_message)
-
end
-
-
1
private
-
-
1
DefaultFailureMessages = BuiltIn::BaseMatcher::DefaultFailureMessages
-
-
# For a matcher that uses the default failure messages, we prefer to
-
# use the override provided by the `description_block`, because it
-
# includes the phrasing that the user has expressed a preference for
-
# by going through the effort of defining a negated matcher.
-
#
-
# However, if the override didn't actually change anything, then we
-
# should return the opposite failure message instead -- the overriden
-
# message is going to be confusing if we return it as-is, as it represents
-
# the non-negated failure message for a negated match (or vice versa).
-
1
def optimal_failure_message(same, inverted)
-
if DefaultFailureMessages.has_default_failure_messages?(@base_matcher)
-
base_message = @base_matcher.__send__(same)
-
overriden = @description_block.call(base_message)
-
return overriden if overriden != base_message
-
end
-
-
@base_matcher.__send__(inverted)
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_matchers "built_in/base_matcher"
-
-
1
module RSpec
-
1
module Matchers
-
# Container module for all built-in matchers. The matcher classes are here
-
# (rather than directly under `RSpec::Matchers`) in order to prevent name
-
# collisions, since `RSpec::Matchers` gets included into the user's namespace.
-
#
-
# Autoloading is used to delay when the matcher classes get loaded, allowing
-
# rspec-matchers to boot faster, and avoiding loading matchers the user is
-
# not using.
-
1
module BuiltIn
-
1
autoload :BeAKindOf, 'rspec/matchers/built_in/be_kind_of'
-
1
autoload :BeAnInstanceOf, 'rspec/matchers/built_in/be_instance_of'
-
1
autoload :BeBetween, 'rspec/matchers/built_in/be_between'
-
1
autoload :Be, 'rspec/matchers/built_in/be'
-
1
autoload :BeComparedTo, 'rspec/matchers/built_in/be'
-
1
autoload :BeFalsey, 'rspec/matchers/built_in/be'
-
1
autoload :BeNil, 'rspec/matchers/built_in/be'
-
1
autoload :BePredicate, 'rspec/matchers/built_in/be'
-
1
autoload :BeTruthy, 'rspec/matchers/built_in/be'
-
1
autoload :BeWithin, 'rspec/matchers/built_in/be_within'
-
1
autoload :Change, 'rspec/matchers/built_in/change'
-
1
autoload :Compound, 'rspec/matchers/built_in/compound'
-
1
autoload :ContainExactly, 'rspec/matchers/built_in/contain_exactly'
-
1
autoload :Cover, 'rspec/matchers/built_in/cover'
-
1
autoload :EndWith, 'rspec/matchers/built_in/start_or_end_with'
-
1
autoload :Eq, 'rspec/matchers/built_in/eq'
-
1
autoload :Eql, 'rspec/matchers/built_in/eql'
-
1
autoload :Equal, 'rspec/matchers/built_in/equal'
-
1
autoload :Exist, 'rspec/matchers/built_in/exist'
-
1
autoload :Has, 'rspec/matchers/built_in/has'
-
1
autoload :HaveAttributes, 'rspec/matchers/built_in/have_attributes'
-
1
autoload :Include, 'rspec/matchers/built_in/include'
-
1
autoload :All, 'rspec/matchers/built_in/all'
-
1
autoload :Match, 'rspec/matchers/built_in/match'
-
1
autoload :NegativeOperatorMatcher, 'rspec/matchers/built_in/operators'
-
1
autoload :OperatorMatcher, 'rspec/matchers/built_in/operators'
-
1
autoload :Output, 'rspec/matchers/built_in/output'
-
1
autoload :PositiveOperatorMatcher, 'rspec/matchers/built_in/operators'
-
1
autoload :RaiseError, 'rspec/matchers/built_in/raise_error'
-
1
autoload :RespondTo, 'rspec/matchers/built_in/respond_to'
-
1
autoload :Satisfy, 'rspec/matchers/built_in/satisfy'
-
1
autoload :StartWith, 'rspec/matchers/built_in/start_or_end_with'
-
1
autoload :ThrowSymbol, 'rspec/matchers/built_in/throw_symbol'
-
1
autoload :YieldControl, 'rspec/matchers/built_in/yield'
-
1
autoload :YieldSuccessiveArgs, 'rspec/matchers/built_in/yield'
-
1
autoload :YieldWithArgs, 'rspec/matchers/built_in/yield'
-
1
autoload :YieldWithNoArgs, 'rspec/matchers/built_in/yield'
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
1
module BuiltIn
-
# @api private
-
#
-
# Used _internally_ as a base class for matchers that ship with
-
# rspec-expectations and rspec-rails.
-
#
-
# ### Warning:
-
#
-
# This class is for internal use, and subject to change without notice. We
-
# strongly recommend that you do not base your custom matchers on this
-
# class. If/when this changes, we will announce it and remove this warning.
-
1
class BaseMatcher
-
1
include RSpec::Matchers::Composable
-
-
# @api private
-
# Used to detect when no arg is passed to `initialize`.
-
# `nil` cannot be used because it's a valid value to pass.
-
1
UNDEFINED = Object.new.freeze
-
-
# @private
-
1
attr_reader :actual, :expected, :rescued_exception
-
-
1
def initialize(expected=UNDEFINED)
-
@expected = expected unless UNDEFINED.equal?(expected)
-
end
-
-
# @api private
-
# Indicates if the match is successful. Delegates to `match`, which
-
# should be defined on a subclass. Takes care of consistently
-
# initializing the `actual` attribute.
-
1
def matches?(actual)
-
@actual = actual
-
match(expected, actual)
-
end
-
-
# @api private
-
# Used to wrap a block of code that will indicate failure by
-
# raising one of the named exceptions.
-
#
-
# This is used by rspec-rails for some of its matchers that
-
# wrap rails' assertions.
-
1
def match_unless_raises(*exceptions)
-
exceptions.unshift Exception if exceptions.empty?
-
begin
-
yield
-
true
-
rescue *exceptions => @rescued_exception
-
false
-
end
-
end
-
-
# @api private
-
# Generates a description using {EnglishPhrasing}.
-
# @return [String]
-
1
def description
-
desc = EnglishPhrasing.split_words(self.class.matcher_name)
-
desc << EnglishPhrasing.list(@expected) if defined?(@expected)
-
desc
-
end
-
-
# @api private
-
# Matchers are not diffable by default. Override this to make your
-
# subclass diffable.
-
1
def diffable?
-
false
-
end
-
-
# @api private
-
# Most matchers are value matchers (i.e. meant to work with `expect(value)`)
-
# rather than block matchers (i.e. meant to work with `expect { }`), so
-
# this defaults to false. Block matchers must override this to return true.
-
1
def supports_block_expectations?
-
false
-
end
-
-
# @api private
-
1
def expects_call_stack_jump?
-
false
-
end
-
-
# @private
-
1
def expected_formatted
-
RSpec::Support::ObjectFormatter.format(@expected)
-
end
-
-
# @private
-
1
def actual_formatted
-
RSpec::Support::ObjectFormatter.format(@actual)
-
end
-
-
# @private
-
1
def self.matcher_name
-
@matcher_name ||= underscore(name.split("::").last)
-
end
-
-
# @private
-
# Borrowed from ActiveSupport.
-
1
def self.underscore(camel_cased_word)
-
word = camel_cased_word.to_s.dup
-
word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
-
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
-
word.tr!("-", "_")
-
word.downcase!
-
word
-
end
-
1
private_class_method :underscore
-
-
1
private
-
-
1
def assert_ivars(*expected_ivars)
-
return unless (expected_ivars - present_ivars).any?
-
ivar_list = EnglishPhrasing.list(expected_ivars)
-
raise "#{self.class.name} needs to supply#{ivar_list}"
-
end
-
-
1
if RUBY_VERSION.to_f < 1.9
-
skipped
# :nocov:
-
skipped
def present_ivars
-
skipped
instance_variables.map { |v| v.to_sym }
-
skipped
end
-
skipped
# :nocov:
-
else
-
1
alias present_ivars instance_variables
-
end
-
-
# @private
-
1
module HashFormatting
-
# `{ :a => 5, :b => 2 }.inspect` produces:
-
#
-
# {:a=>5, :b=>2}
-
#
-
# ...but it looks much better as:
-
#
-
# {:a => 5, :b => 2}
-
#
-
# This is idempotent and safe to run on a string multiple times.
-
1
def improve_hash_formatting(inspect_string)
-
inspect_string.gsub(/(\S)=>(\S)/, '\1 => \2')
-
end
-
1
module_function :improve_hash_formatting
-
end
-
-
1
include HashFormatting
-
-
# @api private
-
# Provides default implementations of failure messages, based on the `description`.
-
1
module DefaultFailureMessages
-
# @api private
-
# Provides a good generic failure message. Based on `description`.
-
# When subclassing, if you are not satisfied with this failure message
-
# you often only need to override `description`.
-
# @return [String]
-
1
def failure_message
-
"expected #{description_of @actual} to #{description}"
-
end
-
-
# @api private
-
# Provides a good generic negative failure message. Based on `description`.
-
# When subclassing, if you are not satisfied with this failure message
-
# you often only need to override `description`.
-
# @return [String]
-
1
def failure_message_when_negated
-
"expected #{description_of @actual} not to #{description}"
-
end
-
-
# @private
-
1
def self.has_default_failure_messages?(matcher)
-
matcher.method(:failure_message).owner == self &&
-
matcher.method(:failure_message_when_negated).owner == self
-
rescue NameError
-
false
-
end
-
end
-
-
1
include DefaultFailureMessages
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
1
module BuiltIn
-
# @api private
-
# Provides the implementation for `contain_exactly` and `match_array`.
-
# Not intended to be instantiated directly.
-
1
class ContainExactly < BaseMatcher
-
# @api private
-
# @return [String]
-
1
def failure_message
-
if Array === actual
-
message = "expected collection contained: #{description_of(safe_sort(surface_descriptions_in expected))}\n"
-
message += "actual collection contained: #{description_of(safe_sort(actual))}\n"
-
message += "the missing elements were: #{description_of(safe_sort(surface_descriptions_in missing_items))}\n" unless missing_items.empty?
-
message += "the extra elements were: #{description_of(safe_sort(extra_items))}\n" unless extra_items.empty?
-
message
-
else
-
"expected a collection that can be converted to an array with " \
-
"`#to_ary` or `#to_a`, but got #{actual_formatted}"
-
end
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
list = EnglishPhrasing.list(surface_descriptions_in(expected))
-
"expected #{actual_formatted} not to contain exactly#{list}"
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
list = EnglishPhrasing.list(surface_descriptions_in(expected))
-
"contain exactly#{list}"
-
end
-
-
1
private
-
-
1
def match(_expected, _actual)
-
return false unless convert_actual_to_an_array
-
match_when_sorted? || (extra_items.empty? && missing_items.empty?)
-
end
-
-
# This cannot always work (e.g. when dealing with unsortable items,
-
# or matchers as expected items), but it's practically free compared to
-
# the slowness of the full matching algorithm, and in common cases this
-
# works, so it's worth a try.
-
1
def match_when_sorted?
-
values_match?(safe_sort(expected), safe_sort(actual))
-
end
-
-
1
def convert_actual_to_an_array
-
if actual.respond_to?(:to_ary)
-
@actual = actual.to_ary
-
elsif should_enumerate?(actual) && actual.respond_to?(:to_a)
-
@actual = actual.to_a
-
else
-
return false
-
end
-
end
-
-
1
def safe_sort(array)
-
array.sort
-
rescue Exception
-
array
-
end
-
-
1
def missing_items
-
@missing_items ||= best_solution.unmatched_expected_indexes.map do |index|
-
expected[index]
-
end
-
end
-
-
1
def extra_items
-
@extra_items ||= best_solution.unmatched_actual_indexes.map do |index|
-
actual[index]
-
end
-
end
-
-
1
def best_solution
-
@best_solution ||= pairings_maximizer.find_best_solution
-
end
-
-
1
def pairings_maximizer
-
@pairings_maximizer ||= begin
-
expected_matches = Hash[Array.new(expected.size) { |i| [i, []] }]
-
actual_matches = Hash[Array.new(actual.size) { |i| [i, []] }]
-
-
expected.each_with_index do |e, ei|
-
actual.each_with_index do |a, ai|
-
next unless values_match?(e, a)
-
-
expected_matches[ei] << ai
-
actual_matches[ai] << ei
-
end
-
end
-
-
PairingsMaximizer.new(expected_matches, actual_matches)
-
end
-
end
-
-
# Once we started supporting composing matchers, the algorithm for this matcher got
-
# much more complicated. Consider this expression:
-
#
-
# expect(["fool", "food"]).to contain_exactly(/foo/, /fool/)
-
#
-
# This should pass (because we can pair /fool/ with "fool" and /foo/ with "food"), but
-
# the original algorithm used by this matcher would pair the first elements it could
-
# (/foo/ with "fool"), which would leave /fool/ and "food" unmatched. When we have
-
# an expected element which is a matcher that matches a superset of actual items
-
# compared to another expected element matcher, we need to consider every possible pairing.
-
#
-
# This class is designed to maximize the number of actual/expected pairings -- or,
-
# conversely, to minimize the number of unpaired items. It's essentially a brute
-
# force solution, but with a few heuristics applied to reduce the size of the
-
# problem space:
-
#
-
# * Any items which match none of the items in the other list are immediately
-
# placed into the `unmatched_expected_indexes` or `unmatched_actual_indexes` array.
-
# The extra items and missing items in the matcher failure message are derived
-
# from these arrays.
-
# * Any items which reciprocally match only each other are paired up and not
-
# considered further.
-
#
-
# What's left is only the items which match multiple items from the other list
-
# (or vice versa). From here, it performs a brute-force depth-first search,
-
# looking for a solution which pairs all elements in both lists, or, barring that,
-
# that produces the fewest unmatched items.
-
#
-
# @private
-
1
class PairingsMaximizer
-
1
Solution = Struct.new(:unmatched_expected_indexes, :unmatched_actual_indexes,
-
:indeterminate_expected_indexes, :indeterminate_actual_indexes) do
-
1
def worse_than?(other)
-
unmatched_item_count > other.unmatched_item_count
-
end
-
-
1
def candidate?
-
indeterminate_expected_indexes.empty? &&
-
indeterminate_actual_indexes.empty?
-
end
-
-
1
def ideal?
-
candidate? && (
-
unmatched_expected_indexes.empty? ||
-
unmatched_actual_indexes.empty?
-
)
-
end
-
-
1
def unmatched_item_count
-
unmatched_expected_indexes.count + unmatched_actual_indexes.count
-
end
-
-
1
def +(derived_candidate_solution)
-
self.class.new(
-
unmatched_expected_indexes + derived_candidate_solution.unmatched_expected_indexes,
-
unmatched_actual_indexes + derived_candidate_solution.unmatched_actual_indexes,
-
# Ignore the indeterminate indexes: by the time we get here,
-
# we've dealt with all indeterminates.
-
[], []
-
)
-
end
-
end
-
-
1
attr_reader :expected_to_actual_matched_indexes, :actual_to_expected_matched_indexes, :solution
-
-
1
def initialize(expected_to_actual_matched_indexes, actual_to_expected_matched_indexes)
-
@expected_to_actual_matched_indexes = expected_to_actual_matched_indexes
-
@actual_to_expected_matched_indexes = actual_to_expected_matched_indexes
-
-
unmatched_expected_indexes, indeterminate_expected_indexes =
-
categorize_indexes(expected_to_actual_matched_indexes, actual_to_expected_matched_indexes)
-
-
unmatched_actual_indexes, indeterminate_actual_indexes =
-
categorize_indexes(actual_to_expected_matched_indexes, expected_to_actual_matched_indexes)
-
-
@solution = Solution.new(unmatched_expected_indexes, unmatched_actual_indexes,
-
indeterminate_expected_indexes, indeterminate_actual_indexes)
-
end
-
-
1
def find_best_solution
-
return solution if solution.candidate?
-
best_solution_so_far = NullSolution
-
-
expected_index = solution.indeterminate_expected_indexes.first
-
actuals = expected_to_actual_matched_indexes[expected_index]
-
-
actuals.each do |actual_index|
-
solution = best_solution_for_pairing(expected_index, actual_index)
-
return solution if solution.ideal?
-
best_solution_so_far = solution if best_solution_so_far.worse_than?(solution)
-
end
-
-
best_solution_so_far
-
end
-
-
1
private
-
-
# @private
-
# Starting solution that is worse than any other real solution.
-
1
NullSolution = Class.new do
-
1
def self.worse_than?(_other)
-
true
-
end
-
end
-
-
1
def categorize_indexes(indexes_to_categorize, other_indexes)
-
unmatched = []
-
indeterminate = []
-
-
indexes_to_categorize.each_pair do |index, matches|
-
if matches.empty?
-
unmatched << index
-
elsif !reciprocal_single_match?(matches, index, other_indexes)
-
indeterminate << index
-
end
-
end
-
-
return unmatched, indeterminate
-
end
-
-
1
def reciprocal_single_match?(matches, index, other_list)
-
return false unless matches.one?
-
other_list[matches.first] == [index]
-
end
-
-
1
def best_solution_for_pairing(expected_index, actual_index)
-
modified_expecteds = apply_pairing_to(
-
solution.indeterminate_expected_indexes,
-
expected_to_actual_matched_indexes, actual_index)
-
-
modified_expecteds.delete(expected_index)
-
-
modified_actuals = apply_pairing_to(
-
solution.indeterminate_actual_indexes,
-
actual_to_expected_matched_indexes, expected_index)
-
-
modified_actuals.delete(actual_index)
-
-
solution + self.class.new(modified_expecteds, modified_actuals).find_best_solution
-
end
-
-
1
def apply_pairing_to(indeterminates, original_matches, other_list_index)
-
indeterminates.inject({}) do |accum, index|
-
accum[index] = original_matches[index] - [other_list_index]
-
accum
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
1
module BuiltIn
-
# @api private
-
# Provides the implementation for `has_<predicate>`.
-
# Not intended to be instantiated directly.
-
1
class Has < BaseMatcher
-
1
def initialize(method_name, *args, &block)
-
3
@method_name, @args, @block = method_name, args, block
-
end
-
-
# @private
-
1
def matches?(actual, &block)
-
3
@actual = actual
-
3
@block ||= block
-
3
predicate_accessible? && predicate_matches?
-
end
-
-
# @private
-
1
def does_not_match?(actual, &block)
-
@actual = actual
-
@block ||= block
-
predicate_accessible? && !predicate_matches?
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message
-
validity_message || "expected ##{predicate}#{failure_message_args_description} to return true, got false"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
validity_message || "expected ##{predicate}#{failure_message_args_description} to return false, got true"
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
[method_description, args_description].compact.join(' ')
-
end
-
-
1
private
-
-
1
def predicate_accessible?
-
3
!private_predicate? && predicate_exists?
-
end
-
-
# support 1.8.7, evaluate once at load time for performance
-
1
if String === methods.first
-
skipped
# :nocov:
-
skipped
def private_predicate?
-
skipped
@actual.private_methods.include? predicate.to_s
-
skipped
end
-
skipped
# :nocov:
-
else
-
1
def private_predicate?
-
3
@actual.private_methods.include? predicate
-
end
-
end
-
-
1
def predicate_exists?
-
3
@actual.respond_to? predicate
-
end
-
-
1
def predicate_matches?
-
3
@actual.__send__(predicate, *@args, &@block)
-
end
-
-
1
def predicate
-
# On 1.9, there appears to be a bug where String#match can return `false`
-
# rather than the match data object. Changing to Regex#match appears to
-
# work around this bug. For an example of this bug, see:
-
# https://travis-ci.org/rspec/rspec-expectations/jobs/27549635
-
9
@predicate ||= :"has_#{Matchers::HAS_REGEX.match(@method_name.to_s).captures.first}?"
-
end
-
-
1
def method_description
-
@method_name.to_s.gsub('_', ' ')
-
end
-
-
1
def args_description
-
return nil if @args.empty?
-
@args.map { |arg| RSpec::Support::ObjectFormatter.format(arg) }.join(', ')
-
end
-
-
1
def failure_message_args_description
-
desc = args_description
-
"(#{desc})" if desc
-
end
-
-
1
def validity_message
-
if private_predicate?
-
"expected #{@actual} to respond to `#{predicate}` but `#{predicate}` is a private method"
-
elsif !predicate_exists?
-
"expected #{@actual} to respond to `#{predicate}`"
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'rspec/support'
-
-
1
module RSpec
-
1
module Matchers
-
1
module BuiltIn
-
# @api private
-
# Provides the implementation for operator matchers.
-
# Not intended to be instantiated directly.
-
# Only available for use with `should`.
-
1
class OperatorMatcher
-
1
class << self
-
# @private
-
1
def registry
-
2
@registry ||= {}
-
end
-
-
# @private
-
1
def register(klass, operator, matcher)
-
1
registry[klass] ||= {}
-
1
registry[klass][operator] = matcher
-
end
-
-
# @private
-
1
def unregister(klass, operator)
-
registry[klass] && registry[klass].delete(operator)
-
end
-
-
# @private
-
1
def get(klass, operator)
-
klass.ancestors.each do |ancestor|
-
matcher = registry[ancestor] && registry[ancestor][operator]
-
return matcher if matcher
-
end
-
-
nil
-
end
-
end
-
-
1
register Enumerable, '=~', BuiltIn::ContainExactly
-
-
1
def initialize(actual)
-
4
@actual = actual
-
end
-
-
# @private
-
1
def self.use_custom_matcher_or_delegate(operator)
-
7
define_method(operator) do |expected|
-
4
if !has_non_generic_implementation_of?(operator) && (matcher = OperatorMatcher.get(@actual.class, operator))
-
@actual.__send__(::RSpec::Matchers.last_expectation_handler.should_method, matcher.new(expected))
-
else
-
4
eval_match(@actual, operator, expected)
-
end
-
end
-
-
7
negative_operator = operator.sub(/^=/, '!')
-
7
if negative_operator != operator && respond_to?(negative_operator)
-
2
define_method(negative_operator) do |_expected|
-
opposite_should = ::RSpec::Matchers.last_expectation_handler.opposite_should_method
-
raise "RSpec does not support `#{::RSpec::Matchers.last_expectation_handler.should_method} #{negative_operator} expected`. " \
-
"Use `#{opposite_should} #{operator} expected` instead."
-
end
-
end
-
end
-
-
1
['==', '===', '=~', '>', '>=', '<', '<='].each do |operator|
-
7
use_custom_matcher_or_delegate operator
-
end
-
-
# @private
-
1
def fail_with_message(message)
-
RSpec::Expectations.fail_with(message, @expected, @actual)
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
"#{@operator} #{RSpec::Support::ObjectFormatter.format(@expected)}"
-
end
-
-
1
private
-
-
1
def has_non_generic_implementation_of?(op)
-
4
Support.method_handle_for(@actual, op).owner != ::Kernel
-
rescue NameError
-
false
-
end
-
-
1
def eval_match(actual, operator, expected)
-
4
::RSpec::Matchers.last_matcher = self
-
4
@operator, @expected = operator, expected
-
4
__delegate_operator(actual, operator, expected)
-
end
-
end
-
-
# @private
-
# Handles operator matcher for `should`.
-
1
class PositiveOperatorMatcher < OperatorMatcher
-
1
def __delegate_operator(actual, operator, expected)
-
4
if actual.__send__(operator, expected)
-
4
true
-
else
-
expected_formatted = RSpec::Support::ObjectFormatter.format(expected)
-
actual_formatted = RSpec::Support::ObjectFormatter.format(actual)
-
-
if ['==', '===', '=~'].include?(operator)
-
fail_with_message("expected: #{expected_formatted}\n got: #{actual_formatted} (using #{operator})")
-
else
-
fail_with_message("expected: #{operator} #{expected_formatted}\n got: #{operator.gsub(/./, ' ')} #{actual_formatted}")
-
end
-
end
-
end
-
end
-
-
# @private
-
# Handles operator matcher for `should_not`.
-
1
class NegativeOperatorMatcher < OperatorMatcher
-
1
def __delegate_operator(actual, operator, expected)
-
return false unless actual.__send__(operator, expected)
-
-
expected_formatted = RSpec::Support::ObjectFormatter.format(expected)
-
actual_formatted = RSpec::Support::ObjectFormatter.format(actual)
-
-
fail_with_message("expected not: #{operator} #{expected_formatted}\n got: #{operator.gsub(/./, ' ')} #{actual_formatted}")
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support "fuzzy_matcher"
-
-
1
module RSpec
-
1
module Matchers
-
# Mixin designed to support the composable matcher features
-
# of RSpec 3+. Mix it into your custom matcher classes to
-
# allow them to be used in a composable fashion.
-
#
-
# @api public
-
1
module Composable
-
# Creates a compound `and` expectation. The matcher will
-
# only pass if both sub-matchers pass.
-
# This can be chained together to form an arbitrarily long
-
# chain of matchers.
-
#
-
# @example
-
# expect(alphabet).to start_with("a").and end_with("z")
-
# expect(alphabet).to start_with("a") & end_with("z")
-
#
-
# @note The negative form (`expect(...).not_to matcher.and other`)
-
# is not supported at this time.
-
1
def and(matcher)
-
BuiltIn::Compound::And.new self, matcher
-
end
-
1
alias & and
-
-
# Creates a compound `or` expectation. The matcher will
-
# pass if either sub-matcher passes.
-
# This can be chained together to form an arbitrarily long
-
# chain of matchers.
-
#
-
# @example
-
# expect(stoplight.color).to eq("red").or eq("green").or eq("yellow")
-
# expect(stoplight.color).to eq("red") | eq("green") | eq("yellow")
-
#
-
# @note The negative form (`expect(...).not_to matcher.or other`)
-
# is not supported at this time.
-
1
def or(matcher)
-
BuiltIn::Compound::Or.new self, matcher
-
end
-
1
alias | or
-
-
# Delegates to `#matches?`. Allows matchers to be used in composable
-
# fashion and also supports using matchers in case statements.
-
1
def ===(value)
-
matches?(value)
-
end
-
-
1
private
-
-
# This provides a generic way to fuzzy-match an expected value against
-
# an actual value. It understands nested data structures (e.g. hashes
-
# and arrays) and is able to match against a matcher being used as
-
# the expected value or within the expected value at any level of
-
# nesting.
-
#
-
# Within a custom matcher you are encouraged to use this whenever your
-
# matcher needs to match two values, unless it needs more precise semantics.
-
# For example, the `eq` matcher _does not_ use this as it is meant to
-
# use `==` (and only `==`) for matching.
-
#
-
# @param expected [Object] what is expected
-
# @param actual [Object] the actual value
-
#
-
# @!visibility public
-
1
def values_match?(expected, actual)
-
expected = with_matchers_cloned(expected)
-
Support::FuzzyMatcher.values_match?(expected, actual)
-
end
-
-
# Returns the description of the given object in a way that is
-
# aware of composed matchers. If the object is a matcher with
-
# a `description` method, returns the description; otherwise
-
# returns `object.inspect`.
-
#
-
# You are encouraged to use this in your custom matcher's
-
# `description`, `failure_message` or
-
# `failure_message_when_negated` implementation if you are
-
# supporting matcher arguments.
-
#
-
# @!visibility public
-
1
def description_of(object)
-
RSpec::Support::ObjectFormatter.format(object)
-
end
-
-
# Transforms the given data structue (typically a hash or array)
-
# into a new data structure that, when `#inspect` is called on it,
-
# will provide descriptions of any contained matchers rather than
-
# the normal `#inspect` output.
-
#
-
# You are encouraged to use this in your custom matcher's
-
# `description`, `failure_message` or
-
# `failure_message_when_negated` implementation if you are
-
# supporting any arguments which may be a data structure
-
# containing matchers.
-
#
-
# @!visibility public
-
1
def surface_descriptions_in(item)
-
if Matchers.is_a_describable_matcher?(item)
-
DescribableItem.new(item)
-
elsif Hash === item
-
Hash[surface_descriptions_in(item.to_a)]
-
elsif Struct === item
-
RSpec::Support::ObjectFormatter.format(item)
-
elsif should_enumerate?(item)
-
begin
-
item.map { |subitem| surface_descriptions_in(subitem) }
-
rescue IOError # STDOUT is enumerable but `map` raises an error
-
RSpec::Support::ObjectFormatter.format(item)
-
end
-
else
-
item
-
end
-
end
-
-
# @private
-
# Historically, a single matcher instance was only checked
-
# against a single value. Given that the matcher was only
-
# used once, it's been common to memoize some intermediate
-
# calculation that is derived from the `actual` value in
-
# order to reuse that intermediate result in the failure
-
# message.
-
#
-
# This can cause a problem when using such a matcher as an
-
# argument to another matcher in a composed matcher expression,
-
# since the matcher instance may be checked against multiple
-
# values and produce invalid results due to the memoization.
-
#
-
# To deal with this, we clone any matchers in `expected` via
-
# this method when using `values_match?`, so that any memoization
-
# does not "leak" between checks.
-
1
def with_matchers_cloned(object)
-
if Matchers.is_a_matcher?(object)
-
object.clone
-
elsif Hash === object
-
Hash[with_matchers_cloned(object.to_a)]
-
elsif Struct === object
-
object
-
elsif should_enumerate?(object)
-
begin
-
object.map { |subobject| with_matchers_cloned(subobject) }
-
rescue IOError # STDOUT is enumerable but `map` raises an error
-
object
-
end
-
else
-
object
-
end
-
end
-
-
1
if String.ancestors.include?(Enumerable) # 1.8.7
-
skipped
# :nocov:
-
skipped
# Strings are not enumerable on 1.9, and on 1.8 they are an infinitely
-
skipped
# nested enumerable: since ruby lacks a character class, it yields
-
skipped
# 1-character strings, which are themselves enumerable, composed of a
-
skipped
# a single 1-character string, which is an enumerable, etc.
-
skipped
#
-
skipped
# @api private
-
skipped
def should_enumerate?(item)
-
skipped
return false if String === item
-
skipped
Enumerable === item && !(Range === item)
-
skipped
end
-
skipped
# :nocov:
-
else
-
# @api private
-
1
def should_enumerate?(item)
-
Enumerable === item && !(Range === item)
-
end
-
end
-
1
module_function :surface_descriptions_in, :should_enumerate?
-
-
# Wraps an item in order to surface its `description` via `inspect`.
-
# @api private
-
1
DescribableItem = Struct.new(:item) do
-
1
def inspect
-
"(#{item.description})"
-
end
-
-
1
def pretty_print(pp)
-
pp.text "(#{item.description})"
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
# Defines the custom matcher DSL.
-
1
module DSL
-
# Defines a custom matcher.
-
# @see RSpec::Matchers
-
1
def define(name, &declarations)
-
warn_about_block_args(name, declarations)
-
define_method name do |*expected, &block_arg|
-
RSpec::Matchers::DSL::Matcher.new(name, declarations, self, *expected, &block_arg)
-
end
-
end
-
1
alias_method :matcher, :define
-
-
1
private
-
-
1
if Proc.method_defined?(:parameters)
-
1
def warn_about_block_args(name, declarations)
-
declarations.parameters.each do |type, arg_name|
-
next unless type == :block
-
RSpec.warning("Your `#{name}` custom matcher receives a block argument (`#{arg_name}`), " \
-
"but due to limitations in ruby, RSpec cannot provide the block. Instead, " \
-
"use the `block_arg` method to access the block")
-
end
-
end
-
else
-
skipped
# :nocov:
-
skipped
def warn_about_block_args(*)
-
skipped
# There's no way to detect block params on 1.8 since the method reflection APIs don't expose it
-
skipped
end
-
skipped
# :nocov:
-
end
-
-
2
RSpec.configure { |c| c.extend self } if RSpec.respond_to?(:configure)
-
-
# Contains the methods that are available from within the
-
# `RSpec::Matchers.define` DSL for creating custom matchers.
-
1
module Macros
-
# Stores the block that is used to determine whether this matcher passes
-
# or fails. The block should return a boolean value. When the matcher is
-
# passed to `expect(...).to` and the block returns `true`, then the expectation
-
# passes. Similarly, when the matcher is passed to `expect(...).not_to` and the
-
# block returns `false`, then the expectation passes.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :be_even do
-
# match do |actual|
-
# actual.even?
-
# end
-
# end
-
#
-
# expect(4).to be_even # passes
-
# expect(3).not_to be_even # passes
-
# expect(3).to be_even # fails
-
# expect(4).not_to be_even # fails
-
#
-
# @yield [Object] actual the actual value (i.e. the value wrapped by `expect`)
-
1
def match(&match_block)
-
define_user_override(:matches?, match_block) do |actual|
-
begin
-
@actual = actual
-
RSpec::Support.with_failure_notifier(RAISE_NOTIFIER) do
-
super(*actual_arg_for(match_block))
-
end
-
rescue RSpec::Expectations::ExpectationNotMetError
-
false
-
end
-
end
-
end
-
-
# @private
-
1
RAISE_NOTIFIER = Proc.new { |err, _opts| raise err }
-
-
# Use this to define the block for a negative expectation (`expect(...).not_to`)
-
# when the positive and negative forms require different handling. This
-
# is rarely necessary, but can be helpful, for example, when specifying
-
# asynchronous processes that require different timeouts.
-
#
-
# @yield [Object] actual the actual value (i.e. the value wrapped by `expect`)
-
1
def match_when_negated(&match_block)
-
define_user_override(:does_not_match?, match_block) do |actual|
-
@actual = actual
-
super(*actual_arg_for(match_block))
-
end
-
end
-
-
# Use this instead of `match` when the block will raise an exception
-
# rather than returning false to indicate a failure.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :accept_as_valid do |candidate_address|
-
# match_unless_raises ValidationException do |validator|
-
# validator.validate(candidate_address)
-
# end
-
# end
-
#
-
# expect(email_validator).to accept_as_valid("person@company.com")
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
1
def match_unless_raises(expected_exception=Exception, &match_block)
-
define_user_override(:matches?, match_block) do |actual|
-
@actual = actual
-
begin
-
super(*actual_arg_for(match_block))
-
rescue expected_exception => @rescued_exception
-
false
-
else
-
true
-
end
-
end
-
end
-
-
# Customizes the failure messsage to use when this matcher is
-
# asked to positively match. Only use this when the message
-
# generated by default doesn't suit your needs.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :have_strength do |expected|
-
# match { your_match_logic }
-
#
-
# failure_message do |actual|
-
# "Expected strength of #{expected}, but had #{actual.strength}"
-
# end
-
# end
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
1
def failure_message(&definition)
-
define_user_override(__method__, definition)
-
end
-
-
# Customize the failure messsage to use when this matcher is asked
-
# to negatively match. Only use this when the message generated by
-
# default doesn't suit your needs.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :have_strength do |expected|
-
# match { your_match_logic }
-
#
-
# failure_message_when_negated do |actual|
-
# "Expected not to have strength of #{expected}, but did"
-
# end
-
# end
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
1
def failure_message_when_negated(&definition)
-
define_user_override(__method__, definition)
-
end
-
-
# Customize the description to use for one-liners. Only use this when
-
# the description generated by default doesn't suit your needs.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :qualify_for do |expected|
-
# match { your_match_logic }
-
#
-
# description do
-
# "qualify for #{expected}"
-
# end
-
# end
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
1
def description(&definition)
-
define_user_override(__method__, definition)
-
end
-
-
# Tells the matcher to diff the actual and expected values in the failure
-
# message.
-
1
def diffable
-
define_method(:diffable?) { true }
-
end
-
-
# Declares that the matcher can be used in a block expectation.
-
# Users will not be able to use your matcher in a block
-
# expectation without declaring this.
-
# (e.g. `expect { do_something }.to matcher`).
-
1
def supports_block_expectations
-
define_method(:supports_block_expectations?) { true }
-
end
-
-
# Convenience for defining methods on this matcher to create a fluent
-
# interface. The trick about fluent interfaces is that each method must
-
# return self in order to chain methods together. `chain` handles that
-
# for you. If the method is invoked and the
-
# `include_chain_clauses_in_custom_matcher_descriptions` config option
-
# hash been enabled, the chained method name and args will be added to the
-
# default description and failure message.
-
#
-
# In the common case where you just want the chained method to store some
-
# value(s) for later use (e.g. in `match`), you can provide one or more
-
# attribute names instead of a block; the chained method will store its
-
# arguments in instance variables with those names, and the values will
-
# be exposed via getters.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :have_errors_on do |key|
-
# chain :with do |message|
-
# @message = message
-
# end
-
#
-
# match do |actual|
-
# actual.errors[key] == @message
-
# end
-
# end
-
#
-
# expect(minor).to have_errors_on(:age).with("Not old enough to participate")
-
1
def chain(method_name, *attr_names, &definition)
-
unless block_given? ^ attr_names.any?
-
raise ArgumentError, "You must pass either a block or some attribute names (but not both) to `chain`."
-
end
-
-
definition = assign_attributes(attr_names) if attr_names.any?
-
-
define_user_override(method_name, definition) do |*args, &block|
-
super(*args, &block)
-
@chained_method_clauses.push([method_name, args])
-
self
-
end
-
end
-
-
1
def assign_attributes(attr_names)
-
attr_reader(*attr_names)
-
private(*attr_names)
-
-
lambda do |*attr_values|
-
attr_names.zip(attr_values) do |attr_name, attr_value|
-
instance_variable_set(:"@#{attr_name}", attr_value)
-
end
-
end
-
end
-
-
# assign_attributes isn't defined in the private section below because
-
# that makes MRI 1.9.2 emit a warning about private attributes.
-
1
private :assign_attributes
-
-
1
private
-
-
# Does the following:
-
#
-
# - Defines the named method using a user-provided block
-
# in @user_method_defs, which is included as an ancestor
-
# in the singleton class in which we eval the `define` block.
-
# - Defines an overriden definition for the same method
-
# usign the provided `our_def` block.
-
# - Provides a default `our_def` block for the common case
-
# of needing to call the user's definition with `@actual`
-
# as an arg, but only if their block's arity can handle it.
-
#
-
# This compiles the user block into an actual method, allowing
-
# them to use normal method constructs like `return`
-
# (e.g. for a early guard statement), while allowing us to define
-
# an override that can provide the wrapped handling
-
# (e.g. assigning `@actual`, rescueing errors, etc) and
-
# can `super` to the user's definition.
-
1
def define_user_override(method_name, user_def, &our_def)
-
@user_method_defs.__send__(:define_method, method_name, &user_def)
-
our_def ||= lambda { super(*actual_arg_for(user_def)) }
-
define_method(method_name, &our_def)
-
end
-
-
# Defines deprecated macro methods from RSpec 2 for backwards compatibility.
-
# @deprecated Use the methods from {Macros} instead.
-
1
module Deprecated
-
# @deprecated Use {Macros#match} instead.
-
1
def match_for_should(&definition)
-
RSpec.deprecate("`match_for_should`", :replacement => "`match`")
-
match(&definition)
-
end
-
-
# @deprecated Use {Macros#match_when_negated} instead.
-
1
def match_for_should_not(&definition)
-
RSpec.deprecate("`match_for_should_not`", :replacement => "`match_when_negated`")
-
match_when_negated(&definition)
-
end
-
-
# @deprecated Use {Macros#failure_message} instead.
-
1
def failure_message_for_should(&definition)
-
RSpec.deprecate("`failure_message_for_should`", :replacement => "`failure_message`")
-
failure_message(&definition)
-
end
-
-
# @deprecated Use {Macros#failure_message_when_negated} instead.
-
1
def failure_message_for_should_not(&definition)
-
RSpec.deprecate("`failure_message_for_should_not`", :replacement => "`failure_message_when_negated`")
-
failure_message_when_negated(&definition)
-
end
-
end
-
end
-
-
# Defines default implementations of the matcher
-
# protocol methods for custom matchers. You can
-
# override any of these using the {RSpec::Matchers::DSL::Macros Macros} methods
-
# from within an `RSpec::Matchers.define` block.
-
1
module DefaultImplementations
-
1
include BuiltIn::BaseMatcher::DefaultFailureMessages
-
-
# @api private
-
# Used internally by objects returns by `should` and `should_not`.
-
1
def diffable?
-
false
-
end
-
-
# The default description.
-
1
def description
-
english_name = EnglishPhrasing.split_words(name)
-
expected_list = EnglishPhrasing.list(expected)
-
"#{english_name}#{expected_list}#{chained_method_clause_sentences}"
-
end
-
-
# Matchers do not support block expectations by default. You
-
# must opt-in.
-
1
def supports_block_expectations?
-
false
-
end
-
-
# Most matchers do not expect call stack jumps.
-
1
def expects_call_stack_jump?
-
false
-
end
-
-
1
private
-
-
1
def chained_method_clause_sentences
-
return '' unless Expectations.configuration.include_chain_clauses_in_custom_matcher_descriptions?
-
-
@chained_method_clauses.map do |(method_name, method_args)|
-
english_name = EnglishPhrasing.split_words(method_name)
-
arg_list = EnglishPhrasing.list(method_args)
-
" #{english_name}#{arg_list}"
-
end.join
-
end
-
end
-
-
# The class used for custom matchers. The block passed to
-
# `RSpec::Matchers.define` will be evaluated in the context
-
# of the singleton class of an instance, and will have the
-
# {RSpec::Matchers::DSL::Macros Macros} methods available.
-
1
class Matcher
-
# Provides default implementations for the matcher protocol methods.
-
1
include DefaultImplementations
-
-
# Allows expectation expressions to be used in the match block.
-
1
include RSpec::Matchers
-
-
# Supports the matcher composability features of RSpec 3+.
-
1
include Composable
-
-
# Makes the macro methods available to an `RSpec::Matchers.define` block.
-
1
extend Macros
-
1
extend Macros::Deprecated
-
-
# Exposes the value being matched against -- generally the object
-
# object wrapped by `expect`.
-
1
attr_reader :actual
-
-
# Exposes the exception raised during the matching by `match_unless_raises`.
-
# Could be useful to extract details for a failure message.
-
1
attr_reader :rescued_exception
-
-
# The block parameter used in the expectation
-
1
attr_reader :block_arg
-
-
# The name of the matcher.
-
1
attr_reader :name
-
-
# @api private
-
1
def initialize(name, declarations, matcher_execution_context, *expected, &block_arg)
-
@name = name
-
@actual = nil
-
@expected_as_array = expected
-
@matcher_execution_context = matcher_execution_context
-
@chained_method_clauses = []
-
@block_arg = block_arg
-
-
class << self
-
# See `Macros#define_user_override` above, for an explanation.
-
include(@user_method_defs = Module.new)
-
self
-
end.class_exec(*expected, &declarations)
-
end
-
-
# Provides the expected value. This will return an array if
-
# multiple arguments were passed to the matcher; otherwise it
-
# will return a single value.
-
# @see #expected_as_array
-
1
def expected
-
if expected_as_array.size == 1
-
expected_as_array[0]
-
else
-
expected_as_array
-
end
-
end
-
-
# Returns the expected value as an an array. This exists primarily
-
# to aid in upgrading from RSpec 2.x, since in RSpec 2, `expected`
-
# always returned an array.
-
# @see #expected
-
1
attr_reader :expected_as_array
-
-
# Adds the name (rather than a cryptic hex number)
-
# so we can identify an instance of
-
# the matcher in error messages (e.g. for `NoMethodError`)
-
1
def inspect
-
"#<#{self.class.name} #{name}>"
-
end
-
-
1
if RUBY_VERSION.to_f >= 1.9
-
# Indicates that this matcher responds to messages
-
# from the `@matcher_execution_context` as well.
-
# Also, supports getting a method object for such methods.
-
1
def respond_to_missing?(method, include_private=false)
-
super || @matcher_execution_context.respond_to?(method, include_private)
-
end
-
else # for 1.8.7
-
skipped
# :nocov:
-
skipped
# Indicates that this matcher responds to messages
-
skipped
# from the `@matcher_execution_context` as well.
-
skipped
def respond_to?(method, include_private=false)
-
skipped
super || @matcher_execution_context.respond_to?(method, include_private)
-
skipped
end
-
skipped
# :nocov:
-
end
-
-
1
private
-
-
1
def actual_arg_for(block)
-
block.arity.zero? ? [] : [@actual]
-
end
-
-
# Takes care of forwarding unhandled messages to the
-
# `@matcher_execution_context` (typically the current
-
# running `RSpec::Core::Example`). This is needed by
-
# rspec-rails so that it can define matchers that wrap
-
# Rails' test helper methods, but it's also a useful
-
# feature in its own right.
-
1
def method_missing(method, *args, &block)
-
if @matcher_execution_context.respond_to?(method)
-
@matcher_execution_context.__send__ method, *args, &block
-
else
-
super(method, *args, &block)
-
end
-
end
-
end
-
end
-
end
-
end
-
-
1
RSpec::Matchers.extend RSpec::Matchers::DSL
-
1
module RSpec
-
1
module Matchers
-
# Facilitates converting ruby objects to English phrases.
-
1
module EnglishPhrasing
-
# Converts a symbol into an English expression.
-
#
-
# split_words(:banana_creme_pie) #=> "banana creme pie"
-
#
-
1
def self.split_words(sym)
-
sym.to_s.gsub(/_/, ' ')
-
end
-
-
# @note The returned string has a leading space except
-
# when given an empty list.
-
#
-
# Converts an object (often a collection of objects)
-
# into an English list.
-
#
-
# list(['banana', 'kiwi', 'mango'])
-
# #=> " \"banana\", \"kiwi\", and \"mango\""
-
#
-
# Given an empty collection, returns the empty string.
-
#
-
# list([]) #=> ""
-
#
-
1
def self.list(obj)
-
return " #{RSpec::Support::ObjectFormatter.format(obj)}" if !obj || Struct === obj
-
items = Array(obj).map { |w| RSpec::Support::ObjectFormatter.format(w) }
-
case items.length
-
when 0
-
""
-
when 1
-
" #{items[0]}"
-
when 2
-
" #{items[0]} and #{items[1]}"
-
else
-
" #{items[0...-1].join(', ')}, and #{items[-1]}"
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
# @api private
-
# Handles list of expected values when there is a need to render
-
# multiple diffs. Also can handle one value.
-
1
class ExpectedsForMultipleDiffs
-
# @private
-
# Default diff label when there is only one matcher in diff
-
# output
-
1
DEFAULT_DIFF_LABEL = "Diff:".freeze
-
-
# @private
-
# Maximum readable matcher description length
-
1
DESCRIPTION_MAX_LENGTH = 65
-
-
1
def initialize(expected_list)
-
@expected_list = expected_list
-
end
-
-
# @api private
-
# Wraps provided expected value in instance of
-
# ExpectedForMultipleDiffs. If provided value is already an
-
# ExpectedForMultipleDiffs then it just returns it.
-
# @param [Any] expected value to be wrapped
-
# @return [RSpec::Matchers::ExpectedsForMultipleDiffs]
-
1
def self.from(expected)
-
return expected if self === expected
-
new([[expected, DEFAULT_DIFF_LABEL]])
-
end
-
-
# @api private
-
# Wraps provided matcher list in instance of
-
# ExpectedForMultipleDiffs.
-
# @param [Array<Any>] matchers list of matchers to wrap
-
# @return [RSpec::Matchers::ExpectedsForMultipleDiffs]
-
1
def self.for_many_matchers(matchers)
-
new(matchers.map { |m| [m.expected, diff_label_for(m)] })
-
end
-
-
# @api private
-
# Returns message with diff(s) appended for provided differ
-
# factory and actual value if there are any
-
# @param [String] message original failure message
-
# @param [Proc] differ
-
# @param [Any] actual value
-
# @return [String]
-
1
def message_with_diff(message, differ, actual)
-
diff = diffs(differ, actual)
-
message = "#{message}\n#{diff}" unless diff.empty?
-
message
-
end
-
-
1
private
-
-
1
def self.diff_label_for(matcher)
-
"Diff for (#{truncated(RSpec::Support::ObjectFormatter.format(matcher))}):"
-
end
-
-
1
def self.truncated(description)
-
return description if description.length <= DESCRIPTION_MAX_LENGTH
-
description[0...DESCRIPTION_MAX_LENGTH - 3] << "..."
-
end
-
-
1
def diffs(differ, actual)
-
@expected_list.map do |(expected, diff_label)|
-
diff = differ.diff(actual, expected)
-
next if diff.strip.empty?
-
"#{diff_label}#{diff}"
-
end.compact.join("\n")
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
1
class << self
-
# @private
-
1
attr_accessor :last_matcher, :last_expectation_handler
-
end
-
-
# @api private
-
# Used by rspec-core to clear the state used to generate
-
# descriptions after an example.
-
1
def self.clear_generated_description
-
self.last_matcher = nil
-
self.last_expectation_handler = nil
-
end
-
-
# @api private
-
# Generates an an example description based on the last expectation.
-
# Used by rspec-core's one-liner syntax.
-
1
def self.generated_description
-
return nil if last_expectation_handler.nil?
-
"#{last_expectation_handler.verb} #{last_description}"
-
end
-
-
1
private
-
-
1
def self.last_description
-
last_matcher.respond_to?(:description) ? last_matcher.description : <<-MESSAGE
-
When you call a matcher in an example without a String, like this:
-
-
specify { expect(object).to matcher }
-
-
or this:
-
-
it { is_expected.to matcher }
-
-
RSpec expects the matcher to have a #description method. You should either
-
add a String to the example this matcher is being used in, or give it a
-
description method. Then you won't have to suffer this lengthy warning again.
-
MESSAGE
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
# Provides the necessary plumbing to wrap a matcher with a decorator.
-
# @private
-
1
class MatcherDelegator
-
1
include Composable
-
1
attr_reader :base_matcher
-
-
1
def initialize(base_matcher)
-
@base_matcher = base_matcher
-
end
-
-
1
def method_missing(*args, &block)
-
base_matcher.__send__(*args, &block)
-
end
-
-
1
if ::RUBY_VERSION.to_f > 1.8
-
1
def respond_to_missing?(name, include_all=false)
-
super || base_matcher.respond_to?(name, include_all)
-
end
-
else
-
skipped
# :nocov:
-
skipped
def respond_to?(name, include_all=false)
-
skipped
super || base_matcher.respond_to?(name, include_all)
-
skipped
end
-
skipped
# :nocov:
-
end
-
-
1
def initialize_copy(other)
-
@base_matcher = @base_matcher.clone
-
super
-
end
-
end
-
end
-
end
-
1
require 'rspec/support'
-
1
RSpec::Support.require_rspec_support 'caller_filter'
-
1
RSpec::Support.require_rspec_support 'warnings'
-
1
RSpec::Support.require_rspec_support 'ruby_features'
-
-
23
RSpec::Support.define_optimized_require_for_rspec(:mocks) { |f| require_relative f }
-
-
%w[
-
instance_method_stasher
-
method_double
-
argument_matchers
-
example_methods
-
proxy
-
test_double
-
argument_list_matcher
-
message_expectation
-
order_group
-
error_generator
-
space
-
mutate_const
-
targets
-
syntax
-
configuration
-
verifying_double
-
version
-
18
].each { |name| RSpec::Support.require_rspec_mocks name }
-
-
# Share the top-level RSpec namespace, because we are a core supported
-
# extension.
-
1
module RSpec
-
# Contains top-level utility methods. While this contains a few
-
# public methods, these are not generally meant to be called from
-
# a test or example. They exist primarily for integration with
-
# test frameworks (such as rspec-core).
-
1
module Mocks
-
# Performs per-test/example setup. This should be called before
-
# an test or example begins.
-
1
def self.setup
-
@space_stack << (@space = space.new_scope)
-
end
-
-
# Verifies any message expectations that were set during the
-
# test or example. This should be called at the end of an example.
-
1
def self.verify
-
space.verify_all
-
end
-
-
# Cleans up all test double state (including any methods that were
-
# redefined on partial doubles). This _must_ be called after
-
# each example, even if an error was raised during the example.
-
1
def self.teardown
-
space.reset_all
-
@space_stack.pop
-
@space = @space_stack.last || @root_space
-
end
-
-
# Adds an allowance (stub) on `subject`
-
#
-
# @param subject the subject to which the message will be added
-
# @param message a symbol, representing the message that will be
-
# added.
-
# @param opts a hash of options, :expected_from is used to set the
-
# original call site
-
# @yield an optional implementation for the allowance
-
#
-
# @example Defines the implementation of `foo` on `bar`, using the passed block
-
# x = 0
-
# RSpec::Mocks.allow_message(bar, :foo) { x += 1 }
-
1
def self.allow_message(subject, message, opts={}, &block)
-
space.proxy_for(subject).add_stub(message, opts, &block)
-
end
-
-
# Sets a message expectation on `subject`.
-
# @param subject the subject on which the message will be expected
-
# @param message a symbol, representing the message that will be
-
# expected.
-
# @param opts a hash of options, :expected_from is used to set the
-
# original call site
-
# @yield an optional implementation for the expectation
-
#
-
# @example Expect the message `foo` to receive `bar`, then call it
-
# RSpec::Mocks.expect_message(bar, :foo)
-
# bar.foo
-
1
def self.expect_message(subject, message, opts={}, &block)
-
space.proxy_for(subject).add_message_expectation(message, opts, &block)
-
end
-
-
# Call the passed block and verify mocks after it has executed. This allows
-
# mock usage in arbitrary places, such as a `before(:all)` hook.
-
1
def self.with_temporary_scope
-
setup
-
-
begin
-
yield
-
verify
-
ensure
-
teardown
-
end
-
end
-
-
1
class << self
-
# @private
-
1
attr_reader :space
-
end
-
1
@space_stack = []
-
1
@root_space = @space = RSpec::Mocks::RootSpace.new
-
-
# @private
-
1
IGNORED_BACKTRACE_LINE = 'this backtrace line is ignored'
-
-
# To speed up boot time a bit, delay loading optional or rarely
-
# used features until their first use.
-
1
autoload :AnyInstance, "rspec/mocks/any_instance"
-
1
autoload :ExpectChain, "rspec/mocks/message_chain"
-
1
autoload :StubChain, "rspec/mocks/message_chain"
-
1
autoload :MarshalExtension, "rspec/mocks/marshal_extension"
-
-
# Namespace for mock-related matchers.
-
1
module Matchers
-
1
autoload :HaveReceived, "rspec/mocks/matchers/have_received"
-
1
autoload :Receive, "rspec/mocks/matchers/receive"
-
1
autoload :ReceiveMessageChain, "rspec/mocks/matchers/receive_message_chain"
-
1
autoload :ReceiveMessages, "rspec/mocks/matchers/receive_messages"
-
end
-
end
-
end
-
# We intentionally do not use the `RSpec::Support.require...` methods
-
# here so that this file can be loaded individually, as documented
-
# below.
-
1
require 'rspec/mocks/argument_matchers'
-
1
require 'rspec/support/fuzzy_matcher'
-
-
1
module RSpec
-
1
module Mocks
-
# Wrapper for matching arguments against a list of expected values. Used by
-
# the `with` method on a `MessageExpectation`:
-
#
-
# expect(object).to receive(:message).with(:a, 'b', 3)
-
# object.message(:a, 'b', 3)
-
#
-
# Values passed to `with` can be literal values or argument matchers that
-
# match against the real objects .e.g.
-
#
-
# expect(object).to receive(:message).with(hash_including(:a => 'b'))
-
#
-
# Can also be used directly to match the contents of any `Array`. This
-
# enables 3rd party mocking libs to take advantage of rspec's argument
-
# matching without using the rest of rspec-mocks.
-
#
-
# require 'rspec/mocks/argument_list_matcher'
-
# include RSpec::Mocks::ArgumentMatchers
-
#
-
# arg_list_matcher = RSpec::Mocks::ArgumentListMatcher.new(123, hash_including(:a => 'b'))
-
# arg_list_matcher.args_match?(123, :a => 'b')
-
#
-
# This class is immutable.
-
#
-
# @see ArgumentMatchers
-
1
class ArgumentListMatcher
-
# @private
-
1
attr_reader :expected_args
-
-
# @api public
-
# @param [Array] expected_args a list of expected literals and/or argument matchers
-
#
-
# Initializes an `ArgumentListMatcher` with a collection of literal
-
# values and/or argument matchers.
-
#
-
# @see ArgumentMatchers
-
# @see #args_match?
-
1
def initialize(*expected_args)
-
1
@expected_args = expected_args
-
1
ensure_expected_args_valid!
-
end
-
-
# @api public
-
# @param [Array] args
-
#
-
# Matches each element in the `expected_args` against the element in the same
-
# position of the arguments passed to `new`.
-
#
-
# @see #initialize
-
1
def args_match?(*args)
-
Support::FuzzyMatcher.values_match?(resolve_expected_args_based_on(args), args)
-
end
-
-
# @private
-
# Resolves abstract arg placeholders like `no_args` and `any_args` into
-
# a more concrete arg list based on the provided `actual_args`.
-
1
def resolve_expected_args_based_on(actual_args)
-
return [] if [ArgumentMatchers::NoArgsMatcher::INSTANCE] == expected_args
-
-
any_args_index = expected_args.index { |a| ArgumentMatchers::AnyArgsMatcher::INSTANCE == a }
-
return expected_args unless any_args_index
-
-
replace_any_args_with_splat_of_anything(any_args_index, actual_args.count)
-
end
-
-
1
private
-
-
1
def replace_any_args_with_splat_of_anything(before_count, actual_args_count)
-
any_args_count = actual_args_count - expected_args.count + 1
-
after_count = expected_args.count - before_count - 1
-
-
any_args = 1.upto(any_args_count).map { ArgumentMatchers::AnyArgMatcher::INSTANCE }
-
expected_args.first(before_count) + any_args + expected_args.last(after_count)
-
end
-
-
1
def ensure_expected_args_valid!
-
2
if expected_args.count { |a| ArgumentMatchers::AnyArgsMatcher::INSTANCE == a } > 1
-
raise ArgumentError, "`any_args` can only be passed to " \
-
"`with` once but you have passed it multiple times."
-
1
elsif expected_args.count > 1 && expected_args.any? { |a| ArgumentMatchers::NoArgsMatcher::INSTANCE == a }
-
raise ArgumentError, "`no_args` can only be passed as a " \
-
"singleton argument to `with` (i.e. `with(no_args)`), " \
-
"but you have passed additional arguments."
-
end
-
end
-
-
# Value that will match all argument lists.
-
#
-
# @private
-
1
MATCH_ALL = new(ArgumentMatchers::AnyArgsMatcher::INSTANCE)
-
end
-
end
-
end
-
# This cannot take advantage of our relative requires, since this file is a
-
# dependency of `rspec/mocks/argument_list_matcher.rb`. See comment there for
-
# details.
-
1
require 'rspec/support/matcher_definition'
-
-
1
module RSpec
-
1
module Mocks
-
# ArgumentMatchers are placeholders that you can include in message
-
# expectations to match arguments against a broader check than simple
-
# equality.
-
#
-
# With the exception of `any_args` and `no_args`, they all match against
-
# the arg in same position in the argument list.
-
#
-
# @see ArgumentListMatcher
-
1
module ArgumentMatchers
-
# Acts like an arg splat, matching any number of args at any point in an arg list.
-
#
-
# @example
-
# expect(object).to receive(:message).with(1, 2, any_args)
-
#
-
# # matches any of these:
-
# object.message(1, 2)
-
# object.message(1, 2, 3)
-
# object.message(1, 2, 3, 4)
-
1
def any_args
-
AnyArgsMatcher::INSTANCE
-
end
-
-
# Matches any argument at all.
-
#
-
# @example
-
# expect(object).to receive(:message).with(anything)
-
1
def anything
-
AnyArgMatcher::INSTANCE
-
end
-
-
# Matches no arguments.
-
#
-
# @example
-
# expect(object).to receive(:message).with(no_args)
-
1
def no_args
-
NoArgsMatcher::INSTANCE
-
end
-
-
# Matches if the actual argument responds to the specified messages.
-
#
-
# @example
-
# expect(object).to receive(:message).with(duck_type(:hello))
-
# expect(object).to receive(:message).with(duck_type(:hello, :goodbye))
-
1
def duck_type(*args)
-
DuckTypeMatcher.new(*args)
-
end
-
-
# Matches a boolean value.
-
#
-
# @example
-
# expect(object).to receive(:message).with(boolean())
-
1
def boolean
-
BooleanMatcher::INSTANCE
-
end
-
-
# Matches a hash that includes the specified key(s) or key/value pairs.
-
# Ignores any additional keys.
-
#
-
# @example
-
# expect(object).to receive(:message).with(hash_including(:key => val))
-
# expect(object).to receive(:message).with(hash_including(:key))
-
# expect(object).to receive(:message).with(hash_including(:key, :key2 => val2))
-
1
def hash_including(*args)
-
HashIncludingMatcher.new(ArgumentMatchers.anythingize_lonely_keys(*args))
-
end
-
-
# Matches an array that includes the specified items at least once.
-
# Ignores duplicates and additional values
-
#
-
# @example
-
# expect(object).to receive(:message).with(array_including(1,2,3))
-
# expect(object).to receive(:message).with(array_including([1,2,3]))
-
1
def array_including(*args)
-
actually_an_array = Array === args.first && args.count == 1 ? args.first : args
-
ArrayIncludingMatcher.new(actually_an_array)
-
end
-
-
# Matches a hash that doesn't include the specified key(s) or key/value.
-
#
-
# @example
-
# expect(object).to receive(:message).with(hash_excluding(:key => val))
-
# expect(object).to receive(:message).with(hash_excluding(:key))
-
# expect(object).to receive(:message).with(hash_excluding(:key, :key2 => :val2))
-
1
def hash_excluding(*args)
-
HashExcludingMatcher.new(ArgumentMatchers.anythingize_lonely_keys(*args))
-
end
-
-
1
alias_method :hash_not_including, :hash_excluding
-
-
# Matches if `arg.instance_of?(klass)`
-
#
-
# @example
-
# expect(object).to receive(:message).with(instance_of(Thing))
-
1
def instance_of(klass)
-
InstanceOf.new(klass)
-
end
-
-
1
alias_method :an_instance_of, :instance_of
-
-
# Matches if `arg.kind_of?(klass)`
-
#
-
# @example
-
# expect(object).to receive(:message).with(kind_of(Thing))
-
1
def kind_of(klass)
-
KindOf.new(klass)
-
end
-
-
1
alias_method :a_kind_of, :kind_of
-
-
# @private
-
1
def self.anythingize_lonely_keys(*args)
-
hash = args.last.class == Hash ? args.delete_at(-1) : {}
-
args.each { | arg | hash[arg] = AnyArgMatcher::INSTANCE }
-
hash
-
end
-
-
# Intended to be subclassed by stateless, immutable argument matchers.
-
# Provides a `<klass name>::INSTANCE` constant for accessing a global
-
# singleton instance of the matcher. There is no need to construct
-
# multiple instance since there is no state. It also facilities the
-
# special case logic we need for some of these matchers, by making it
-
# easy to do comparisons like: `[klass::INSTANCE] == args` rather than
-
# `args.count == 1 && klass === args.first`.
-
#
-
# @private
-
1
class SingletonMatcher
-
1
private_class_method :new
-
-
1
def self.inherited(subklass)
-
4
subklass.const_set(:INSTANCE, subklass.send(:new))
-
end
-
end
-
-
# @private
-
1
class AnyArgsMatcher < SingletonMatcher
-
1
def description
-
"*(any args)"
-
end
-
end
-
-
# @private
-
1
class AnyArgMatcher < SingletonMatcher
-
1
def ===(_other)
-
true
-
end
-
-
1
def description
-
"anything"
-
end
-
end
-
-
# @private
-
1
class NoArgsMatcher < SingletonMatcher
-
1
def description
-
"no args"
-
end
-
end
-
-
# @private
-
1
class BooleanMatcher < SingletonMatcher
-
1
def ===(value)
-
true == value || false == value
-
end
-
-
1
def description
-
"boolean"
-
end
-
end
-
-
# @private
-
1
class BaseHashMatcher
-
1
def initialize(expected)
-
@expected = expected
-
end
-
-
1
def ===(predicate, actual)
-
@expected.__send__(predicate) do |k, v|
-
actual.key?(k) && Support::FuzzyMatcher.values_match?(v, actual[k])
-
end
-
rescue NoMethodError
-
false
-
end
-
-
1
def description(name)
-
"#{name}(#{formatted_expected_hash.inspect.sub(/^\{/, "").sub(/\}$/, "")})"
-
end
-
-
1
private
-
-
1
def formatted_expected_hash
-
Hash[
-
@expected.map do |k, v|
-
k = RSpec::Support.rspec_description_for_object(k)
-
v = RSpec::Support.rspec_description_for_object(v)
-
-
[k, v]
-
end
-
]
-
end
-
end
-
-
# @private
-
1
class HashIncludingMatcher < BaseHashMatcher
-
1
def ===(actual)
-
super(:all?, actual)
-
end
-
-
1
def description
-
super("hash_including")
-
end
-
end
-
-
# @private
-
1
class HashExcludingMatcher < BaseHashMatcher
-
1
def ===(actual)
-
super(:none?, actual)
-
end
-
-
1
def description
-
super("hash_not_including")
-
end
-
end
-
-
# @private
-
1
class ArrayIncludingMatcher
-
1
def initialize(expected)
-
@expected = expected
-
end
-
-
1
def ===(actual)
-
actual = actual.uniq
-
@expected.uniq.all? do |expected_element|
-
actual.any? do |actual_element|
-
RSpec::Support::FuzzyMatcher.values_match?(expected_element, actual_element)
-
end
-
end
-
end
-
-
1
def description
-
"array_including(#{formatted_expected_values})"
-
end
-
-
1
private
-
-
1
def formatted_expected_values
-
@expected.map do |x|
-
RSpec::Support.rspec_description_for_object(x)
-
end.join(", ")
-
end
-
end
-
-
# @private
-
1
class DuckTypeMatcher
-
1
def initialize(*methods_to_respond_to)
-
@methods_to_respond_to = methods_to_respond_to
-
end
-
-
1
def ===(value)
-
@methods_to_respond_to.all? { |message| value.respond_to?(message) }
-
end
-
-
1
def description
-
"duck_type(#{@methods_to_respond_to.map(&:inspect).join(', ')})"
-
end
-
end
-
-
# @private
-
1
class InstanceOf
-
1
def initialize(klass)
-
@klass = klass
-
end
-
-
1
def ===(actual)
-
actual.instance_of?(@klass)
-
end
-
-
1
def description
-
"an_instance_of(#{@klass.name})"
-
end
-
end
-
-
# @private
-
1
class KindOf
-
1
def initialize(klass)
-
@klass = klass
-
end
-
-
1
def ===(actual)
-
actual.kind_of?(@klass)
-
end
-
-
1
def description
-
"kind of #{@klass.name}"
-
end
-
end
-
-
1
matcher_namespace = name + '::'
-
1
::RSpec::Support.register_matcher_definition do |object|
-
# This is the best we have for now. We should tag all of our matchers
-
# with a module or something so we can test for it directly.
-
#
-
# (Note Module#parent in ActiveSupport is defined in a similar way.)
-
begin
-
object.class.name.include?(matcher_namespace)
-
rescue NoMethodError
-
# Some objects, like BasicObject, don't implemented standard
-
# reflection methods.
-
false
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support "object_formatter"
-
-
1
module RSpec
-
1
module Mocks
-
# Raised when a message expectation is not satisfied.
-
1
MockExpectationError = Class.new(Exception)
-
-
# Raised when a test double is used after it has been torn
-
# down (typically at the end of an rspec-core example).
-
1
ExpiredTestDoubleError = Class.new(MockExpectationError)
-
-
# Raised when doubles or partial doubles are used outside of the per-test lifecycle.
-
1
OutsideOfExampleError = Class.new(StandardError)
-
-
# Raised when an expectation customization method (e.g. `with`,
-
# `and_return`) is called on a message expectation which has already been
-
# invoked.
-
1
MockExpectationAlreadyInvokedError = Class.new(Exception)
-
-
# Raised for situations that RSpec cannot support due to mutations made
-
# externally on arguments that RSpec is holding onto to use for later
-
# comparisons.
-
#
-
# @deprecated We no longer raise this error but the constant remains until
-
# RSpec 4 for SemVer reasons.
-
1
CannotSupportArgMutationsError = Class.new(StandardError)
-
-
# @private
-
1
UnsupportedMatcherError = Class.new(StandardError)
-
# @private
-
1
NegationUnsupportedError = Class.new(StandardError)
-
# @private
-
1
VerifyingDoubleNotDefinedError = Class.new(StandardError)
-
-
# @private
-
1
class ErrorGenerator
-
1
attr_writer :opts
-
-
1
def initialize(target=nil)
-
@target = target
-
end
-
-
# @private
-
1
def opts
-
@opts ||= {}
-
end
-
-
# @private
-
1
def raise_unexpected_message_error(message, args)
-
__raise "#{intro} received unexpected message :#{message} with #{format_args(args)}"
-
end
-
-
# @private
-
1
def raise_unexpected_message_args_error(expectation, args_for_multiple_calls, source_id=nil)
-
__raise error_message(expectation, args_for_multiple_calls), nil, source_id
-
end
-
-
# @private
-
1
def raise_missing_default_stub_error(expectation, args_for_multiple_calls)
-
message = error_message(expectation, args_for_multiple_calls)
-
message << "\n Please stub a default value first if message might be received with other args as well. \n"
-
-
__raise message
-
end
-
-
# @private
-
1
def raise_similar_message_args_error(expectation, args_for_multiple_calls, backtrace_line=nil)
-
__raise error_message(expectation, args_for_multiple_calls), backtrace_line
-
end
-
-
1
def default_error_message(expectation, expected_args, actual_args)
-
[
-
intro,
-
"received",
-
expectation.message.inspect,
-
unexpected_arguments_message(expected_args, actual_args),
-
].join(" ")
-
end
-
-
# rubocop:disable Style/ParameterLists
-
# @private
-
1
def raise_expectation_error(message, expected_received_count, argument_list_matcher,
-
actual_received_count, expectation_count_type, args,
-
backtrace_line=nil, source_id=nil)
-
expected_part = expected_part_of_expectation_error(expected_received_count, expectation_count_type, argument_list_matcher)
-
received_part = received_part_of_expectation_error(actual_received_count, args)
-
__raise "(#{intro(:unwrapped)}).#{message}#{format_args(args)}\n #{expected_part}\n #{received_part}", backtrace_line, source_id
-
end
-
# rubocop:enable Style/ParameterLists
-
-
# @private
-
1
def raise_unimplemented_error(doubled_module, method_name, object)
-
message = case object
-
when InstanceVerifyingDouble
-
"the %s class does not implement the instance method: %s" <<
-
if ObjectMethodReference.for(doubled_module, method_name).implemented?
-
". Perhaps you meant to use `class_double` instead?"
-
else
-
""
-
end
-
when ClassVerifyingDouble
-
"the %s class does not implement the class method: %s" <<
-
if InstanceMethodReference.for(doubled_module, method_name).implemented?
-
". Perhaps you meant to use `instance_double` instead?"
-
else
-
""
-
end
-
else
-
"%s does not implement: %s"
-
end
-
-
__raise message % [doubled_module.description, method_name]
-
end
-
-
# @private
-
1
def raise_non_public_error(method_name, visibility)
-
raise NoMethodError, "%s method `%s' called on %s" % [
-
visibility, method_name, intro
-
]
-
end
-
-
# @private
-
1
def raise_invalid_arguments_error(verifier)
-
__raise verifier.error_message
-
end
-
-
# @private
-
1
def raise_expired_test_double_error
-
raise ExpiredTestDoubleError,
-
"#{intro} was originally created in one example but has leaked into " \
-
"another example and can no longer be used. rspec-mocks' doubles are " \
-
"designed to only last for one example, and you need to create a new " \
-
"one in each example you wish to use it for."
-
end
-
-
# @private
-
1
def describe_expectation(verb, message, expected_received_count, _actual_received_count, args)
-
"#{verb} #{message}#{format_args(args)} #{count_message(expected_received_count)}"
-
end
-
-
# @private
-
1
def raise_out_of_order_error(message)
-
__raise "#{intro} received :#{message} out of order"
-
end
-
-
# @private
-
1
def raise_missing_block_error(args_to_yield)
-
__raise "#{intro} asked to yield |#{arg_list(args_to_yield)}| but no block was passed"
-
end
-
-
# @private
-
1
def raise_wrong_arity_error(args_to_yield, signature)
-
__raise "#{intro} yielded |#{arg_list(args_to_yield)}| to block with #{signature.description}"
-
end
-
-
# @private
-
1
def raise_only_valid_on_a_partial_double(method)
-
__raise "#{intro} is a pure test double. `#{method}` is only " \
-
"available on a partial double."
-
end
-
-
# @private
-
1
def raise_expectation_on_unstubbed_method(method)
-
__raise "#{intro} expected to have received #{method}, but that " \
-
"object is not a spy or method has not been stubbed."
-
end
-
-
# @private
-
1
def raise_expectation_on_mocked_method(method)
-
__raise "#{intro} expected to have received #{method}, but that " \
-
"method has been mocked instead of stubbed or spied."
-
end
-
-
# @private
-
1
def raise_double_negation_error(wrapped_expression)
-
__raise "Isn't life confusing enough? You've already set a " \
-
"negative message expectation and now you are trying to " \
-
"negate it again with `never`. What does an expression like " \
-
"`#{wrapped_expression}.not_to receive(:msg).never` even mean?"
-
end
-
-
# @private
-
1
def raise_verifying_double_not_defined_error(ref)
-
notify(VerifyingDoubleNotDefinedError.new(
-
"#{ref.description.inspect} is not a defined constant. " \
-
"Perhaps you misspelt it? " \
-
"Disable check with `verify_doubled_constant_names` configuration option."
-
))
-
end
-
-
# @private
-
1
def raise_have_received_disallowed(type, reason)
-
__raise "Using #{type}(...) with the `have_received` " \
-
"matcher is not supported#{reason}."
-
end
-
-
# @private
-
1
def raise_cant_constrain_count_for_negated_have_received_error(count_constraint)
-
__raise "can't use #{count_constraint} when negative"
-
end
-
-
# @private
-
1
def raise_method_not_stubbed_error(method_name)
-
__raise "The method `#{method_name}` was not stubbed or was already unstubbed"
-
end
-
-
# @private
-
1
def raise_already_invoked_error(message, calling_customization)
-
error_message = "The message expectation for #{intro}.#{message} has already been invoked " \
-
"and cannot be modified further (e.g. using `#{calling_customization}`). All message expectation " \
-
"customizations must be applied before it is used for the first time."
-
-
notify MockExpectationAlreadyInvokedError.new(error_message)
-
end
-
-
1
private
-
-
1
def received_part_of_expectation_error(actual_received_count, args)
-
"received: #{count_message(actual_received_count)}" +
-
method_call_args_description(args) do
-
actual_received_count > 0 && args.length > 0
-
end
-
end
-
-
1
def expected_part_of_expectation_error(expected_received_count, expectation_count_type, argument_list_matcher)
-
"expected: #{count_message(expected_received_count, expectation_count_type)}" +
-
method_call_args_description(argument_list_matcher.expected_args) do
-
argument_list_matcher.expected_args.length > 0
-
end
-
end
-
-
1
def method_call_args_description(args)
-
case args.first
-
when ArgumentMatchers::AnyArgsMatcher then " with any arguments"
-
when ArgumentMatchers::NoArgsMatcher then " with no arguments"
-
else
-
if yield
-
" with arguments: #{format_args(args)}"
-
else
-
""
-
end
-
end
-
end
-
-
1
def unexpected_arguments_message(expected_args_string, actual_args_string)
-
"with unexpected arguments\n expected: #{expected_args_string}\n got: #{actual_args_string}"
-
end
-
-
1
def error_message(expectation, args_for_multiple_calls)
-
expected_args = format_args(expectation.expected_args)
-
actual_args = format_received_args(args_for_multiple_calls)
-
message = default_error_message(expectation, expected_args, actual_args)
-
-
if args_for_multiple_calls.one?
-
diff = diff_message(expectation.expected_args, args_for_multiple_calls.first)
-
message << "\nDiff:#{diff}" unless diff.strip.empty?
-
end
-
-
message
-
end
-
-
1
def diff_message(expected_args, actual_args)
-
formatted_expected_args = expected_args.map do |x|
-
RSpec::Support.rspec_description_for_object(x)
-
end
-
-
formatted_expected_args, actual_args = unpack_string_args(formatted_expected_args, actual_args)
-
-
differ.diff(actual_args, formatted_expected_args)
-
end
-
-
1
def unpack_string_args(formatted_expected_args, actual_args)
-
if [formatted_expected_args, actual_args].all? { |x| list_of_exactly_one_string?(x) }
-
[formatted_expected_args.first, actual_args.first]
-
else
-
[formatted_expected_args, actual_args]
-
end
-
end
-
-
1
def list_of_exactly_one_string?(args)
-
Array === args && args.count == 1 && String === args.first
-
end
-
-
1
def differ
-
RSpec::Support::Differ.new(:color => RSpec::Mocks.configuration.color?)
-
end
-
-
1
def intro(unwrapped=false)
-
case @target
-
when TestDouble then TestDoubleFormatter.format(@target, unwrapped)
-
when Class then
-
formatted = "#{@target.inspect} (class)"
-
return formatted if unwrapped
-
"#<#{formatted}>"
-
when NilClass then "nil"
-
else @target
-
end
-
end
-
-
1
def __raise(message, backtrace_line=nil, source_id=nil)
-
message = opts[:message] unless opts[:message].nil?
-
exception = RSpec::Mocks::MockExpectationError.new(message)
-
prepend_to_backtrace(exception, backtrace_line) if backtrace_line
-
notify exception, :source_id => source_id
-
end
-
-
1
if RSpec::Support::Ruby.jruby?
-
def prepend_to_backtrace(exception, line)
-
raise exception
-
rescue RSpec::Mocks::MockExpectationError => with_backtrace
-
with_backtrace.backtrace.unshift(line)
-
end
-
else
-
1
def prepend_to_backtrace(exception, line)
-
exception.set_backtrace(caller.unshift line)
-
end
-
end
-
-
1
def notify(*args)
-
RSpec::Support.notify_failure(*args)
-
end
-
-
1
def format_args(args)
-
return "(no args)" if args.empty?
-
"(#{arg_list(args)})"
-
end
-
-
1
def arg_list(args)
-
args.map { |arg| RSpec::Support::ObjectFormatter.format(arg) }.join(", ")
-
end
-
-
1
def format_received_args(args_for_multiple_calls)
-
grouped_args(args_for_multiple_calls).map do |args_for_one_call, index|
-
"#{format_args(args_for_one_call)}#{group_count(index, args_for_multiple_calls)}"
-
end.join("\n ")
-
end
-
-
1
def count_message(count, expectation_count_type=nil)
-
return "at least #{times(count.abs)}" if count < 0 || expectation_count_type == :at_least
-
return "at most #{times(count)}" if expectation_count_type == :at_most
-
times(count)
-
end
-
-
1
def times(count)
-
"#{count} time#{count == 1 ? '' : 's'}"
-
end
-
-
1
def grouped_args(args)
-
Hash[args.group_by { |x| x }.map { |k, v| [k, v.count] }]
-
end
-
-
1
def group_count(index, args)
-
" (#{times(index)})" if args.size > 1 || index > 1
-
end
-
end
-
-
# @private
-
1
def self.error_generator
-
@error_generator ||= ErrorGenerator.new
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_mocks 'object_reference'
-
-
1
module RSpec
-
1
module Mocks
-
# Contains methods intended to be used from within code examples.
-
# Mix this in to your test context (such as a test framework base class)
-
# to use rspec-mocks with your test framework. If you're using rspec-core,
-
# it'll take care of doing this for you.
-
1
module ExampleMethods
-
1
include RSpec::Mocks::ArgumentMatchers
-
-
# @overload double()
-
# @overload double(name)
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload double(stubs)
-
# @param stubs (Hash) hash of message/return-value pairs
-
# @overload double(name, stubs)
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs (Hash) hash of message/return-value pairs
-
# @return (Double)
-
#
-
# Constructs an instance of [RSpec::Mocks::Double](RSpec::Mocks::Double) configured
-
# with an optional name, used for reporting in failure messages, and an optional
-
# hash of message/return-value pairs.
-
#
-
# @example
-
# book = double("book", :title => "The RSpec Book")
-
# book.title #=> "The RSpec Book"
-
#
-
# card = double("card", :suit => "Spades", :rank => "A")
-
# card.suit #=> "Spades"
-
# card.rank #=> "A"
-
#
-
1
def double(*args)
-
ExampleMethods.declare_double(Double, *args)
-
end
-
-
# @overload instance_double(doubled_class)
-
# @param doubled_class [String, Class]
-
# @overload instance_double(doubled_class, name)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload instance_double(doubled_class, stubs)
-
# @param doubled_class [String, Class]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload instance_double(doubled_class, name, stubs)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return InstanceVerifyingDouble
-
#
-
# Constructs a test double against a specific class. If the given class
-
# name has been loaded, only instance methods defined on the class are
-
# allowed to be stubbed. In all other ways it behaves like a
-
# [double](double).
-
1
def instance_double(doubled_class, *args)
-
ref = ObjectReference.for(doubled_class)
-
ExampleMethods.declare_verifying_double(InstanceVerifyingDouble, ref, *args)
-
end
-
-
# @overload class_double(doubled_class)
-
# @param doubled_class [String, Module]
-
# @overload class_double(doubled_class, name)
-
# @param doubled_class [String, Module]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload class_double(doubled_class, stubs)
-
# @param doubled_class [String, Module]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload class_double(doubled_class, name, stubs)
-
# @param doubled_class [String, Module]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return ClassVerifyingDouble
-
#
-
# Constructs a test double against a specific class. If the given class
-
# name has been loaded, only class methods defined on the class are
-
# allowed to be stubbed. In all other ways it behaves like a
-
# [double](double).
-
1
def class_double(doubled_class, *args)
-
ref = ObjectReference.for(doubled_class)
-
ExampleMethods.declare_verifying_double(ClassVerifyingDouble, ref, *args)
-
end
-
-
# @overload object_double(object_or_name)
-
# @param object_or_name [String, Object]
-
# @overload object_double(object_or_name, name)
-
# @param object_or_name [String, Object]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload object_double(object_or_name, stubs)
-
# @param object_or_name [String, Object]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload object_double(object_or_name, name, stubs)
-
# @param object_or_name [String, Object]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return ObjectVerifyingDouble
-
#
-
# Constructs a test double against a specific object. Only the methods
-
# the object responds to are allowed to be stubbed. If a String argument
-
# is provided, it is assumed to reference a constant object which is used
-
# for verification. In all other ways it behaves like a [double](double).
-
1
def object_double(object_or_name, *args)
-
ref = ObjectReference.for(object_or_name, :allow_direct_object_refs)
-
ExampleMethods.declare_verifying_double(ObjectVerifyingDouble, ref, *args)
-
end
-
-
# @overload spy()
-
# @overload spy(name)
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload spy(stubs)
-
# @param stubs (Hash) hash of message/return-value pairs
-
# @overload spy(name, stubs)
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs (Hash) hash of message/return-value pairs
-
# @return (Double)
-
#
-
# Constructs a test double that is optimized for use with
-
# `have_received`. With a normal double one has to stub methods in order
-
# to be able to spy them. A spy automatically spies on all methods.
-
1
def spy(*args)
-
double(*args).as_null_object
-
end
-
-
# @overload instance_spy(doubled_class)
-
# @param doubled_class [String, Class]
-
# @overload instance_spy(doubled_class, name)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload instance_spy(doubled_class, stubs)
-
# @param doubled_class [String, Class]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload instance_spy(doubled_class, name, stubs)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return InstanceVerifyingDouble
-
#
-
# Constructs a test double that is optimized for use with `have_received`
-
# against a specific class. If the given class name has been loaded, only
-
# instance methods defined on the class are allowed to be stubbed. With
-
# a normal double one has to stub methods in order to be able to spy
-
# them. An instance_spy automatically spies on all instance methods to
-
# which the class responds.
-
1
def instance_spy(*args)
-
instance_double(*args).as_null_object
-
end
-
-
# @overload object_spy(object_or_name)
-
# @param object_or_name [String, Object]
-
# @overload object_spy(object_or_name, name)
-
# @param object_or_name [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload object_spy(object_or_name, stubs)
-
# @param object_or_name [String, Object]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload object_spy(object_or_name, name, stubs)
-
# @param object_or_name [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return ObjectVerifyingDouble
-
#
-
# Constructs a test double that is optimized for use with `have_received`
-
# against a specific object. Only instance methods defined on the object
-
# are allowed to be stubbed. With a normal double one has to stub
-
# methods in order to be able to spy them. An object_spy automatically
-
# spies on all methods to which the object responds.
-
1
def object_spy(*args)
-
object_double(*args).as_null_object
-
end
-
-
# @overload class_spy(doubled_class)
-
# @param doubled_class [String, Module]
-
# @overload class_spy(doubled_class, name)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload class_spy(doubled_class, stubs)
-
# @param doubled_class [String, Module]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload class_spy(doubled_class, name, stubs)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return ClassVerifyingDouble
-
#
-
# Constructs a test double that is optimized for use with `have_received`
-
# against a specific class. If the given class name has been loaded,
-
# only class methods defined on the class are allowed to be stubbed.
-
# With a normal double one has to stub methods in order to be able to spy
-
# them. An class_spy automatically spies on all class methods to which the
-
# class responds.
-
1
def class_spy(*args)
-
class_double(*args).as_null_object
-
end
-
-
# Disables warning messages about expectations being set on nil.
-
#
-
# By default warning messages are issued when expectations are set on
-
# nil. This is to prevent false-positives and to catch potential bugs
-
# early on.
-
1
def allow_message_expectations_on_nil
-
RSpec::Mocks.space.proxy_for(nil).warn_about_expectations = false
-
end
-
-
# Stubs the named constant with the given value.
-
# Like method stubs, the constant will be restored
-
# to its original value (or lack of one, if it was
-
# undefined) when the example completes.
-
#
-
# @param constant_name [String] The fully qualified name of the constant. The current
-
# constant scoping at the point of call is not considered.
-
# @param value [Object] The value to make the constant refer to. When the
-
# example completes, the constant will be restored to its prior state.
-
# @param options [Hash] Stubbing options.
-
# @option options :transfer_nested_constants [Boolean, Array<Symbol>] Determines
-
# what nested constants, if any, will be transferred from the original value
-
# of the constant to the new value of the constant. This only works if both
-
# the original and new values are modules (or classes).
-
# @return [Object] the stubbed value of the constant
-
#
-
# @example
-
# stub_const("MyClass", Class.new) # => Replaces (or defines) MyClass with a new class object.
-
# stub_const("SomeModel::PER_PAGE", 5) # => Sets SomeModel::PER_PAGE to 5.
-
#
-
# class CardDeck
-
# SUITS = [:Spades, :Diamonds, :Clubs, :Hearts]
-
# NUM_CARDS = 52
-
# end
-
#
-
# stub_const("CardDeck", Class.new)
-
# CardDeck::SUITS # => uninitialized constant error
-
# CardDeck::NUM_CARDS # => uninitialized constant error
-
#
-
# stub_const("CardDeck", Class.new, :transfer_nested_constants => true)
-
# CardDeck::SUITS # => our suits array
-
# CardDeck::NUM_CARDS # => 52
-
#
-
# stub_const("CardDeck", Class.new, :transfer_nested_constants => [:SUITS])
-
# CardDeck::SUITS # => our suits array
-
# CardDeck::NUM_CARDS # => uninitialized constant error
-
1
def stub_const(constant_name, value, options={})
-
ConstantMutator.stub(constant_name, value, options)
-
end
-
-
# Hides the named constant with the given value. The constant will be
-
# undefined for the duration of the test.
-
#
-
# Like method stubs, the constant will be restored to its original value
-
# when the example completes.
-
#
-
# @param constant_name [String] The fully qualified name of the constant.
-
# The current constant scoping at the point of call is not considered.
-
#
-
# @example
-
# hide_const("MyClass") # => MyClass is now an undefined constant
-
1
def hide_const(constant_name)
-
ConstantMutator.hide(constant_name)
-
end
-
-
# Verifies that the given object received the expected message during the
-
# course of the test. On a spy objects or as null object doubles this
-
# works for any method, on other objects the method must have
-
# been stubbed beforehand in order for messages to be verified.
-
#
-
# Stubbing and verifying messages received in this way implements the
-
# Test Spy pattern.
-
#
-
# @param method_name [Symbol] name of the method expected to have been
-
# called.
-
#
-
# @example
-
# invitation = double('invitation', accept: true)
-
# user.accept_invitation(invitation)
-
# expect(invitation).to have_received(:accept)
-
#
-
# # You can also use most message expectations:
-
# expect(invitation).to have_received(:accept).with(mailer).once
-
#
-
# @note `have_received(...).with(...)` is unable to work properly when
-
# passed arguments are mutated after the spy records the received message.
-
1
def have_received(method_name, &block)
-
Matchers::HaveReceived.new(method_name, &block)
-
end
-
-
# @method expect
-
# Used to wrap an object in preparation for setting a mock expectation
-
# on it.
-
#
-
# @example
-
# expect(obj).to receive(:foo).with(5).and_return(:return_value)
-
#
-
# @note This method is usually provided by rspec-expectations. However,
-
# if you use rspec-mocks without rspec-expectations, there's a definition
-
# of it that is made available here. If you disable the `:expect` syntax
-
# this method will be undefined.
-
-
# @method allow
-
# Used to wrap an object in preparation for stubbing a method
-
# on it.
-
#
-
# @example
-
# allow(dbl).to receive(:foo).with(5).and_return(:return_value)
-
#
-
# @note If you disable the `:expect` syntax this method will be undefined.
-
-
# @method expect_any_instance_of
-
# Used to wrap a class in preparation for setting a mock expectation
-
# on instances of it.
-
#
-
# @example
-
# expect_any_instance_of(MyClass).to receive(:foo)
-
#
-
# @note If you disable the `:expect` syntax this method will be undefined.
-
-
# @method allow_any_instance_of
-
# Used to wrap a class in preparation for stubbing a method
-
# on instances of it.
-
#
-
# @example
-
# allow_any_instance_of(MyClass).to receive(:foo)
-
#
-
# @note This is only available when you have enabled the `expect` syntax.
-
-
# @method receive
-
# Used to specify a message that you expect or allow an object
-
# to receive. The object returned by `receive` supports the same
-
# fluent interface that `should_receive` and `stub` have always
-
# supported, allowing you to constrain the arguments or number of
-
# times, and configure how the object should respond to the message.
-
#
-
# @example
-
# expect(obj).to receive(:hello).with("world").exactly(3).times
-
#
-
# @note If you disable the `:expect` syntax this method will be undefined.
-
-
# @method receive_messages
-
# Shorthand syntax used to setup message(s), and their return value(s),
-
# that you expect or allow an object to receive. The method takes a hash
-
# of messages and their respective return values. Unlike with `receive`,
-
# you cannot apply further customizations using a block or the fluent
-
# interface.
-
#
-
# @example
-
# allow(obj).to receive_messages(:speak => "Hello World")
-
# allow(obj).to receive_messages(:speak => "Hello", :meow => "Meow")
-
#
-
# @note If you disable the `:expect` syntax this method will be undefined.
-
-
# @method receive_message_chain
-
# @overload receive_message_chain(method1, method2)
-
# @overload receive_message_chain("method1.method2")
-
# @overload receive_message_chain(method1, method_to_value_hash)
-
#
-
# stubs/mocks a chain of messages on an object or test double.
-
#
-
# ## Warning:
-
#
-
# Chains can be arbitrarily long, which makes it quite painless to
-
# violate the Law of Demeter in violent ways, so you should consider any
-
# use of `receive_message_chain` a code smell. Even though not all code smells
-
# indicate real problems (think fluent interfaces), `receive_message_chain` still
-
# results in brittle examples. For example, if you write
-
# `allow(foo).to receive_message_chain(:bar, :baz => 37)` in a spec and then the
-
# implementation calls `foo.baz.bar`, the stub will not work.
-
#
-
# @example
-
# allow(double).to receive_message_chain("foo.bar") { :baz }
-
# allow(double).to receive_message_chain(:foo, :bar => :baz)
-
# allow(double).to receive_message_chain(:foo, :bar) { :baz }
-
#
-
# # Given any of ^^ these three forms ^^:
-
# double.foo.bar # => :baz
-
#
-
# # Common use in Rails/ActiveRecord:
-
# allow(Article).to receive_message_chain("recent.published") { [Article.new] }
-
#
-
# @note If you disable the `:expect` syntax this method will be undefined.
-
-
# @private
-
1
def self.included(klass)
-
1
klass.class_exec do
-
# This gets mixed in so that if `RSpec::Matchers` is included in
-
# `klass` later, it's definition of `expect` will take precedence.
-
1
include ExpectHost unless method_defined?(:expect)
-
end
-
end
-
-
# @private
-
1
def self.extended(object)
-
# This gets extended in so that if `RSpec::Matchers` is included in
-
# `klass` later, it's definition of `expect` will take precedence.
-
object.extend ExpectHost unless object.respond_to?(:expect)
-
end
-
-
# @private
-
1
def self.declare_verifying_double(type, ref, *args)
-
if RSpec::Mocks.configuration.verify_doubled_constant_names? &&
-
!ref.defined?
-
-
RSpec::Mocks.error_generator.raise_verifying_double_not_defined_error(ref)
-
end
-
-
RSpec::Mocks.configuration.verifying_double_callbacks.each do |block|
-
block.call(ref)
-
end
-
-
declare_double(type, ref, *args)
-
end
-
-
# @private
-
1
def self.declare_double(type, *args)
-
args << {} unless Hash === args.last
-
type.new(*args)
-
end
-
-
# This module exists to host the `expect` method for cases where
-
# rspec-mocks is used w/o rspec-expectations.
-
1
module ExpectHost
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class InstanceMethodStasher
-
1
def initialize(object, method)
-
@object = object
-
@method = method
-
@klass = (class << object; self; end)
-
-
@original_method = nil
-
@method_is_stashed = false
-
end
-
-
1
attr_reader :original_method
-
-
1
if RUBY_VERSION.to_f < 1.9
-
# @private
-
def method_is_stashed?
-
@method_is_stashed
-
end
-
-
# @private
-
def stash
-
return if !method_defined_directly_on_klass? || @method_is_stashed
-
-
@klass.__send__(:alias_method, stashed_method_name, @method)
-
@method_is_stashed = true
-
end
-
-
# @private
-
def stashed_method_name
-
"obfuscated_by_rspec_mocks__#{@method}"
-
end
-
private :stashed_method_name
-
-
# @private
-
def restore
-
return unless @method_is_stashed
-
-
if @klass.__send__(:method_defined?, @method)
-
@klass.__send__(:undef_method, @method)
-
end
-
@klass.__send__(:alias_method, @method, stashed_method_name)
-
@klass.__send__(:remove_method, stashed_method_name)
-
@method_is_stashed = false
-
end
-
else
-
-
# @private
-
1
def method_is_stashed?
-
!!@original_method
-
end
-
-
# @private
-
1
def stash
-
return unless method_defined_directly_on_klass?
-
@original_method ||= ::RSpec::Support.method_handle_for(@object, @method)
-
end
-
-
# @private
-
1
def restore
-
return unless @original_method
-
-
if @klass.__send__(:method_defined?, @method)
-
@klass.__send__(:undef_method, @method)
-
end
-
-
handle_restoration_failures do
-
@klass.__send__(:define_method, @method, @original_method)
-
end
-
-
@original_method = nil
-
end
-
end
-
-
1
if RUBY_DESCRIPTION.include?('2.0.0p247') || RUBY_DESCRIPTION.include?('2.0.0p195')
-
# ruby 2.0.0-p247 and 2.0.0-p195 both have a bug that we can't work around :(.
-
# https://bugs.ruby-lang.org/issues/8686
-
def handle_restoration_failures
-
yield
-
rescue TypeError
-
RSpec.warn_with(
-
"RSpec failed to properly restore a partial double (#{@object.inspect}) " \
-
"to its original state due to a known bug in MRI 2.0.0-p195 & p247 " \
-
"(https://bugs.ruby-lang.org/issues/8686). This object may remain " \
-
"screwed up for the rest of this process. Please upgrade to 2.0.0-p353 or above.",
-
:call_site => nil, :use_spec_location_as_call_site => true
-
)
-
end
-
else
-
1
def handle_restoration_failures
-
# No known reasons for restoration to fail on other rubies.
-
yield
-
end
-
end
-
-
1
private
-
-
# @private
-
1
def method_defined_directly_on_klass?
-
method_defined_on_klass? && method_owned_by_klass?
-
end
-
-
# @private
-
1
def method_defined_on_klass?(klass=@klass)
-
MethodReference.method_defined_at_any_visibility?(klass, @method)
-
end
-
-
1
def method_owned_by_klass?
-
owner = @klass.instance_method(@method).owner
-
-
# On Ruby 2.0.0+ the owner of a method on a class which has been
-
# `prepend`ed may actually be an instance, e.g.
-
# `#<MyClass:0x007fbb94e3cd10>`, rather than the expected `MyClass`.
-
owner = owner.class unless Module === owner
-
-
# On some 1.9s (e.g. rubinius) aliased methods
-
# can report the wrong owner. Example:
-
# class MyClass
-
# class << self
-
# alias alternate_new new
-
# end
-
# end
-
#
-
# MyClass.owner(:alternate_new) returns `Class` when incorrect,
-
# but we need to consider the owner to be `MyClass` because
-
# it is not actually available on `Class` but is on `MyClass`.
-
# Hence, we verify that the owner actually has the method defined.
-
# If the given owner does not have the method defined, we assume
-
# that the method is actually owned by @klass.
-
owner == @klass || !(method_defined_on_klass?(owner))
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# A message expectation that only allows concrete return values to be set
-
# for a message. While this same effect can be achieved using a standard
-
# MessageExpecation, this version is much faster and so can be used as an
-
# optimization.
-
#
-
# @private
-
1
class SimpleMessageExpectation
-
1
def initialize(message, response, error_generator, backtrace_line=nil)
-
@message, @response, @error_generator, @backtrace_line = message.to_sym, response, error_generator, backtrace_line
-
@received = false
-
end
-
-
1
def invoke(*_)
-
@received = true
-
@response
-
end
-
-
1
def matches?(message, *_)
-
@message == message.to_sym
-
end
-
-
1
def called_max_times?
-
false
-
end
-
-
1
def verify_messages_received
-
return if @received
-
@error_generator.raise_expectation_error(
-
@message, 1, ArgumentListMatcher::MATCH_ALL, 0, nil, [], @backtrace_line
-
)
-
end
-
-
1
def unadvise(_)
-
end
-
end
-
-
# Represents an individual method stub or message expectation. The methods
-
# defined here can be used to configure how it behaves. The methods return
-
# `self` so that they can be chained together to form a fluent interface.
-
1
class MessageExpectation
-
# @!group Configuring Responses
-
-
# @overload and_return(value)
-
# @overload and_return(first_value, second_value)
-
#
-
# Tells the object to return a value when it receives the message. Given
-
# more than one value, the first value is returned the first time the
-
# message is received, the second value is returned the next time, etc,
-
# etc.
-
#
-
# If the message is received more times than there are values, the last
-
# value is received for every subsequent call.
-
#
-
# @return [nil] No further chaining is supported after this.
-
# @example
-
# allow(counter).to receive(:count).and_return(1)
-
# counter.count # => 1
-
# counter.count # => 1
-
#
-
# allow(counter).to receive(:count).and_return(1,2,3)
-
# counter.count # => 1
-
# counter.count # => 2
-
# counter.count # => 3
-
# counter.count # => 3
-
# counter.count # => 3
-
# # etc
-
1
def and_return(first_value, *values)
-
raise_already_invoked_error_if_necessary(__method__)
-
if negative?
-
raise "`and_return` is not supported with negative message expectations"
-
end
-
-
if block_given?
-
raise ArgumentError, "Implementation blocks aren't supported with `and_return`"
-
end
-
-
values.unshift(first_value)
-
@expected_received_count = [@expected_received_count, values.size].max unless ignoring_args? || (@expected_received_count == 0 && @at_least)
-
self.terminal_implementation_action = AndReturnImplementation.new(values)
-
-
nil
-
end
-
-
# Tells the object to delegate to the original unmodified method
-
# when it receives the message.
-
#
-
# @note This is only available on partial doubles.
-
#
-
# @return [nil] No further chaining is supported after this.
-
# @example
-
# expect(counter).to receive(:increment).and_call_original
-
# original_count = counter.count
-
# counter.increment
-
# expect(counter.count).to eq(original_count + 1)
-
1
def and_call_original
-
and_wrap_original do |original, *args, &block|
-
original.call(*args, &block)
-
end
-
end
-
-
# Decorates the stubbed method with the supplied block. The original
-
# unmodified method is passed to the block along with any method call
-
# arguments so you can delegate to it, whilst still being able to
-
# change what args are passed to it and/or change the return value.
-
#
-
# @note This is only available on partial doubles.
-
#
-
# @return [nil] No further chaining is supported after this.
-
# @example
-
# expect(api).to receive(:large_list).and_wrap_original do |original_method, *args, &block|
-
# original_method.call(*args, &block).first(10)
-
# end
-
1
def and_wrap_original(&block)
-
if RSpec::Mocks::TestDouble === @method_double.object
-
@error_generator.raise_only_valid_on_a_partial_double(:and_call_original)
-
else
-
warn_about_stub_override if implementation.inner_action
-
@implementation = AndWrapOriginalImplementation.new(@method_double.original_implementation_callable, block)
-
@yield_receiver_to_implementation_block = false
-
end
-
-
nil
-
end
-
-
# @overload and_raise
-
# @overload and_raise(ExceptionClass)
-
# @overload and_raise(ExceptionClass, message)
-
# @overload and_raise(exception_instance)
-
#
-
# Tells the object to raise an exception when the message is received.
-
#
-
# @return [nil] No further chaining is supported after this.
-
# @note
-
# When you pass an exception class, the MessageExpectation will raise
-
# an instance of it, creating it with `exception` and passing `message`
-
# if specified. If the exception class initializer requires more than
-
# one parameters, you must pass in an instance and not the class,
-
# otherwise this method will raise an ArgumentError exception.
-
#
-
# @example
-
# allow(car).to receive(:go).and_raise
-
# allow(car).to receive(:go).and_raise(OutOfGas)
-
# allow(car).to receive(:go).and_raise(OutOfGas, "At least 2 oz of gas needed to drive")
-
# allow(car).to receive(:go).and_raise(OutOfGas.new(2, :oz))
-
1
def and_raise(*args)
-
raise_already_invoked_error_if_necessary(__method__)
-
self.terminal_implementation_action = Proc.new { raise(*args) }
-
nil
-
end
-
-
# @overload and_throw(symbol)
-
# @overload and_throw(symbol, object)
-
#
-
# Tells the object to throw a symbol (with the object if that form is
-
# used) when the message is received.
-
#
-
# @return [nil] No further chaining is supported after this.
-
# @example
-
# allow(car).to receive(:go).and_throw(:out_of_gas)
-
# allow(car).to receive(:go).and_throw(:out_of_gas, :level => 0.1)
-
1
def and_throw(*args)
-
raise_already_invoked_error_if_necessary(__method__)
-
self.terminal_implementation_action = Proc.new { throw(*args) }
-
nil
-
end
-
-
# Tells the object to yield one or more args to a block when the message
-
# is received.
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# stream.stub(:open).and_yield(StringIO.new)
-
1
def and_yield(*args, &block)
-
raise_already_invoked_error_if_necessary(__method__)
-
yield @eval_context = Object.new if block
-
-
# Initialize args to yield now that it's being used, see also: comment
-
# in constructor.
-
@args_to_yield ||= []
-
-
@args_to_yield << args
-
self.initial_implementation_action = AndYieldImplementation.new(@args_to_yield, @eval_context, @error_generator)
-
self
-
end
-
# @!endgroup
-
-
# @!group Constraining Receive Counts
-
-
# Constrain a message expectation to be received a specific number of
-
# times.
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# expect(dealer).to receive(:deal_card).exactly(10).times
-
1
def exactly(n, &block)
-
raise_already_invoked_error_if_necessary(__method__)
-
self.inner_implementation_action = block
-
set_expected_received_count :exactly, n
-
self
-
end
-
-
# Constrain a message expectation to be received at least a specific
-
# number of times.
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# expect(dealer).to receive(:deal_card).at_least(9).times
-
1
def at_least(n, &block)
-
raise_already_invoked_error_if_necessary(__method__)
-
set_expected_received_count :at_least, n
-
-
if n == 0
-
raise "at_least(0) has been removed, use allow(...).to receive(:message) instead"
-
end
-
-
self.inner_implementation_action = block
-
-
self
-
end
-
-
# Constrain a message expectation to be received at most a specific
-
# number of times.
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# expect(dealer).to receive(:deal_card).at_most(10).times
-
1
def at_most(n, &block)
-
raise_already_invoked_error_if_necessary(__method__)
-
self.inner_implementation_action = block
-
set_expected_received_count :at_most, n
-
self
-
end
-
-
# Syntactic sugar for `exactly`, `at_least` and `at_most`
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# expect(dealer).to receive(:deal_card).exactly(10).times
-
# expect(dealer).to receive(:deal_card).at_least(10).times
-
# expect(dealer).to receive(:deal_card).at_most(10).times
-
1
def times(&block)
-
self.inner_implementation_action = block
-
self
-
end
-
-
# Expect a message not to be received at all.
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# expect(car).to receive(:stop).never
-
1
def never
-
error_generator.raise_double_negation_error("expect(obj)") if negative?
-
@expected_received_count = 0
-
self
-
end
-
-
# Expect a message to be received exactly one time.
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# expect(car).to receive(:go).once
-
1
def once(&block)
-
self.inner_implementation_action = block
-
set_expected_received_count :exactly, 1
-
self
-
end
-
-
# Expect a message to be received exactly two times.
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# expect(car).to receive(:go).twice
-
1
def twice(&block)
-
self.inner_implementation_action = block
-
set_expected_received_count :exactly, 2
-
self
-
end
-
-
# Expect a message to be received exactly three times.
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# expect(car).to receive(:go).thrice
-
1
def thrice(&block)
-
self.inner_implementation_action = block
-
set_expected_received_count :exactly, 3
-
self
-
end
-
# @!endgroup
-
-
# @!group Other Constraints
-
-
# Constrains a stub or message expectation to invocations with specific
-
# arguments.
-
#
-
# With a stub, if the message might be received with other args as well,
-
# you should stub a default value first, and then stub or mock the same
-
# message using `with` to constrain to specific arguments.
-
#
-
# A message expectation will fail if the message is received with different
-
# arguments.
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# allow(cart).to receive(:add) { :failure }
-
# allow(cart).to receive(:add).with(Book.new(:isbn => 1934356379)) { :success }
-
# cart.add(Book.new(:isbn => 1234567890))
-
# # => :failure
-
# cart.add(Book.new(:isbn => 1934356379))
-
# # => :success
-
#
-
# expect(cart).to receive(:add).with(Book.new(:isbn => 1934356379)) { :success }
-
# cart.add(Book.new(:isbn => 1234567890))
-
# # => failed expectation
-
# cart.add(Book.new(:isbn => 1934356379))
-
# # => passes
-
1
def with(*args, &block)
-
raise_already_invoked_error_if_necessary(__method__)
-
if args.empty?
-
raise ArgumentError,
-
"`with` must have at least one argument. Use `no_args` matcher to set the expectation of receiving no arguments."
-
end
-
-
self.inner_implementation_action = block
-
@argument_list_matcher = ArgumentListMatcher.new(*args)
-
self
-
end
-
-
# Expect messages to be received in a specific order.
-
#
-
# @return [MessageExpecation] self, to support further chaining.
-
# @example
-
# expect(api).to receive(:prepare).ordered
-
# expect(api).to receive(:run).ordered
-
# expect(api).to receive(:finish).ordered
-
1
def ordered(&block)
-
self.inner_implementation_action = block
-
additional_expected_calls.times do
-
@order_group.register(self)
-
end
-
@ordered = true
-
self
-
end
-
-
# @private
-
# Contains the parts of `MessageExpecation` that aren't part of
-
# rspec-mocks' public API. The class is very big and could really use
-
# some collaborators it delegates to for this stuff but for now this was
-
# the simplest way to split the public from private stuff to make it
-
# easier to publish the docs for the APIs we want published.
-
1
module ImplementationDetails
-
1
attr_accessor :error_generator, :implementation
-
1
attr_reader :message
-
1
attr_reader :orig_object
-
1
attr_writer :expected_received_count, :expected_from, :argument_list_matcher
-
1
protected :expected_received_count=, :expected_from=, :error_generator, :error_generator=, :implementation=
-
-
# rubocop:disable Style/ParameterLists
-
1
def initialize(error_generator, expectation_ordering, expected_from, method_double,
-
type=:expectation, opts={}, &implementation_block)
-
@error_generator = error_generator
-
@error_generator.opts = opts
-
@expected_from = expected_from
-
@method_double = method_double
-
@orig_object = @method_double.object
-
@message = @method_double.method_name
-
@actual_received_count = 0
-
@expected_received_count = type == :expectation ? 1 : :any
-
@argument_list_matcher = ArgumentListMatcher::MATCH_ALL
-
@order_group = expectation_ordering
-
@order_group.register(self) unless type == :stub
-
@expectation_type = type
-
@ordered = false
-
@at_least = @at_most = @exactly = nil
-
-
# Initialized to nil so that we don't allocate an array for every
-
# mock or stub. See also comment in `and_yield`.
-
@args_to_yield = nil
-
@eval_context = nil
-
@yield_receiver_to_implementation_block = false
-
-
@implementation = Implementation.new
-
self.inner_implementation_action = implementation_block
-
end
-
# rubocop:enable Style/ParameterLists
-
-
1
def expected_args
-
@argument_list_matcher.expected_args
-
end
-
-
1
def and_yield_receiver_to_implementation
-
@yield_receiver_to_implementation_block = true
-
self
-
end
-
-
1
def yield_receiver_to_implementation_block?
-
@yield_receiver_to_implementation_block
-
end
-
-
1
def matches?(message, *args)
-
@message == message && @argument_list_matcher.args_match?(*args)
-
end
-
-
1
def safe_invoke(parent_stub, *args, &block)
-
invoke_incrementing_actual_calls_by(1, false, parent_stub, *args, &block)
-
end
-
-
1
def invoke(parent_stub, *args, &block)
-
invoke_incrementing_actual_calls_by(1, true, parent_stub, *args, &block)
-
end
-
-
1
def invoke_without_incrementing_received_count(parent_stub, *args, &block)
-
invoke_incrementing_actual_calls_by(0, true, parent_stub, *args, &block)
-
end
-
-
1
def negative?
-
@expected_received_count == 0 && !@at_least
-
end
-
-
1
def called_max_times?
-
@expected_received_count != :any &&
-
!@at_least &&
-
@expected_received_count > 0 &&
-
@actual_received_count >= @expected_received_count
-
end
-
-
1
def matches_name_but_not_args(message, *args)
-
@message == message && !@argument_list_matcher.args_match?(*args)
-
end
-
-
1
def verify_messages_received
-
return if expected_messages_received?
-
generate_error
-
end
-
-
1
def expected_messages_received?
-
ignoring_args? || matches_exact_count? || matches_at_least_count? || matches_at_most_count?
-
end
-
-
1
def ensure_expected_ordering_received!
-
@order_group.verify_invocation_order(self) if @ordered
-
true
-
end
-
-
1
def ignoring_args?
-
@expected_received_count == :any
-
end
-
-
1
def matches_at_least_count?
-
@at_least && @actual_received_count >= @expected_received_count
-
end
-
-
1
def matches_at_most_count?
-
@at_most && @actual_received_count <= @expected_received_count
-
end
-
-
1
def matches_exact_count?
-
@expected_received_count == @actual_received_count
-
end
-
-
1
def similar_messages
-
@similar_messages ||= []
-
end
-
-
1
def advise(*args)
-
similar_messages << args
-
end
-
-
1
def unadvise(args)
-
similar_messages.delete_if { |message| args.include?(message) }
-
end
-
-
1
def generate_error
-
if similar_messages.empty?
-
@error_generator.raise_expectation_error(
-
@message, @expected_received_count, @argument_list_matcher,
-
@actual_received_count, expectation_count_type, expected_args,
-
@expected_from, exception_source_id
-
)
-
else
-
@error_generator.raise_similar_message_args_error(
-
self, @similar_messages, @expected_from
-
)
-
end
-
end
-
-
1
def raise_unexpected_message_args_error(args_for_multiple_calls)
-
@error_generator.raise_unexpected_message_args_error(self, args_for_multiple_calls, exception_source_id)
-
end
-
-
1
def expectation_count_type
-
return :at_least if @at_least
-
return :at_most if @at_most
-
nil
-
end
-
-
1
def description_for(verb)
-
@error_generator.describe_expectation(
-
verb, @message, @expected_received_count,
-
@actual_received_count, expected_args
-
)
-
end
-
-
1
def raise_out_of_order_error
-
@error_generator.raise_out_of_order_error @message
-
end
-
-
1
def additional_expected_calls
-
return 0 if @expectation_type == :stub || !@exactly
-
@expected_received_count - 1
-
end
-
-
1
def ordered?
-
@ordered
-
end
-
-
1
def negative_expectation_for?(message)
-
@message == message && negative?
-
end
-
-
1
def actual_received_count_matters?
-
@at_least || @at_most || @exactly
-
end
-
-
1
def increase_actual_received_count!
-
@actual_received_count += 1
-
end
-
-
1
private
-
-
1
def exception_source_id
-
@exception_source_id ||= "#{self.class.name} #{__id__}"
-
end
-
-
1
def invoke_incrementing_actual_calls_by(increment, allowed_to_fail, parent_stub, *args, &block)
-
args.unshift(orig_object) if yield_receiver_to_implementation_block?
-
-
if negative? || (allowed_to_fail && (@exactly || @at_most) && (@actual_received_count == @expected_received_count))
-
# args are the args we actually received, @argument_list_matcher is the
-
# list of args we were expecting
-
@error_generator.raise_expectation_error(
-
@message, @expected_received_count,
-
@argument_list_matcher,
-
@actual_received_count + increment,
-
expectation_count_type, args, nil, exception_source_id
-
)
-
end
-
-
@order_group.handle_order_constraint self
-
-
if implementation.present?
-
implementation.call(*args, &block)
-
elsif parent_stub
-
parent_stub.invoke(nil, *args, &block)
-
end
-
ensure
-
@actual_received_count += increment
-
end
-
-
1
def has_been_invoked?
-
@actual_received_count > 0
-
end
-
-
1
def raise_already_invoked_error_if_necessary(calling_customization)
-
return unless has_been_invoked?
-
-
error_generator.raise_already_invoked_error(message, calling_customization)
-
end
-
-
1
def set_expected_received_count(relativity, n)
-
@at_least = (relativity == :at_least)
-
@at_most = (relativity == :at_most)
-
@exactly = (relativity == :exactly)
-
@expected_received_count = case n
-
when Numeric then n
-
when :once then 1
-
when :twice then 2
-
when :thrice then 3
-
end
-
end
-
-
1
def initial_implementation_action=(action)
-
implementation.initial_action = action
-
end
-
-
1
def inner_implementation_action=(action)
-
return unless action
-
warn_about_stub_override if implementation.inner_action
-
implementation.inner_action = action
-
end
-
-
1
def terminal_implementation_action=(action)
-
implementation.terminal_action = action
-
end
-
-
1
def warn_about_stub_override
-
RSpec.warning(
-
"You're overriding a previous stub implementation of `#{@message}`. " \
-
"Called from #{CallerFilter.first_non_rspec_line}."
-
)
-
end
-
end
-
-
1
include ImplementationDetails
-
end
-
-
# Handles the implementation of an `and_yield` declaration.
-
# @private
-
1
class AndYieldImplementation
-
1
def initialize(args_to_yield, eval_context, error_generator)
-
@args_to_yield = args_to_yield
-
@eval_context = eval_context
-
@error_generator = error_generator
-
end
-
-
1
def call(*_args_to_ignore, &block)
-
return if @args_to_yield.empty? && @eval_context.nil?
-
-
@error_generator.raise_missing_block_error @args_to_yield unless block
-
value = nil
-
block_signature = Support::BlockSignature.new(block)
-
-
@args_to_yield.each do |args|
-
unless Support::StrictSignatureVerifier.new(block_signature, args).valid?
-
@error_generator.raise_wrong_arity_error(args, block_signature)
-
end
-
-
value = @eval_context ? @eval_context.instance_exec(*args, &block) : block.call(*args)
-
end
-
value
-
end
-
end
-
-
# Handles the implementation of an `and_return` implementation.
-
# @private
-
1
class AndReturnImplementation
-
1
def initialize(values_to_return)
-
@values_to_return = values_to_return
-
end
-
-
1
def call(*_args_to_ignore, &_block)
-
if @values_to_return.size > 1
-
@values_to_return.shift
-
else
-
@values_to_return.first
-
end
-
end
-
end
-
-
# Represents a configured implementation. Takes into account
-
# any number of sub-implementations.
-
# @private
-
1
class Implementation
-
1
attr_accessor :initial_action, :inner_action, :terminal_action
-
-
1
def call(*args, &block)
-
actions.map do |action|
-
action.call(*args, &block)
-
end.last
-
end
-
-
1
def present?
-
actions.any?
-
end
-
-
1
private
-
-
1
def actions
-
[initial_action, inner_action, terminal_action].compact
-
end
-
end
-
-
# Represents an `and_call_original` implementation.
-
# @private
-
1
class AndWrapOriginalImplementation
-
1
def initialize(method, block)
-
@method = method
-
@block = block
-
end
-
-
1
CannotModifyFurtherError = Class.new(StandardError)
-
-
1
def initial_action=(_value)
-
raise cannot_modify_further_error
-
end
-
-
1
def inner_action=(_value)
-
raise cannot_modify_further_error
-
end
-
-
1
def terminal_action=(_value)
-
raise cannot_modify_further_error
-
end
-
-
1
def present?
-
true
-
end
-
-
1
def inner_action
-
true
-
end
-
-
1
def call(*args, &block)
-
@block.call(@method, *args, &block)
-
end
-
-
1
private
-
-
1
def cannot_modify_further_error
-
CannotModifyFurtherError.new "This method has already been configured " \
-
"to call the original implementation, and cannot be modified further."
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class MethodDouble
-
# @private
-
1
attr_reader :method_name, :object, :expectations, :stubs
-
-
# @private
-
1
def initialize(object, method_name, proxy)
-
@method_name = method_name
-
@object = object
-
@proxy = proxy
-
-
@original_visibility = nil
-
@method_stasher = InstanceMethodStasher.new(object, method_name)
-
@method_is_proxied = false
-
@expectations = []
-
@stubs = []
-
end
-
-
1
def original_implementation_callable
-
# If original method is not present, uses the `method_missing`
-
# handler of the object. This accounts for cases where the user has not
-
# correctly defined `respond_to?`, and also 1.8 which does not provide
-
# method handles for missing methods even if `respond_to?` is correct.
-
@original_implementation_callable ||= original_method ||
-
Proc.new do |*args, &block|
-
@object.__send__(:method_missing, @method_name, *args, &block)
-
end
-
end
-
-
1
alias_method :save_original_implementation_callable!, :original_implementation_callable
-
-
1
def original_method
-
@original_method ||=
-
@method_stasher.original_method ||
-
@proxy.original_method_handle_for(method_name)
-
end
-
-
# @private
-
1
def visibility
-
@proxy.visibility_for(@method_name)
-
end
-
-
# @private
-
1
def object_singleton_class
-
class << @object; self; end
-
end
-
-
# @private
-
1
def configure_method
-
@original_visibility = visibility
-
@method_stasher.stash unless @method_is_proxied
-
define_proxy_method
-
end
-
-
# @private
-
1
def define_proxy_method
-
return if @method_is_proxied
-
-
save_original_implementation_callable!
-
definition_target.class_exec(self, method_name, visibility) do |method_double, method_name, visibility|
-
define_method(method_name) do |*args, &block|
-
method_double.proxy_method_invoked(self, *args, &block)
-
end
-
__send__(visibility, method_name)
-
end
-
-
@method_is_proxied = true
-
end
-
-
# The implementation of the proxied method. Subclasses may override this
-
# method to perform additional operations.
-
#
-
# @private
-
1
def proxy_method_invoked(_obj, *args, &block)
-
@proxy.message_received method_name, *args, &block
-
end
-
-
# @private
-
1
def restore_original_method
-
return show_frozen_warning if object_singleton_class.frozen?
-
return unless @method_is_proxied
-
-
remove_method_from_definition_target
-
@method_stasher.restore if @method_stasher.method_is_stashed?
-
restore_original_visibility
-
-
@method_is_proxied = false
-
end
-
-
# @private
-
1
def show_frozen_warning
-
RSpec.warn_with(
-
"WARNING: rspec-mocks was unable to restore the original `#{@method_name}` " \
-
"method on #{@object.inspect} because it has been frozen. If you reuse this " \
-
"object, `#{@method_name}` will continue to respond with its stub implementation.",
-
:call_site => nil,
-
:use_spec_location_as_call_site => true
-
)
-
end
-
-
# @private
-
1
def restore_original_visibility
-
return unless @original_visibility &&
-
MethodReference.method_defined_at_any_visibility?(object_singleton_class, @method_name)
-
-
object_singleton_class.__send__(@original_visibility, method_name)
-
end
-
-
# @private
-
1
def verify
-
expectations.each { |e| e.verify_messages_received }
-
end
-
-
# @private
-
1
def reset
-
restore_original_method
-
clear
-
end
-
-
# @private
-
1
def clear
-
expectations.clear
-
stubs.clear
-
end
-
-
# The type of message expectation to create has been extracted to its own
-
# method so that subclasses can override it.
-
#
-
# @private
-
1
def message_expectation_class
-
MessageExpectation
-
end
-
-
# @private
-
1
def add_expectation(error_generator, expectation_ordering, expected_from, opts, &implementation)
-
configure_method
-
expectation = message_expectation_class.new(error_generator, expectation_ordering,
-
expected_from, self, :expectation, opts, &implementation)
-
expectations << expectation
-
expectation
-
end
-
-
# @private
-
1
def build_expectation(error_generator, expectation_ordering)
-
expected_from = IGNORED_BACKTRACE_LINE
-
message_expectation_class.new(error_generator, expectation_ordering, expected_from, self)
-
end
-
-
# @private
-
1
def add_stub(error_generator, expectation_ordering, expected_from, opts={}, &implementation)
-
configure_method
-
stub = message_expectation_class.new(error_generator, expectation_ordering, expected_from,
-
self, :stub, opts, &implementation)
-
stubs.unshift stub
-
stub
-
end
-
-
# A simple stub can only return a concrete value for a message, and
-
# cannot match on arguments. It is used as an optimization over
-
# `add_stub` / `add_expectation` where it is known in advance that this
-
# is all that will be required of a stub, such as when passing attributes
-
# to the `double` example method. They do not stash or restore existing method
-
# definitions.
-
#
-
# @private
-
1
def add_simple_stub(method_name, response)
-
setup_simple_method_double method_name, response, stubs
-
end
-
-
# @private
-
1
def add_simple_expectation(method_name, response, error_generator, backtrace_line)
-
setup_simple_method_double method_name, response, expectations, error_generator, backtrace_line
-
end
-
-
# @private
-
1
def setup_simple_method_double(method_name, response, collection, error_generator=nil, backtrace_line=nil)
-
define_proxy_method
-
-
me = SimpleMessageExpectation.new(method_name, response, error_generator, backtrace_line)
-
collection.unshift me
-
me
-
end
-
-
# @private
-
1
def add_default_stub(*args, &implementation)
-
return if stubs.any?
-
add_stub(*args, &implementation)
-
end
-
-
# @private
-
1
def remove_stub
-
raise_method_not_stubbed_error if stubs.empty?
-
remove_stub_if_present
-
end
-
-
# @private
-
1
def remove_stub_if_present
-
expectations.empty? ? reset : stubs.clear
-
end
-
-
# @private
-
1
def raise_method_not_stubbed_error
-
RSpec::Mocks.error_generator.raise_method_not_stubbed_error(method_name)
-
end
-
-
# In Ruby 2.0.0 and above prepend will alter the method lookup chain.
-
# We use an object's singleton class to define method doubles upon,
-
# however if the object has had it's singleton class (as opposed to
-
# it's actual class) prepended too then the the method lookup chain
-
# will look in the prepended module first, **before** the singleton
-
# class.
-
#
-
# This code works around that by providing a mock definition target
-
# that is either the singleton class, or if necessary, a prepended module
-
# of our own.
-
#
-
1
if Support::RubyFeatures.module_prepends_supported?
-
-
1
private
-
-
# We subclass `Module` in order to be able to easily detect our prepended module.
-
1
RSpecPrependedModule = Class.new(Module)
-
-
1
def definition_target
-
@definition_target ||= usable_rspec_prepended_module || object_singleton_class
-
end
-
-
1
def usable_rspec_prepended_module
-
@proxy.prepended_modules_of_singleton_class.each do |mod|
-
# If we have one of our modules prepended before one of the user's
-
# modules that defines the method, use that, since our module's
-
# definition will take precedence.
-
return mod if RSpecPrependedModule === mod
-
-
# If we hit a user module with the method defined first,
-
# we must create a new prepend module, even if one exists later,
-
# because ours will only take precedence if it comes first.
-
return new_rspec_prepended_module if mod.method_defined?(method_name)
-
end
-
-
nil
-
end
-
-
1
def new_rspec_prepended_module
-
RSpecPrependedModule.new.tap do |mod|
-
object_singleton_class.__send__ :prepend, mod
-
end
-
end
-
-
else
-
-
private
-
-
def definition_target
-
object_singleton_class
-
end
-
-
end
-
-
1
private
-
-
1
def remove_method_from_definition_target
-
definition_target.__send__(:remove_method, @method_name)
-
rescue NameError
-
# This can happen when the method has been monkeyed with by
-
# something outside RSpec. This happens, for example, when
-
# `file.write` has been stubbed, and then `file.reopen(other_io)`
-
# is later called, as `File#reopen` appears to redefine `write`.
-
#
-
# Note: we could avoid rescuing this by checking
-
# `definition_target.instance_method(@method_name).owner == definition_target`,
-
# saving us from the cost of the expensive exception, but this error is
-
# extremely rare (it was discovered on 2014-12-30, only happens on
-
# RUBY_VERSION < 2.0 and our spec suite only hits this condition once),
-
# so we'd rather avoid the cost of that check for every method double,
-
# and risk the rare situation where this exception will get raised.
-
RSpec.warn_with(
-
"WARNING: RSpec could not fully restore #{@object.inspect}." \
-
"#{@method_name}, possibly because the method has been redefined " \
-
"by something outside of RSpec."
-
)
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# Represents a method on an object that may or may not be defined.
-
# The method may be an instance method on a module or a method on
-
# any object.
-
#
-
# @private
-
1
class MethodReference
-
1
def self.for(object_reference, method_name)
-
new(object_reference, method_name)
-
end
-
-
1
def initialize(object_reference, method_name)
-
@object_reference = object_reference
-
@method_name = method_name
-
end
-
-
# A method is implemented if sending the message does not result in
-
# a `NoMethodError`. It might be dynamically implemented by
-
# `method_missing`.
-
1
def implemented?
-
@object_reference.when_loaded do |m|
-
method_implemented?(m)
-
end
-
end
-
-
# Returns true if we definitively know that sending the method
-
# will result in a `NoMethodError`.
-
#
-
# This is not simply the inverse of `implemented?`: there are
-
# cases when we don't know if a method is implemented and
-
# both `implemented?` and `unimplemented?` will return false.
-
1
def unimplemented?
-
@object_reference.when_loaded do |_m|
-
return !implemented?
-
end
-
-
# If it's not loaded, then it may be implemented but we can't check.
-
false
-
end
-
-
# A method is defined if we are able to get a `Method` object for it.
-
# In that case, we can assert against metadata like the arity.
-
1
def defined?
-
@object_reference.when_loaded do |m|
-
method_defined?(m)
-
end
-
end
-
-
1
def with_signature
-
return unless (original = original_method)
-
yield Support::MethodSignature.new(original)
-
end
-
-
1
def visibility
-
@object_reference.when_loaded do |m|
-
return visibility_from(m)
-
end
-
-
# When it's not loaded, assume it's public. We don't want to
-
# wrongly treat the method as private.
-
:public
-
end
-
-
1
private
-
-
1
def original_method
-
@object_reference.when_loaded do |m|
-
self.defined? && find_method(m)
-
end
-
end
-
-
1
def self.instance_method_visibility_for(klass, method_name)
-
if klass.public_method_defined?(method_name)
-
:public
-
elsif klass.private_method_defined?(method_name)
-
:private
-
elsif klass.protected_method_defined?(method_name)
-
:protected
-
end
-
end
-
-
1
class << self
-
1
alias method_defined_at_any_visibility? instance_method_visibility_for
-
end
-
-
1
def self.method_visibility_for(object, method_name)
-
instance_method_visibility_for(class << object; self; end, method_name).tap do |vis|
-
# If the method is not defined on the class, `instance_method_visibility_for`
-
# returns `nil`. However, it may be handled dynamically by `method_missing`,
-
# so here we check `respond_to` (passing false to not check private methods).
-
#
-
# This only considers the public case, but I don't think it's possible to
-
# write `method_missing` in such a way that it handles a dynamic message
-
# with private or protected visibility. Ruby doesn't provide you with
-
# the caller info.
-
return :public if vis.nil? && object.respond_to?(method_name, false)
-
end
-
end
-
end
-
-
# @private
-
1
class InstanceMethodReference < MethodReference
-
1
private
-
-
1
def method_implemented?(mod)
-
MethodReference.method_defined_at_any_visibility?(mod, @method_name)
-
end
-
-
# Ideally, we'd use `respond_to?` for `method_implemented?` but we need a
-
# reference to an instance to do that and we don't have one. Note that
-
# we may get false negatives: if the method is implemented via
-
# `method_missing`, we'll return `false` even though it meets our
-
# definition of "implemented". However, it's the best we can do.
-
1
alias method_defined? method_implemented?
-
-
# works around the fact that repeated calls for method parameters will
-
# falsely return empty arrays on JRuby in certain circumstances, this
-
# is necessary here because we can't dup/clone UnboundMethods.
-
#
-
# This is necessary due to a bug in JRuby prior to 1.7.5 fixed in:
-
# https://github.com/jruby/jruby/commit/99a0613fe29935150d76a9a1ee4cf2b4f63f4a27
-
1
if RUBY_PLATFORM == 'java' && JRUBY_VERSION.split('.')[-1].to_i < 5
-
def find_method(mod)
-
mod.dup.instance_method(@method_name)
-
end
-
else
-
1
def find_method(mod)
-
mod.instance_method(@method_name)
-
end
-
end
-
-
1
def visibility_from(mod)
-
MethodReference.instance_method_visibility_for(mod, @method_name)
-
end
-
end
-
-
# @private
-
1
class ObjectMethodReference < MethodReference
-
1
def self.for(object_reference, method_name)
-
if ClassNewMethodReference.applies_to?(method_name) { object_reference.when_loaded { |o| o } }
-
ClassNewMethodReference.new(object_reference, method_name)
-
else
-
super
-
end
-
end
-
-
1
private
-
-
1
def method_implemented?(object)
-
object.respond_to?(@method_name, true)
-
end
-
-
1
def method_defined?(object)
-
(class << object; self; end).method_defined?(@method_name)
-
end
-
-
1
def find_method(object)
-
object.method(@method_name)
-
end
-
-
1
def visibility_from(object)
-
MethodReference.method_visibility_for(object, @method_name)
-
end
-
end
-
-
# When a class's `.new` method is stubbed, we want to use the method
-
# signature from `#initialize` because `.new`'s signature is a generic
-
# `def new(*args)` and it simply delegates to `#initialize` and forwards
-
# all args...so the method with the actually used signature is `#initialize`.
-
#
-
# This method reference implementation handles that specific case.
-
# @private
-
1
class ClassNewMethodReference < ObjectMethodReference
-
1
def self.applies_to?(method_name)
-
return false unless method_name == :new
-
klass = yield
-
return false unless klass.respond_to?(:new, true)
-
-
# We only want to apply our special logic to normal `new` methods.
-
# Methods that the user has monkeyed with should be left as-is.
-
klass.method(:new).owner == ::Class
-
end
-
-
1
def with_signature
-
@object_reference.when_loaded do |klass|
-
yield Support::MethodSignature.new(klass.instance_method(:initialize))
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'recursive_const_methods'
-
-
1
module RSpec
-
1
module Mocks
-
# Provides information about constants that may (or may not)
-
# have been mutated by rspec-mocks.
-
1
class Constant
-
1
extend Support::RecursiveConstMethods
-
-
# @api private
-
1
def initialize(name)
-
@name = name
-
@previously_defined = false
-
@stubbed = false
-
@hidden = false
-
@valid_name = true
-
yield self if block_given?
-
end
-
-
# @return [String] The fully qualified name of the constant.
-
1
attr_reader :name
-
-
# @return [Object, nil] The original value (e.g. before it
-
# was mutated by rspec-mocks) of the constant, or
-
# nil if the constant was not previously defined.
-
1
attr_accessor :original_value
-
-
# @private
-
1
attr_writer :previously_defined, :stubbed, :hidden, :valid_name
-
-
# @return [Boolean] Whether or not the constant was defined
-
# before the current example.
-
1
def previously_defined?
-
@previously_defined
-
end
-
-
# @return [Boolean] Whether or not rspec-mocks has mutated
-
# (stubbed or hidden) this constant.
-
1
def mutated?
-
@stubbed || @hidden
-
end
-
-
# @return [Boolean] Whether or not rspec-mocks has stubbed
-
# this constant.
-
1
def stubbed?
-
@stubbed
-
end
-
-
# @return [Boolean] Whether or not rspec-mocks has hidden
-
# this constant.
-
1
def hidden?
-
@hidden
-
end
-
-
# @return [Boolean] Whether or not the provided constant name
-
# is a valid Ruby constant name.
-
1
def valid_name?
-
@valid_name
-
end
-
-
# The default `to_s` isn't very useful, so a custom version is provided.
-
1
def to_s
-
"#<#{self.class.name} #{name}>"
-
end
-
1
alias inspect to_s
-
-
# @private
-
1
def self.unmutated(name)
-
previously_defined = recursive_const_defined?(name)
-
rescue NameError
-
new(name) do |c|
-
c.valid_name = false
-
end
-
else
-
new(name) do |const|
-
const.previously_defined = previously_defined
-
const.original_value = recursive_const_get(name) if previously_defined
-
end
-
end
-
-
# Queries rspec-mocks to find out information about the named constant.
-
#
-
# @param [String] name the name of the constant
-
# @return [Constant] an object contaning information about the named
-
# constant.
-
1
def self.original(name)
-
mutator = ::RSpec::Mocks.space.constant_mutator_for(name)
-
mutator ? mutator.to_constant : unmutated(name)
-
end
-
end
-
-
# Provides a means to stub constants.
-
1
class ConstantMutator
-
1
extend Support::RecursiveConstMethods
-
-
# Stubs a constant.
-
#
-
# @param (see ExampleMethods#stub_const)
-
# @option (see ExampleMethods#stub_const)
-
# @return (see ExampleMethods#stub_const)
-
#
-
# @see ExampleMethods#stub_const
-
# @note It's recommended that you use `stub_const` in your
-
# examples. This is an alternate public API that is provided
-
# so you can stub constants in other contexts (e.g. helper
-
# classes).
-
1
def self.stub(constant_name, value, options={})
-
mutator = if recursive_const_defined?(constant_name, &raise_on_invalid_const)
-
DefinedConstantReplacer
-
else
-
UndefinedConstantSetter
-
end
-
-
mutate(mutator.new(constant_name, value, options[:transfer_nested_constants]))
-
value
-
end
-
-
# Hides a constant.
-
#
-
# @param (see ExampleMethods#hide_const)
-
#
-
# @see ExampleMethods#hide_const
-
# @note It's recommended that you use `hide_const` in your
-
# examples. This is an alternate public API that is provided
-
# so you can hide constants in other contexts (e.g. helper
-
# classes).
-
1
def self.hide(constant_name)
-
mutate(ConstantHider.new(constant_name, nil, {}))
-
nil
-
end
-
-
# Contains common functionality used by all of the constant mutators.
-
#
-
# @private
-
1
class BaseMutator
-
1
include Support::RecursiveConstMethods
-
-
1
attr_reader :original_value, :full_constant_name
-
-
1
def initialize(full_constant_name, mutated_value, transfer_nested_constants)
-
@full_constant_name = normalize_const_name(full_constant_name)
-
@mutated_value = mutated_value
-
@transfer_nested_constants = transfer_nested_constants
-
@context_parts = @full_constant_name.split('::')
-
@const_name = @context_parts.pop
-
@reset_performed = false
-
end
-
-
1
def to_constant
-
const = Constant.new(full_constant_name)
-
const.original_value = original_value
-
-
const
-
end
-
-
1
def idempotently_reset
-
reset unless @reset_performed
-
@reset_performed = true
-
end
-
end
-
-
# Hides a defined constant for the duration of an example.
-
#
-
# @private
-
1
class ConstantHider < BaseMutator
-
1
def mutate
-
return unless (@defined = recursive_const_defined?(full_constant_name))
-
@context = recursive_const_get(@context_parts.join('::'))
-
@original_value = get_const_defined_on(@context, @const_name)
-
-
@context.__send__(:remove_const, @const_name)
-
end
-
-
1
def to_constant
-
return Constant.unmutated(full_constant_name) unless @defined
-
-
const = super
-
const.hidden = true
-
const.previously_defined = true
-
-
const
-
end
-
-
1
def reset
-
return unless @defined
-
@context.const_set(@const_name, @original_value)
-
end
-
end
-
-
# Replaces a defined constant for the duration of an example.
-
#
-
# @private
-
1
class DefinedConstantReplacer < BaseMutator
-
1
def initialize(*args)
-
super
-
@constants_to_transfer = []
-
end
-
-
1
def mutate
-
@context = recursive_const_get(@context_parts.join('::'))
-
@original_value = get_const_defined_on(@context, @const_name)
-
-
@constants_to_transfer = verify_constants_to_transfer!
-
-
@context.__send__(:remove_const, @const_name)
-
@context.const_set(@const_name, @mutated_value)
-
-
transfer_nested_constants
-
end
-
-
1
def to_constant
-
const = super
-
const.stubbed = true
-
const.previously_defined = true
-
-
const
-
end
-
-
1
def reset
-
@constants_to_transfer.each do |const|
-
@mutated_value.__send__(:remove_const, const)
-
end
-
-
@context.__send__(:remove_const, @const_name)
-
@context.const_set(@const_name, @original_value)
-
end
-
-
1
def transfer_nested_constants
-
@constants_to_transfer.each do |const|
-
@mutated_value.const_set(const, get_const_defined_on(original_value, const))
-
end
-
end
-
-
1
def verify_constants_to_transfer!
-
return [] unless should_transfer_nested_constants?
-
-
{ @original_value => "the original value", @mutated_value => "the stubbed value" }.each do |value, description|
-
next if value.respond_to?(:constants)
-
-
raise ArgumentError,
-
"Cannot transfer nested constants for #{@full_constant_name} " \
-
"since #{description} is not a class or module and only classes " \
-
"and modules support nested constants."
-
end
-
-
if Array === @transfer_nested_constants
-
@transfer_nested_constants = @transfer_nested_constants.map(&:to_s) if RUBY_VERSION == '1.8.7'
-
undefined_constants = @transfer_nested_constants - constants_defined_on(@original_value)
-
-
if undefined_constants.any?
-
available_constants = constants_defined_on(@original_value) - @transfer_nested_constants
-
raise ArgumentError,
-
"Cannot transfer nested constant(s) #{undefined_constants.join(' and ')} " \
-
"for #{@full_constant_name} since they are not defined. Did you mean " \
-
"#{available_constants.join(' or ')}?"
-
end
-
-
@transfer_nested_constants
-
else
-
constants_defined_on(@original_value)
-
end
-
end
-
-
1
def should_transfer_nested_constants?
-
return true if @transfer_nested_constants
-
return false unless RSpec::Mocks.configuration.transfer_nested_constants?
-
@original_value.respond_to?(:constants) && @mutated_value.respond_to?(:constants)
-
end
-
end
-
-
# Sets an undefined constant for the duration of an example.
-
#
-
# @private
-
1
class UndefinedConstantSetter < BaseMutator
-
1
def mutate
-
@parent = @context_parts.inject(Object) do |klass, name|
-
if const_defined_on?(klass, name)
-
get_const_defined_on(klass, name)
-
else
-
ConstantMutator.stub(name_for(klass, name), Module.new)
-
end
-
end
-
-
@parent.const_set(@const_name, @mutated_value)
-
end
-
-
1
def to_constant
-
const = super
-
const.stubbed = true
-
const.previously_defined = false
-
-
const
-
end
-
-
1
def reset
-
@parent.__send__(:remove_const, @const_name)
-
end
-
-
1
private
-
-
1
def name_for(parent, name)
-
root = if parent == Object
-
''
-
else
-
parent.name
-
end
-
root + '::' + name
-
end
-
end
-
-
# Uses the mutator to mutate (stub or hide) a constant. Ensures that
-
# the mutator is correctly registered so it can be backed out at the end
-
# of the test.
-
#
-
# @private
-
1
def self.mutate(mutator)
-
::RSpec::Mocks.space.register_constant_mutator(mutator)
-
mutator.mutate
-
end
-
-
# Used internally by the constant stubbing to raise a helpful
-
# error when a constant like "A::B::C" is stubbed and A::B is
-
# not a module (and thus, it's impossible to define "A::B::C"
-
# since only modules can have nested constants).
-
#
-
# @api private
-
1
def self.raise_on_invalid_const
-
lambda do |const_name, failed_name|
-
raise "Cannot stub constant #{failed_name} on #{const_name} " \
-
"since #{const_name} is not a module."
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class ObjectReference
-
# Returns an appropriate Object or Module reference based
-
# on the given argument.
-
1
def self.for(object_module_or_name, allow_direct_object_refs=false)
-
case object_module_or_name
-
when Module
-
if anonymous_module?(object_module_or_name)
-
DirectObjectReference.new(object_module_or_name)
-
else
-
# Use a `NamedObjectReference` if it has a name because this
-
# will use the original value of the constant in case it has
-
# been stubbed.
-
NamedObjectReference.new(name_of(object_module_or_name))
-
end
-
when String
-
NamedObjectReference.new(object_module_or_name)
-
else
-
if allow_direct_object_refs
-
DirectObjectReference.new(object_module_or_name)
-
else
-
raise ArgumentError,
-
"Module or String expected, got #{object_module_or_name.inspect}"
-
end
-
end
-
end
-
-
1
if Module.new.name.nil?
-
1
def self.anonymous_module?(mod)
-
!name_of(mod)
-
end
-
else # 1.8.7
-
def self.anonymous_module?(mod)
-
name_of(mod) == ""
-
end
-
end
-
1
private_class_method :anonymous_module?
-
-
1
def self.name_of(mod)
-
MODULE_NAME_METHOD.bind(mod).call
-
end
-
1
private_class_method :name_of
-
-
# @private
-
1
MODULE_NAME_METHOD = Module.instance_method(:name)
-
end
-
-
# An implementation of rspec-mocks' reference interface.
-
# Used when an object is passed to {ExampleMethods#object_double}, or
-
# an anonymous class or module is passed to {ExampleMethods#instance_double}
-
# or {ExampleMethods#class_double}.
-
# Represents a reference to that object.
-
# @see NamedObjectReference
-
1
class DirectObjectReference
-
# @param object [Object] the object to which this refers
-
1
def initialize(object)
-
@object = object
-
end
-
-
# @return [String] the object's description (via `#inspect`).
-
1
def description
-
@object.inspect
-
end
-
-
# Defined for interface parity with the other object reference
-
# implementations. Raises an `ArgumentError` to indicate that `as_stubbed_const`
-
# is invalid when passing an object argument to `object_double`.
-
1
def const_to_replace
-
raise ArgumentError,
-
"Can not perform constant replacement with an anonymous object."
-
end
-
-
# The target of the verifying double (the object itself).
-
#
-
# @return [Object]
-
1
def target
-
@object
-
end
-
-
# Always returns true for an object as the class is defined.
-
#
-
# @return [true]
-
1
def defined?
-
true
-
end
-
-
# Yields if the reference target is loaded, providing a generic mechanism
-
# to optionally run a bit of code only when a reference's target is
-
# loaded.
-
#
-
# This specific implementation always yields because direct references
-
# are always loaded.
-
#
-
# @yield [Object] the target of this reference.
-
1
def when_loaded
-
yield @object
-
end
-
end
-
-
# An implementation of rspec-mocks' reference interface.
-
# Used when a string is passed to {ExampleMethods#object_double},
-
# and when a string, named class or named module is passed to
-
# {ExampleMethods#instance_double}, or {ExampleMethods#class_double}.
-
# Represents a reference to the object named (via a constant lookup)
-
# by the string.
-
# @see DirectObjectReference
-
1
class NamedObjectReference
-
# @param const_name [String] constant name
-
1
def initialize(const_name)
-
@const_name = const_name
-
end
-
-
# @return [Boolean] true if the named constant is defined, false otherwise.
-
1
def defined?
-
!!object
-
end
-
-
# @return [String] the constant name to replace with a double.
-
1
def const_to_replace
-
@const_name
-
end
-
1
alias description const_to_replace
-
-
# @return [Object, nil] the target of the verifying double (the named object), or
-
# nil if it is not defined.
-
1
def target
-
object
-
end
-
-
# Yields if the reference target is loaded, providing a generic mechanism
-
# to optionally run a bit of code only when a reference's target is
-
# loaded.
-
#
-
# @yield [Object] the target object
-
1
def when_loaded
-
yield object if object
-
end
-
-
1
private
-
-
1
def object
-
return @object if defined?(@object)
-
@object = Constant.original(@const_name).original_value
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class OrderGroup
-
1
def initialize
-
@expectations = []
-
@invocation_order = []
-
@index = 0
-
end
-
-
# @private
-
1
def register(expectation)
-
@expectations << expectation
-
end
-
-
1
def invoked(message)
-
@invocation_order << message
-
end
-
-
# @private
-
1
def ready_for?(expectation)
-
remaining_expectations.find(&:ordered?) == expectation
-
end
-
-
# @private
-
1
def consume
-
remaining_expectations.each_with_index do |expectation, index|
-
next unless expectation.ordered?
-
-
@index += index + 1
-
return expectation
-
end
-
nil
-
end
-
-
# @private
-
1
def handle_order_constraint(expectation)
-
return unless expectation.ordered? && remaining_expectations.include?(expectation)
-
return consume if ready_for?(expectation)
-
expectation.raise_out_of_order_error
-
end
-
-
1
def verify_invocation_order(expectation)
-
expectation.raise_out_of_order_error unless expectations_invoked_in_order?
-
true
-
end
-
-
1
def clear
-
@index = 0
-
@invocation_order.clear
-
@expectations.clear
-
end
-
-
1
def empty?
-
@expectations.empty?
-
end
-
-
1
private
-
-
1
def remaining_expectations
-
@expectations[@index..-1] || []
-
end
-
-
1
def expectations_invoked_in_order?
-
invoked_expectations == expected_invocations
-
end
-
-
1
def invoked_expectations
-
@expectations.select { |e| e.ordered? && @invocation_order.include?(e) }
-
end
-
-
1
def expected_invocations
-
@invocation_order.map { |invocation| expectation_for(invocation) }.compact
-
end
-
-
1
def expectation_for(message)
-
@expectations.find { |e| message == e }
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class Proxy
-
1
SpecificMessage = Struct.new(:object, :message, :args) do
-
1
def ==(expectation)
-
expectation.orig_object == object && expectation.matches?(message, *args)
-
end
-
end
-
-
# @private
-
1
def ensure_implemented(*_args)
-
# noop for basic proxies, see VerifyingProxy for behaviour.
-
end
-
-
# @private
-
1
def initialize(object, order_group, options={})
-
@object = object
-
@order_group = order_group
-
@error_generator = ErrorGenerator.new(object)
-
@messages_received = []
-
@options = options
-
@null_object = false
-
@method_doubles = Hash.new { |h, k| h[k] = MethodDouble.new(@object, k, self) }
-
end
-
-
# @private
-
1
attr_reader :object
-
-
# @private
-
1
def null_object?
-
@null_object
-
end
-
-
# @private
-
# Tells the object to ignore any messages that aren't explicitly set as
-
# stubs or message expectations.
-
1
def as_null_object
-
@null_object = true
-
@object
-
end
-
-
# @private
-
1
def original_method_handle_for(_message)
-
nil
-
end
-
-
1
DEFAULT_MESSAGE_EXPECTATION_OPTS = {}.freeze
-
-
# @private
-
1
def add_message_expectation(method_name, opts=DEFAULT_MESSAGE_EXPECTATION_OPTS, &block)
-
location = opts.fetch(:expected_from) { CallerFilter.first_non_rspec_line }
-
meth_double = method_double_for(method_name)
-
-
if null_object? && !block
-
meth_double.add_default_stub(@error_generator, @order_group, location, opts) do
-
@object
-
end
-
end
-
-
meth_double.add_expectation @error_generator, @order_group, location, opts, &block
-
end
-
-
# @private
-
1
def add_simple_expectation(method_name, response, location)
-
method_double_for(method_name).add_simple_expectation method_name, response, @error_generator, location
-
end
-
-
# @private
-
1
def build_expectation(method_name)
-
meth_double = method_double_for(method_name)
-
-
meth_double.build_expectation(
-
@error_generator,
-
@order_group
-
)
-
end
-
-
# @private
-
1
def replay_received_message_on(expectation, &block)
-
expected_method_name = expectation.message
-
meth_double = method_double_for(expected_method_name)
-
-
if meth_double.expectations.any?
-
@error_generator.raise_expectation_on_mocked_method(expected_method_name)
-
end
-
-
unless null_object? || meth_double.stubs.any?
-
@error_generator.raise_expectation_on_unstubbed_method(expected_method_name)
-
end
-
-
@messages_received.each do |(actual_method_name, args, _)|
-
next unless expectation.matches?(actual_method_name, *args)
-
-
expectation.safe_invoke(nil)
-
block.call(*args) if block
-
end
-
end
-
-
# @private
-
1
def check_for_unexpected_arguments(expectation)
-
return if @messages_received.empty?
-
-
return if @messages_received.any? { |method_name, args, _| expectation.matches?(method_name, *args) }
-
-
name_but_not_args, others = @messages_received.partition do |(method_name, args, _)|
-
expectation.matches_name_but_not_args(method_name, *args)
-
end
-
-
return if name_but_not_args.empty? && !others.empty?
-
-
expectation.raise_unexpected_message_args_error(name_but_not_args.map { |args| args[1] })
-
end
-
-
# @private
-
1
def add_stub(method_name, opts={}, &implementation)
-
location = opts.fetch(:expected_from) { CallerFilter.first_non_rspec_line }
-
method_double_for(method_name).add_stub @error_generator, @order_group, location, opts, &implementation
-
end
-
-
# @private
-
1
def add_simple_stub(method_name, response)
-
method_double_for(method_name).add_simple_stub method_name, response
-
end
-
-
# @private
-
1
def remove_stub(method_name)
-
method_double_for(method_name).remove_stub
-
end
-
-
# @private
-
1
def remove_stub_if_present(method_name)
-
method_double_for(method_name).remove_stub_if_present
-
end
-
-
# @private
-
1
def verify
-
@method_doubles.each_value { |d| d.verify }
-
end
-
-
# @private
-
1
def reset
-
@messages_received.clear
-
end
-
-
# @private
-
1
def received_message?(method_name, *args, &block)
-
@messages_received.any? { |array| array == [method_name, args, block] }
-
end
-
-
# @private
-
1
def messages_arg_list
-
@messages_received.map { |_, args, _| args }
-
end
-
-
# @private
-
1
def has_negative_expectation?(message)
-
method_double_for(message).expectations.find { |expectation| expectation.negative_expectation_for?(message) }
-
end
-
-
# @private
-
1
def record_message_received(message, *args, &block)
-
@order_group.invoked SpecificMessage.new(object, message, args)
-
@messages_received << [message, args, block]
-
end
-
-
# @private
-
1
def message_received(message, *args, &block)
-
record_message_received message, *args, &block
-
-
expectation = find_matching_expectation(message, *args)
-
stub = find_matching_method_stub(message, *args)
-
-
if (stub && expectation && expectation.called_max_times?) || (stub && !expectation)
-
expectation.increase_actual_received_count! if expectation && expectation.actual_received_count_matters?
-
if (expectation = find_almost_matching_expectation(message, *args))
-
expectation.advise(*args) unless expectation.expected_messages_received?
-
end
-
stub.invoke(nil, *args, &block)
-
elsif expectation
-
expectation.unadvise(messages_arg_list)
-
expectation.invoke(stub, *args, &block)
-
elsif (expectation = find_almost_matching_expectation(message, *args))
-
expectation.advise(*args) if null_object? unless expectation.expected_messages_received?
-
-
if null_object? || !has_negative_expectation?(message)
-
expectation.raise_unexpected_message_args_error([args])
-
end
-
elsif (stub = find_almost_matching_stub(message, *args))
-
stub.advise(*args)
-
raise_missing_default_stub_error(stub, [args])
-
elsif Class === @object
-
@object.superclass.__send__(message, *args, &block)
-
else
-
@object.__send__(:method_missing, message, *args, &block)
-
end
-
end
-
-
# @private
-
1
def raise_unexpected_message_error(method_name, args)
-
@error_generator.raise_unexpected_message_error method_name, args
-
end
-
-
# @private
-
1
def raise_missing_default_stub_error(expectation, args_for_multiple_calls)
-
@error_generator.raise_missing_default_stub_error(expectation, args_for_multiple_calls)
-
end
-
-
# @private
-
1
def visibility_for(_method_name)
-
# This is the default (for test doubles). Subclasses override this.
-
:public
-
end
-
-
1
if Support::RubyFeatures.module_prepends_supported?
-
1
def self.prepended_modules_of(klass)
-
ancestors = klass.ancestors
-
-
# `|| 0` is necessary for Ruby 2.0, where the singleton class
-
# is only in the ancestor list when there are prepended modules.
-
singleton_index = ancestors.index(klass) || 0
-
-
ancestors[0, singleton_index]
-
end
-
-
1
def prepended_modules_of_singleton_class
-
@prepended_modules_of_singleton_class ||= RSpec::Mocks::Proxy.prepended_modules_of(@object.singleton_class)
-
end
-
end
-
-
1
private
-
-
1
def method_double_for(message)
-
@method_doubles[message.to_sym]
-
end
-
-
1
def find_matching_expectation(method_name, *args)
-
find_best_matching_expectation_for(method_name) do |expectation|
-
expectation.matches?(method_name, *args)
-
end
-
end
-
-
1
def find_almost_matching_expectation(method_name, *args)
-
find_best_matching_expectation_for(method_name) do |expectation|
-
expectation.matches_name_but_not_args(method_name, *args)
-
end
-
end
-
-
1
def find_best_matching_expectation_for(method_name)
-
first_match = nil
-
-
method_double_for(method_name).expectations.each do |expectation|
-
next unless yield expectation
-
return expectation unless expectation.called_max_times?
-
first_match ||= expectation
-
end
-
-
first_match
-
end
-
-
1
def find_matching_method_stub(method_name, *args)
-
method_double_for(method_name).stubs.find { |stub| stub.matches?(method_name, *args) }
-
end
-
-
1
def find_almost_matching_stub(method_name, *args)
-
method_double_for(method_name).stubs.find { |stub| stub.matches_name_but_not_args(method_name, *args) }
-
end
-
end
-
-
# @private
-
1
class TestDoubleProxy < Proxy
-
1
def reset
-
@method_doubles.clear
-
object.__disallow_further_usage!
-
super
-
end
-
end
-
-
# @private
-
1
class PartialDoubleProxy < Proxy
-
1
def original_method_handle_for(message)
-
if any_instance_class_recorder_observing_method?(@object.class, message)
-
message = ::RSpec::Mocks.space.
-
any_instance_recorder_for(@object.class).
-
build_alias_method_name(message)
-
end
-
-
::RSpec::Support.method_handle_for(@object, message)
-
rescue NameError
-
nil
-
end
-
-
# @private
-
1
def add_simple_expectation(method_name, response, location)
-
method_double_for(method_name).configure_method
-
super
-
end
-
-
# @private
-
1
def add_simple_stub(method_name, response)
-
method_double_for(method_name).configure_method
-
super
-
end
-
-
# @private
-
1
def visibility_for(method_name)
-
# We fall back to :public because by default we allow undefined methods
-
# to be stubbed, and when we do so, we make them public.
-
MethodReference.method_visibility_for(@object, method_name) || :public
-
end
-
-
1
def reset
-
@method_doubles.each_value { |d| d.reset }
-
super
-
end
-
-
1
def message_received(message, *args, &block)
-
RSpec::Mocks.space.any_instance_recorders_from_ancestry_of(object).each do |subscriber|
-
subscriber.notify_received_message(object, message, args, block)
-
end
-
super
-
end
-
-
1
private
-
-
1
def any_instance_class_recorder_observing_method?(klass, method_name)
-
only_return_existing = true
-
recorder = ::RSpec::Mocks.space.any_instance_recorder_for(klass, only_return_existing)
-
return true if recorder && recorder.already_observing?(method_name)
-
-
superklass = klass.superclass
-
return false if superklass.nil?
-
any_instance_class_recorder_observing_method?(superklass, method_name)
-
end
-
end
-
-
# @private
-
# When we mock or stub a method on a class, we have to treat it a bit different,
-
# because normally singleton method definitions only affect the object on which
-
# they are defined, but on classes they affect subclasses, too. As a result,
-
# we need some special handling to get the original method.
-
1
module PartialClassDoubleProxyMethods
-
1
def initialize(source_space, *args)
-
@source_space = source_space
-
super(*args)
-
end
-
-
# Consider this situation:
-
#
-
# class A; end
-
# class B < A; end
-
#
-
# allow(A).to receive(:new)
-
# expect(B).to receive(:new).and_call_original
-
#
-
# When getting the original definition for `B.new`, we cannot rely purely on
-
# using `B.method(:new)` before our redefinition is defined on `B`, because
-
# `B.method(:new)` will return a method that will execute the stubbed version
-
# of the method on `A` since singleton methods on classes are in the lookup
-
# hierarchy.
-
#
-
# To do it properly, we need to find the original definition of `new` from `A`
-
# from _before_ `A` was stubbed, and we need to rebind it to `B` so that it will
-
# run with the proper `self`.
-
#
-
# That's what this method (together with `original_unbound_method_handle_from_ancestor_for`)
-
# does.
-
1
def original_method_handle_for(message)
-
unbound_method = superclass_proxy &&
-
superclass_proxy.original_unbound_method_handle_from_ancestor_for(message.to_sym)
-
-
return super unless unbound_method
-
unbound_method.bind(object)
-
end
-
-
1
protected
-
-
1
def original_unbound_method_handle_from_ancestor_for(message)
-
method_double = @method_doubles.fetch(message) do
-
# The fact that there is no method double for this message indicates
-
# that it has not been redefined by rspec-mocks. We need to continue
-
# looking up the ancestor chain.
-
return superclass_proxy &&
-
superclass_proxy.original_unbound_method_handle_from_ancestor_for(message)
-
end
-
-
method_double.original_method.unbind
-
end
-
-
1
def superclass_proxy
-
return @superclass_proxy if defined?(@superclass_proxy)
-
-
if (superclass = object.superclass)
-
@superclass_proxy = @source_space.superclass_proxy_for(superclass)
-
else
-
@superclass_proxy = nil
-
end
-
end
-
end
-
-
# @private
-
1
class PartialClassDoubleProxy < PartialDoubleProxy
-
1
include PartialClassDoubleProxyMethods
-
end
-
-
# @private
-
1
class ProxyForNil < PartialDoubleProxy
-
1
def initialize(order_group)
-
@warn_about_expectations = true
-
super(nil, order_group)
-
end
-
-
1
attr_accessor :warn_about_expectations
-
1
alias warn_about_expectations? warn_about_expectations
-
-
1
def add_message_expectation(method_name, opts={}, &block)
-
warn(method_name) if warn_about_expectations?
-
super
-
end
-
-
1
def add_negative_message_expectation(location, method_name, &implementation)
-
warn(method_name) if warn_about_expectations?
-
super
-
end
-
-
1
def add_stub(method_name, opts={}, &implementation)
-
warn(method_name) if warn_about_expectations?
-
super
-
end
-
-
1
private
-
-
1
def warn(method_name)
-
source = CallerFilter.first_non_rspec_line
-
Kernel.warn("An expectation of :#{method_name} was set on nil. Called from #{source}. Use allow_message_expectations_on_nil to disable warnings.")
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# Allows a thread to lock out other threads from a critical section of code,
-
# while allowing the thread with the lock to reenter that section.
-
#
-
# Based on Monitor as of 2.2 -
-
# https://github.com/ruby/ruby/blob/eb7ddaa3a47bf48045d26c72eb0f263a53524ebc/lib/monitor.rb#L9
-
#
-
# Depends on Mutex, but Mutex is only available as part of core since 1.9.1:
-
# exists - http://ruby-doc.org/core-1.9.1/Mutex.html
-
# dne - http://ruby-doc.org/core-1.9.0/Mutex.html
-
#
-
# @private
-
1
class ReentrantMutex
-
1
def initialize
-
@owner = nil
-
@count = 0
-
@mutex = Mutex.new
-
end
-
-
1
def synchronize
-
enter
-
yield
-
ensure
-
exit
-
end
-
-
1
private
-
-
1
def enter
-
@mutex.lock if @owner != Thread.current
-
@owner = Thread.current
-
@count += 1
-
end
-
-
1
def exit
-
@count -= 1
-
return unless @count == 0
-
@owner = nil
-
@mutex.unlock
-
end
-
end
-
-
1
if defined? ::Mutex
-
# On 1.9 and up, this is in core, so we just use the real one
-
1
Mutex = ::Mutex
-
else # For 1.8.7
-
skipped
# :nocov:
-
skipped
RSpec::Support.require_rspec_mocks "mutex"
-
skipped
# :nocov:
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_mocks 'reentrant_mutex'
-
-
1
module RSpec
-
1
module Mocks
-
# @private
-
# Provides a default space implementation for outside
-
# the scope of an example. Called "root" because it serves
-
# as the root of the space stack.
-
1
class RootSpace
-
1
def proxy_for(*_args)
-
raise_lifecycle_message
-
end
-
-
1
def any_instance_recorder_for(*_args)
-
raise_lifecycle_message
-
end
-
-
1
def any_instance_proxy_for(*_args)
-
raise_lifecycle_message
-
end
-
-
1
def register_constant_mutator(_mutator)
-
raise_lifecycle_message
-
end
-
-
1
def any_instance_recorders_from_ancestry_of(_object)
-
raise_lifecycle_message
-
end
-
-
1
def reset_all
-
end
-
-
1
def verify_all
-
end
-
-
1
def registered?(_object)
-
false
-
end
-
-
1
def superclass_proxy_for(*_args)
-
raise_lifecycle_message
-
end
-
-
1
def new_scope
-
Space.new
-
end
-
-
1
private
-
-
1
def raise_lifecycle_message
-
raise OutsideOfExampleError,
-
"The use of doubles or partial doubles from rspec-mocks outside of the per-test lifecycle is not supported."
-
end
-
end
-
-
# @private
-
1
class Space
-
1
attr_reader :proxies, :any_instance_recorders, :proxy_mutex, :any_instance_mutex
-
-
1
def initialize
-
@proxies = {}
-
@any_instance_recorders = {}
-
@constant_mutators = []
-
@expectation_ordering = OrderGroup.new
-
@proxy_mutex = new_mutex
-
@any_instance_mutex = new_mutex
-
end
-
-
1
def new_scope
-
NestedSpace.new(self)
-
end
-
-
1
def verify_all
-
proxies.values.each { |proxy| proxy.verify }
-
any_instance_recorders.each_value { |recorder| recorder.verify }
-
end
-
-
1
def reset_all
-
proxies.each_value { |proxy| proxy.reset }
-
@constant_mutators.reverse.each { |mut| mut.idempotently_reset }
-
any_instance_recorders.each_value { |recorder| recorder.stop_all_observation! }
-
any_instance_recorders.clear
-
end
-
-
1
def register_constant_mutator(mutator)
-
@constant_mutators << mutator
-
end
-
-
1
def constant_mutator_for(name)
-
@constant_mutators.find { |m| m.full_constant_name == name }
-
end
-
-
1
def any_instance_recorder_for(klass, only_return_existing=false)
-
any_instance_mutex.synchronize do
-
id = klass.__id__
-
any_instance_recorders.fetch(id) do
-
return nil if only_return_existing
-
any_instance_recorder_not_found_for(id, klass)
-
end
-
end
-
end
-
-
1
def any_instance_proxy_for(klass)
-
AnyInstance::Proxy.new(any_instance_recorder_for(klass), proxies_of(klass))
-
end
-
-
1
def proxies_of(klass)
-
proxies.values.select { |proxy| klass === proxy.object }
-
end
-
-
1
def proxy_for(object)
-
proxy_mutex.synchronize do
-
id = id_for(object)
-
proxies.fetch(id) { proxy_not_found_for(id, object) }
-
end
-
end
-
-
1
def superclass_proxy_for(klass)
-
proxy_mutex.synchronize do
-
id = id_for(klass)
-
proxies.fetch(id) { superclass_proxy_not_found_for(id, klass) }
-
end
-
end
-
-
1
alias ensure_registered proxy_for
-
-
1
def registered?(object)
-
proxies.key?(id_for object)
-
end
-
-
1
def any_instance_recorders_from_ancestry_of(object)
-
# Optimization: `any_instance` is a feature we generally
-
# recommend not using, so we can often early exit here
-
# without doing an O(N) linear search over the number of
-
# ancestors in the object's class hierarchy.
-
return [] if any_instance_recorders.empty?
-
-
# We access the ancestors through the singleton class, to avoid calling
-
# `class` in case `class` has been stubbed.
-
(class << object; ancestors; end).map do |klass|
-
any_instance_recorders[klass.__id__]
-
end.compact
-
end
-
-
1
private
-
-
1
def new_mutex
-
Mocks::ReentrantMutex.new
-
end
-
-
1
def proxy_not_found_for(id, object)
-
proxies[id] = case object
-
when NilClass then ProxyForNil.new(@expectation_ordering)
-
when TestDouble then object.__build_mock_proxy_unless_expired(@expectation_ordering)
-
when Class
-
class_proxy_with_callback_verification_strategy(object, CallbackInvocationStrategy.new)
-
else
-
if RSpec::Mocks.configuration.verify_partial_doubles?
-
VerifyingPartialDoubleProxy.new(object, @expectation_ordering)
-
else
-
PartialDoubleProxy.new(object, @expectation_ordering)
-
end
-
end
-
end
-
-
1
def superclass_proxy_not_found_for(id, object)
-
raise "superclass_proxy_not_found_for called with something that is not a class" unless Class === object
-
proxies[id] = class_proxy_with_callback_verification_strategy(object, NoCallbackInvocationStrategy.new)
-
end
-
-
1
def class_proxy_with_callback_verification_strategy(object, strategy)
-
if RSpec::Mocks.configuration.verify_partial_doubles?
-
VerifyingPartialClassDoubleProxy.new(
-
self,
-
object,
-
@expectation_ordering,
-
strategy
-
)
-
else
-
PartialClassDoubleProxy.new(self, object, @expectation_ordering)
-
end
-
end
-
-
1
def any_instance_recorder_not_found_for(id, klass)
-
any_instance_recorders[id] = AnyInstance::Recorder.new(klass)
-
end
-
-
1
if defined?(::BasicObject) && !::BasicObject.method_defined?(:__id__) # for 1.9.2
-
require 'securerandom'
-
-
def id_for(object)
-
id = object.__id__
-
-
return id if object.equal?(::ObjectSpace._id2ref(id))
-
# this suggests that object.__id__ is proxying through to some wrapped object
-
-
object.instance_exec do
-
@__id_for_rspec_mocks_space ||= ::SecureRandom.uuid
-
end
-
end
-
else
-
1
def id_for(object)
-
object.__id__
-
end
-
end
-
end
-
-
# @private
-
1
class NestedSpace < Space
-
1
def initialize(parent)
-
@parent = parent
-
super()
-
end
-
-
1
def proxies_of(klass)
-
super + @parent.proxies_of(klass)
-
end
-
-
1
def constant_mutator_for(name)
-
super || @parent.constant_mutator_for(name)
-
end
-
-
1
def registered?(object)
-
super || @parent.registered?(object)
-
end
-
-
1
private
-
-
1
def proxy_not_found_for(id, object)
-
@parent.proxies[id] || super
-
end
-
-
1
def any_instance_recorder_not_found_for(id, klass)
-
@parent.any_instance_recorders[id] || super
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @api private
-
# Provides methods for enabling and disabling the available syntaxes
-
# provided by rspec-mocks.
-
1
module Syntax
-
# @private
-
1
def self.warn_about_should!
-
1
@warn_about_should = true
-
end
-
-
# @private
-
1
def self.warn_unless_should_configured(method_name , replacement="the new `:expect` syntax or explicitly enable `:should`")
-
if @warn_about_should
-
RSpec.deprecate(
-
"Using `#{method_name}` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax",
-
:replacement => replacement
-
)
-
-
@warn_about_should = false
-
end
-
end
-
-
# @api private
-
# Enables the should syntax (`dbl.stub`, `dbl.should_receive`, etc).
-
1
def self.enable_should(syntax_host=default_should_syntax_host)
-
2
@warn_about_should = false if syntax_host == default_should_syntax_host
-
2
return if should_enabled?(syntax_host)
-
-
1
syntax_host.class_exec do
-
1
def should_receive(message, opts={}, &block)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
::RSpec::Mocks.expect_message(self, message, opts, &block)
-
end
-
-
1
def should_not_receive(message, &block)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
::RSpec::Mocks.expect_message(self, message, {}, &block).never
-
end
-
-
1
def stub(message_or_hash, opts={}, &block)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
if ::Hash === message_or_hash
-
message_or_hash.each { |message, value| stub(message).and_return value }
-
else
-
::RSpec::Mocks.allow_message(self, message_or_hash, opts, &block)
-
end
-
end
-
-
1
def unstub(message)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__, "`allow(...).to_receive(...).and_call_original` or explicitly enable `:should`")
-
::RSpec::Mocks.space.proxy_for(self).remove_stub(message)
-
end
-
-
1
def stub_chain(*chain, &blk)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
::RSpec::Mocks::StubChain.stub_chain_on(self, *chain, &blk)
-
end
-
-
1
def as_null_object
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
@_null_object = true
-
::RSpec::Mocks.space.proxy_for(self).as_null_object
-
end
-
-
1
def null_object?
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
defined?(@_null_object)
-
end
-
-
1
def received_message?(message, *args, &block)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
::RSpec::Mocks.space.proxy_for(self).received_message?(message, *args, &block)
-
end
-
-
1
unless Class.respond_to? :any_instance
-
1
Class.class_exec do
-
1
def any_instance
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
::RSpec::Mocks.space.any_instance_proxy_for(self)
-
end
-
end
-
end
-
end
-
end
-
-
# @api private
-
# Disables the should syntax (`dbl.stub`, `dbl.should_receive`, etc).
-
1
def self.disable_should(syntax_host=default_should_syntax_host)
-
return unless should_enabled?(syntax_host)
-
-
syntax_host.class_exec do
-
undef should_receive
-
undef should_not_receive
-
undef stub
-
undef unstub
-
undef stub_chain
-
undef as_null_object
-
undef null_object?
-
undef received_message?
-
end
-
-
Class.class_exec do
-
undef any_instance
-
end
-
end
-
-
# @api private
-
# Enables the expect syntax (`expect(dbl).to receive`, `allow(dbl).to receive`, etc).
-
1
def self.enable_expect(syntax_host=::RSpec::Mocks::ExampleMethods)
-
2
return if expect_enabled?(syntax_host)
-
-
1
syntax_host.class_exec do
-
1
def receive(method_name, &block)
-
Matchers::Receive.new(method_name, block)
-
end
-
-
1
def receive_messages(message_return_value_hash)
-
matcher = Matchers::ReceiveMessages.new(message_return_value_hash)
-
matcher.warn_about_block if block_given?
-
matcher
-
end
-
-
1
def receive_message_chain(*messages, &block)
-
Matchers::ReceiveMessageChain.new(messages, &block)
-
end
-
-
1
def allow(target)
-
AllowanceTarget.new(target)
-
end
-
-
1
def expect_any_instance_of(klass)
-
AnyInstanceExpectationTarget.new(klass)
-
end
-
-
1
def allow_any_instance_of(klass)
-
AnyInstanceAllowanceTarget.new(klass)
-
end
-
end
-
-
1
RSpec::Mocks::ExampleMethods::ExpectHost.class_exec do
-
1
def expect(target)
-
ExpectationTarget.new(target)
-
end
-
end
-
end
-
-
# @api private
-
# Disables the expect syntax (`expect(dbl).to receive`, `allow(dbl).to receive`, etc).
-
1
def self.disable_expect(syntax_host=::RSpec::Mocks::ExampleMethods)
-
return unless expect_enabled?(syntax_host)
-
-
syntax_host.class_exec do
-
undef receive
-
undef receive_messages
-
undef receive_message_chain
-
undef allow
-
undef expect_any_instance_of
-
undef allow_any_instance_of
-
end
-
-
RSpec::Mocks::ExampleMethods::ExpectHost.class_exec do
-
undef expect
-
end
-
end
-
-
# @api private
-
# Indicates whether or not the should syntax is enabled.
-
1
def self.should_enabled?(syntax_host=default_should_syntax_host)
-
2
syntax_host.method_defined?(:should_receive)
-
end
-
-
# @api private
-
# Indicates whether or not the expect syntax is enabled.
-
1
def self.expect_enabled?(syntax_host=::RSpec::Mocks::ExampleMethods)
-
2
syntax_host.method_defined?(:allow)
-
end
-
-
# @api private
-
# Determines where the methods like `should_receive`, and `stub` are added.
-
1
def self.default_should_syntax_host
-
# JRuby 1.7.4 introduces a regression whereby `defined?(::BasicObject) => nil`
-
# yet `BasicObject` still exists and patching onto ::Object breaks things
-
# e.g. SimpleDelegator expectations won't work
-
#
-
# See: https://github.com/jruby/jruby/issues/814
-
4
if defined?(JRUBY_VERSION) && JRUBY_VERSION == '1.7.4' && RUBY_VERSION.to_f > 1.8
-
return ::BasicObject
-
end
-
-
# On 1.8.7, Object.ancestors.last == Kernel but
-
# things blow up if we include `RSpec::Mocks::Methods`
-
# into Kernel...not sure why.
-
4
return Object unless defined?(::BasicObject)
-
-
# MacRuby has BasicObject but it's not the root class.
-
4
return Object unless Object.ancestors.last == ::BasicObject
-
-
4
::BasicObject
-
end
-
end
-
end
-
end
-
-
1
if defined?(BasicObject)
-
# The legacy `:should` syntax adds the following methods directly to
-
# `BasicObject` so that they are available off of any object. Note, however,
-
# that this syntax does not always play nice with delegate/proxy objects.
-
# We recommend you use the non-monkeypatching `:expect` syntax instead.
-
# @see Class
-
1
class BasicObject
-
# @method should_receive
-
# Sets an expectation that this object should receive a message before
-
# the end of the example.
-
#
-
# @example
-
# logger = double('logger')
-
# thing_that_logs = ThingThatLogs.new(logger)
-
# logger.should_receive(:log)
-
# thing_that_logs.do_something_that_logs_a_message
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
# @see RSpec::Mocks::ExampleMethods#expect
-
-
# @method should_not_receive
-
# Sets and expectation that this object should _not_ receive a message
-
# during this example.
-
# @see RSpec::Mocks::ExampleMethods#expect
-
-
# @method stub
-
# Tells the object to respond to the message with the specified value.
-
#
-
# @example
-
# counter.stub(:count).and_return(37)
-
# counter.stub(:count => 37)
-
# counter.stub(:count) { 37 }
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
# @see RSpec::Mocks::ExampleMethods#allow
-
-
# @method unstub
-
# Removes a stub. On a double, the object will no longer respond to
-
# `message`. On a real object, the original method (if it exists) is
-
# restored.
-
#
-
# This is rarely used, but can be useful when a stub is set up during a
-
# shared `before` hook for the common case, but you want to replace it
-
# for a special case.
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
-
# @method stub_chain
-
# @overload stub_chain(method1, method2)
-
# @overload stub_chain("method1.method2")
-
# @overload stub_chain(method1, method_to_value_hash)
-
#
-
# Stubs a chain of methods.
-
#
-
# ## Warning:
-
#
-
# Chains can be arbitrarily long, which makes it quite painless to
-
# violate the Law of Demeter in violent ways, so you should consider any
-
# use of `stub_chain` a code smell. Even though not all code smells
-
# indicate real problems (think fluent interfaces), `stub_chain` still
-
# results in brittle examples. For example, if you write
-
# `foo.stub_chain(:bar, :baz => 37)` in a spec and then the
-
# implementation calls `foo.baz.bar`, the stub will not work.
-
#
-
# @example
-
# double.stub_chain("foo.bar") { :baz }
-
# double.stub_chain(:foo, :bar => :baz)
-
# double.stub_chain(:foo, :bar) { :baz }
-
#
-
# # Given any of ^^ these three forms ^^:
-
# double.foo.bar # => :baz
-
#
-
# # Common use in Rails/ActiveRecord:
-
# Article.stub_chain("recent.published") { [Article.new] }
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
# @see RSpec::Mocks::ExampleMethods#receive_message_chain
-
-
# @method as_null_object
-
# Tells the object to respond to all messages. If specific stub values
-
# are declared, they'll work as expected. If not, the receiver is
-
# returned.
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
-
# @method null_object?
-
# Returns true if this object has received `as_null_object`
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
end
-
end
-
-
# The legacy `:should` syntax adds the `any_instance` to `Class`.
-
# We generally recommend you use the newer `:expect` syntax instead,
-
# which allows you to stub any instance of a class using
-
# `allow_any_instance_of(klass)` or mock any instance using
-
# `expect_any_instance_of(klass)`.
-
# @see BasicObject
-
1
class Class
-
# @method any_instance
-
# Used to set stubs and message expectations on any instance of a given
-
# class. Returns a [Recorder](Recorder), which records messages like
-
# `stub` and `should_receive` for later playback on instances of the
-
# class.
-
#
-
# @example
-
# Car.any_instance.should_receive(:go)
-
# race = Race.new
-
# race.cars << Car.new
-
# race.go # assuming this delegates to all of its cars
-
# # this example would pass
-
#
-
# Account.any_instance.stub(:balance) { Money.new(:USD, 25) }
-
# Account.new.balance # => Money.new(:USD, 25))
-
#
-
# @return [Recorder]
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
# @see RSpec::Mocks::ExampleMethods#expect_any_instance_of
-
# @see RSpec::Mocks::ExampleMethods#allow_any_instance_of
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class TargetBase
-
1
def initialize(target)
-
@target = target
-
end
-
-
1
def self.delegate_to(matcher_method)
-
4
define_method(:to) do |matcher, &block|
-
unless matcher_allowed?(matcher)
-
raise_unsupported_matcher(:to, matcher)
-
end
-
define_matcher(matcher, matcher_method, &block)
-
end
-
end
-
-
1
def self.delegate_not_to(matcher_method, options={})
-
4
method_name = options.fetch(:from)
-
4
define_method(method_name) do |matcher, &block|
-
case matcher
-
when Matchers::Receive
-
define_matcher(matcher, matcher_method, &block)
-
when Matchers::ReceiveMessages, Matchers::ReceiveMessageChain
-
raise_negation_unsupported(method_name, matcher)
-
else
-
raise_unsupported_matcher(method_name, matcher)
-
end
-
end
-
end
-
-
1
def self.disallow_negation(method_name)
-
4
define_method(method_name) do |matcher, *_args|
-
raise_negation_unsupported(method_name, matcher)
-
end
-
end
-
-
1
private
-
-
1
def matcher_allowed?(matcher)
-
matcher.class.name.start_with?("RSpec::Mocks::Matchers".freeze)
-
end
-
-
1
def define_matcher(matcher, name, &block)
-
matcher.__send__(name, @target, &block)
-
end
-
-
1
def raise_unsupported_matcher(method_name, matcher)
-
raise UnsupportedMatcherError,
-
"only the `receive` or `receive_messages` matchers are supported " \
-
"with `#{expression}(...).#{method_name}`, but you have provided: #{matcher}"
-
end
-
-
1
def raise_negation_unsupported(method_name, matcher)
-
raise NegationUnsupportedError,
-
"`#{expression}(...).#{method_name} #{matcher.name}` is not supported since it " \
-
"doesn't really make sense. What would it even mean?"
-
end
-
-
1
def expression
-
self.class::EXPRESSION
-
end
-
end
-
-
# @private
-
1
class AllowanceTarget < TargetBase
-
1
EXPRESSION = :allow
-
1
delegate_to :setup_allowance
-
1
disallow_negation :not_to
-
1
disallow_negation :to_not
-
end
-
-
# @private
-
1
class ExpectationTarget < TargetBase
-
1
EXPRESSION = :expect
-
1
delegate_to :setup_expectation
-
1
delegate_not_to :setup_negative_expectation, :from => :not_to
-
1
delegate_not_to :setup_negative_expectation, :from => :to_not
-
end
-
-
# @private
-
1
class AnyInstanceAllowanceTarget < TargetBase
-
1
EXPRESSION = :allow_any_instance_of
-
1
delegate_to :setup_any_instance_allowance
-
1
disallow_negation :not_to
-
1
disallow_negation :to_not
-
end
-
-
# @private
-
1
class AnyInstanceExpectationTarget < TargetBase
-
1
EXPRESSION = :expect_any_instance_of
-
1
delegate_to :setup_any_instance_expectation
-
1
delegate_not_to :setup_any_instance_negative_expectation, :from => :not_to
-
1
delegate_not_to :setup_any_instance_negative_expectation, :from => :to_not
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# Implements the methods needed for a pure test double. RSpec::Mocks::Double
-
# includes this module, and it is provided for cases where you want a
-
# pure test double without subclassing RSpec::Mocks::Double.
-
1
module TestDouble
-
# Creates a new test double with a `name` (that will be used in error
-
# messages only)
-
1
def initialize(name=nil, stubs={})
-
@__expired = false
-
if Hash === name && stubs.empty?
-
stubs = name
-
@name = nil
-
else
-
@name = name
-
end
-
assign_stubs(stubs)
-
end
-
-
# Tells the object to respond to all messages. If specific stub values
-
# are declared, they'll work as expected. If not, the receiver is
-
# returned.
-
1
def as_null_object
-
__mock_proxy.as_null_object
-
end
-
-
# Returns true if this object has received `as_null_object`
-
1
def null_object?
-
__mock_proxy.null_object?
-
end
-
-
# This allows for comparing the mock to other objects that proxy such as
-
# ActiveRecords belongs_to proxy objects. By making the other object run
-
# the comparison, we're sure the call gets delegated to the proxy
-
# target.
-
1
def ==(other)
-
other == __mock_proxy
-
end
-
-
# @private
-
1
def inspect
-
TestDoubleFormatter.format(self)
-
end
-
-
# @private
-
1
def to_s
-
inspect.gsub('<', '[').gsub('>', ']')
-
end
-
-
# @private
-
1
def respond_to?(message, incl_private=false)
-
__mock_proxy.null_object? ? true : super
-
end
-
-
# @private
-
1
def __build_mock_proxy_unless_expired(order_group)
-
__raise_expired_error || __build_mock_proxy(order_group)
-
end
-
-
# @private
-
1
def __disallow_further_usage!
-
@__expired = true
-
end
-
-
# Override for default freeze implementation to prevent freezing of test
-
# doubles.
-
1
def freeze
-
RSpec.warn_with("WARNING: you attempted to freeze a test double. This is explicitly a no-op as freezing doubles can lead to undesired behaviour when resetting tests.")
-
end
-
-
1
private
-
-
1
def method_missing(message, *args, &block)
-
proxy = __mock_proxy
-
proxy.record_message_received(message, *args, &block)
-
-
if proxy.null_object?
-
case message
-
when :to_int then return 0
-
when :to_a, :to_ary then return nil
-
when :to_str then return to_s
-
else return self
-
end
-
end
-
-
# Defined private and protected methods will still trigger `method_missing`
-
# when called publicly. We want ruby's method visibility error to get raised,
-
# so we simply delegate to `super` in that case.
-
# ...well, we would delegate to `super`, but there's a JRuby
-
# bug, so we raise our own visibility error instead:
-
# https://github.com/jruby/jruby/issues/1398
-
visibility = proxy.visibility_for(message)
-
if visibility == :private || visibility == :protected
-
ErrorGenerator.new(self).raise_non_public_error(
-
message, visibility
-
)
-
end
-
-
# Required wrapping doubles in an Array on Ruby 1.9.2
-
raise NoMethodError if [:to_a, :to_ary].include? message
-
proxy.raise_unexpected_message_error(message, args)
-
end
-
-
1
def assign_stubs(stubs)
-
stubs.each_pair do |message, response|
-
__mock_proxy.add_simple_stub(message, response)
-
end
-
end
-
-
1
def __mock_proxy
-
::RSpec::Mocks.space.proxy_for(self)
-
end
-
-
1
def __build_mock_proxy(order_group)
-
TestDoubleProxy.new(self, order_group)
-
end
-
-
1
def __raise_expired_error
-
return false unless @__expired
-
ErrorGenerator.new(self).raise_expired_test_double_error
-
end
-
-
1
def initialize_copy(other)
-
as_null_object if other.null_object?
-
super
-
end
-
end
-
-
# A generic test double object. `double`, `instance_double` and friends
-
# return an instance of this.
-
1
class Double
-
1
include TestDouble
-
end
-
-
# @private
-
1
module TestDoubleFormatter
-
1
def self.format(dbl, unwrap=false)
-
format = "#{type_desc(dbl)}#{verified_module_desc(dbl)} #{name_desc(dbl)}"
-
return format if unwrap
-
"#<#{format}>"
-
end
-
-
1
class << self
-
1
private
-
-
1
def type_desc(dbl)
-
case dbl
-
when InstanceVerifyingDouble then "InstanceDouble"
-
when ClassVerifyingDouble then "ClassDouble"
-
when ObjectVerifyingDouble then "ObjectDouble"
-
else "Double"
-
end
-
end
-
-
# @private
-
1
IVAR_GET = Object.instance_method(:instance_variable_get)
-
-
1
def verified_module_desc(dbl)
-
return nil unless VerifyingDouble === dbl
-
"(#{IVAR_GET.bind(dbl).call(:@doubled_module).description})"
-
end
-
-
1
def name_desc(dbl)
-
return "(anonymous)" unless (name = IVAR_GET.bind(dbl).call(:@name))
-
name.inspect
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_mocks 'verifying_proxy'
-
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
module VerifyingDouble
-
1
def respond_to?(message, include_private=false)
-
return super unless null_object?
-
-
method_ref = __mock_proxy.method_reference[message]
-
-
case method_ref.visibility
-
when :public then true
-
when :private then include_private
-
when :protected then include_private || RUBY_VERSION.to_f < 2.0
-
else !method_ref.unimplemented?
-
end
-
end
-
-
1
def method_missing(message, *args, &block)
-
# Null object conditional is an optimization. If not a null object,
-
# validity of method expectations will have been checked at definition
-
# time.
-
if null_object?
-
if @__sending_message == message
-
__mock_proxy.ensure_implemented(message)
-
else
-
__mock_proxy.ensure_publicly_implemented(message, self)
-
end
-
-
__mock_proxy.validate_arguments!(message, args)
-
end
-
-
super
-
end
-
-
# @private
-
1
module SilentIO
-
1
def self.method_missing(*); end
-
1
def self.respond_to?(*)
-
1
true
-
end
-
end
-
-
# Redefining `__send__` causes ruby to issue a warning.
-
1
old, $stderr = $stderr, SilentIO
-
1
def __send__(name, *args, &block)
-
@__sending_message = name
-
super
-
ensure
-
@__sending_message = nil
-
end
-
1
$stderr = old
-
-
1
def send(name, *args, &block)
-
__send__(name, *args, &block)
-
end
-
-
1
def initialize(doubled_module, *args)
-
@doubled_module = doubled_module
-
-
possible_name = args.first
-
name = if String === possible_name || Symbol === possible_name
-
args.shift
-
end
-
-
super(name, *args)
-
@__sending_message = nil
-
end
-
end
-
-
# A mock providing a custom proxy that can verify the validity of any
-
# method stubs or expectations against the public instance methods of the
-
# given class.
-
#
-
# @private
-
1
class InstanceVerifyingDouble
-
1
include TestDouble
-
1
include VerifyingDouble
-
-
1
def __build_mock_proxy(order_group)
-
VerifyingProxy.new(self, order_group,
-
@doubled_module,
-
InstanceMethodReference
-
)
-
end
-
end
-
-
# An awkward module necessary because we cannot otherwise have
-
# ClassVerifyingDouble inherit from Module and still share these methods.
-
#
-
# @private
-
1
module ObjectVerifyingDoubleMethods
-
1
include TestDouble
-
1
include VerifyingDouble
-
-
1
def as_stubbed_const(options={})
-
ConstantMutator.stub(@doubled_module.const_to_replace, self, options)
-
self
-
end
-
-
1
private
-
-
1
def __build_mock_proxy(order_group)
-
VerifyingProxy.new(self, order_group,
-
@doubled_module,
-
ObjectMethodReference
-
)
-
end
-
end
-
-
# Similar to an InstanceVerifyingDouble, except that it verifies against
-
# public methods of the given object.
-
#
-
# @private
-
1
class ObjectVerifyingDouble
-
1
include ObjectVerifyingDoubleMethods
-
end
-
-
# Effectively the same as an ObjectVerifyingDouble (since a class is a type
-
# of object), except with Module in the inheritance chain so that
-
# transferring nested constants to work.
-
#
-
# @private
-
1
class ClassVerifyingDouble < Module
-
1
include ObjectVerifyingDoubleMethods
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'method_signature_verifier'
-
-
1
module RSpec
-
1
module Mocks
-
# A message expectation that knows about the real implementation of the
-
# message being expected, so that it can verify that any expectations
-
# have the valid arguments.
-
# @api private
-
1
class VerifyingMessageExpectation < MessageExpectation
-
# A level of indirection is used here rather than just passing in the
-
# method itself, since method look up is expensive and we only want to
-
# do it if actually needed.
-
#
-
# Conceptually the method reference makes more sense as a constructor
-
# argument since it should be immutable, but it is significantly more
-
# straight forward to build the object in pieces so for now it stays as
-
# an accessor.
-
1
attr_accessor :method_reference
-
-
1
def initialize(*args)
-
super
-
end
-
-
# @private
-
1
def with(*args, &block)
-
super(*args, &block).tap do
-
validate_expected_arguments! do |signature|
-
example_call_site_args = [:an_arg] * signature.min_non_kw_args
-
example_call_site_args << :kw_args_hash if signature.required_kw_args.any?
-
@argument_list_matcher.resolve_expected_args_based_on(example_call_site_args)
-
end
-
end
-
end
-
-
1
private
-
-
1
def validate_expected_arguments!
-
return if method_reference.nil?
-
-
method_reference.with_signature do |signature|
-
args = yield signature
-
verifier = Support::LooseSignatureVerifier.new(signature, args)
-
-
unless verifier.valid?
-
# Fail fast is required, otherwise the message expecation will fail
-
# as well ("expected method not called") and clobber this one.
-
@failed_fast = true
-
@error_generator.raise_invalid_arguments_error(verifier)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_mocks 'verifying_message_expecation'
-
1
RSpec::Support.require_rspec_mocks 'method_reference'
-
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class CallbackInvocationStrategy
-
1
def call(doubled_module)
-
RSpec::Mocks.configuration.verifying_double_callbacks.each do |block|
-
block.call doubled_module
-
end
-
end
-
end
-
-
# @private
-
1
class NoCallbackInvocationStrategy
-
1
def call(_doubled_module)
-
end
-
end
-
-
# @private
-
1
module VerifyingProxyMethods
-
1
def add_stub(method_name, opts={}, &implementation)
-
ensure_implemented(method_name)
-
super
-
end
-
-
1
def add_simple_stub(method_name, *args)
-
ensure_implemented(method_name)
-
super
-
end
-
-
1
def add_message_expectation(method_name, opts={}, &block)
-
ensure_implemented(method_name)
-
super
-
end
-
-
1
def ensure_implemented(method_name)
-
return unless method_reference[method_name].unimplemented?
-
-
@error_generator.raise_unimplemented_error(
-
@doubled_module,
-
method_name,
-
@object
-
)
-
end
-
-
1
def ensure_publicly_implemented(method_name, _object)
-
ensure_implemented(method_name)
-
visibility = method_reference[method_name].visibility
-
-
return if visibility == :public
-
@error_generator.raise_non_public_error(method_name, visibility)
-
end
-
end
-
-
# A verifying proxy mostly acts like a normal proxy, except that it
-
# contains extra logic to try and determine the validity of any expectation
-
# set on it. This includes whether or not methods have been defined and the
-
# validatiy of arguments on method calls.
-
#
-
# In all other ways this behaves like a normal proxy. It only adds the
-
# verification behaviour to specific methods then delegates to the parent
-
# implementation.
-
#
-
# These checks are only activated if the doubled class has already been
-
# loaded, otherwise they are disabled. This allows for testing in
-
# isolation.
-
#
-
# @private
-
1
class VerifyingProxy < TestDoubleProxy
-
1
include VerifyingProxyMethods
-
-
1
def initialize(object, order_group, doubled_module, method_reference_class)
-
super(object, order_group)
-
@object = object
-
@doubled_module = doubled_module
-
@method_reference_class = method_reference_class
-
-
# A custom method double is required to pass through a way to lookup
-
# methods to determine their parameters. This is only relevant if the doubled
-
# class is loaded.
-
@method_doubles = Hash.new do |h, k|
-
h[k] = VerifyingMethodDouble.new(@object, k, self, method_reference[k])
-
end
-
end
-
-
1
def method_reference
-
@method_reference ||= Hash.new do |h, k|
-
h[k] = @method_reference_class.for(@doubled_module, k)
-
end
-
end
-
-
1
def visibility_for(method_name)
-
method_reference[method_name].visibility
-
end
-
-
1
def validate_arguments!(method_name, args)
-
@method_doubles[method_name].validate_arguments!(args)
-
end
-
end
-
-
# @private
-
1
DEFAULT_CALLBACK_INVOCATION_STRATEGY = CallbackInvocationStrategy.new
-
-
# @private
-
1
class VerifyingPartialDoubleProxy < PartialDoubleProxy
-
1
include VerifyingProxyMethods
-
-
1
def initialize(object, expectation_ordering, optional_callback_invocation_strategy=DEFAULT_CALLBACK_INVOCATION_STRATEGY)
-
super(object, expectation_ordering)
-
@doubled_module = DirectObjectReference.new(object)
-
-
# A custom method double is required to pass through a way to lookup
-
# methods to determine their parameters.
-
@method_doubles = Hash.new do |h, k|
-
h[k] = VerifyingExistingMethodDouble.for(object, k, self)
-
end
-
-
optional_callback_invocation_strategy.call(@doubled_module)
-
end
-
-
1
def method_reference
-
@method_doubles
-
end
-
end
-
-
# @private
-
1
class VerifyingPartialClassDoubleProxy < VerifyingPartialDoubleProxy
-
1
include PartialClassDoubleProxyMethods
-
end
-
-
# @private
-
1
class VerifyingMethodDouble < MethodDouble
-
1
def initialize(object, method_name, proxy, method_reference)
-
super(object, method_name, proxy)
-
@method_reference = method_reference
-
end
-
-
1
def message_expectation_class
-
VerifyingMessageExpectation
-
end
-
-
1
def add_expectation(*args, &block)
-
# explict params necessary for 1.8.7 see #626
-
super(*args, &block).tap { |x| x.method_reference = @method_reference }
-
end
-
-
1
def add_stub(*args, &block)
-
# explict params necessary for 1.8.7 see #626
-
super(*args, &block).tap { |x| x.method_reference = @method_reference }
-
end
-
-
1
def proxy_method_invoked(obj, *args, &block)
-
validate_arguments!(args)
-
super
-
end
-
-
1
def validate_arguments!(actual_args)
-
@method_reference.with_signature do |signature|
-
verifier = Support::StrictSignatureVerifier.new(signature, actual_args)
-
raise ArgumentError, verifier.error_message unless verifier.valid?
-
end
-
end
-
end
-
-
# A VerifyingMethodDouble fetches the method to verify against from the
-
# original object, using a MethodReference. This works for pure doubles,
-
# but when the original object is itself the one being modified we need to
-
# collapse the reference and the method double into a single object so that
-
# we can access the original pristine method definition.
-
#
-
# @private
-
1
class VerifyingExistingMethodDouble < VerifyingMethodDouble
-
1
def initialize(object, method_name, proxy)
-
super(object, method_name, proxy, self)
-
-
@valid_method = object.respond_to?(method_name, true)
-
-
# Trigger an eager find of the original method since if we find it any
-
# later we end up getting a stubbed method with incorrect arity.
-
save_original_implementation_callable!
-
end
-
-
1
def with_signature
-
yield Support::MethodSignature.new(original_implementation_callable)
-
end
-
-
1
def unimplemented?
-
!@valid_method
-
end
-
-
1
def self.for(object, method_name, proxy)
-
if ClassNewMethodReference.applies_to?(method_name) { object }
-
VerifyingExistingClassNewMethodDouble
-
else
-
self
-
end.new(object, method_name, proxy)
-
end
-
end
-
-
# Used in place of a `VerifyingExistingMethodDouble` for the specific case
-
# of mocking or stubbing a `new` method on a class. In this case, we substitute
-
# the method signature from `#initialize` since new's signature is just `*args`.
-
#
-
# @private
-
1
class VerifyingExistingClassNewMethodDouble < VerifyingExistingMethodDouble
-
1
def with_signature
-
yield Support::MethodSignature.new(object.instance_method(:initialize))
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# Version information for RSpec mocks.
-
1
module Version
-
# Version of RSpec mocks currently in use in SemVer format.
-
1
STRING = '3.3.2'
-
end
-
end
-
end
-
1
require 'rspec/rails/feature_check'
-
-
# Namespace for all core RSpec projects.
-
1
module RSpec
-
# Namespace for rspec-rails code.
-
1
module Rails
-
# Railtie to hook into Rails.
-
1
class Railtie < ::Rails::Railtie
-
# Rails-3.0.1 requires config.app_generators instead of 3.0.0's config.generators
-
1
generators = config.respond_to?(:app_generators) ? config.app_generators : config.generators
-
1
generators.integration_tool :rspec
-
1
generators.test_framework :rspec
-
-
1
generators do
-
::Rails::Generators.hidden_namespaces.reject! { |namespace| namespace.start_with?("rspec") }
-
end
-
-
1
rake_tasks do
-
load "rspec/rails/tasks/rspec.rake"
-
end
-
-
# This is called after the environment has been loaded but before Rails
-
# sets the default for the `preview_path`
-
1
initializer "rspec_rails.action_mailer",
-
:before => "action_mailer.set_configs" do |app|
-
1
setup_preview_path(app)
-
end
-
-
1
private
-
-
1
def setup_preview_path(app)
-
1
return unless supports_action_mailer_previews?(app.config)
-
1
options = app.config.action_mailer
-
1
config_default_preview_path(options) if config_preview_path?(options)
-
end
-
-
1
def config_preview_path?(options)
-
# We cannot use `respond_to?(:show_previews)` here as it will always
-
# return `true`.
-
1
if ::Rails::VERSION::STRING < '4.2'
-
::Rails.env.development?
-
1
elsif options.show_previews.nil?
-
1
options.show_previews = ::Rails.env.development?
-
else
-
options.show_previews
-
end
-
end
-
-
1
def config_default_preview_path(options)
-
return unless options.preview_path.blank?
-
options.preview_path = "#{::Rails.root}/spec/mailers/previews"
-
end
-
-
1
def supports_action_mailer_previews?(config)
-
# These checks avoid loading `ActionMailer`. Using `defined?` has the
-
# side-effect of the class getting loaded if it is available. This is
-
# problematic because loading `ActionMailer::Base` will cause it to
-
# read the config settings; this is the only time the config is read.
-
# If the config is loaded now, any settings declared in a config block
-
# in an initializer will be ignored.
-
#
-
# If the action mailer railtie has not been loaded then `config` will
-
# not respond to the method. However, we cannot use
-
# `config.action_mailer.respond_to?(:preview_path)` here as it will
-
# always return `true`.
-
1
config.respond_to?(:action_mailer) && ::Rails::VERSION::STRING > '4.1'
-
end
-
end
-
end
-
end
-
# @api private
-
1
module RSpec
-
1
module Rails
-
# @private
-
# Disable some cops until https://github.com/bbatsov/rubocop/issues/1310
-
# rubocop:disable Style/IndentationConsistency
-
1
module FeatureCheck
-
# rubocop:disable Style/IndentationWidth
-
1
module_function
-
# rubocop:enable Style/IndentationWidth
-
-
1
def can_check_pending_migrations?
-
has_active_record_migration? &&
-
::ActiveRecord::Migration.respond_to?(:check_pending!)
-
end
-
-
1
def can_maintain_test_schema?
-
has_active_record_migration? &&
-
::ActiveRecord::Migration.respond_to?(:maintain_test_schema!)
-
end
-
-
1
def has_active_job?
-
defined?(::ActiveJob)
-
end
-
-
1
def has_active_record?
-
defined?(::ActiveRecord)
-
end
-
-
1
def has_active_record_migration?
-
has_active_record? && defined?(::ActiveRecord::Migration)
-
end
-
-
1
def has_action_mailer?
-
defined?(::ActionMailer)
-
end
-
-
1
def has_action_mailer_preview?
-
has_action_mailer? && defined?(::ActionMailer::Preview)
-
end
-
-
1
def has_action_mailer_show_preview?
-
has_action_mailer_preview? &&
-
::ActionMailer::Base.respond_to?(:show_previews=)
-
end
-
-
1
def has_1_9_hash_syntax?
-
::Rails::VERSION::STRING > '4.0'
-
end
-
-
1
def type_metatag(type)
-
if has_1_9_hash_syntax?
-
"type: :#{type}"
-
else
-
":type => :#{type}"
-
end
-
end
-
end
-
# rubocop:enable Style/IndentationConsistency
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# @api private
-
#
-
# Defines a helper method that is optimized to require files from the
-
# named lib. The passed block MUST be `{ |f| require_relative f }`
-
# because for `require_relative` to work properly from within the named
-
# lib the line of code must be IN that lib.
-
#
-
# `require_relative` is preferred when available because it is always O(1),
-
# regardless of the number of dirs in $LOAD_PATH. `require`, on the other
-
# hand, does a linear O(N) search over the dirs in the $LOAD_PATH until
-
# it can resolve the file relative to one of the dirs.
-
1
def self.define_optimized_require_for_rspec(lib, &require_relative)
-
5
name = "require_rspec_#{lib}"
-
-
5
if Kernel.respond_to?(:require_relative)
-
10
(class << self; self; end).__send__(:define_method, name) do |f|
-
91
require_relative.call("#{lib}/#{f}")
-
end
-
else
-
(class << self; self; end).__send__(:define_method, name) do |f|
-
require "rspec/#{lib}/#{f}"
-
end
-
end
-
end
-
-
23
define_optimized_require_for_rspec(:support) { |f| require_relative(f) }
-
1
require_rspec_support "version"
-
1
require_rspec_support "ruby_features"
-
-
# @api private
-
1
KERNEL_METHOD_METHOD = ::Kernel.instance_method(:method)
-
-
# @api private
-
#
-
# Used internally to get a method handle for a particular object
-
# and method name.
-
#
-
# Includes handling for a few special cases:
-
#
-
# - Objects that redefine #method (e.g. an HTTPRequest struct)
-
# - BasicObject subclasses that mixin a Kernel dup (e.g. SimpleDelegator)
-
# - Objects that undefine method and delegate everything to another
-
# object (e.g. Mongoid association objects)
-
1
if RubyFeatures.supports_rebinding_module_methods?
-
1
def self.method_handle_for(object, method_name)
-
4
KERNEL_METHOD_METHOD.bind(object).call(method_name)
-
rescue NameError => original
-
begin
-
handle = object.method(method_name)
-
raise original unless handle.is_a? Method
-
handle
-
rescue Exception
-
raise original
-
end
-
end
-
else
-
def self.method_handle_for(object, method_name)
-
if ::Kernel === object
-
KERNEL_METHOD_METHOD.bind(object).call(method_name)
-
else
-
object.method(method_name)
-
end
-
rescue NameError => original
-
begin
-
handle = object.method(method_name)
-
raise original unless handle.is_a? Method
-
handle
-
rescue Exception
-
raise original
-
end
-
end
-
end
-
-
# A single thread local variable so we don't excessively pollute that namespace.
-
1
def self.thread_local_data
-
Thread.current[:__rspec] ||= {}
-
end
-
-
1
def self.failure_notifier=(callable)
-
thread_local_data[:failure_notifier] = callable
-
end
-
-
# @private
-
1
DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure }
-
-
1
def self.failure_notifier
-
thread_local_data[:failure_notifier] || DEFAULT_FAILURE_NOTIFIER
-
end
-
-
1
def self.notify_failure(failure, options={})
-
failure_notifier.call(failure, options)
-
end
-
-
1
def self.with_failure_notifier(callable)
-
orig_notifier = failure_notifier
-
self.failure_notifier = callable
-
yield
-
ensure
-
self.failure_notifier = orig_notifier
-
end
-
-
# The Differ is only needed when a a spec fails with a diffable failure.
-
# In the more common case of all specs passing or the only failures being
-
# non-diffable, we can avoid the extra cost of loading the differ, diff-lcs,
-
# pp, etc by avoiding an unnecessary require. Instead, autoload will take
-
# care of loading the differ on first use.
-
1
autoload :Differ, "rspec/support/differ"
-
end
-
end
-
1
RSpec::Support.require_rspec_support "ruby_features"
-
-
1
module RSpec
-
# Consistent implementation for "cleaning" the caller method to strip out
-
# non-rspec lines. This enables errors to be reported at the call site in
-
# the code using the library, which is far more useful than the particular
-
# internal method that raised an error.
-
1
class CallerFilter
-
1
RSPEC_LIBS = %w[
-
core
-
mocks
-
expectations
-
support
-
matchers
-
rails
-
]
-
-
1
ADDITIONAL_TOP_LEVEL_FILES = %w[ autorun ]
-
-
1
LIB_REGEX = %r{/lib/rspec/(#{(RSPEC_LIBS + ADDITIONAL_TOP_LEVEL_FILES).join('|')})(\.rb|/)}
-
-
# rubygems/core_ext/kernel_require.rb isn't actually part of rspec (obviously) but we want
-
# it ignored when we are looking for the first meaningful line of the backtrace outside
-
# of RSpec. It can show up in the backtrace as the immediate first caller
-
# when `CallerFilter.first_non_rspec_line` is called from the top level of a required
-
# file, but it depends on if rubygems is loaded or not. We don't want to have to deal
-
# with this complexity in our `RSpec.deprecate` calls, so we ignore it here.
-
1
IGNORE_REGEX = Regexp.union(LIB_REGEX, "rubygems/core_ext/kernel_require.rb")
-
-
1
if RSpec::Support::RubyFeatures.caller_locations_supported?
-
# This supports args because it's more efficient when the caller specifies
-
# these. It allows us to skip frames the caller knows are part of RSpec,
-
# and to decrease the increment size if the caller is confident the line will
-
# be found in a small number of stack frames from `skip_frames`.
-
#
-
# Note that there is a risk to passing a `skip_frames` value that is too high:
-
# If it skippped the first non-rspec line, then this method would return the
-
# 2nd or 3rd (or whatever) non-rspec line. Thus, you generally shouldn't pass
-
# values for these parameters, particularly since most places that use this are
-
# not hot spots (generally it gets used for deprecation warnings). However,
-
# if you do have a hot spot that calls this, passing `skip_frames` can make
-
# a significant difference. Just make sure that that particular use is tested
-
# so that if the provided `skip_frames` changes to no longer be accurate in
-
# such a way that would return the wrong stack frame, a test will fail to tell you.
-
#
-
# See benchmarks/skip_frames_for_caller_filter.rb for measurements.
-
1
def self.first_non_rspec_line(skip_frames=3, increment=5)
-
# Why a default `skip_frames` of 3?
-
# By the time `caller_locations` is called below, the first 3 frames are:
-
# lib/rspec/support/caller_filter.rb:63:in `block in first_non_rspec_line'
-
# lib/rspec/support/caller_filter.rb:62:in `loop'
-
# lib/rspec/support/caller_filter.rb:62:in `first_non_rspec_line'
-
-
# `caller` is an expensive method that scales linearly with the size of
-
# the stack. The performance hit for fetching it in chunks is small,
-
# and since the target line is probably near the top of the stack, the
-
# overall improvement of a chunked search like this is significant.
-
#
-
# See benchmarks/caller.rb for measurements.
-
-
# The default increment of 5 for this method are mostly arbitrary, but
-
# is chosen to give good performance on the common case of creating a double.
-
-
loop do
-
stack = caller_locations(skip_frames, increment)
-
raise "No non-lib lines in stack" unless stack
-
-
line = stack.find { |l| l.path !~ IGNORE_REGEX }
-
return line.to_s if line
-
-
skip_frames += increment
-
increment *= 2 # The choice of two here is arbitrary.
-
end
-
end
-
else
-
# Earlier rubies do not support the two argument form of `caller`. This
-
# fallback is logically the same, but slower.
-
def self.first_non_rspec_line(*)
-
caller.find { |line| line !~ IGNORE_REGEX }
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'ruby_features'
-
-
1
module RSpec
-
1
module Support
-
# @api private
-
#
-
# Replacement for fileutils#mkdir_p because we don't want to require parts
-
# of stdlib in RSpec.
-
1
class DirectoryMaker
-
# @api private
-
#
-
# Implements nested directory construction
-
1
def self.mkdir_p(path)
-
stack = generate_stack(path)
-
path.split(File::SEPARATOR).each do |part|
-
stack = generate_path(stack, part)
-
begin
-
Dir.mkdir(stack) unless directory_exists?(stack)
-
rescue Errno::EEXIST => e
-
raise e unless directory_exists?(stack)
-
rescue Errno::ENOTDIR => e
-
raise Errno::EEXIST, e.message
-
end
-
end
-
end
-
-
1
if OS.windows_file_path?
-
def self.generate_stack(path)
-
if path.start_with?(File::SEPARATOR)
-
File::SEPARATOR
-
elsif path[1] == ':'
-
''
-
else
-
'.'
-
end
-
end
-
def self.generate_path(stack, part)
-
if stack == ''
-
part
-
elsif stack == File::SEPARATOR
-
File.join('', part)
-
else
-
File.join(stack, part)
-
end
-
end
-
else
-
1
def self.generate_stack(path)
-
path.start_with?(File::SEPARATOR) ? File::SEPARATOR : "."
-
end
-
1
def self.generate_path(stack, part)
-
File.join(stack, part)
-
end
-
end
-
-
1
def self.directory_exists?(dirname)
-
File.exist?(dirname) && File.directory?(dirname)
-
end
-
1
private_class_method :directory_exists?
-
1
private_class_method :generate_stack
-
1
private_class_method :generate_path
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# @private
-
1
class EncodedString
-
# Reduce allocations by storing constants.
-
1
UTF_8 = "UTF-8"
-
1
US_ASCII = "US-ASCII"
-
#
-
# In MRI 2.1 'invalid: :replace' changed to also replace an invalid byte sequence
-
# see https://github.com/ruby/ruby/blob/v2_1_0/NEWS#L176
-
# https://www.ruby-forum.com/topic/6861247
-
# https://twitter.com/nalsh/status/553413844685438976
-
#
-
# For example, given:
-
# "\x80".force_encoding("Emacs-Mule").encode(:invalid => :replace).bytes.to_a
-
#
-
# On MRI 2.1 or above: 63 # '?'
-
# else : 128 # "\x80"
-
#
-
# Ruby's default replacement string is:
-
# U+FFFD ("\xEF\xBF\xBD"), for Unicode encoding forms, else
-
# ? ("\x3F")
-
1
REPLACE = "?"
-
1
ENCODE_UNCONVERTABLE_BYTES = {
-
:invalid => :replace,
-
:undef => :replace,
-
:replace => REPLACE
-
}
-
1
ENCODE_NO_CONVERTER = {
-
:invalid => :replace,
-
:replace => REPLACE
-
}
-
-
1
def initialize(string, encoding=nil)
-
@encoding = encoding
-
@source_encoding = detect_source_encoding(string)
-
@string = matching_encoding(string)
-
end
-
1
attr_reader :source_encoding
-
-
1
delegated_methods = String.instance_methods.map(&:to_s) & %w[eql? lines == encoding empty?]
-
1
delegated_methods.each do |name|
-
5
define_method(name) { |*args, &block| @string.__send__(name, *args, &block) }
-
end
-
-
1
def <<(string)
-
@string << matching_encoding(string)
-
end
-
-
1
def split(regex_or_string)
-
@string.split(matching_encoding(regex_or_string))
-
end
-
-
1
def to_s
-
@string
-
end
-
1
alias :to_str :to_s
-
-
1
if String.method_defined?(:encoding)
-
-
1
private
-
-
# Encoding Exceptions:
-
#
-
# Raised by Encoding and String methods:
-
# Encoding::UndefinedConversionError:
-
# when a transcoding operation fails
-
# if the String contains characters invalid for the target encoding
-
# e.g. "\x80".encode('UTF-8','ASCII-8BIT')
-
# vs "\x80".encode('UTF-8','ASCII-8BIT', undef: :replace, replace: '<undef>')
-
# # => '<undef>'
-
# Encoding::CompatibilityError
-
# when Encoding.compatibile?(str1, str2) is nil
-
# e.g. utf_16le_emoji_string.split("\n")
-
# e.g. valid_unicode_string.encode(utf8_encoding) << ascii_string
-
# Encoding::InvalidByteSequenceError:
-
# when the string being transcoded contains a byte invalid for
-
# either the source or target encoding
-
# e.g. "\x80".encode('UTF-8','US-ASCII')
-
# vs "\x80".encode('UTF-8','US-ASCII', invalid: :replace, replace: '<byte>')
-
# # => '<byte>'
-
# ArgumentError
-
# when operating on a string with invalid bytes
-
# e.g."\x80".split("\n")
-
# TypeError
-
# when a symbol is passed as an encoding
-
# Encoding.find(:"UTF-8")
-
# when calling force_encoding on an object
-
# that doesn't respond to #to_str
-
#
-
# Raised by transcoding methods:
-
# Encoding::ConverterNotFoundError:
-
# when a named encoding does not correspond with a known converter
-
# e.g. 'abc'.force_encoding('UTF-8').encode('foo')
-
# or a converter path cannot be found
-
# e.g. "\x80".force_encoding('ASCII-8BIT').encode('Emacs-Mule')
-
#
-
# Raised by byte <-> char conversions
-
# RangeError: out of char range
-
# e.g. the UTF-16LE emoji: 128169.chr
-
1
def matching_encoding(string)
-
string = remove_invalid_bytes(string)
-
string.encode(@encoding)
-
rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError
-
string.encode(@encoding, ENCODE_UNCONVERTABLE_BYTES)
-
rescue Encoding::ConverterNotFoundError
-
string.dup.force_encoding(@encoding).encode(ENCODE_NO_CONVERTER)
-
end
-
-
# Prevents raising ArgumentError
-
1
if String.method_defined?(:scrub)
-
# https://github.com/ruby/ruby/blob/eeb05e8c11/doc/NEWS-2.1.0#L120-L123
-
# https://github.com/ruby/ruby/blob/v2_1_0/string.c#L8242
-
# https://github.com/hsbt/string-scrub
-
# https://github.com/rubinius/rubinius/blob/v2.5.2/kernel/common/string.rb#L1913-L1972
-
1
def remove_invalid_bytes(string)
-
string.scrub(REPLACE)
-
end
-
else
-
# http://stackoverflow.com/a/8711118/879854
-
# Loop over chars in a string replacing chars
-
# with invalid encoding, which is a pretty good proxy
-
# for the invalid byte sequence that causes an ArgumentError
-
def remove_invalid_bytes(string)
-
string.chars.map do |char|
-
char.valid_encoding? ? char : REPLACE
-
end.join
-
end
-
end
-
-
1
def detect_source_encoding(string)
-
string.encoding
-
end
-
-
1
def self.pick_encoding(source_a, source_b)
-
Encoding.compatible?(source_a, source_b) || Encoding.default_external
-
end
-
else
-
-
def self.pick_encoding(_source_a, _source_b)
-
end
-
-
private
-
-
def matching_encoding(string)
-
string
-
end
-
-
def detect_source_encoding(_string)
-
US_ASCII
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# Provides a means to fuzzy-match between two arbitrary objects.
-
# Understands array/hash nesting. Uses `===` or `==` to
-
# perform the matching.
-
1
module FuzzyMatcher
-
# @api private
-
1
def self.values_match?(expected, actual)
-
if Hash === actual
-
return hashes_match?(expected, actual) if Hash === expected
-
elsif Array === expected && Enumerable === actual && !(Struct === actual)
-
return arrays_match?(expected, actual.to_a)
-
end
-
-
return true if expected == actual
-
-
begin
-
expected === actual
-
rescue ArgumentError
-
# Some objects, like 0-arg lambdas on 1.9+, raise
-
# ArgumentError for `expected === actual`.
-
false
-
end
-
end
-
-
# @private
-
1
def self.arrays_match?(expected_list, actual_list)
-
return false if expected_list.size != actual_list.size
-
-
expected_list.zip(actual_list).all? do |expected, actual|
-
values_match?(expected, actual)
-
end
-
end
-
-
# @private
-
1
def self.hashes_match?(expected_hash, actual_hash)
-
return false if expected_hash.size != actual_hash.size
-
-
expected_hash.all? do |expected_key, expected_value|
-
actual_value = actual_hash.fetch(expected_key) { return false }
-
values_match?(expected_value, actual_value)
-
end
-
end
-
-
1
private_class_method :arrays_match?, :hashes_match?
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# @private
-
1
def self.matcher_definitions
-
2
@matcher_definitions ||= []
-
end
-
-
# Used internally to break cyclic dependency between mocks, expectations,
-
# and support. We don't currently have a consistent implementation of our
-
# matchers, though we are considering changing that:
-
# https://github.com/rspec/rspec-mocks/issues/513
-
#
-
# @private
-
1
def self.register_matcher_definition(&block)
-
2
matcher_definitions << block
-
end
-
-
# Remove a previously registered matcher. Useful for cleaning up after
-
# yourself in specs.
-
#
-
# @private
-
1
def self.deregister_matcher_definition(&block)
-
matcher_definitions.delete(block)
-
end
-
-
# @private
-
1
def self.is_a_matcher?(object)
-
matcher_definitions.any? { |md| md.call(object) }
-
end
-
-
# @api private
-
#
-
# gives a string representation of an object for use in RSpec descriptions
-
1
def self.rspec_description_for_object(object)
-
if RSpec::Support.is_a_matcher?(object) && object.respond_to?(:description)
-
object.description
-
else
-
object
-
end
-
end
-
end
-
end
-
1
require 'rspec/support'
-
1
RSpec::Support.require_rspec_support "ruby_features"
-
1
RSpec::Support.require_rspec_support "matcher_definition"
-
-
1
module RSpec
-
1
module Support
-
# Extracts info about the number of arguments and allowed/required
-
# keyword args of a given method.
-
#
-
# @private
-
1
class MethodSignature
-
1
attr_reader :min_non_kw_args, :max_non_kw_args, :optional_kw_args, :required_kw_args
-
-
1
def initialize(method)
-
@method = method
-
@optional_kw_args = []
-
@required_kw_args = []
-
classify_parameters
-
end
-
-
1
def non_kw_args_arity_description
-
case max_non_kw_args
-
when min_non_kw_args then min_non_kw_args.to_s
-
when INFINITY then "#{min_non_kw_args} or more"
-
else "#{min_non_kw_args} to #{max_non_kw_args}"
-
end
-
end
-
-
1
def valid_non_kw_args?(positional_arg_count)
-
min_non_kw_args <= positional_arg_count &&
-
positional_arg_count <= max_non_kw_args
-
end
-
-
1
if RubyFeatures.optional_and_splat_args_supported?
-
1
def description
-
@description ||= begin
-
parts = []
-
-
unless non_kw_args_arity_description == "0"
-
parts << "arity of #{non_kw_args_arity_description}"
-
end
-
-
if @optional_kw_args.any?
-
parts << "optional keyword args (#{@optional_kw_args.map(&:inspect).join(", ")})"
-
end
-
-
if @required_kw_args.any?
-
parts << "required keyword args (#{@required_kw_args.map(&:inspect).join(", ")})"
-
end
-
-
parts << "any additional keyword args" if @allows_any_kw_args
-
-
parts.join(" and ")
-
end
-
end
-
-
1
def missing_kw_args_from(given_kw_args)
-
@required_kw_args - given_kw_args
-
end
-
-
1
def invalid_kw_args_from(given_kw_args)
-
return [] if @allows_any_kw_args
-
given_kw_args - @allowed_kw_args
-
end
-
-
1
def has_kw_args_in?(args)
-
Hash === args.last && could_contain_kw_args?(args)
-
end
-
-
# Without considering what the last arg is, could it
-
# contain keyword arguments?
-
1
def could_contain_kw_args?(args)
-
return false if args.count <= min_non_kw_args
-
@allows_any_kw_args || @allowed_kw_args.any?
-
end
-
-
1
def classify_parameters
-
optional_non_kw_args = @min_non_kw_args = 0
-
@allows_any_kw_args = false
-
-
@method.parameters.each do |(type, name)|
-
case type
-
# def foo(a:)
-
when :keyreq then @required_kw_args << name
-
# def foo(a: 1)
-
when :key then @optional_kw_args << name
-
# def foo(**kw_args)
-
when :keyrest then @allows_any_kw_args = true
-
# def foo(a)
-
when :req then @min_non_kw_args += 1
-
# def foo(a = 1)
-
when :opt then optional_non_kw_args += 1
-
# def foo(*a)
-
when :rest then optional_non_kw_args = INFINITY
-
end
-
end
-
-
@max_non_kw_args = @min_non_kw_args + optional_non_kw_args
-
@allowed_kw_args = @required_kw_args + @optional_kw_args
-
end
-
else
-
def description
-
"arity of #{non_kw_args_arity_description}"
-
end
-
-
def missing_kw_args_from(_given_kw_args)
-
[]
-
end
-
-
def invalid_kw_args_from(_given_kw_args)
-
[]
-
end
-
-
def has_kw_args_in?(_args)
-
false
-
end
-
-
def could_contain_kw_args?(*)
-
false
-
end
-
-
def classify_parameters
-
arity = @method.arity
-
if arity < 0
-
# `~` inverts the one's complement and gives us the
-
# number of required args
-
@min_non_kw_args = ~arity
-
@max_non_kw_args = INFINITY
-
else
-
@min_non_kw_args = arity
-
@max_non_kw_args = arity
-
end
-
end
-
end
-
-
1
INFINITY = 1 / 0.0
-
end
-
-
# Deals with the slightly different semantics of block arguments.
-
# For methods, arguments are required unless a default value is provided.
-
# For blocks, arguments are optional, even if no default value is provided.
-
#
-
# However, we want to treat block args as required since you virtually
-
# always want to pass a value for each received argument and our
-
# `and_yield` has treated block args as required for many years.
-
#
-
# @api private
-
1
class BlockSignature < MethodSignature
-
1
if RubyFeatures.optional_and_splat_args_supported?
-
1
def classify_parameters
-
super
-
@min_non_kw_args = @max_non_kw_args unless @max_non_kw_args == INFINITY
-
end
-
end
-
end
-
-
# Abstract base class for signature verifiers.
-
#
-
# @api private
-
1
class MethodSignatureVerifier
-
1
attr_reader :non_kw_args, :kw_args
-
-
1
def initialize(signature, args)
-
@signature = signature
-
@non_kw_args, @kw_args = split_args(*args)
-
end
-
-
1
def valid?
-
missing_kw_args.empty? &&
-
invalid_kw_args.empty? &&
-
valid_non_kw_args?
-
end
-
-
1
def error_message
-
if missing_kw_args.any?
-
"Missing required keyword arguments: %s" % [
-
missing_kw_args.join(", ")
-
]
-
elsif invalid_kw_args.any?
-
"Invalid keyword arguments provided: %s" % [
-
invalid_kw_args.join(", ")
-
]
-
elsif !valid_non_kw_args?
-
"Wrong number of arguments. Expected %s, got %s." % [
-
@signature.non_kw_args_arity_description,
-
non_kw_args.length
-
]
-
end
-
end
-
-
1
private
-
-
1
def valid_non_kw_args?
-
@signature.valid_non_kw_args?(non_kw_args.length)
-
end
-
-
1
def missing_kw_args
-
@signature.missing_kw_args_from(kw_args)
-
end
-
-
1
def invalid_kw_args
-
@signature.invalid_kw_args_from(kw_args)
-
end
-
-
1
def split_args(*args)
-
kw_args = if @signature.has_kw_args_in?(args)
-
args.pop.keys
-
else
-
[]
-
end
-
-
[args, kw_args]
-
end
-
end
-
-
# Figures out wether a given method can accept various arguments.
-
# Surprisingly non-trivial.
-
#
-
# @private
-
1
StrictSignatureVerifier = MethodSignatureVerifier
-
-
# Allows matchers to be used instead of providing keyword arguments. In
-
# practice, when this happens only the arity of the method is verified.
-
#
-
# @private
-
1
class LooseSignatureVerifier < MethodSignatureVerifier
-
1
private
-
-
1
def split_args(*args)
-
if RSpec::Support.is_a_matcher?(args.last) && @signature.could_contain_kw_args?(args)
-
args.pop
-
@signature = SignatureWithKeywordArgumentsMatcher.new(@signature)
-
end
-
-
super(*args)
-
end
-
-
# If a matcher is used in a signature in place of keyword arguments, all
-
# keyword argument validation needs to be skipped since the matcher is
-
# opaque.
-
#
-
# Instead, keyword arguments will be validated when the method is called
-
# and they are actually known.
-
#
-
# @private
-
1
class SignatureWithKeywordArgumentsMatcher
-
1
def initialize(signature)
-
@signature = signature
-
end
-
-
1
def missing_kw_args_from(_kw_args)
-
[]
-
end
-
-
1
def invalid_kw_args_from(_kw_args)
-
[]
-
end
-
-
1
def non_kw_args_arity_description
-
@signature.non_kw_args_arity_description
-
end
-
-
1
def valid_non_kw_args?(*args)
-
@signature.valid_non_kw_args?(*args)
-
end
-
-
1
def has_kw_args_in?(args)
-
@signature.has_kw_args_in?(args)
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# Provide additional output details beyond what `inspect` provides when
-
# printing Time, DateTime, or BigDecimal
-
1
module ObjectFormatter
-
# @api private
-
1
def self.format(object)
-
prepare_for_inspection(object).inspect
-
end
-
-
# rubocop:disable MethodLength
-
-
# @private
-
# Prepares the provided object to be formatted by wrapping it as needed
-
# in something that, when `inspect` is called on it, will produce the
-
# desired output.
-
#
-
# This allows us to apply the desired formatting to hash/array data structures
-
# at any level of nesting, simply by walking that structure and replacing items
-
# with custom items that have `inspect` defined to return the desired output
-
# for that item. Then we can just use `Array#inspect` or `Hash#inspect` to
-
# format the entire thing.
-
1
def self.prepare_for_inspection(object)
-
case object
-
when Array
-
return object.map { |o| prepare_for_inspection(o) }
-
when Hash
-
return prepare_hash(object)
-
when Time
-
inspection = format_time(object)
-
else
-
if defined?(DateTime) && DateTime === object
-
inspection = format_date_time(object)
-
elsif defined?(BigDecimal) && BigDecimal === object
-
inspection = "#{object.to_s 'F'} (#{object.inspect})"
-
elsif RSpec::Support.is_a_matcher?(object) && object.respond_to?(:description)
-
inspection = object.description
-
else
-
return object
-
end
-
end
-
-
InspectableItem.new(inspection)
-
end
-
# rubocop:enable MethodLength
-
-
# @private
-
1
def self.prepare_hash(input)
-
input.inject({}) do |hash, (k, v)|
-
hash[prepare_for_inspection(k)] = prepare_for_inspection(v)
-
hash
-
end
-
end
-
-
1
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
-
-
1
if Time.method_defined?(:nsec)
-
# @private
-
1
def self.format_time(time)
-
time.strftime("#{TIME_FORMAT}.#{"%09d" % time.nsec} %z")
-
end
-
else # for 1.8.7
-
# @private
-
def self.format_time(time)
-
time.strftime("#{TIME_FORMAT}.#{"%06d" % time.usec} %z")
-
end
-
end
-
-
1
DATE_TIME_FORMAT = "%a, %d %b %Y %H:%M:%S.%N %z"
-
# ActiveSupport sometimes overrides inspect. If `ActiveSupport` is
-
# defined use a custom format string that includes more time precision.
-
# @private
-
1
def self.format_date_time(date_time)
-
if defined?(ActiveSupport)
-
date_time.strftime(DATE_TIME_FORMAT)
-
else
-
date_time.inspect
-
end
-
end
-
-
# @private
-
1
InspectableItem = Struct.new(:inspection) do
-
1
def inspect
-
inspection
-
end
-
-
1
def pretty_print(pp)
-
pp.text inspection
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# Provides recursive constant lookup methods useful for
-
# constant stubbing.
-
1
module RecursiveConstMethods
-
# We only want to consider constants that are defined directly on a
-
# particular module, and not include top-level/inherited constants.
-
# Unfortunately, the constant API changed between 1.8 and 1.9, so
-
# we need to conditionally define methods to ignore the top-level/inherited
-
# constants.
-
#
-
# Given:
-
# class A; B = 1; end
-
# class C < A; end
-
#
-
# On 1.8:
-
# - C.const_get("Hash") # => ::Hash
-
# - C.const_defined?("Hash") # => false
-
# - C.constants # => ["B"]
-
# - None of these methods accept the extra `inherit` argument
-
# On 1.9:
-
# - C.const_get("Hash") # => ::Hash
-
# - C.const_defined?("Hash") # => true
-
# - C.const_get("Hash", false) # => raises NameError
-
# - C.const_defined?("Hash", false) # => false
-
# - C.constants # => [:B]
-
# - C.constants(false) #=> []
-
1
if Module.method(:const_defined?).arity == 1
-
def const_defined_on?(mod, const_name)
-
mod.const_defined?(const_name)
-
end
-
-
def get_const_defined_on(mod, const_name)
-
return mod.const_get(const_name) if const_defined_on?(mod, const_name)
-
-
raise NameError, "uninitialized constant #{mod.name}::#{const_name}"
-
end
-
-
def constants_defined_on(mod)
-
mod.constants.select { |c| const_defined_on?(mod, c) }
-
end
-
else
-
1
def const_defined_on?(mod, const_name)
-
mod.const_defined?(const_name, false)
-
end
-
-
1
def get_const_defined_on(mod, const_name)
-
mod.const_get(const_name, false)
-
end
-
-
1
def constants_defined_on(mod)
-
mod.constants(false)
-
end
-
end
-
-
1
def recursive_const_get(const_name)
-
normalize_const_name(const_name).split('::').inject(Object) do |mod, name|
-
get_const_defined_on(mod, name)
-
end
-
end
-
-
1
def recursive_const_defined?(const_name)
-
parts = normalize_const_name(const_name).split('::')
-
parts.inject([Object, '']) do |(mod, full_name), name|
-
yield(full_name, name) if block_given? && !(Module === mod)
-
return false unless const_defined_on?(mod, name)
-
[get_const_defined_on(mod, name), [mod, name].join('::')]
-
end
-
end
-
-
1
def normalize_const_name(const_name)
-
const_name.sub(/\A::/, '')
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
1
module Version
-
1
STRING = '3.3.0'
-
end
-
end
-
end
-
1
require 'rspec/support'
-
1
RSpec::Support.require_rspec_support "caller_filter"
-
-
1
module RSpec
-
1
module Support
-
1
module Warnings
-
1
def deprecate(deprecated, options={})
-
warn_with "DEPRECATION: #{deprecated} is deprecated.", options
-
end
-
-
# @private
-
#
-
# Used internally to print deprecation warnings
-
# when rspec-core isn't loaded
-
1
def warn_deprecation(message, options={})
-
warn_with "DEPRECATION: \n #{message}", options
-
end
-
-
# @private
-
#
-
# Used internally to print warnings
-
1
def warning(text, options={})
-
warn_with "WARNING: #{text}.", options
-
end
-
-
# @private
-
#
-
# Used internally to print longer warnings
-
1
def warn_with(message, options={})
-
call_site = options.fetch(:call_site) { CallerFilter.first_non_rspec_line }
-
message << " Use #{options[:replacement]} instead." if options[:replacement]
-
message << " Called from #{call_site}." if call_site
-
::Kernel.warn message
-
end
-
end
-
end
-
-
1
extend RSpec::Support::Warnings
-
end
-
1
dir = File.dirname(__FILE__)
-
1
$LOAD_PATH.unshift dir unless $LOAD_PATH.include?(dir)
-
-
1
require 'sass/version'
-
-
# The module that contains everything Sass-related:
-
#
-
# * {Sass::Engine} is the class used to render Sass/SCSS within Ruby code.
-
# * {Sass::Plugin} is interfaces with web frameworks (Rails and Merb in particular).
-
# * {Sass::SyntaxError} is raised when Sass encounters an error.
-
# * {Sass::CSS} handles conversion of CSS to Sass.
-
#
-
# Also see the {file:SASS_REFERENCE.md full Sass reference}.
-
1
module Sass
-
1
class << self
-
# @private
-
1
attr_accessor :tests_running
-
end
-
-
# The global load paths for Sass files. This is meant for plugins and
-
# libraries to register the paths to their Sass stylesheets to that they may
-
# be `@imported`. This load path is used by every instance of {Sass::Engine}.
-
# They are lower-precedence than any load paths passed in via the
-
# {file:SASS_REFERENCE.md#load_paths-option `:load_paths` option}.
-
#
-
# If the `SASS_PATH` environment variable is set,
-
# the initial value of `load_paths` will be initialized based on that.
-
# The variable should be a colon-separated list of path names
-
# (semicolon-separated on Windows).
-
#
-
# Note that files on the global load path are never compiled to CSS
-
# themselves, even if they aren't partials. They exist only to be imported.
-
#
-
# @example
-
# Sass.load_paths << File.dirname(__FILE__ + '/sass')
-
# @return [Array<String, Pathname, Sass::Importers::Base>]
-
1
def self.load_paths
-
@load_paths ||= if ENV['SASS_PATH']
-
ENV['SASS_PATH'].split(Sass::Util.windows? ? ';' : ':')
-
else
-
[]
-
end
-
end
-
-
# Compile a Sass or SCSS string to CSS.
-
# Defaults to SCSS.
-
#
-
# @param contents [String] The contents of the Sass file.
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#Options the Sass options documentation}
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
1
def self.compile(contents, options = {})
-
options[:syntax] ||= :scss
-
Engine.new(contents, options).to_css
-
end
-
-
# Compile a file on disk to CSS.
-
#
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
#
-
# @overload compile_file(filename, options = {})
-
# Return the compiled CSS rather than writing it to a file.
-
#
-
# @param filename [String] The path to the Sass, SCSS, or CSS file on disk.
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#Options the Sass options documentation}
-
# @return [String] The compiled CSS.
-
#
-
# @overload compile_file(filename, css_filename, options = {})
-
# Write the compiled CSS to a file.
-
#
-
# @param filename [String] The path to the Sass, SCSS, or CSS file on disk.
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#Options the Sass options documentation}
-
# @param css_filename [String] The location to which to write the compiled CSS.
-
1
def self.compile_file(filename, *args)
-
options = args.last.is_a?(Hash) ? args.pop : {}
-
css_filename = args.shift
-
result = Sass::Engine.for_file(filename, options).render
-
if css_filename
-
options[:css_filename] ||= css_filename
-
open(css_filename, "w") {|css_file| css_file.write(result)}
-
nil
-
else
-
result
-
end
-
end
-
end
-
-
1
require 'sass/logger'
-
1
require 'sass/util'
-
-
1
require 'sass/engine'
-
1
require 'sass/plugin' if defined?(Merb::Plugins)
-
1
require 'sass/railtie'
-
1
require 'sass/features'
-
1
require 'stringio'
-
-
1
module Sass
-
# Sass cache stores are in charge of storing cached information,
-
# especially parse trees for Sass documents.
-
#
-
# User-created importers must inherit from {CacheStores::Base}.
-
1
module CacheStores
-
end
-
end
-
-
1
require 'sass/cache_stores/base'
-
1
require 'sass/cache_stores/filesystem'
-
1
require 'sass/cache_stores/memory'
-
1
require 'sass/cache_stores/chain'
-
1
module Sass
-
1
module CacheStores
-
# An abstract base class for backends for the Sass cache.
-
# Any key-value store can act as such a backend;
-
# it just needs to implement the
-
# \{#_store} and \{#_retrieve} methods.
-
#
-
# To use a cache store with Sass,
-
# use the {file:SASS_REFERENCE.md#cache_store-option `:cache_store` option}.
-
#
-
# @abstract
-
1
class Base
-
# Store cached contents for later retrieval
-
# Must be implemented by all CacheStore subclasses
-
#
-
# Note: cache contents contain binary data.
-
#
-
# @param key [String] The key to store the contents under
-
# @param version [String] The current sass version.
-
# Cached contents must not be retrieved across different versions of sass.
-
# @param sha [String] The sha of the sass source.
-
# Cached contents must not be retrieved if the sha has changed.
-
# @param contents [String] The contents to store.
-
1
def _store(key, version, sha, contents)
-
raise "#{self.class} must implement #_store."
-
end
-
-
# Retrieved cached contents.
-
# Must be implemented by all subclasses.
-
#
-
# Note: if the key exists but the sha or version have changed,
-
# then the key may be deleted by the cache store, if it wants to do so.
-
#
-
# @param key [String] The key to retrieve
-
# @param version [String] The current sass version.
-
# Cached contents must not be retrieved across different versions of sass.
-
# @param sha [String] The sha of the sass source.
-
# Cached contents must not be retrieved if the sha has changed.
-
# @return [String] The contents that were previously stored.
-
# @return [NilClass] when the cache key is not found or the version or sha have changed.
-
1
def _retrieve(key, version, sha)
-
raise "#{self.class} must implement #_retrieve."
-
end
-
-
# Store a {Sass::Tree::RootNode}.
-
#
-
# @param key [String] The key to store it under.
-
# @param sha [String] The checksum for the contents that are being stored.
-
# @param root [Object] The root node to cache.
-
1
def store(key, sha, root)
-
_store(key, Sass::VERSION, sha, Marshal.dump(root))
-
rescue TypeError, LoadError => e
-
Sass::Util.sass_warn "Warning. Error encountered while saving cache #{path_to(key)}: #{e}"
-
nil
-
end
-
-
# Retrieve a {Sass::Tree::RootNode}.
-
#
-
# @param key [String] The key the root element was stored under.
-
# @param sha [String] The checksum of the root element's content.
-
# @return [Object] The cached object.
-
1
def retrieve(key, sha)
-
contents = _retrieve(key, Sass::VERSION, sha)
-
Marshal.load(contents) if contents
-
rescue EOFError, TypeError, ArgumentError, LoadError => e
-
Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
-
nil
-
end
-
-
# Return the key for the sass file.
-
#
-
# The `(sass_dirname, sass_basename)` pair
-
# should uniquely identify the Sass document,
-
# but otherwise there are no restrictions on their content.
-
#
-
# @param sass_dirname [String]
-
# The fully-expanded location of the Sass file.
-
# This corresponds to the directory name on a filesystem.
-
# @param sass_basename [String] The name of the Sass file that is being referenced.
-
# This corresponds to the basename on a filesystem.
-
1
def key(sass_dirname, sass_basename)
-
dir = Digest::SHA1.hexdigest(sass_dirname)
-
filename = "#{sass_basename}c"
-
"#{dir}/#{filename}"
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module CacheStores
-
# A meta-cache that chains multiple caches together.
-
# Specifically:
-
#
-
# * All `#store`s are passed to all caches.
-
# * `#retrieve`s are passed to each cache until one has a hit.
-
# * When one cache has a hit, the value is `#store`d in all earlier caches.
-
1
class Chain < Base
-
# Create a new cache chaining the given caches.
-
#
-
# @param caches [Array<Sass::CacheStores::Base>] The caches to chain.
-
1
def initialize(*caches)
-
@caches = caches
-
end
-
-
# @see Base#store
-
1
def store(key, sha, obj)
-
@caches.each {|c| c.store(key, sha, obj)}
-
end
-
-
# @see Base#retrieve
-
1
def retrieve(key, sha)
-
@caches.each_with_index do |c, i|
-
obj = c.retrieve(key, sha)
-
next unless obj
-
@caches[0...i].each {|prev| prev.store(key, sha, obj)}
-
return obj
-
end
-
nil
-
end
-
end
-
end
-
end
-
1
require 'fileutils'
-
-
1
module Sass
-
1
module CacheStores
-
# A backend for the Sass cache using the filesystem.
-
1
class Filesystem < Base
-
# The directory where the cached files will be stored.
-
#
-
# @return [String]
-
1
attr_accessor :cache_location
-
-
# @param cache_location [String] see \{#cache\_location}
-
1
def initialize(cache_location)
-
@cache_location = cache_location
-
end
-
-
# @see Base#\_retrieve
-
1
def _retrieve(key, version, sha)
-
return unless File.readable?(path_to(key))
-
begin
-
File.open(path_to(key), "rb") do |f|
-
if f.readline("\n").strip == version && f.readline("\n").strip == sha
-
return f.read
-
end
-
end
-
File.unlink path_to(key)
-
rescue Errno::ENOENT
-
# Already deleted. Race condition?
-
end
-
nil
-
rescue EOFError, TypeError, ArgumentError => e
-
Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
-
end
-
-
# @see Base#\_store
-
1
def _store(key, version, sha, contents)
-
compiled_filename = path_to(key)
-
FileUtils.mkdir_p(File.dirname(compiled_filename))
-
Sass::Util.atomic_create_and_write_file(compiled_filename) do |f|
-
f.puts(version)
-
f.puts(sha)
-
f.write(contents)
-
end
-
rescue Errno::EACCES
-
# pass
-
end
-
-
1
private
-
-
# Returns the path to a file for the given key.
-
#
-
# @param key [String]
-
# @return [String] The path to the cache file.
-
1
def path_to(key)
-
key = key.gsub(/[<>:\\|?*%]/) {|c| "%%%03d" % c.ord}
-
File.join(cache_location, key)
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module CacheStores
-
# A backend for the Sass cache using in-process memory.
-
1
class Memory < Base
-
# Since the {Memory} store is stored in the Sass tree's options hash,
-
# when the options get serialized as part of serializing the tree,
-
# you get crazy exponential growth in the size of the cached objects
-
# unless you don't dump the cache.
-
#
-
# @private
-
1
def _dump(depth)
-
""
-
end
-
-
# If we deserialize this class, just make a new empty one.
-
#
-
# @private
-
1
def self._load(repr)
-
Memory.new
-
end
-
-
# Create a new, empty cache store.
-
1
def initialize
-
@contents = {}
-
end
-
-
# @see Base#retrieve
-
1
def retrieve(key, sha)
-
return unless @contents.has_key?(key)
-
return unless @contents[key][:sha] == sha
-
obj = @contents[key][:obj]
-
obj.respond_to?(:deep_copy) ? obj.deep_copy : obj.dup
-
end
-
-
# @see Base#store
-
1
def store(key, sha, obj)
-
@contents[key] = {:sha => sha, :obj => obj}
-
end
-
-
# Destructively clear the cache.
-
1
def reset!
-
@contents = {}
-
end
-
end
-
end
-
end
-
1
module Sass
-
# A deprecation warning that should only be printed once for a given line in a
-
# given file.
-
#
-
# A global Deprecation instance should be created for each type of deprecation
-
# warning, and `warn` should be called each time a warning is needed.
-
1
class Deprecation
-
1
@@allow_double_warnings = false
-
-
# Runs a block in which double deprecation warnings for the same location
-
# are allowed.
-
1
def self.allow_double_warnings
-
old_allow_double_warnings = @@allow_double_warnings
-
@@allow_double_warnings = true
-
yield
-
ensure
-
@@allow_double_warnings = old_allow_double_warnings
-
end
-
-
1
def initialize
-
# A set of filename, line pairs for which warnings have been emitted.
-
6
@seen = Set.new
-
end
-
-
# Prints `message` as a deprecation warning associated with `filename`,
-
# `line`, and optionally `column`.
-
#
-
# This ensures that only one message will be printed for each line of a
-
# given file.
-
#
-
# @overload warn(filename, line, message)
-
# @param filename [String, nil]
-
# @param line [Number]
-
# @param message [String]
-
# @overload warn(filename, line, column, message)
-
# @param filename [String, nil]
-
# @param line [Number]
-
# @param column [Number]
-
# @param message [String]
-
1
def warn(filename, line, column_or_message, message = nil)
-
return if !@@allow_double_warnings && @seen.add?([filename, line]).nil?
-
if message
-
column = column_or_message
-
else
-
message = column_or_message
-
end
-
-
location = "line #{line}"
-
location << ", column #{column}" if column
-
location << " of #{filename}" if filename
-
-
Sass::Util.sass_warn("DEPRECATION WARNING on #{location}:\n#{message}")
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'digest/sha1'
-
1
require 'sass/cache_stores'
-
1
require 'sass/deprecation'
-
1
require 'sass/source/position'
-
1
require 'sass/source/range'
-
1
require 'sass/source/map'
-
1
require 'sass/tree/node'
-
1
require 'sass/tree/root_node'
-
1
require 'sass/tree/rule_node'
-
1
require 'sass/tree/comment_node'
-
1
require 'sass/tree/prop_node'
-
1
require 'sass/tree/directive_node'
-
1
require 'sass/tree/media_node'
-
1
require 'sass/tree/supports_node'
-
1
require 'sass/tree/css_import_node'
-
1
require 'sass/tree/variable_node'
-
1
require 'sass/tree/mixin_def_node'
-
1
require 'sass/tree/mixin_node'
-
1
require 'sass/tree/trace_node'
-
1
require 'sass/tree/content_node'
-
1
require 'sass/tree/function_node'
-
1
require 'sass/tree/return_node'
-
1
require 'sass/tree/extend_node'
-
1
require 'sass/tree/if_node'
-
1
require 'sass/tree/while_node'
-
1
require 'sass/tree/for_node'
-
1
require 'sass/tree/each_node'
-
1
require 'sass/tree/debug_node'
-
1
require 'sass/tree/warn_node'
-
1
require 'sass/tree/import_node'
-
1
require 'sass/tree/charset_node'
-
1
require 'sass/tree/at_root_node'
-
1
require 'sass/tree/keyframe_rule_node'
-
1
require 'sass/tree/error_node'
-
1
require 'sass/tree/visitors/base'
-
1
require 'sass/tree/visitors/perform'
-
1
require 'sass/tree/visitors/cssize'
-
1
require 'sass/tree/visitors/extend'
-
1
require 'sass/tree/visitors/convert'
-
1
require 'sass/tree/visitors/to_css'
-
1
require 'sass/tree/visitors/deep_copy'
-
1
require 'sass/tree/visitors/set_options'
-
1
require 'sass/tree/visitors/check_nesting'
-
1
require 'sass/selector'
-
1
require 'sass/environment'
-
1
require 'sass/script'
-
1
require 'sass/scss'
-
1
require 'sass/stack'
-
1
require 'sass/error'
-
1
require 'sass/importers'
-
1
require 'sass/shared'
-
1
require 'sass/media'
-
1
require 'sass/supports'
-
-
1
module Sass
-
# A Sass mixin or function.
-
#
-
# `name`: `String`
-
# : The name of the mixin/function.
-
#
-
# `args`: `Array<(Script::Tree::Node, Script::Tree::Node)>`
-
# : The arguments for the mixin/function.
-
# Each element is a tuple containing the variable node of the argument
-
# and the parse tree for the default value of the argument.
-
#
-
# `splat`: `Script::Tree::Node?`
-
# : The variable node of the splat argument for this callable, or null.
-
#
-
# `environment`: {Sass::Environment}
-
# : The environment in which the mixin/function was defined.
-
# This is captured so that the mixin/function can have access
-
# to local variables defined in its scope.
-
#
-
# `tree`: `Array<Tree::Node>`
-
# : The parse tree for the mixin/function.
-
#
-
# `has_content`: `Boolean`
-
# : Whether the callable accepts a content block.
-
#
-
# `type`: `String`
-
# : The user-friendly name of the type of the callable.
-
#
-
# `origin`: `Symbol`
-
# : From whence comes the callable: `:stylesheet`, `:builtin`, `:css`
-
# A callable with an origin of `:stylesheet` was defined in the stylesheet itself.
-
# A callable with an origin of `:builtin` was defined in ruby.
-
# A callable (function) with an origin of `:css` returns a function call with arguments to CSS.
-
1
Callable = Struct.new(:name, :args, :splat, :environment, :tree, :has_content, :type, :origin)
-
-
# This class handles the parsing and compilation of the Sass template.
-
# Example usage:
-
#
-
# template = File.read('stylesheets/sassy.sass')
-
# sass_engine = Sass::Engine.new(template)
-
# output = sass_engine.render
-
# puts output
-
1
class Engine
-
1
@@old_property_deprecation = Deprecation.new
-
-
# A line of Sass code.
-
#
-
# `text`: `String`
-
# : The text in the line, without any whitespace at the beginning or end.
-
#
-
# `tabs`: `Integer`
-
# : The level of indentation of the line.
-
#
-
# `index`: `Integer`
-
# : The line number in the original document.
-
#
-
# `offset`: `Integer`
-
# : The number of bytes in on the line that the text begins.
-
# This ends up being the number of bytes of leading whitespace.
-
#
-
# `filename`: `String`
-
# : The name of the file in which this line appeared.
-
#
-
# `children`: `Array<Line>`
-
# : The lines nested below this one.
-
#
-
# `comment_tab_str`: `String?`
-
# : The prefix indentation for this comment, if it is a comment.
-
1
class Line < Struct.new(:text, :tabs, :index, :offset, :filename, :children, :comment_tab_str)
-
1
def comment?
-
text[0] == COMMENT_CHAR && (text[1] == SASS_COMMENT_CHAR || text[1] == CSS_COMMENT_CHAR)
-
end
-
end
-
-
# The character that begins a CSS property.
-
1
PROPERTY_CHAR = ?:
-
-
# The character that designates the beginning of a comment,
-
# either Sass or CSS.
-
1
COMMENT_CHAR = ?/
-
-
# The character that follows the general COMMENT_CHAR and designates a Sass comment,
-
# which is not output as a CSS comment.
-
1
SASS_COMMENT_CHAR = ?/
-
-
# The character that indicates that a comment allows interpolation
-
# and should be preserved even in `:compressed` mode.
-
1
SASS_LOUD_COMMENT_CHAR = ?!
-
-
# The character that follows the general COMMENT_CHAR and designates a CSS comment,
-
# which is embedded in the CSS document.
-
1
CSS_COMMENT_CHAR = ?*
-
-
# The character used to denote a compiler directive.
-
1
DIRECTIVE_CHAR = ?@
-
-
# Designates a non-parsed rule.
-
1
ESCAPE_CHAR = ?\\
-
-
# Designates block as mixin definition rather than CSS rules to output
-
1
MIXIN_DEFINITION_CHAR = ?=
-
-
# Includes named mixin declared using MIXIN_DEFINITION_CHAR
-
1
MIXIN_INCLUDE_CHAR = ?+
-
-
# The regex that matches and extracts data from
-
# properties of the form `:name prop`.
-
1
PROPERTY_OLD = /^:([^\s=:"]+)\s*(?:\s+|$)(.*)/
-
-
# The default options for Sass::Engine.
-
# @api public
-
1
DEFAULT_OPTIONS = {
-
:style => :nested,
-
:load_paths => [],
-
:cache => true,
-
:cache_location => './.sass-cache',
-
:syntax => :sass,
-
:filesystem_importer => Sass::Importers::Filesystem
-
}.freeze
-
-
# Converts a Sass options hash into a standard form, filling in
-
# default values and resolving aliases.
-
#
-
# @param options [{Symbol => Object}] The options hash;
-
# see {file:SASS_REFERENCE.md#Options the Sass options documentation}
-
# @return [{Symbol => Object}] The normalized options hash.
-
# @private
-
1
def self.normalize_options(options)
-
options = DEFAULT_OPTIONS.merge(options.reject {|_k, v| v.nil?})
-
-
# If the `:filename` option is passed in without an importer,
-
# assume it's using the default filesystem importer.
-
options[:importer] ||= options[:filesystem_importer].new(".") if options[:filename]
-
-
# Tracks the original filename of the top-level Sass file
-
options[:original_filename] ||= options[:filename]
-
-
options[:cache_store] ||= Sass::CacheStores::Chain.new(
-
Sass::CacheStores::Memory.new, Sass::CacheStores::Filesystem.new(options[:cache_location]))
-
# Support both, because the docs said one and the other actually worked
-
# for quite a long time.
-
options[:line_comments] ||= options[:line_numbers]
-
-
options[:load_paths] = (options[:load_paths] + Sass.load_paths).map do |p|
-
next p unless p.is_a?(String) || (defined?(Pathname) && p.is_a?(Pathname))
-
options[:filesystem_importer].new(p.to_s)
-
end
-
-
# Remove any deprecated importers if the location is imported explicitly
-
options[:load_paths].reject! do |importer|
-
importer.is_a?(Sass::Importers::DeprecatedPath) &&
-
options[:load_paths].find do |other_importer|
-
other_importer.is_a?(Sass::Importers::Filesystem) &&
-
other_importer != importer &&
-
other_importer.root == importer.root
-
end
-
end
-
-
# Backwards compatibility
-
options[:property_syntax] ||= options[:attribute_syntax]
-
case options[:property_syntax]
-
when :alternate; options[:property_syntax] = :new
-
when :normal; options[:property_syntax] = :old
-
end
-
options[:sourcemap] = :auto if options[:sourcemap] == true
-
options[:sourcemap] = :none if options[:sourcemap] == false
-
-
options
-
end
-
-
# Returns the {Sass::Engine} for the given file.
-
# This is preferable to Sass::Engine.new when reading from a file
-
# because it properly sets up the Engine's metadata,
-
# enables parse-tree caching,
-
# and infers the syntax from the filename.
-
#
-
# @param filename [String] The path to the Sass or SCSS file
-
# @param options [{Symbol => Object}] The options hash;
-
# See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
-
# @return [Sass::Engine] The Engine for the given Sass or SCSS file.
-
# @raise [Sass::SyntaxError] if there's an error in the document.
-
1
def self.for_file(filename, options)
-
had_syntax = options[:syntax]
-
-
if had_syntax
-
# Use what was explicitly specified
-
elsif filename =~ /\.scss$/
-
options.merge!(:syntax => :scss)
-
elsif filename =~ /\.sass$/
-
options.merge!(:syntax => :sass)
-
end
-
-
Sass::Engine.new(File.read(filename), options.merge(:filename => filename))
-
end
-
-
# The options for the Sass engine.
-
# See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
-
#
-
# @return [{Symbol => Object}]
-
1
attr_reader :options
-
-
# Creates a new Engine. Note that Engine should only be used directly
-
# when compiling in-memory Sass code.
-
# If you're compiling a single Sass file from the filesystem,
-
# use \{Sass::Engine.for\_file}.
-
# If you're compiling multiple files from the filesystem,
-
# use {Sass::Plugin}.
-
#
-
# @param template [String] The Sass template.
-
# This template can be encoded using any encoding
-
# that can be converted to Unicode.
-
# If the template contains an `@charset` declaration,
-
# that overrides the Ruby encoding
-
# (see {file:SASS_REFERENCE.md#Encodings the encoding documentation})
-
# @param options [{Symbol => Object}] An options hash.
-
# See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
-
# @see {Sass::Engine.for_file}
-
# @see {Sass::Plugin}
-
1
def initialize(template, options = {})
-
@options = self.class.normalize_options(options)
-
@template = template
-
@checked_encoding = false
-
@filename = nil
-
@line = nil
-
end
-
-
# Render the template to CSS.
-
#
-
# @return [String] The CSS
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
1
def render
-
return _to_tree.render unless @options[:quiet]
-
Sass::Util.silence_sass_warnings {_to_tree.render}
-
end
-
-
# Render the template to CSS and return the source map.
-
#
-
# @param sourcemap_uri [String] The sourcemap URI to use in the
-
# `@sourceMappingURL` comment. If this is relative, it should be relative
-
# to the location of the CSS file.
-
# @return [(String, Sass::Source::Map)] The rendered CSS and the associated
-
# source map
-
# @raise [Sass::SyntaxError] if there's an error in the document, or if the
-
# public URL for this document couldn't be determined.
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
1
def render_with_sourcemap(sourcemap_uri)
-
return _render_with_sourcemap(sourcemap_uri) unless @options[:quiet]
-
Sass::Util.silence_sass_warnings {_render_with_sourcemap(sourcemap_uri)}
-
end
-
-
1
alias_method :to_css, :render
-
-
# Parses the document into its parse tree. Memoized.
-
#
-
# @return [Sass::Tree::Node] The root of the parse tree.
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
1
def to_tree
-
@tree ||= if @options[:quiet]
-
Sass::Util.silence_sass_warnings {_to_tree}
-
else
-
_to_tree
-
end
-
end
-
-
# Returns the original encoding of the document.
-
#
-
# @return [Encoding, nil]
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
1
def source_encoding
-
check_encoding!
-
@source_encoding
-
end
-
-
# Gets a set of all the documents
-
# that are (transitive) dependencies of this document,
-
# not including the document itself.
-
#
-
# @return [[Sass::Engine]] The dependency documents.
-
1
def dependencies
-
_dependencies(Set.new, engines = Set.new)
-
Sass::Util.array_minus(engines, [self])
-
end
-
-
# Helper for \{#dependencies}.
-
#
-
# @private
-
1
def _dependencies(seen, engines)
-
key = [@options[:filename], @options[:importer]]
-
return if seen.include?(key)
-
seen << key
-
engines << self
-
to_tree.grep(Tree::ImportNode) do |n|
-
next if n.css_import?
-
n.imported_file._dependencies(seen, engines)
-
end
-
end
-
-
1
private
-
-
1
def _render_with_sourcemap(sourcemap_uri)
-
filename = @options[:filename]
-
importer = @options[:importer]
-
sourcemap_dir = @options[:sourcemap_filename] &&
-
File.dirname(File.expand_path(@options[:sourcemap_filename]))
-
if filename.nil?
-
raise Sass::SyntaxError.new(<<ERR)
-
Error generating source map: couldn't determine public URL for the source stylesheet.
-
No filename is available so there's nothing for the source map to link to.
-
ERR
-
elsif importer.nil?
-
raise Sass::SyntaxError.new(<<ERR)
-
Error generating source map: couldn't determine public URL for "#{filename}".
-
Without a public URL, there's nothing for the source map to link to.
-
An importer was not set for this file.
-
ERR
-
elsif Sass::Util.silence_warnings do
-
sourcemap_dir = nil if @options[:sourcemap] == :file
-
importer.public_url(filename, sourcemap_dir).nil?
-
end
-
raise Sass::SyntaxError.new(<<ERR)
-
Error generating source map: couldn't determine public URL for "#{filename}".
-
Without a public URL, there's nothing for the source map to link to.
-
Custom importers should define the #public_url method.
-
ERR
-
end
-
-
rendered, sourcemap = _to_tree.render_with_sourcemap
-
compressed = @options[:style] == :compressed
-
rendered << "\n" if rendered[-1] != ?\n
-
rendered << "\n" unless compressed
-
rendered << "/*# sourceMappingURL="
-
rendered << URI::DEFAULT_PARSER.escape(sourcemap_uri)
-
rendered << " */\n"
-
return rendered, sourcemap
-
end
-
-
1
def _to_tree
-
check_encoding!
-
-
if (@options[:cache] || @options[:read_cache]) &&
-
@options[:filename] && @options[:importer]
-
key = sassc_key
-
sha = Digest::SHA1.hexdigest(@template)
-
-
if (root = @options[:cache_store].retrieve(key, sha))
-
root.options = @options
-
return root
-
end
-
end
-
-
if @options[:syntax] == :scss
-
root = Sass::SCSS::Parser.new(@template, @options[:filename], @options[:importer]).parse
-
else
-
root = Tree::RootNode.new(@template)
-
append_children(root, tree(tabulate(@template)).first, true)
-
end
-
-
root.options = @options
-
if @options[:cache] && key && sha
-
begin
-
old_options = root.options
-
root.options = {}
-
@options[:cache_store].store(key, sha, root)
-
ensure
-
root.options = old_options
-
end
-
end
-
root
-
rescue SyntaxError => e
-
e.modify_backtrace(:filename => @options[:filename], :line => @line)
-
e.sass_template = @template
-
raise e
-
end
-
-
1
def sassc_key
-
@options[:cache_store].key(*@options[:importer].key(@options[:filename], @options))
-
end
-
-
1
def check_encoding!
-
return if @checked_encoding
-
@checked_encoding = true
-
@template, @source_encoding = Sass::Util.check_sass_encoding(@template)
-
end
-
-
1
def tabulate(string)
-
tab_str = nil
-
comment_tab_str = nil
-
first = true
-
lines = []
-
string.scan(/^[^\n]*?$/).each_with_index do |line, index|
-
index += (@options[:line] || 1)
-
if line.strip.empty?
-
lines.last.text << "\n" if lines.last && lines.last.comment?
-
next
-
end
-
-
line_tab_str = line[/^\s*/]
-
unless line_tab_str.empty?
-
if tab_str.nil?
-
comment_tab_str ||= line_tab_str
-
next if try_comment(line, lines.last, "", comment_tab_str, index)
-
comment_tab_str = nil
-
end
-
-
tab_str ||= line_tab_str
-
-
raise SyntaxError.new("Indenting at the beginning of the document is illegal.",
-
:line => index) if first
-
-
raise SyntaxError.new("Indentation can't use both tabs and spaces.",
-
:line => index) if tab_str.include?(?\s) && tab_str.include?(?\t)
-
end
-
first &&= !tab_str.nil?
-
if tab_str.nil?
-
lines << Line.new(line.strip, 0, index, 0, @options[:filename], [])
-
next
-
end
-
-
comment_tab_str ||= line_tab_str
-
if try_comment(line, lines.last, tab_str * lines.last.tabs, comment_tab_str, index)
-
next
-
else
-
comment_tab_str = nil
-
end
-
-
line_tabs = line_tab_str.scan(tab_str).size
-
if tab_str * line_tabs != line_tab_str
-
message = <<END.strip.tr("\n", ' ')
-
Inconsistent indentation: #{Sass::Shared.human_indentation line_tab_str, true} used for indentation,
-
but the rest of the document was indented using #{Sass::Shared.human_indentation tab_str}.
-
END
-
raise SyntaxError.new(message, :line => index)
-
end
-
-
lines << Line.new(line.strip, line_tabs, index, line_tab_str.size, @options[:filename], [])
-
end
-
lines
-
end
-
-
# @comment
-
1
def try_comment(line, last, tab_str, comment_tab_str, index)
-
return unless last && last.comment?
-
# Nested comment stuff must be at least one whitespace char deeper
-
# than the normal indentation
-
return unless line =~ /^#{tab_str}\s/
-
unless line =~ /^(?:#{comment_tab_str})(.*)$/
-
raise SyntaxError.new(<<MSG.strip.tr("\n", " "), :line => index)
-
Inconsistent indentation:
-
previous line was indented by #{Sass::Shared.human_indentation comment_tab_str},
-
but this line was indented by #{Sass::Shared.human_indentation line[/^\s*/]}.
-
MSG
-
end
-
-
last.comment_tab_str ||= comment_tab_str
-
last.text << "\n" << line
-
true
-
end
-
-
1
def tree(arr, i = 0)
-
return [], i if arr[i].nil?
-
-
base = arr[i].tabs
-
nodes = []
-
while (line = arr[i]) && line.tabs >= base
-
if line.tabs > base
-
nodes.last.children, i = tree(arr, i)
-
else
-
nodes << line
-
i += 1
-
end
-
end
-
return nodes, i
-
end
-
-
1
def build_tree(parent, line, root = false)
-
@line = line.index
-
@offset = line.offset
-
node_or_nodes = parse_line(parent, line, root)
-
-
Array(node_or_nodes).each do |node|
-
# Node is a symbol if it's non-outputting, like a variable assignment
-
next unless node.is_a? Tree::Node
-
-
node.line = line.index
-
node.filename = line.filename
-
-
append_children(node, line.children, false)
-
end
-
-
node_or_nodes
-
end
-
-
1
def append_children(parent, children, root)
-
continued_rule = nil
-
continued_comment = nil
-
children.each do |line|
-
child = build_tree(parent, line, root)
-
-
if child.is_a?(Tree::RuleNode)
-
if child.continued? && child.children.empty?
-
if continued_rule
-
continued_rule.add_rules child
-
else
-
continued_rule = child
-
end
-
next
-
elsif continued_rule
-
continued_rule.add_rules child
-
continued_rule.children = child.children
-
continued_rule, child = nil, continued_rule
-
end
-
elsif continued_rule
-
continued_rule = nil
-
end
-
-
if child.is_a?(Tree::CommentNode) && child.type == :silent
-
if continued_comment &&
-
child.line == continued_comment.line +
-
continued_comment.lines + 1
-
continued_comment.value.last.sub!(%r{ \*/\Z}, '')
-
child.value.first.gsub!(%r{\A/\*}, ' *')
-
continued_comment.value += ["\n"] + child.value
-
next
-
end
-
-
continued_comment = child
-
end
-
-
check_for_no_children(child)
-
validate_and_append_child(parent, child, line, root)
-
end
-
-
parent
-
end
-
-
1
def validate_and_append_child(parent, child, line, root)
-
case child
-
when Array
-
child.each {|c| validate_and_append_child(parent, c, line, root)}
-
when Tree::Node
-
parent << child
-
end
-
end
-
-
1
def check_for_no_children(node)
-
return unless node.is_a?(Tree::RuleNode) && node.children.empty?
-
Sass::Util.sass_warn(<<WARNING.strip)
-
WARNING on line #{node.line}#{" of #{node.filename}" if node.filename}:
-
This selector doesn't have any properties and will not be rendered.
-
WARNING
-
end
-
-
1
def parse_line(parent, line, root)
-
case line.text[0]
-
when PROPERTY_CHAR
-
if line.text[1] == PROPERTY_CHAR ||
-
(@options[:property_syntax] == :new &&
-
line.text =~ PROPERTY_OLD && $2.empty?)
-
# Support CSS3-style pseudo-elements,
-
# which begin with ::,
-
# as well as pseudo-classes
-
# if we're using the new property syntax
-
Tree::RuleNode.new(parse_interp(line.text), full_line_range(line))
-
else
-
name_start_offset = line.offset + 1 # +1 for the leading ':'
-
name, value = line.text.scan(PROPERTY_OLD)[0]
-
raise SyntaxError.new("Invalid property: \"#{line.text}\".",
-
:line => @line) if name.nil? || value.nil?
-
-
@@old_property_deprecation.warn(@options[:filename], @line, <<WARNING)
-
Old-style properties like "#{line.text}" are deprecated and will be an error in future versions of Sass.
-
Use "#{name}: #{value}" instead.
-
WARNING
-
-
value_start_offset = name_end_offset = name_start_offset + name.length
-
unless value.empty?
-
# +1 and -1 both compensate for the leading ':', which is part of line.text
-
value_start_offset = name_start_offset + line.text.index(value, name.length + 1) - 1
-
end
-
-
property = parse_property(name, parse_interp(name), value, :old, line, value_start_offset)
-
property.name_source_range = Sass::Source::Range.new(
-
Sass::Source::Position.new(@line, to_parser_offset(name_start_offset)),
-
Sass::Source::Position.new(@line, to_parser_offset(name_end_offset)),
-
@options[:filename], @options[:importer])
-
property
-
end
-
when ?$
-
parse_variable(line)
-
when COMMENT_CHAR
-
parse_comment(line)
-
when DIRECTIVE_CHAR
-
parse_directive(parent, line, root)
-
when ESCAPE_CHAR
-
Tree::RuleNode.new(parse_interp(line.text[1..-1]), full_line_range(line))
-
when MIXIN_DEFINITION_CHAR
-
parse_mixin_definition(line)
-
when MIXIN_INCLUDE_CHAR
-
if line.text[1].nil? || line.text[1] == ?\s
-
Tree::RuleNode.new(parse_interp(line.text), full_line_range(line))
-
else
-
parse_mixin_include(line, root)
-
end
-
else
-
parse_property_or_rule(line)
-
end
-
end
-
-
1
def parse_property_or_rule(line)
-
scanner = Sass::Util::MultibyteStringScanner.new(line.text)
-
hack_char = scanner.scan(/[:\*\.]|\#(?!\{)/)
-
offset = line.offset
-
offset += hack_char.length if hack_char
-
parser = Sass::SCSS::Parser.new(scanner,
-
@options[:filename], @options[:importer],
-
@line, to_parser_offset(offset))
-
-
unless (res = parser.parse_interp_ident)
-
parsed = parse_interp(line.text, line.offset)
-
return Tree::RuleNode.new(parsed, full_line_range(line))
-
end
-
-
ident_range = Sass::Source::Range.new(
-
Sass::Source::Position.new(@line, to_parser_offset(line.offset)),
-
Sass::Source::Position.new(@line, parser.offset),
-
@options[:filename], @options[:importer])
-
offset = parser.offset - 1
-
res.unshift(hack_char) if hack_char
-
-
# Handle comments after a property name but before the colon.
-
if (comment = scanner.scan(Sass::SCSS::RX::COMMENT))
-
res << comment
-
offset += comment.length
-
end
-
-
name = line.text[0...scanner.pos]
-
could_be_property =
-
if name.start_with?('--')
-
(scanned = scanner.scan(/\s*:/))
-
else
-
(scanned = scanner.scan(/\s*:(?:\s+|$)/))
-
end
-
-
if could_be_property # test for a property
-
offset += scanned.length
-
property = parse_property(name, res, scanner.rest, :new, line, offset)
-
property.name_source_range = ident_range
-
property
-
else
-
res.pop if comment
-
-
if (trailing = (scanner.scan(/\s*#{Sass::SCSS::RX::COMMENT}/) ||
-
scanner.scan(/\s*#{Sass::SCSS::RX::SINGLE_LINE_COMMENT}/)))
-
trailing.strip!
-
end
-
interp_parsed = parse_interp(scanner.rest)
-
selector_range = Sass::Source::Range.new(
-
ident_range.start_pos,
-
Sass::Source::Position.new(@line, to_parser_offset(line.offset) + line.text.length),
-
@options[:filename], @options[:importer])
-
rule = Tree::RuleNode.new(res + interp_parsed, selector_range)
-
rule << Tree::CommentNode.new([trailing], :silent) if trailing
-
rule
-
end
-
end
-
-
# @comment
-
# rubocop:disable ParameterLists
-
1
def parse_property(name, parsed_name, value, prop, line, start_offset)
-
# rubocop:enable ParameterLists
-
-
if name.start_with?('--')
-
unless line.children.empty?
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath custom properties.",
-
:line => @line + 1)
-
end
-
-
parser = Sass::SCSS::Parser.new(value,
-
@options[:filename], @options[:importer],
-
@line, to_parser_offset(@offset))
-
parsed_value = parser.parse_declaration_value
-
end_offset = start_offset + value.length
-
elsif value.strip.empty?
-
parsed_value = [Sass::Script::Tree::Literal.new(Sass::Script::Value::String.new(""))]
-
end_offset = start_offset
-
else
-
expr = parse_script(value, :offset => to_parser_offset(start_offset))
-
end_offset = expr.source_range.end_pos.offset - 1
-
parsed_value = [expr]
-
end
-
node = Tree::PropNode.new(parse_interp(name), parsed_value, prop)
-
node.value_source_range = Sass::Source::Range.new(
-
Sass::Source::Position.new(line.index, to_parser_offset(start_offset)),
-
Sass::Source::Position.new(line.index, to_parser_offset(end_offset)),
-
@options[:filename], @options[:importer])
-
if !node.custom_property? && value.strip.empty? && line.children.empty?
-
raise SyntaxError.new(
-
"Invalid property: \"#{node.declaration}\" (no value)." +
-
node.pseudo_class_selector_message)
-
end
-
-
node
-
end
-
-
1
def parse_variable(line)
-
name, value, flags = line.text.scan(Script::MATCH)[0]
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath variable declarations.",
-
:line => @line + 1) unless line.children.empty?
-
raise SyntaxError.new("Invalid variable: \"#{line.text}\".",
-
:line => @line) unless name && value
-
flags = flags ? flags.split(/\s+/) : []
-
if (invalid_flag = flags.find {|f| f != '!default' && f != '!global'})
-
raise SyntaxError.new("Invalid flag \"#{invalid_flag}\".", :line => @line)
-
end
-
-
# This workaround is needed for the case when the variable value is part of the identifier,
-
# otherwise we end up with the offset equal to the value index inside the name:
-
# $red_color: red;
-
var_lhs_length = 1 + name.length # 1 stands for '$'
-
index = line.text.index(value, line.offset + var_lhs_length) || 0
-
expr = parse_script(value, :offset => to_parser_offset(line.offset + index))
-
-
Tree::VariableNode.new(name, expr, flags.include?('!default'), flags.include?('!global'))
-
end
-
-
1
def parse_comment(line)
-
if line.text[1] == CSS_COMMENT_CHAR || line.text[1] == SASS_COMMENT_CHAR
-
silent = line.text[1] == SASS_COMMENT_CHAR
-
loud = !silent && line.text[2] == SASS_LOUD_COMMENT_CHAR
-
if silent
-
value = [line.text]
-
else
-
value = self.class.parse_interp(
-
line.text, line.index, to_parser_offset(line.offset), :filename => @filename)
-
end
-
value = Sass::Util.with_extracted_values(value) do |str|
-
str = str.gsub(/^#{line.comment_tab_str}/m, '')[2..-1] # get rid of // or /*
-
format_comment_text(str, silent)
-
end
-
type = if silent
-
:silent
-
elsif loud
-
:loud
-
else
-
:normal
-
end
-
comment = Tree::CommentNode.new(value, type)
-
comment.line = line.index
-
text = line.text.rstrip
-
if text.include?("\n")
-
end_offset = text.length - text.rindex("\n")
-
else
-
end_offset = to_parser_offset(line.offset + text.length)
-
end
-
comment.source_range = Sass::Source::Range.new(
-
Sass::Source::Position.new(@line, to_parser_offset(line.offset)),
-
Sass::Source::Position.new(@line + text.count("\n"), end_offset),
-
@options[:filename])
-
comment
-
else
-
Tree::RuleNode.new(parse_interp(line.text), full_line_range(line))
-
end
-
end
-
-
1
DIRECTIVES = Set[:mixin, :include, :function, :return, :debug, :warn, :for,
-
:each, :while, :if, :else, :extend, :import, :media, :charset, :content,
-
:at_root, :error]
-
-
1
def parse_directive(parent, line, root)
-
directive, whitespace, value = line.text[1..-1].split(/(\s+)/, 2)
-
raise SyntaxError.new("Invalid directive: '@'.") unless directive
-
offset = directive.size + whitespace.size + 1 if whitespace
-
-
directive_name = directive.tr('-', '_').to_sym
-
if DIRECTIVES.include?(directive_name)
-
return send("parse_#{directive_name}_directive", parent, line, root, value, offset)
-
end
-
-
unprefixed_directive = directive.gsub(/^-[a-z0-9]+-/i, '')
-
if unprefixed_directive == 'supports'
-
parser = Sass::SCSS::Parser.new(value, @options[:filename], @line)
-
return Tree::SupportsNode.new(directive, parser.parse_supports_condition)
-
end
-
-
Tree::DirectiveNode.new(
-
value.nil? ? ["@#{directive}"] : ["@#{directive} "] + parse_interp(value, offset))
-
end
-
-
1
def parse_while_directive(parent, line, root, value, offset)
-
raise SyntaxError.new("Invalid while directive '@while': expected expression.") unless value
-
Tree::WhileNode.new(parse_script(value, :offset => offset))
-
end
-
-
1
def parse_if_directive(parent, line, root, value, offset)
-
raise SyntaxError.new("Invalid if directive '@if': expected expression.") unless value
-
Tree::IfNode.new(parse_script(value, :offset => offset))
-
end
-
-
1
def parse_debug_directive(parent, line, root, value, offset)
-
raise SyntaxError.new("Invalid debug directive '@debug': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath debug directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::DebugNode.new(parse_script(value, :offset => offset))
-
end
-
-
1
def parse_error_directive(parent, line, root, value, offset)
-
raise SyntaxError.new("Invalid error directive '@error': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath error directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::ErrorNode.new(parse_script(value, :offset => offset))
-
end
-
-
1
def parse_extend_directive(parent, line, root, value, offset)
-
raise SyntaxError.new("Invalid extend directive '@extend': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath extend directives.",
-
:line => @line + 1) unless line.children.empty?
-
optional = !!value.gsub!(/\s+#{Sass::SCSS::RX::OPTIONAL}$/, '')
-
offset = line.offset + line.text.index(value).to_i
-
interp_parsed = parse_interp(value, offset)
-
selector_range = Sass::Source::Range.new(
-
Sass::Source::Position.new(@line, to_parser_offset(offset)),
-
Sass::Source::Position.new(@line, to_parser_offset(line.offset) + line.text.length),
-
@options[:filename], @options[:importer]
-
)
-
Tree::ExtendNode.new(interp_parsed, optional, selector_range)
-
end
-
-
1
def parse_warn_directive(parent, line, root, value, offset)
-
raise SyntaxError.new("Invalid warn directive '@warn': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath warn directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::WarnNode.new(parse_script(value, :offset => offset))
-
end
-
-
1
def parse_return_directive(parent, line, root, value, offset)
-
raise SyntaxError.new("Invalid @return: expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath return directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::ReturnNode.new(parse_script(value, :offset => offset))
-
end
-
-
1
def parse_charset_directive(parent, line, root, value, offset)
-
name = value && value[/\A(["'])(.*)\1\Z/, 2] # "
-
raise SyntaxError.new("Invalid charset directive '@charset': expected string.") unless name
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath charset directives.",
-
:line => @line + 1) unless line.children.empty?
-
Tree::CharsetNode.new(name)
-
end
-
-
1
def parse_media_directive(parent, line, root, value, offset)
-
parser = Sass::SCSS::Parser.new(value,
-
@options[:filename], @options[:importer],
-
@line, to_parser_offset(@offset))
-
offset = line.offset + line.text.index('media').to_i - 1
-
parsed_media_query_list = parser.parse_media_query_list.to_a
-
node = Tree::MediaNode.new(parsed_media_query_list)
-
node.source_range = Sass::Source::Range.new(
-
Sass::Source::Position.new(@line, to_parser_offset(offset)),
-
Sass::Source::Position.new(@line, to_parser_offset(line.offset) + line.text.length),
-
@options[:filename], @options[:importer])
-
node
-
end
-
-
1
def parse_at_root_directive(parent, line, root, value, offset)
-
return Sass::Tree::AtRootNode.new unless value
-
-
if value.start_with?('(')
-
parser = Sass::SCSS::Parser.new(value,
-
@options[:filename], @options[:importer],
-
@line, to_parser_offset(@offset))
-
offset = line.offset + line.text.index('at-root').to_i - 1
-
return Tree::AtRootNode.new(parser.parse_at_root_query)
-
end
-
-
at_root_node = Tree::AtRootNode.new
-
parsed = parse_interp(value, offset)
-
rule_node = Tree::RuleNode.new(parsed, full_line_range(line))
-
-
# The caller expects to automatically add children to the returned node
-
# and we want it to add children to the rule node instead, so we
-
# manually handle the wiring here and return nil so the caller doesn't
-
# duplicate our efforts.
-
append_children(rule_node, line.children, false)
-
at_root_node << rule_node
-
parent << at_root_node
-
nil
-
end
-
-
1
def parse_for_directive(parent, line, root, value, offset)
-
var, from_expr, to_name, to_expr =
-
value.scan(/^([^\s]+)\s+from\s+(.+)\s+(to|through)\s+(.+)$/).first
-
-
if var.nil? # scan failed, try to figure out why for error message
-
if value !~ /^[^\s]+/
-
expected = "variable name"
-
elsif value !~ /^[^\s]+\s+from\s+.+/
-
expected = "'from <expr>'"
-
else
-
expected = "'to <expr>' or 'through <expr>'"
-
end
-
raise SyntaxError.new("Invalid for directive '@for #{value}': expected #{expected}.")
-
end
-
raise SyntaxError.new("Invalid variable \"#{var}\".") unless var =~ Script::VALIDATE
-
-
var = var[1..-1]
-
parsed_from = parse_script(from_expr, :offset => line.offset + line.text.index(from_expr))
-
parsed_to = parse_script(to_expr, :offset => line.offset + line.text.index(to_expr))
-
Tree::ForNode.new(var, parsed_from, parsed_to, to_name == 'to')
-
end
-
-
1
def parse_each_directive(parent, line, root, value, offset)
-
vars, list_expr = value.scan(/^([^\s]+(?:\s*,\s*[^\s]+)*)\s+in\s+(.+)$/).first
-
-
if vars.nil? # scan failed, try to figure out why for error message
-
if value !~ /^[^\s]+/
-
expected = "variable name"
-
elsif value !~ /^[^\s]+(?:\s*,\s*[^\s]+)*[^\s]+\s+from\s+.+/
-
expected = "'in <expr>'"
-
end
-
raise SyntaxError.new("Invalid each directive '@each #{value}': expected #{expected}.")
-
end
-
-
vars = vars.split(',').map do |var|
-
var.strip!
-
raise SyntaxError.new("Invalid variable \"#{var}\".") unless var =~ Script::VALIDATE
-
var[1..-1]
-
end
-
-
parsed_list = parse_script(list_expr, :offset => line.offset + line.text.index(list_expr))
-
Tree::EachNode.new(vars, parsed_list)
-
end
-
-
1
def parse_else_directive(parent, line, root, value, offset)
-
previous = parent.children.last
-
raise SyntaxError.new("@else must come after @if.") unless previous.is_a?(Tree::IfNode)
-
-
if value
-
if value !~ /^if\s+(.+)/
-
raise SyntaxError.new("Invalid else directive '@else #{value}': expected 'if <expr>'.")
-
end
-
expr = parse_script($1, :offset => line.offset + line.text.index($1))
-
end
-
-
node = Tree::IfNode.new(expr)
-
append_children(node, line.children, false)
-
previous.add_else node
-
nil
-
end
-
-
1
def parse_import_directive(parent, line, root, value, offset)
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath import directives.",
-
:line => @line + 1) unless line.children.empty?
-
-
scanner = Sass::Util::MultibyteStringScanner.new(value)
-
values = []
-
-
loop do
-
unless (node = parse_import_arg(scanner, offset + scanner.pos))
-
raise SyntaxError.new(
-
"Invalid @import: expected file to import, was #{scanner.rest.inspect}",
-
:line => @line)
-
end
-
values << node
-
break unless scanner.scan(/,\s*/)
-
end
-
-
if scanner.scan(/;/)
-
raise SyntaxError.new("Invalid @import: expected end of line, was \";\".",
-
:line => @line)
-
end
-
-
values
-
end
-
-
# @comment
-
# rubocop:disable MethodLength
-
1
def parse_import_arg(scanner, offset)
-
return if scanner.eos?
-
-
if scanner.match?(/url\(/i)
-
script_parser = Sass::Script::Parser.new(scanner, @line, to_parser_offset(offset), @options)
-
str = script_parser.parse_string
-
-
if scanner.eos?
-
end_pos = str.source_range.end_pos
-
node = Tree::CssImportNode.new(str)
-
else
-
supports_parser = Sass::SCSS::Parser.new(scanner,
-
@options[:filename], @options[:importer],
-
@line, str.source_range.end_pos.offset)
-
supports_condition = supports_parser.parse_supports_clause
-
-
if scanner.eos?
-
node = Tree::CssImportNode.new(str, [], supports_condition)
-
else
-
media_parser = Sass::SCSS::Parser.new(scanner,
-
@options[:filename], @options[:importer],
-
@line, str.source_range.end_pos.offset)
-
media = media_parser.parse_media_query_list
-
end_pos = Sass::Source::Position.new(@line, media_parser.offset + 1)
-
node = Tree::CssImportNode.new(str, media.to_a, supports_condition)
-
end
-
end
-
-
node.source_range = Sass::Source::Range.new(
-
str.source_range.start_pos, end_pos,
-
@options[:filename], @options[:importer])
-
return node
-
end
-
-
unless (quoted_val = scanner.scan(Sass::SCSS::RX::STRING))
-
scanned = scanner.scan(/[^,;]+/)
-
node = Tree::ImportNode.new(scanned)
-
start_parser_offset = to_parser_offset(offset)
-
node.source_range = Sass::Source::Range.new(
-
Sass::Source::Position.new(@line, start_parser_offset),
-
Sass::Source::Position.new(@line, start_parser_offset + scanned.length),
-
@options[:filename], @options[:importer])
-
return node
-
end
-
-
start_offset = offset
-
offset += scanner.matched.length
-
val = Sass::Script::Value::String.value(scanner[1] || scanner[2])
-
scanned = scanner.scan(/\s*/)
-
if !scanner.match?(/[,;]|$/)
-
offset += scanned.length if scanned
-
media_parser = Sass::SCSS::Parser.new(scanner,
-
@options[:filename], @options[:importer], @line, offset)
-
media = media_parser.parse_media_query_list
-
node = Tree::CssImportNode.new(quoted_val, media.to_a)
-
node.source_range = Sass::Source::Range.new(
-
Sass::Source::Position.new(@line, to_parser_offset(start_offset)),
-
Sass::Source::Position.new(@line, media_parser.offset),
-
@options[:filename], @options[:importer])
-
elsif val =~ %r{^(https?:)?//}
-
node = Tree::CssImportNode.new(quoted_val)
-
node.source_range = Sass::Source::Range.new(
-
Sass::Source::Position.new(@line, to_parser_offset(start_offset)),
-
Sass::Source::Position.new(@line, to_parser_offset(offset)),
-
@options[:filename], @options[:importer])
-
else
-
node = Tree::ImportNode.new(val)
-
node.source_range = Sass::Source::Range.new(
-
Sass::Source::Position.new(@line, to_parser_offset(start_offset)),
-
Sass::Source::Position.new(@line, to_parser_offset(offset)),
-
@options[:filename], @options[:importer])
-
end
-
node
-
end
-
# @comment
-
# rubocop:enable MethodLength
-
-
1
def parse_mixin_directive(parent, line, root, value, offset)
-
parse_mixin_definition(line)
-
end
-
-
1
MIXIN_DEF_RE = /^(?:=|@mixin)\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
1
def parse_mixin_definition(line)
-
name, arg_string = line.text.scan(MIXIN_DEF_RE).first
-
raise SyntaxError.new("Invalid mixin \"#{line.text[1..-1]}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, splat = Script::Parser.new(arg_string.strip, @line, to_parser_offset(offset), @options).
-
parse_mixin_definition_arglist
-
Tree::MixinDefNode.new(name, args, splat)
-
end
-
-
1
CONTENT_RE = /^@content\s*(.+)?$/
-
1
def parse_content_directive(parent, line, root, value, offset)
-
trailing = line.text.scan(CONTENT_RE).first.first
-
unless trailing.nil?
-
raise SyntaxError.new(
-
"Invalid content directive. Trailing characters found: \"#{trailing}\".")
-
end
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath @content directives.",
-
:line => line.index + 1) unless line.children.empty?
-
Tree::ContentNode.new
-
end
-
-
1
def parse_include_directive(parent, line, root, value, offset)
-
parse_mixin_include(line, root)
-
end
-
-
1
MIXIN_INCLUDE_RE = /^(?:\+|@include)\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
1
def parse_mixin_include(line, root)
-
name, arg_string = line.text.scan(MIXIN_INCLUDE_RE).first
-
raise SyntaxError.new("Invalid mixin include \"#{line.text}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, keywords, splat, kwarg_splat =
-
Script::Parser.new(arg_string.strip, @line, to_parser_offset(offset), @options).
-
parse_mixin_include_arglist
-
Tree::MixinNode.new(name, args, keywords, splat, kwarg_splat)
-
end
-
-
1
FUNCTION_RE = /^@function\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
1
def parse_function_directive(parent, line, root, value, offset)
-
name, arg_string = line.text.scan(FUNCTION_RE).first
-
raise SyntaxError.new("Invalid function definition \"#{line.text}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, splat = Script::Parser.new(arg_string.strip, @line, to_parser_offset(offset), @options).
-
parse_function_definition_arglist
-
Tree::FunctionNode.new(name, args, splat)
-
end
-
-
1
def parse_script(script, options = {})
-
line = options[:line] || @line
-
offset = options[:offset] || @offset + 1
-
Script.parse(script, line, offset, @options)
-
end
-
-
1
def format_comment_text(text, silent)
-
content = text.split("\n")
-
-
if content.first && content.first.strip.empty?
-
removed_first = true
-
content.shift
-
end
-
-
return "/* */" if content.empty?
-
content.last.gsub!(%r{ ?\*/ *$}, '')
-
first = content.shift unless removed_first
-
content.map! {|l| l.gsub!(/^\*( ?)/, '\1') || (l.empty? ? "" : " ") + l}
-
content.unshift first unless removed_first
-
if silent
-
"/*" + content.join("\n *") + " */"
-
else
-
# The #gsub fixes the case of a trailing */
-
"/*" + content.join("\n *").gsub(/ \*\Z/, '') + " */"
-
end
-
end
-
-
1
def parse_interp(text, offset = 0)
-
self.class.parse_interp(text, @line, offset, :filename => @filename)
-
end
-
-
# Parser tracks 1-based line and offset, so our offset should be converted.
-
1
def to_parser_offset(offset)
-
offset + 1
-
end
-
-
1
def full_line_range(line)
-
Sass::Source::Range.new(
-
Sass::Source::Position.new(@line, to_parser_offset(line.offset)),
-
Sass::Source::Position.new(@line, to_parser_offset(line.offset) + line.text.length),
-
@options[:filename], @options[:importer])
-
end
-
-
# It's important that this have strings (at least)
-
# at the beginning, the end, and between each Script::Tree::Node.
-
#
-
# @private
-
1
def self.parse_interp(text, line, offset, options)
-
res = []
-
rest = Sass::Shared.handle_interpolation text do |scan|
-
escapes = scan[2].size
-
res << scan.matched[0...-2 - escapes]
-
if escapes.odd?
-
res << "\\" * (escapes - 1) << '#{'
-
else
-
res << "\\" * [0, escapes - 1].max
-
if scan[1].include?("\n")
-
line += scan[1].count("\n")
-
offset = scan.matched_size - scan[1].rindex("\n")
-
else
-
offset += scan.matched_size
-
end
-
node = Script::Parser.new(scan, line, offset, options).parse_interpolated
-
offset = node.source_range.end_pos.offset
-
res << node
-
end
-
end
-
res << rest
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Sass
-
# The abstract base class for lexical environments for SassScript.
-
1
class BaseEnvironment
-
1
class << self
-
# Note: when updating this,
-
# update sass/yard/inherited_hash.rb as well.
-
1
def inherited_hash_accessor(name)
-
inherited_hash_reader(name)
-
inherited_hash_writer(name)
-
end
-
-
1
def inherited_hash_reader(name)
-
3
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{name}(name)
-
_#{name}(name.tr('_', '-'))
-
end
-
-
def _#{name}(name)
-
(@#{name}s && @#{name}s[name]) || @parent && @parent._#{name}(name)
-
end
-
protected :_#{name}
-
-
def is_#{name}_global?(name)
-
return !@parent if @#{name}s && @#{name}s.has_key?(name)
-
@parent && @parent.is_#{name}_global?(name)
-
end
-
RUBY
-
end
-
-
1
def inherited_hash_writer(name)
-
3
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def set_#{name}(name, value)
-
name = name.tr('_', '-')
-
@#{name}s[name] = value unless try_set_#{name}(name, value)
-
end
-
-
def try_set_#{name}(name, value)
-
@#{name}s ||= {}
-
if @#{name}s.include?(name)
-
@#{name}s[name] = value
-
true
-
elsif @parent && !@parent.global?
-
@parent.try_set_#{name}(name, value)
-
else
-
false
-
end
-
end
-
protected :try_set_#{name}
-
-
def set_local_#{name}(name, value)
-
@#{name}s ||= {}
-
@#{name}s[name.tr('_', '-')] = value
-
end
-
-
def set_global_#{name}(name, value)
-
global_env.set_#{name}(name, value)
-
end
-
RUBY
-
end
-
end
-
-
# The options passed to the Sass Engine.
-
1
attr_reader :options
-
-
1
attr_writer :caller
-
1
attr_writer :content
-
1
attr_writer :selector
-
-
# variable
-
# Script::Value
-
1
inherited_hash_reader :var
-
-
# mixin
-
# Sass::Callable
-
1
inherited_hash_reader :mixin
-
-
# function
-
# Sass::Callable
-
1
inherited_hash_reader :function
-
-
# @param options [{Symbol => Object}] The options hash. See
-
# {file:SASS_REFERENCE.md#Options the Sass options documentation}.
-
# @param parent [Environment] See \{#parent}
-
1
def initialize(parent = nil, options = nil)
-
@parent = parent
-
@options = options || (parent && parent.options) || {}
-
@stack = @parent.nil? ? Sass::Stack.new : nil
-
@caller = nil
-
@content = nil
-
@filename = nil
-
@functions = nil
-
@mixins = nil
-
@selector = nil
-
@vars = nil
-
end
-
-
# Returns whether this is the global environment.
-
#
-
# @return [Boolean]
-
1
def global?
-
@parent.nil?
-
end
-
-
# The environment of the caller of this environment's mixin or function.
-
# @return {Environment?}
-
1
def caller
-
@caller || (@parent && @parent.caller)
-
end
-
-
# The content passed to this environment. This is naturally only set
-
# for mixin body environments with content passed in.
-
#
-
# @return {[Array<Sass::Tree::Node>, Environment]?} The content nodes and
-
# the lexical environment of the content block.
-
1
def content
-
@content || (@parent && @parent.content)
-
end
-
-
# The selector for the current CSS rule, or nil if there is no
-
# current CSS rule.
-
#
-
# @return [Selector::CommaSequence?] The current selector, with any
-
# nesting fully resolved.
-
1
def selector
-
@selector || (@caller && @caller.selector) || (@parent && @parent.selector)
-
end
-
-
# The top-level Environment object.
-
#
-
# @return [Environment]
-
1
def global_env
-
@global_env ||= global? ? self : @parent.global_env
-
end
-
-
# The import/mixin stack.
-
#
-
# @return [Sass::Stack]
-
1
def stack
-
@stack || global_env.stack
-
end
-
end
-
-
# The lexical environment for SassScript.
-
# This keeps track of variable, mixin, and function definitions.
-
#
-
# A new environment is created for each level of Sass nesting.
-
# This allows variables to be lexically scoped.
-
# The new environment refers to the environment in the upper scope,
-
# so it has access to variables defined in enclosing scopes,
-
# but new variables are defined locally.
-
#
-
# Environment also keeps track of the {Engine} options
-
# so that they can be made available to {Sass::Script::Functions}.
-
1
class Environment < BaseEnvironment
-
# The enclosing environment,
-
# or nil if this is the global environment.
-
#
-
# @return [Environment]
-
1
attr_reader :parent
-
-
# variable
-
# Script::Value
-
1
inherited_hash_writer :var
-
-
# mixin
-
# Sass::Callable
-
1
inherited_hash_writer :mixin
-
-
# function
-
# Sass::Callable
-
1
inherited_hash_writer :function
-
end
-
-
# A read-only wrapper for a lexical environment for SassScript.
-
1
class ReadOnlyEnvironment < BaseEnvironment
-
1
def initialize(parent = nil, options = nil)
-
super
-
@content_cached = nil
-
end
-
# The read-only environment of the caller of this environment's mixin or function.
-
#
-
# @see BaseEnvironment#caller
-
# @return {ReadOnlyEnvironment}
-
1
def caller
-
return @caller if @caller
-
env = super
-
@caller ||= env.is_a?(ReadOnlyEnvironment) ? env : ReadOnlyEnvironment.new(env, env.options)
-
end
-
-
# The content passed to this environment. If the content's environment isn't already
-
# read-only, it's made read-only.
-
#
-
# @see BaseEnvironment#content
-
#
-
# @return {[Array<Sass::Tree::Node>, ReadOnlyEnvironment]?} The content nodes and
-
# the lexical environment of the content block.
-
# Returns `nil` when there is no content in this environment.
-
1
def content
-
# Return the cached content from a previous invocation if any
-
return @content if @content_cached
-
# get the content with a read-write environment from the superclass
-
read_write_content = super
-
if read_write_content
-
tree, env = read_write_content
-
# make the content's environment read-only
-
if env && !env.is_a?(ReadOnlyEnvironment)
-
env = ReadOnlyEnvironment.new(env, env.options)
-
end
-
@content_cached = true
-
@content = [tree, env]
-
else
-
@content_cached = true
-
@content = nil
-
end
-
end
-
end
-
-
# An environment that can write to in-scope global variables, but doesn't
-
# create new variables in the global scope. Useful for top-level control
-
# directives.
-
1
class SemiGlobalEnvironment < Environment
-
1
def try_set_var(name, value)
-
@vars ||= {}
-
if @vars.include?(name)
-
@vars[name] = value
-
true
-
elsif @parent
-
@parent.try_set_var(name, value)
-
else
-
false
-
end
-
end
-
end
-
end
-
1
module Sass
-
# An exception class that keeps track of
-
# the line of the Sass template it was raised on
-
# and the Sass file that was being parsed (if applicable).
-
#
-
# All Sass errors are raised as {Sass::SyntaxError}s.
-
#
-
# When dealing with SyntaxErrors,
-
# it's important to provide filename and line number information.
-
# This will be used in various error reports to users, including backtraces;
-
# see \{#sass\_backtrace} for details.
-
#
-
# Some of this information is usually provided as part of the constructor.
-
# New backtrace entries can be added with \{#add\_backtrace},
-
# which is called when an exception is raised between files (e.g. with `@import`).
-
#
-
# Often, a chunk of code will all have similar backtrace information -
-
# the same filename or even line.
-
# It may also be useful to have a default line number set.
-
# In those situations, the default values can be used
-
# by omitting the information on the original exception,
-
# and then calling \{#modify\_backtrace} in a wrapper `rescue`.
-
# When doing this, be sure that all exceptions ultimately end up
-
# with the information filled in.
-
1
class SyntaxError < StandardError
-
# The backtrace of the error within Sass files.
-
# This is an array of hashes containing information for a single entry.
-
# The hashes have the following keys:
-
#
-
# `:filename`
-
# : The name of the file in which the exception was raised,
-
# or `nil` if no filename is available.
-
#
-
# `:mixin`
-
# : The name of the mixin in which the exception was raised,
-
# or `nil` if it wasn't raised in a mixin.
-
#
-
# `:line`
-
# : The line of the file on which the error occurred. Never nil.
-
#
-
# This information is also included in standard backtrace format
-
# in the output of \{#backtrace}.
-
#
-
# @return [Aray<{Symbol => Object>}]
-
1
attr_accessor :sass_backtrace
-
-
# The text of the template where this error was raised.
-
#
-
# @return [String]
-
1
attr_accessor :sass_template
-
-
# @param msg [String] The error message
-
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
-
# See \{#sass\_backtrace}
-
1
def initialize(msg, attrs = {})
-
@message = msg
-
@sass_backtrace = []
-
add_backtrace(attrs)
-
end
-
-
# The name of the file in which the exception was raised.
-
# This could be `nil` if no filename is available.
-
#
-
# @return [String, nil]
-
1
def sass_filename
-
sass_backtrace.first[:filename]
-
end
-
-
# The name of the mixin in which the error occurred.
-
# This could be `nil` if the error occurred outside a mixin.
-
#
-
# @return [String]
-
1
def sass_mixin
-
sass_backtrace.first[:mixin]
-
end
-
-
# The line of the Sass template on which the error occurred.
-
#
-
# @return [Integer]
-
1
def sass_line
-
sass_backtrace.first[:line]
-
end
-
-
# Adds an entry to the exception's Sass backtrace.
-
#
-
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
-
# See \{#sass\_backtrace}
-
1
def add_backtrace(attrs)
-
sass_backtrace << attrs.reject {|_k, v| v.nil?}
-
end
-
-
# Modify the top Sass backtrace entries
-
# (that is, the most deeply nested ones)
-
# to have the given attributes.
-
#
-
# Specifically, this goes through the backtrace entries
-
# from most deeply nested to least,
-
# setting the given attributes for each entry.
-
# If an entry already has one of the given attributes set,
-
# the pre-existing attribute takes precedence
-
# and is not used for less deeply-nested entries
-
# (even if they don't have that attribute set).
-
#
-
# @param attrs [{Symbol => Object}] The information to add to the backtrace entry.
-
# See \{#sass\_backtrace}
-
1
def modify_backtrace(attrs)
-
attrs = attrs.reject {|_k, v| v.nil?}
-
# Move backwards through the backtrace
-
(0...sass_backtrace.size).to_a.reverse_each do |i|
-
entry = sass_backtrace[i]
-
sass_backtrace[i] = attrs.merge(entry)
-
attrs.reject! {|k, _v| entry.include?(k)}
-
break if attrs.empty?
-
end
-
end
-
-
# @return [String] The error message
-
1
def to_s
-
@message
-
end
-
-
# Returns the standard exception backtrace,
-
# including the Sass backtrace.
-
#
-
# @return [Array<String>]
-
1
def backtrace
-
return nil if super.nil?
-
return super if sass_backtrace.all? {|h| h.empty?}
-
sass_backtrace.map do |h|
-
"#{h[:filename] || '(sass)'}:#{h[:line]}" +
-
(h[:mixin] ? ":in `#{h[:mixin]}'" : "")
-
end + super
-
end
-
-
# Returns a string representation of the Sass backtrace.
-
#
-
# @param default_filename [String] The filename to use for unknown files
-
# @see #sass_backtrace
-
# @return [String]
-
1
def sass_backtrace_str(default_filename = "an unknown file")
-
lines = message.split("\n")
-
msg = lines[0] + lines[1..-1].
-
map {|l| "\n" + (" " * "Error: ".size) + l}.join
-
"Error: #{msg}" +
-
sass_backtrace.each_with_index.map do |entry, i|
-
"\n #{i == 0 ? 'on' : 'from'} line #{entry[:line]}" +
-
" of #{entry[:filename] || default_filename}" +
-
(entry[:mixin] ? ", in `#{entry[:mixin]}'" : "")
-
end.join
-
end
-
-
1
class << self
-
# Returns an error report for an exception in CSS format.
-
#
-
# @param e [Exception]
-
# @param line_offset [Integer] The number of the first line of the Sass template.
-
# @return [String] The error report
-
# @raise [Exception] `e`, if the
-
# {file:SASS_REFERENCE.md#full_exception-option `:full_exception`} option
-
# is set to false.
-
1
def exception_to_css(e, line_offset = 1)
-
header = header_string(e, line_offset)
-
-
<<END
-
/*
-
#{header.gsub('*/', '*\\/')}
-
-
Backtrace:\n#{e.backtrace.join("\n").gsub('*/', '*\\/')}
-
*/
-
body:before {
-
white-space: pre;
-
font-family: monospace;
-
content: "#{header.gsub('"', '\"').gsub("\n", '\\A ')}"; }
-
END
-
end
-
-
1
private
-
-
1
def header_string(e, line_offset)
-
unless e.is_a?(Sass::SyntaxError) && e.sass_line && e.sass_template
-
return "#{e.class}: #{e.message}"
-
end
-
-
line_num = e.sass_line + 1 - line_offset
-
min = [line_num - 6, 0].max
-
section = e.sass_template.rstrip.split("\n")[min...line_num + 5]
-
return e.sass_backtrace_str if section.nil? || section.empty?
-
-
e.sass_backtrace_str + "\n\n" + section.each_with_index.
-
map {|line, i| "#{line_offset + min + i}: #{line}"}.join("\n")
-
end
-
end
-
end
-
-
# The class for Sass errors that are raised due to invalid unit conversions
-
# in SassScript.
-
1
class UnitConversionError < SyntaxError; end
-
end
-
1
require 'set'
-
1
module Sass
-
# Provides `Sass.has_feature?` which allows for simple feature detection
-
# by providing a feature name.
-
1
module Features
-
# This is the set of features that can be detected.
-
#
-
# When this is updated, the documentation of `feature-exists()` should be
-
# updated as well.
-
1
KNOWN_FEATURES = Set[*%w(
-
global-variable-shadowing
-
extend-selector-pseudoclass
-
units-level-3
-
at-error
-
custom-property
-
)]
-
-
# Check if a feature exists by name. This is used to implement
-
# the Sass function `feature-exists($feature)`
-
#
-
# @param feature_name [String] The case sensitive name of the feature to
-
# check if it exists in this version of Sass.
-
# @return [Boolean] whether the feature of that name exists.
-
1
def has_feature?(feature_name)
-
KNOWN_FEATURES.include?(feature_name)
-
end
-
-
# Add a feature to Sass. Plugins can use this to easily expose their
-
# availability to end users. Plugins must prefix their feature
-
# names with a dash to distinguish them from official features.
-
#
-
# @example
-
# Sass.add_feature("-import-globbing")
-
# Sass.add_feature("-math-cos")
-
#
-
#
-
# @param feature_name [String] The case sensitive name of the feature to
-
# to add to Sass. Must begin with a dash.
-
1
def add_feature(feature_name)
-
unless feature_name[0] == ?-
-
raise ArgumentError.new("Plugin feature names must begin with a dash")
-
end
-
KNOWN_FEATURES << feature_name
-
end
-
end
-
-
1
extend Features
-
end
-
1
module Sass
-
# Sass importers are in charge of taking paths passed to `@import`
-
# and finding the appropriate Sass code for those paths.
-
# By default, this code is always loaded from the filesystem,
-
# but importers could be added to load from a database or over HTTP.
-
#
-
# Each importer is in charge of a single load path
-
# (or whatever the corresponding notion is for the backend).
-
# Importers can be placed in the {file:SASS_REFERENCE.md#load_paths-option `:load_paths` array}
-
# alongside normal filesystem paths.
-
#
-
# When resolving an `@import`, Sass will go through the load paths
-
# looking for an importer that successfully imports the path.
-
# Once one is found, the imported file is used.
-
#
-
# User-created importers must inherit from {Importers::Base}.
-
1
module Importers
-
end
-
end
-
-
1
require 'sass/importers/base'
-
1
require 'sass/importers/filesystem'
-
1
require 'sass/importers/deprecated_path'
-
1
module Sass
-
1
module Importers
-
# The abstract base class for Sass importers.
-
# All importers should inherit from this.
-
#
-
# At the most basic level, an importer is given a string
-
# and must return a {Sass::Engine} containing some Sass code.
-
# This string can be interpreted however the importer wants;
-
# however, subclasses are encouraged to use the URI format
-
# for pathnames.
-
#
-
# Importers that have some notion of "relative imports"
-
# should take a single load path in their constructor,
-
# and interpret paths as relative to that.
-
# They should also implement the \{#find\_relative} method.
-
#
-
# Importers should be serializable via `Marshal.dump`.
-
#
-
# @abstract
-
1
class Base
-
# Find a Sass file relative to another file.
-
# Importers without a notion of "relative paths"
-
# should just return nil here.
-
#
-
# If the importer does have a notion of "relative paths",
-
# it should ignore its load path during this method.
-
#
-
# See \{#find} for important information on how this method should behave.
-
#
-
# The `:filename` option passed to the returned {Sass::Engine}
-
# should be of a format that could be passed to \{#find}.
-
#
-
# @param uri [String] The URI to import. This is not necessarily relative,
-
# but this method should only return true if it is.
-
# @param base [String] The base filename. If `uri` is relative,
-
# it should be interpreted as relative to `base`.
-
# `base` is guaranteed to be in a format importable by this importer.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` that's currently being resolved.
-
# @return [Sass::Engine, nil] An Engine containing the imported file,
-
# or nil if it couldn't be found or was in the wrong format.
-
1
def find_relative(uri, base, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Find a Sass file, if it exists.
-
#
-
# This is the primary entry point of the Importer.
-
# It corresponds directly to an `@import` statement in Sass.
-
# It should do three basic things:
-
#
-
# * Determine if the URI is in this importer's format.
-
# If not, return nil.
-
# * Determine if the file indicated by the URI actually exists and is readable.
-
# If not, return nil.
-
# * Read the file and place the contents in a {Sass::Engine}.
-
# Return that engine.
-
#
-
# If this importer's format allows for file extensions,
-
# it should treat them the same way as the default {Filesystem} importer.
-
# If the URI explicitly has a `.sass` or `.scss` filename,
-
# the importer should look for that exact file
-
# and import it as the syntax indicated.
-
# If it doesn't exist, the importer should return nil.
-
#
-
# If the URI doesn't have either of these extensions,
-
# the importer should look for files with the extensions.
-
# If no such files exist, it should return nil.
-
#
-
# The {Sass::Engine} to be returned should be passed `options`,
-
# with a few modifications. `:syntax` should be set appropriately,
-
# `:filename` should be set to `uri`,
-
# and `:importer` should be set to this importer.
-
#
-
# @param uri [String] The URI to import.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` that's currently being resolved.
-
# This is safe for subclasses to modify destructively.
-
# Callers should only pass in a value they don't mind being destructively modified.
-
# @return [Sass::Engine, nil] An Engine containing the imported file,
-
# or nil if it couldn't be found or was in the wrong format.
-
1
def find(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Returns the time the given Sass file was last modified.
-
#
-
# If the given file has been deleted or the time can't be accessed
-
# for some other reason, this should return nil.
-
#
-
# @param uri [String] The URI of the file to check.
-
# Comes from a `:filename` option set on an engine returned by this importer.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` currently being checked.
-
# @return [Time, nil]
-
1
def mtime(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Get the cache key pair for the given Sass URI.
-
# The URI need not be checked for validity.
-
#
-
# The only strict requirement is that the returned pair of strings
-
# uniquely identify the file at the given URI.
-
# However, the first component generally corresponds roughly to the directory,
-
# and the second to the basename, of the URI.
-
#
-
# Note that keys must be unique *across importers*.
-
# Thus it's probably a good idea to include the importer name
-
# at the beginning of the first component.
-
#
-
# @param uri [String] A URI known to be valid for this importer.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` currently being checked.
-
# @return [(String, String)] The key pair which uniquely identifies
-
# the file at the given URI.
-
1
def key(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Get the publicly-visible URL for an imported file. This URL is used by
-
# source maps to link to the source stylesheet. This may return `nil` to
-
# indicate that no public URL is available; however, this will cause
-
# sourcemap generation to fail if any CSS is generated from files imported
-
# from this importer.
-
#
-
# If an absolute "file:" URI can be produced for an imported file, that
-
# should be preferred to returning `nil`. However, a URL relative to
-
# `sourcemap_directory` should be preferred over an absolute "file:" URI.
-
#
-
# @param uri [String] A URI known to be valid for this importer.
-
# @param sourcemap_directory [String, NilClass] The absolute path to a
-
# directory on disk where the sourcemap will be saved. If uri refers to
-
# a file on disk that's accessible relative to sourcemap_directory, this
-
# may return a relative URL. This may be `nil` if the sourcemap's
-
# eventual location is unknown.
-
# @return [String?] The publicly-visible URL for this file, or `nil`
-
# indicating that no publicly-visible URL exists. This should be
-
# appropriately URL-escaped.
-
1
def public_url(uri, sourcemap_directory)
-
return if @public_url_warning_issued
-
@public_url_warning_issued = true
-
Sass::Util.sass_warn <<WARNING
-
WARNING: #{self.class.name} should define the #public_url method.
-
WARNING
-
nil
-
end
-
-
# A string representation of the importer.
-
# Should be overridden by subclasses.
-
#
-
# This is used to help debugging,
-
# and should usually just show the load path encapsulated by this importer.
-
#
-
# @return [String]
-
1
def to_s
-
Sass::Util.abstract(self)
-
end
-
-
# If the importer is based on files on the local filesystem
-
# this method should return folders which should be watched
-
# for changes.
-
#
-
# @return [Array<String>] List of absolute paths of directories to watch
-
1
def directories_to_watch
-
[]
-
end
-
-
# If this importer is based on files on the local filesystem This method
-
# should return true if the file, when changed, should trigger a
-
# recompile.
-
#
-
# It is acceptable for non-sass files to be watched and trigger a recompile.
-
#
-
# @param filename [String] The absolute filename for a file that has changed.
-
# @return [Boolean] When the file changed should cause a recompile.
-
1
def watched_file?(filename)
-
false
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Importers
-
# This importer emits a deprecation warning the first time it is used to
-
# import a file. It is used to deprecate the current working
-
# directory from the list of automatic sass load paths.
-
1
class DeprecatedPath < Filesystem
-
# @param root [String] The absolute, expanded path to the folder that is deprecated.
-
1
def initialize(root)
-
@specified_root = root
-
@warning_given = false
-
super
-
end
-
-
# @see Sass::Importers::Base#find
-
1
def find(*args)
-
found = super
-
if found && !@warning_given
-
@warning_given = true
-
Sass::Util.sass_warn deprecation_warning
-
end
-
found
-
end
-
-
# @see Base#directories_to_watch
-
1
def directories_to_watch
-
# The current working directory was not watched in Sass 3.2,
-
# so we continue not to watch it while it's deprecated.
-
[]
-
end
-
-
# @see Sass::Importers::Base#to_s
-
1
def to_s
-
"#{@root} (DEPRECATED)"
-
end
-
-
1
protected
-
-
# @return [String] The deprecation warning that will be printed the first
-
# time an import occurs.
-
1
def deprecation_warning
-
path = @specified_root == "." ? "the current working directory" : @specified_root
-
<<WARNING
-
DEPRECATION WARNING: Importing from #{path} will not be
-
automatic in future versions of Sass. To avoid future errors, you can add it
-
to your environment explicitly by setting `SASS_PATH=#{@specified_root}`, by using the -I command
-
line option, or by changing your Sass configuration options.
-
WARNING
-
end
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Sass
-
1
module Importers
-
# The default importer, used for any strings found in the load path.
-
# Simply loads Sass files from the filesystem using the default logic.
-
1
class Filesystem < Base
-
1
attr_accessor :root
-
-
# Creates a new filesystem importer that imports files relative to a given path.
-
#
-
# @param root [String] The root path.
-
# This importer will import files relative to this path.
-
1
def initialize(root)
-
@root = File.expand_path(root)
-
@real_root = Sass::Util.realpath(@root).to_s
-
@same_name_warnings = Set.new
-
end
-
-
# @see Base#find_relative
-
1
def find_relative(name, base, options)
-
_find(File.dirname(base), name, options)
-
end
-
-
# @see Base#find
-
1
def find(name, options)
-
_find(@root, name, options)
-
end
-
-
# @see Base#mtime
-
1
def mtime(name, options)
-
file, _ = Sass::Util.destructure(find_real_file(@root, name, options))
-
File.mtime(file) if file
-
rescue Errno::ENOENT
-
nil
-
end
-
-
# @see Base#key
-
1
def key(name, options)
-
[self.class.name + ":" + File.dirname(File.expand_path(name)),
-
File.basename(name)]
-
end
-
-
# @see Base#to_s
-
1
def to_s
-
@root
-
end
-
-
1
def hash
-
@root.hash
-
end
-
-
1
def eql?(other)
-
!other.nil? && other.respond_to?(:root) && root.eql?(other.root)
-
end
-
-
# @see Base#directories_to_watch
-
1
def directories_to_watch
-
[root]
-
end
-
-
# @see Base#watched_file?
-
1
def watched_file?(filename)
-
# Check against the root with symlinks resolved, since Listen
-
# returns fully-resolved paths.
-
filename =~ /\.s[ac]ss$/ && filename.start_with?(@real_root + File::SEPARATOR)
-
end
-
-
1
def public_url(name, sourcemap_directory)
-
file_pathname = Sass::Util.cleanpath(File.absolute_path(name, @root))
-
return Sass::Util.file_uri_from_path(file_pathname) if sourcemap_directory.nil?
-
-
sourcemap_pathname = Sass::Util.cleanpath(sourcemap_directory)
-
begin
-
Sass::Util.file_uri_from_path(
-
Sass::Util.relative_path_from(file_pathname, sourcemap_pathname))
-
rescue ArgumentError # when a relative path cannot be constructed
-
Sass::Util.file_uri_from_path(file_pathname)
-
end
-
end
-
-
1
protected
-
-
# If a full uri is passed, this removes the root from it
-
# otherwise returns the name unchanged
-
1
def remove_root(name)
-
if name.index(@root + "/") == 0
-
name[(@root.length + 1)..-1]
-
else
-
name
-
end
-
end
-
-
# A hash from file extensions to the syntaxes for those extensions.
-
# The syntaxes must be `:sass` or `:scss`.
-
#
-
# This can be overridden by subclasses that want normal filesystem importing
-
# with unusual extensions.
-
#
-
# @return [{String => Symbol}]
-
1
def extensions
-
{'sass' => :sass, 'scss' => :scss}
-
end
-
-
# Given an `@import`ed path, returns an array of possible
-
# on-disk filenames and their corresponding syntaxes for that path.
-
#
-
# @param name [String] The filename.
-
# @return [Array(String, Symbol)] An array of pairs.
-
# The first element of each pair is a filename to look for;
-
# the second element is the syntax that file would be in (`:sass` or `:scss`).
-
1
def possible_files(name)
-
name = escape_glob_characters(name)
-
dirname, basename, extname = split(name)
-
sorted_exts = extensions.sort
-
syntax = extensions[extname]
-
-
if syntax
-
ret = [["#{dirname}/{_,}#{basename}.#{extensions.invert[syntax]}", syntax]]
-
else
-
ret = sorted_exts.map {|ext, syn| ["#{dirname}/{_,}#{basename}.#{ext}", syn]}
-
end
-
-
# JRuby chokes when trying to import files from JARs when the path starts with './'.
-
ret.map {|f, s| [f.sub(%r{^\./}, ''), s]}
-
end
-
-
1
def escape_glob_characters(name)
-
name.gsub(/[\*\[\]\{\}\?]/) do |char|
-
"\\#{char}"
-
end
-
end
-
-
1
REDUNDANT_DIRECTORY = /#{Regexp.escape(File::SEPARATOR)}\.#{Regexp.escape(File::SEPARATOR)}/
-
# Given a base directory and an `@import`ed name,
-
# finds an existent file that matches the name.
-
#
-
# @param dir [String] The directory relative to which to search.
-
# @param name [String] The filename to search for.
-
# @return [(String, Symbol)] A filename-syntax pair.
-
1
def find_real_file(dir, name, options)
-
# On windows 'dir' or 'name' can be in native File::ALT_SEPARATOR form.
-
dir = dir.gsub(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
-
name = name.gsub(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
-
-
found = possible_files(remove_root(name)).map do |f, s|
-
path = if dir == "." || Sass::Util.pathname(f).absolute?
-
f
-
else
-
"#{escape_glob_characters(dir)}/#{f}"
-
end
-
Dir[path].map do |full_path|
-
full_path.gsub!(REDUNDANT_DIRECTORY, File::SEPARATOR)
-
[Sass::Util.cleanpath(full_path).to_s, s]
-
end
-
end.flatten(1)
-
return if found.empty?
-
-
if found.size > 1 && !@same_name_warnings.include?(found.first.first)
-
found.each {|(f, _)| @same_name_warnings << f}
-
relative_to = Sass::Util.pathname(dir)
-
if options[:_from_import_node]
-
# If _line exists, we're here due to an actual import in an
-
# import_node and we want to print a warning for a user writing an
-
# ambiguous import.
-
candidates = found.map do |(f, _)|
-
" " + Sass::Util.pathname(f).relative_path_from(relative_to).to_s
-
end.join("\n")
-
raise Sass::SyntaxError.new(<<MESSAGE)
-
It's not clear which file to import for '@import "#{name}"'.
-
Candidates:
-
#{candidates}
-
Please delete or rename all but one of these files.
-
MESSAGE
-
else
-
# Otherwise, we're here via StalenessChecker, and we want to print a
-
# warning for a user running `sass --watch` with two ambiguous files.
-
candidates = found.map {|(f, _)| " " + File.basename(f)}.join("\n")
-
Sass::Util.sass_warn <<WARNING
-
WARNING: In #{File.dirname(name)}:
-
There are multiple files that match the name "#{File.basename(name)}":
-
#{candidates}
-
WARNING
-
end
-
end
-
found.first
-
end
-
-
# Splits a filename into three parts, a directory part, a basename, and an extension
-
# Only the known extensions returned from the extensions method will be recognized as such.
-
1
def split(name)
-
extension = nil
-
dirname, basename = File.dirname(name), File.basename(name)
-
if basename =~ /^(.*)\.(#{extensions.keys.map {|e| Regexp.escape(e)}.join('|')})$/
-
basename = $1
-
extension = $2
-
end
-
[dirname, basename, extension]
-
end
-
-
1
private
-
-
1
def _find(dir, name, options)
-
full_filename, syntax = Sass::Util.destructure(find_real_file(dir, name, options))
-
return unless full_filename && File.readable?(full_filename)
-
-
# TODO: this preserves historical behavior, but it's possible
-
# :filename should be either normalized to the native format
-
# or consistently URI-format.
-
full_filename = full_filename.tr("\\", "/") if Sass::Util.windows?
-
-
options[:syntax] = syntax
-
options[:filename] = full_filename
-
options[:importer] = self
-
Sass::Engine.new(File.read(full_filename), options)
-
end
-
end
-
end
-
end
-
1
module Sass::Logger; end
-
-
1
require "sass/logger/log_level"
-
1
require "sass/logger/base"
-
1
require "sass/logger/delayed"
-
-
1
module Sass
-
1
class << self
-
1
def logger=(l)
-
1
Thread.current[:sass_logger] = l
-
end
-
-
1
def logger
-
Thread.current[:sass_logger] ||= Sass::Logger::Base.new
-
end
-
end
-
end
-
1
require 'sass/logger/log_level'
-
-
1
class Sass::Logger::Base
-
1
include Sass::Logger::LogLevel
-
-
1
attr_accessor :log_level
-
1
attr_accessor :disabled
-
1
attr_accessor :io
-
-
1
log_level :trace
-
1
log_level :debug
-
1
log_level :info
-
1
log_level :warn
-
1
log_level :error
-
-
1
def initialize(log_level = :debug, io = nil)
-
1
self.log_level = log_level
-
1
self.io = io
-
end
-
-
1
def logging_level?(level)
-
!disabled && self.class.log_level?(level, log_level)
-
end
-
-
1
def log(level, message)
-
_log(level, message) if logging_level?(level)
-
end
-
-
1
def _log(level, message)
-
if io
-
io.puts(message)
-
else
-
Kernel.warn(message)
-
end
-
end
-
end
-
1
require 'sass/logger/log_level'
-
-
# A logger that delays messages until they're explicitly flushed to an inner
-
# logger.
-
#
-
# This can be installed around the current logger by calling \{#install!}, and
-
# the original logger can be replaced by calling \{#uninstall!}. The log
-
# messages can be flushed by calling \{#flush}.
-
1
class Sass::Logger::Delayed < Sass::Logger::Base
-
# Installs a new delayed logger as the current Sass logger, wrapping the
-
# original logger.
-
#
-
# This can be undone by calling \{#uninstall!}.
-
#
-
# @return [Sass::Logger::Delayed] The newly-created logger.
-
1
def self.install!
-
logger = Sass::Logger::Delayed.new(Sass.logger)
-
Sass.logger = logger
-
logger
-
end
-
-
# Creates a delayed logger wrapping `inner`.
-
#
-
# @param inner [Sass::Logger::Base] The wrapped logger.
-
1
def initialize(inner)
-
self.log_level = inner.log_level
-
@inner = inner
-
@messages = []
-
end
-
-
# Flushes all queued logs to the wrapped logger.
-
1
def flush
-
@messages.each {|(l, m)| @inner.log(l, m)}
-
end
-
-
# Uninstalls this logger from \{Sass.logger\}. This should only be called if
-
# the logger was installed using \{#install!}
-
1
def uninstall!
-
if Sass.logger != self
-
throw Exception.new("Can't uninstall a logger that's not currently installed.")
-
end
-
-
@inner.log_level = log_level
-
Sass.logger = @inner
-
end
-
-
1
def _log(level, message)
-
@messages << [level, message]
-
end
-
end
-
1
module Sass
-
1
module Logger
-
1
module LogLevel
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
end
-
-
1
module ClassMethods
-
1
def inherited(subclass)
-
2
subclass.log_levels = subclass.superclass.log_levels.dup
-
end
-
-
1
attr_writer :log_levels
-
-
1
def log_levels
-
12
@log_levels ||= {}
-
end
-
-
1
def log_level?(level, min_level)
-
log_levels[level] >= log_levels[min_level]
-
end
-
-
1
def log_level(name, options = {})
-
5
if options[:prepend]
-
level = log_levels.values.min
-
level = level.nil? ? 0 : level - 1
-
else
-
5
level = log_levels.values.max
-
5
level = level.nil? ? 0 : level + 1
-
end
-
5
log_levels.update(name => level)
-
5
define_logger(name)
-
end
-
-
1
def define_logger(name, options = {})
-
5
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{name}(message)
-
#{options.fetch(:to, :log)}(#{name.inspect}, message)
-
end
-
RUBY
-
end
-
end
-
end
-
end
-
end
-
# A namespace for the `@media` query parse tree.
-
1
module Sass::Media
-
# A comma-separated list of queries.
-
#
-
# media_query [ ',' S* media_query ]*
-
1
class QueryList
-
# The queries contained in this list.
-
#
-
# @return [Array<Query>]
-
1
attr_accessor :queries
-
-
# @param queries [Array<Query>] See \{#queries}
-
1
def initialize(queries)
-
@queries = queries
-
end
-
-
# Merges this query list with another. The returned query list
-
# queries for the intersection between the two inputs.
-
#
-
# Both query lists should be resolved.
-
#
-
# @param other [QueryList]
-
# @return [QueryList?] The merged list, or nil if there is no intersection.
-
1
def merge(other)
-
new_queries = queries.map {|q1| other.queries.map {|q2| q1.merge(q2)}}.flatten.compact
-
return if new_queries.empty?
-
QueryList.new(new_queries)
-
end
-
-
# Returns the CSS for the media query list.
-
#
-
# @return [String]
-
1
def to_css
-
queries.map {|q| q.to_css}.join(', ')
-
end
-
-
# Returns the Sass/SCSS code for the media query list.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
1
def to_src(options)
-
queries.map {|q| q.to_src(options)}.join(', ')
-
end
-
-
# Returns a representation of the query as an array of strings and
-
# potentially {Sass::Script::Tree::Node}s (if there's interpolation in it).
-
# When the interpolation is resolved and the strings are joined together,
-
# this will be the string representation of this query.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
def to_a
-
Sass::Util.intersperse(queries.map {|q| q.to_a}, ', ').flatten
-
end
-
-
# Returns a deep copy of this query list and all its children.
-
#
-
# @return [QueryList]
-
1
def deep_copy
-
QueryList.new(queries.map {|q| q.deep_copy})
-
end
-
end
-
-
# A single media query.
-
#
-
# [ [ONLY | NOT]? S* media_type S* | expression ] [ AND S* expression ]*
-
1
class Query
-
# The modifier for the query.
-
#
-
# When parsed as Sass code, this contains strings and SassScript nodes. When
-
# parsed as CSS, it contains a single string (accessible via
-
# \{#resolved_modifier}).
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :modifier
-
-
# The type of the query (e.g. `"screen"` or `"print"`).
-
#
-
# When parsed as Sass code, this contains strings and SassScript nodes. When
-
# parsed as CSS, it contains a single string (accessible via
-
# \{#resolved_type}).
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :type
-
-
# The trailing expressions in the query.
-
#
-
# When parsed as Sass code, each expression contains strings and SassScript
-
# nodes. When parsed as CSS, each one contains a single string.
-
#
-
# @return [Array<Array<String, Sass::Script::Tree::Node>>]
-
1
attr_accessor :expressions
-
-
# @param modifier [Array<String, Sass::Script::Tree::Node>] See \{#modifier}
-
# @param type [Array<String, Sass::Script::Tree::Node>] See \{#type}
-
# @param expressions [Array<Array<String, Sass::Script::Tree::Node>>] See \{#expressions}
-
1
def initialize(modifier, type, expressions)
-
@modifier = modifier
-
@type = type
-
@expressions = expressions
-
end
-
-
# See \{#modifier}.
-
# @return [String]
-
1
def resolved_modifier
-
# modifier should contain only a single string
-
modifier.first || ''
-
end
-
-
# See \{#type}.
-
# @return [String]
-
1
def resolved_type
-
# type should contain only a single string
-
type.first || ''
-
end
-
-
# Merges this query with another. The returned query queries for
-
# the intersection between the two inputs.
-
#
-
# Both queries should be resolved.
-
#
-
# @param other [Query]
-
# @return [Query?] The merged query, or nil if there is no intersection.
-
1
def merge(other)
-
m1, t1 = resolved_modifier.downcase, resolved_type.downcase
-
m2, t2 = other.resolved_modifier.downcase, other.resolved_type.downcase
-
t1 = t2 if t1.empty?
-
t2 = t1 if t2.empty?
-
if (m1 == 'not') ^ (m2 == 'not')
-
return if t1 == t2
-
type = m1 == 'not' ? t2 : t1
-
mod = m1 == 'not' ? m2 : m1
-
elsif m1 == 'not' && m2 == 'not'
-
# CSS has no way of representing "neither screen nor print"
-
return unless t1 == t2
-
type = t1
-
mod = 'not'
-
elsif t1 != t2
-
return
-
else # t1 == t2, neither m1 nor m2 are "not"
-
type = t1
-
mod = m1.empty? ? m2 : m1
-
end
-
Query.new([mod], [type], other.expressions + expressions)
-
end
-
-
# Returns the CSS for the media query.
-
#
-
# @return [String]
-
1
def to_css
-
css = ''
-
css << resolved_modifier
-
css << ' ' unless resolved_modifier.empty?
-
css << resolved_type
-
css << ' and ' unless resolved_type.empty? || expressions.empty?
-
css << expressions.map do |e|
-
# It's possible for there to be script nodes in Expressions even when
-
# we're converting to CSS in the case where we parsed the document as
-
# CSS originally (as in css_test.rb).
-
e.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.to_sass : c.to_s}.join
-
end.join(' and ')
-
css
-
end
-
-
# Returns the Sass/SCSS code for the media query.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
1
def to_src(options)
-
src = ''
-
src << Sass::Media._interp_to_src(modifier, options)
-
src << ' ' unless modifier.empty?
-
src << Sass::Media._interp_to_src(type, options)
-
src << ' and ' unless type.empty? || expressions.empty?
-
src << expressions.map do |e|
-
Sass::Media._interp_to_src(e, options)
-
end.join(' and ')
-
src
-
end
-
-
# @see \{MediaQuery#to\_a}
-
1
def to_a
-
res = []
-
res += modifier
-
res << ' ' unless modifier.empty?
-
res += type
-
res << ' and ' unless type.empty? || expressions.empty?
-
res += Sass::Util.intersperse(expressions, ' and ').flatten
-
res
-
end
-
-
# Returns a deep copy of this query and all its children.
-
#
-
# @return [Query]
-
1
def deep_copy
-
Query.new(
-
modifier.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.deep_copy : c},
-
type.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.deep_copy : c},
-
expressions.map {|e| e.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.deep_copy : c}})
-
end
-
end
-
-
# Converts an interpolation array to source.
-
#
-
# @param interp [Array<String, Sass::Script::Tree::Node>] The interpolation array to convert.
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
1
def self._interp_to_src(interp, options)
-
interp.map {|r| r.is_a?(String) ? r : r.to_sass(options)}.join
-
end
-
end
-
# Rails 3.0.0.beta.2+, < 3.1
-
1
if defined?(ActiveSupport) && ActiveSupport.public_methods.include?(:on_load) &&
-
!Sass::Util.ap_geq?('3.1.0.beta')
-
require 'sass/plugin/configuration'
-
ActiveSupport.on_load(:before_configuration) do
-
require 'sass'
-
require 'sass/plugin'
-
require 'sass/plugin/rails'
-
end
-
end
-
1
module Sass
-
# The root directory of the Sass source tree.
-
# This may be overridden by the package manager
-
# if the lib directory is separated from the main source tree.
-
# @api public
-
1
ROOT_DIR = File.expand_path(File.join(__FILE__, "../../.."))
-
end
-
1
require 'sass/scss/rx'
-
-
1
module Sass
-
# SassScript is code that's embedded in Sass documents
-
# to allow for property values to be computed from variables.
-
#
-
# This module contains code that handles the parsing and evaluation of SassScript.
-
1
module Script
-
# The regular expression used to parse variables.
-
1
MATCH = /^\$(#{Sass::SCSS::RX::IDENT})\s*:\s*(.+?)
-
(!#{Sass::SCSS::RX::IDENT}(?:\s+!#{Sass::SCSS::RX::IDENT})*)?$/x
-
-
# The regular expression used to validate variables without matching.
-
1
VALIDATE = /^\$#{Sass::SCSS::RX::IDENT}$/
-
-
# Parses a string of SassScript
-
#
-
# @param value [String] The SassScript
-
# @param line [Integer] The number of the line on which the SassScript appeared.
-
# Used for error reporting
-
# @param offset [Integer] The number of characters in on `line` that the SassScript started.
-
# Used for error reporting
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#Options the Sass options documentation}
-
# @return [Script::Tree::Node] The root node of the parse tree
-
1
def self.parse(value, line, offset, options = {})
-
Parser.parse(value, line, offset, options)
-
rescue Sass::SyntaxError => e
-
e.message << ": #{value.inspect}." if e.message == "SassScript error"
-
e.modify_backtrace(:line => line, :filename => options[:filename])
-
raise e
-
end
-
-
1
require 'sass/script/functions'
-
1
require 'sass/script/parser'
-
1
require 'sass/script/tree'
-
1
require 'sass/script/value'
-
-
# @private
-
1
CONST_RENAMES = {
-
:Literal => Sass::Script::Value::Base,
-
:ArgList => Sass::Script::Value::ArgList,
-
:Bool => Sass::Script::Value::Bool,
-
:Color => Sass::Script::Value::Color,
-
:List => Sass::Script::Value::List,
-
:Null => Sass::Script::Value::Null,
-
:Number => Sass::Script::Value::Number,
-
:String => Sass::Script::Value::String,
-
:Node => Sass::Script::Tree::Node,
-
:Funcall => Sass::Script::Tree::Funcall,
-
:Interpolation => Sass::Script::Tree::Interpolation,
-
:Operation => Sass::Script::Tree::Operation,
-
:StringInterpolation => Sass::Script::Tree::StringInterpolation,
-
:UnaryOperation => Sass::Script::Tree::UnaryOperation,
-
:Variable => Sass::Script::Tree::Variable,
-
}
-
-
# @private
-
1
def self.const_missing(name)
-
klass = CONST_RENAMES[name]
-
super unless klass
-
CONST_RENAMES.each {|n, k| const_set(n, k)}
-
klass
-
end
-
end
-
end
-
1
module Sass
-
1
module Script
-
# This is a subclass of {Lexer} for use in parsing plain CSS properties.
-
#
-
# @see Sass::SCSS::CssParser
-
1
class CssLexer < Lexer
-
1
private
-
-
1
def token
-
important || super
-
end
-
-
1
def string(re, *args)
-
if re == :uri
-
uri = scan(URI)
-
return unless uri
-
return [:string, Script::Value::String.new(uri)]
-
end
-
-
return unless scan(STRING)
-
string_value = Sass::Script::Value::String.value(@scanner[1] || @scanner[2])
-
value = Script::Value::String.new(string_value, :string)
-
[:string, value]
-
end
-
-
1
def important
-
s = scan(IMPORTANT)
-
return unless s
-
[:raw, s]
-
end
-
end
-
end
-
end
-
1
require 'sass/script'
-
1
require 'sass/script/css_lexer'
-
-
1
module Sass
-
1
module Script
-
# This is a subclass of {Parser} for use in parsing plain CSS properties.
-
#
-
# @see Sass::SCSS::CssParser
-
1
class CssParser < Parser
-
1
private
-
-
# @private
-
1
def lexer_class; CssLexer; end
-
-
# We need a production that only does /,
-
# since * and % aren't allowed in plain CSS
-
1
production :div, :unary_plus, :div
-
-
1
def string
-
tok = try_tok(:string)
-
return number unless tok
-
return if @lexer.peek && @lexer.peek.type == :begin_interpolation
-
literal_node(tok.value, tok.source_range)
-
end
-
-
# Short-circuit all the SassScript-only productions
-
1
alias_method :interpolation, :space
-
1
alias_method :or_expr, :div
-
1
alias_method :unary_div, :ident
-
1
alias_method :paren, :string
-
end
-
end
-
end
-
1
require 'sass/script/value/helpers'
-
-
1
module Sass::Script
-
# @comment
-
# YARD can't handle some multiline tags, and we need really long tags for function declarations.
-
# rubocop:disable LineLength
-
# Methods in this module are accessible from the SassScript context.
-
# For example, you can write
-
#
-
# $color: hsl(120deg, 100%, 50%)
-
#
-
# and it will call {Functions#hsl}.
-
#
-
# The following functions are provided:
-
#
-
# *Note: These functions are described in more detail below.*
-
#
-
# ## RGB Functions
-
#
-
# \{#rgb rgb($red, $green, $blue)}
-
# : Creates a {Sass::Script::Value::Color Color} from red, green, and blue
-
# values.
-
#
-
# \{#rgba rgba($red, $green, $blue, $alpha)}
-
# : Creates a {Sass::Script::Value::Color Color} from red, green, blue, and
-
# alpha values.
-
#
-
# \{#red red($color)}
-
# : Gets the red component of a color.
-
#
-
# \{#green green($color)}
-
# : Gets the green component of a color.
-
#
-
# \{#blue blue($color)}
-
# : Gets the blue component of a color.
-
#
-
# \{#mix mix($color1, $color2, \[$weight\])}
-
# : Mixes two colors together.
-
#
-
# ## HSL Functions
-
#
-
# \{#hsl hsl($hue, $saturation, $lightness)}
-
# : Creates a {Sass::Script::Value::Color Color} from hue, saturation, and
-
# lightness values.
-
#
-
# \{#hsla hsla($hue, $saturation, $lightness, $alpha)}
-
# : Creates a {Sass::Script::Value::Color Color} from hue, saturation,
-
# lightness, and alpha values.
-
#
-
# \{#hue hue($color)}
-
# : Gets the hue component of a color.
-
#
-
# \{#saturation saturation($color)}
-
# : Gets the saturation component of a color.
-
#
-
# \{#lightness lightness($color)}
-
# : Gets the lightness component of a color.
-
#
-
# \{#adjust_hue adjust-hue($color, $degrees)}
-
# : Changes the hue of a color.
-
#
-
# \{#lighten lighten($color, $amount)}
-
# : Makes a color lighter.
-
#
-
# \{#darken darken($color, $amount)}
-
# : Makes a color darker.
-
#
-
# \{#saturate saturate($color, $amount)}
-
# : Makes a color more saturated.
-
#
-
# \{#desaturate desaturate($color, $amount)}
-
# : Makes a color less saturated.
-
#
-
# \{#grayscale grayscale($color)}
-
# : Converts a color to grayscale.
-
#
-
# \{#complement complement($color)}
-
# : Returns the complement of a color.
-
#
-
# \{#invert invert($color, \[$weight\])}
-
# : Returns the inverse of a color.
-
#
-
# ## Opacity Functions
-
#
-
# \{#alpha alpha($color)} / \{#opacity opacity($color)}
-
# : Gets the alpha component (opacity) of a color.
-
#
-
# \{#rgba rgba($color, $alpha)}
-
# : Changes the alpha component for a color.
-
#
-
# \{#opacify opacify($color, $amount)} / \{#fade_in fade-in($color, $amount)}
-
# : Makes a color more opaque.
-
#
-
# \{#transparentize transparentize($color, $amount)} / \{#fade_out fade-out($color, $amount)}
-
# : Makes a color more transparent.
-
#
-
# ## Other Color Functions
-
#
-
# \{#adjust_color adjust-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Increases or decreases one or more components of a color.
-
#
-
# \{#scale_color scale-color($color, \[$red\], \[$green\], \[$blue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Fluidly scales one or more properties of a color.
-
#
-
# \{#change_color change-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Changes one or more properties of a color.
-
#
-
# \{#ie_hex_str ie-hex-str($color)}
-
# : Converts a color into the format understood by IE filters.
-
#
-
# ## String Functions
-
#
-
# \{#unquote unquote($string)}
-
# : Removes quotes from a string.
-
#
-
# \{#quote quote($string)}
-
# : Adds quotes to a string.
-
#
-
# \{#str_length str-length($string)}
-
# : Returns the number of characters in a string.
-
#
-
# \{#str_insert str-insert($string, $insert, $index)}
-
# : Inserts `$insert` into `$string` at `$index`.
-
#
-
# \{#str_index str-index($string, $substring)}
-
# : Returns the index of the first occurrence of `$substring` in `$string`.
-
#
-
# \{#str_slice str-slice($string, $start-at, [$end-at])}
-
# : Extracts a substring from `$string`.
-
#
-
# \{#to_upper_case to-upper-case($string)}
-
# : Converts a string to upper case.
-
#
-
# \{#to_lower_case to-lower-case($string)}
-
# : Converts a string to lower case.
-
#
-
# ## Number Functions
-
#
-
# \{#percentage percentage($number)}
-
# : Converts a unitless number to a percentage.
-
#
-
# \{#round round($number)}
-
# : Rounds a number to the nearest whole number.
-
#
-
# \{#ceil ceil($number)}
-
# : Rounds a number up to the next whole number.
-
#
-
# \{#floor floor($number)}
-
# : Rounds a number down to the previous whole number.
-
#
-
# \{#abs abs($number)}
-
# : Returns the absolute value of a number.
-
#
-
# \{#min min($numbers...)\}
-
# : Finds the minimum of several numbers.
-
#
-
# \{#max max($numbers...)\}
-
# : Finds the maximum of several numbers.
-
#
-
# \{#random random([$limit])\}
-
# : Returns a random number.
-
#
-
# ## List Functions {#list-functions}
-
#
-
# Lists in Sass are immutable; all list functions return a new list rather
-
# than updating the existing list in-place.
-
#
-
# All list functions work for maps as well, treating them as lists of pairs.
-
#
-
# \{#length length($list)}
-
# : Returns the length of a list.
-
#
-
# \{#nth nth($list, $n)}
-
# : Returns a specific item in a list.
-
#
-
# \{#set-nth set-nth($list, $n, $value)}
-
# : Replaces the nth item in a list.
-
#
-
# \{#join join($list1, $list2, \[$separator, $bracketed\])}
-
# : Joins together two lists into one.
-
#
-
# \{#append append($list1, $val, \[$separator\])}
-
# : Appends a single value onto the end of a list.
-
#
-
# \{#zip zip($lists...)}
-
# : Combines several lists into a single multidimensional list.
-
#
-
# \{#index index($list, $value)}
-
# : Returns the position of a value within a list.
-
#
-
# \{#list_separator list-separator($list)}
-
# : Returns the separator of a list.
-
#
-
# \{#is_bracketed is-bracketed($list)}
-
# : Returns whether a list has square brackets.
-
#
-
# ## Map Functions {#map-functions}
-
#
-
# Maps in Sass are immutable; all map functions return a new map rather than
-
# updating the existing map in-place.
-
#
-
# \{#map_get map-get($map, $key)}
-
# : Returns the value in a map associated with a given key.
-
#
-
# \{#map_merge map-merge($map1, $map2)}
-
# : Merges two maps together into a new map.
-
#
-
# \{#map_remove map-remove($map, $keys...)}
-
# : Returns a new map with keys removed.
-
#
-
# \{#map_keys map-keys($map)}
-
# : Returns a list of all keys in a map.
-
#
-
# \{#map_values map-values($map)}
-
# : Returns a list of all values in a map.
-
#
-
# \{#map_has_key map-has-key($map, $key)}
-
# : Returns whether a map has a value associated with a given key.
-
#
-
# \{#keywords keywords($args)}
-
# : Returns the keywords passed to a function that takes variable arguments.
-
#
-
# ## Selector Functions
-
#
-
# Selector functions are very liberal in the formats they support
-
# for selector arguments. They can take a plain string, a list of
-
# lists as returned by `&` or anything in between:
-
#
-
# * A plain string, such as `".foo .bar, .baz .bang"`.
-
# * A space-separated list of strings such as `(".foo" ".bar")`.
-
# * A comma-separated list of strings such as `(".foo .bar", ".baz .bang")`.
-
# * A comma-separated list of space-separated lists of strings such
-
# as `((".foo" ".bar"), (".baz" ".bang"))`.
-
#
-
# In general, selector functions allow placeholder selectors
-
# (`%foo`) but disallow parent-reference selectors (`&`).
-
#
-
# \{#selector_nest selector-nest($selectors...)}
-
# : Nests selector beneath one another like they would be nested in the
-
# stylesheet.
-
#
-
# \{#selector_append selector-append($selectors...)}
-
# : Appends selectors to one another without spaces in between.
-
#
-
# \{#selector_extend selector-extend($selector, $extendee, $extender)}
-
# : Extends `$extendee` with `$extender` within `$selector`.
-
#
-
# \{#selector_replace selector-replace($selector, $original, $replacement)}
-
# : Replaces `$original` with `$replacement` within `$selector`.
-
#
-
# \{#selector_unify selector-unify($selector1, $selector2)}
-
# : Unifies two selectors to produce a selector that matches
-
# elements matched by both.
-
#
-
# \{#is_superselector is-superselector($super, $sub)}
-
# : Returns whether `$super` matches all the elements `$sub` does, and
-
# possibly more.
-
#
-
# \{#simple_selectors simple-selectors($selector)}
-
# : Returns the simple selectors that comprise a compound selector.
-
#
-
# \{#selector_parse selector-parse($selector)}
-
# : Parses a selector into the format returned by `&`.
-
#
-
# ## Introspection Functions
-
#
-
# \{#feature_exists feature-exists($feature)}
-
# : Returns whether a feature exists in the current Sass runtime.
-
#
-
# \{#variable_exists variable-exists($name)}
-
# : Returns whether a variable with the given name exists in the current scope.
-
#
-
# \{#global_variable_exists global-variable-exists($name)}
-
# : Returns whether a variable with the given name exists in the global scope.
-
#
-
# \{#function_exists function-exists($name)}
-
# : Returns whether a function with the given name exists.
-
#
-
# \{#mixin_exists mixin-exists($name)}
-
# : Returns whether a mixin with the given name exists.
-
#
-
# \{#content_exists content-exists()}
-
# : Returns whether the current mixin was passed a content block.
-
#
-
# \{#inspect inspect($value)}
-
# : Returns the string representation of a value as it would be represented in Sass.
-
#
-
# \{#type_of type-of($value)}
-
# : Returns the type of a value.
-
#
-
# \{#unit unit($number)}
-
# : Returns the unit(s) associated with a number.
-
#
-
# \{#unitless unitless($number)}
-
# : Returns whether a number has units.
-
#
-
# \{#comparable comparable($number1, $number2)}
-
# : Returns whether two numbers can be added, subtracted, or compared.
-
#
-
# \{#call call($function, $args...)}
-
# : Dynamically calls a Sass function reference returned by `get-function`.
-
#
-
# \{#get_function get-function($name, $css: false)}
-
# : Looks up a function with the given name in the current lexical scope
-
# and returns a reference to it.
-
#
-
# ## Miscellaneous Functions
-
#
-
# \{#if if($condition, $if-true, $if-false)}
-
# : Returns one of two values, depending on whether or not `$condition` is
-
# true.
-
#
-
# \{#unique_id unique-id()}
-
# : Returns a unique CSS identifier.
-
#
-
# ## Adding Custom Functions
-
#
-
# New Sass functions can be added by adding Ruby methods to this module.
-
# For example:
-
#
-
# module Sass::Script::Functions
-
# def reverse(string)
-
# assert_type string, :String
-
# Sass::Script::Value::String.new(string.value.reverse)
-
# end
-
# declare :reverse, [:string]
-
# end
-
#
-
# Calling {declare} tells Sass the argument names for your function.
-
# If omitted, the function will still work, but will not be able to accept keyword arguments.
-
# {declare} can also allow your function to take arbitrary keyword arguments.
-
#
-
# There are a few things to keep in mind when modifying this module.
-
# First of all, the arguments passed are {Value} objects.
-
# Value objects are also expected to be returned.
-
# This means that Ruby values must be unwrapped and wrapped.
-
#
-
# Most Value objects support the {Value::Base#value value} accessor for getting
-
# their Ruby values. Color objects, though, must be accessed using
-
# {Sass::Script::Value::Color#rgb rgb}, {Sass::Script::Value::Color#red red},
-
# {Sass::Script::Value::Color#blue green}, or {Sass::Script::Value::Color#blue
-
# blue}.
-
#
-
# Second, making Ruby functions accessible from Sass introduces the temptation
-
# to do things like database access within stylesheets.
-
# This is generally a bad idea;
-
# since Sass files are by default only compiled once,
-
# dynamic code is not a great fit.
-
#
-
# If you really, really need to compile Sass on each request,
-
# first make sure you have adequate caching set up.
-
# Then you can use {Sass::Engine} to render the code,
-
# using the {file:SASS_REFERENCE.md#custom-option `options` parameter}
-
# to pass in data that {EvaluationContext#options can be accessed}
-
# from your Sass functions.
-
#
-
# Within one of the functions in this module,
-
# methods of {EvaluationContext} can be used.
-
#
-
# ### Caveats
-
#
-
# When creating new {Value} objects within functions, be aware that it's not
-
# safe to call {Value::Base#to_s #to_s} (or other methods that use the string
-
# representation) on those objects without first setting {Tree::Node#options=
-
# the #options attribute}.
-
#
-
# @comment
-
# rubocop:enable LineLength
-
# rubocop:disable ModuleLength
-
1
module Functions
-
1
@signatures = {}
-
-
# A class representing a Sass function signature.
-
#
-
# @attr args [Array<String>] The names of the arguments to the function.
-
# @attr delayed_args [Array<String>] The names of the arguments whose evaluation should be
-
# delayed.
-
# @attr var_args [Boolean] Whether the function takes a variable number of arguments.
-
# @attr var_kwargs [Boolean] Whether the function takes an arbitrary set of keyword arguments.
-
1
Signature = Struct.new(:args, :delayed_args, :var_args, :var_kwargs, :deprecated)
-
-
# Declare a Sass signature for a Ruby-defined function.
-
# This includes the names of the arguments,
-
# whether the function takes a variable number of arguments,
-
# and whether the function takes an arbitrary set of keyword arguments.
-
#
-
# It's not necessary to declare a signature for a function.
-
# However, without a signature it won't support keyword arguments.
-
#
-
# A single function can have multiple signatures declared
-
# as long as each one takes a different number of arguments.
-
# It's also possible to declare multiple signatures
-
# that all take the same number of arguments,
-
# but none of them but the first will be used
-
# unless the user uses keyword arguments.
-
#
-
# @example
-
# declare :rgba, [:hex, :alpha]
-
# declare :rgba, [:red, :green, :blue, :alpha]
-
# declare :accepts_anything, [], :var_args => true, :var_kwargs => true
-
# declare :some_func, [:foo, :bar, :baz], :var_kwargs => true
-
#
-
# @param method_name [Symbol] The name of the method
-
# whose signature is being declared.
-
# @param args [Array<Symbol>] The names of the arguments for the function signature.
-
# @option options :var_args [Boolean] (false)
-
# Whether the function accepts a variable number of (unnamed) arguments
-
# in addition to the named arguments.
-
# @option options :var_kwargs [Boolean] (false)
-
# Whether the function accepts other keyword arguments
-
# in addition to those in `:args`.
-
# If this is true, the Ruby function will be passed a hash from strings
-
# to {Value}s as the last argument.
-
# In addition, if this is true and `:var_args` is not,
-
# Sass will ensure that the last argument passed is a hash.
-
1
def self.declare(method_name, args, options = {})
-
93
delayed_args = []
-
93
args = args.map do |a|
-
134
a = a.to_s
-
134
if a[0] == ?&
-
2
a = a[1..-1]
-
2
delayed_args << a
-
end
-
134
a
-
end
-
# We don't expose this functionality except to certain builtin methods.
-
93
if delayed_args.any? && method_name != :if
-
raise ArgumentError.new("Delayed arguments are not allowed for method #{method_name}")
-
end
-
93
@signatures[method_name] ||= []
-
@signatures[method_name] << Signature.new(
-
args,
-
delayed_args,
-
options[:var_args],
-
options[:var_kwargs],
-
93
options[:deprecated] && options[:deprecated].map {|a| a.to_s})
-
end
-
-
# Determine the correct signature for the number of arguments
-
# passed in for a given function.
-
# If no signatures match, the first signature is returned for error messaging.
-
#
-
# @param method_name [Symbol] The name of the Ruby function to be called.
-
# @param arg_arity [Integer] The number of unnamed arguments the function was passed.
-
# @param kwarg_arity [Integer] The number of keyword arguments the function was passed.
-
#
-
# @return [{Symbol => Object}, nil]
-
# The signature options for the matching signature,
-
# or nil if no signatures are declared for this function. See {declare}.
-
1
def self.signature(method_name, arg_arity, kwarg_arity)
-
return unless @signatures[method_name]
-
@signatures[method_name].each do |signature|
-
sig_arity = signature.args.size
-
return signature if sig_arity == arg_arity + kwarg_arity
-
next unless sig_arity < arg_arity + kwarg_arity
-
-
# We have enough args.
-
# Now we need to figure out which args are varargs
-
# and if the signature allows them.
-
t_arg_arity, t_kwarg_arity = arg_arity, kwarg_arity
-
if sig_arity > t_arg_arity
-
# we transfer some kwargs arity to args arity
-
# if it does not have enough args -- assuming the names will work out.
-
t_kwarg_arity -= (sig_arity - t_arg_arity)
-
t_arg_arity = sig_arity
-
end
-
-
if (t_arg_arity == sig_arity || t_arg_arity > sig_arity && signature.var_args) &&
-
(t_kwarg_arity == 0 || t_kwarg_arity > 0 && signature.var_kwargs)
-
return signature
-
end
-
end
-
@signatures[method_name].first
-
end
-
-
# Sets the random seed used by Sass's internal random number generator.
-
#
-
# This can be used to ensure consistent random number sequences which
-
# allows for consistent results when testing, etc.
-
#
-
# @param seed [Integer]
-
# @return [Integer] The same seed.
-
1
def self.random_seed=(seed)
-
@random_number_generator = Random.new(seed)
-
end
-
-
# Get Sass's internal random number generator.
-
#
-
# @return [Random]
-
1
def self.random_number_generator
-
@random_number_generator ||= Random.new
-
end
-
-
# The context in which methods in {Script::Functions} are evaluated.
-
# That means that all instance methods of {EvaluationContext}
-
# are available to use in functions.
-
1
class EvaluationContext
-
1
include Functions
-
1
include Value::Helpers
-
-
# The human-readable names for [Sass::Script::Value::Base]. The default is
-
# just the downcased name of the type.
-
1
TYPE_NAMES = {:ArgList => 'variable argument list'}
-
-
# The environment for this function. This environment's
-
# {Environment#parent} is the global environment, and its
-
# {Environment#caller} is a read-only view of the local environment of the
-
# caller of this function.
-
#
-
# @return [Environment]
-
1
attr_reader :environment
-
-
# The options hash for the {Sass::Engine} that is processing the function call
-
#
-
# @return [{Symbol => Object}]
-
1
attr_reader :options
-
-
# @param environment [Environment] See \{#environment}
-
1
def initialize(environment)
-
@environment = environment
-
@options = environment.options
-
end
-
-
# Asserts that the type of a given SassScript value
-
# is the expected type (designated by a symbol).
-
#
-
# Valid types are `:Bool`, `:Color`, `:Number`, and `:String`.
-
# Note that `:String` will match both double-quoted strings
-
# and unquoted identifiers.
-
#
-
# @example
-
# assert_type value, :String
-
# assert_type value, :Number
-
# @param value [Sass::Script::Value::Base] A SassScript value
-
# @param type [Symbol, Array<Symbol>] The name(s) of the type the value is expected to be
-
# @param name [String, Symbol, nil] The name of the argument.
-
# @raise [ArgumentError] if value is not of the correct type.
-
1
def assert_type(value, type, name = nil)
-
valid_types = Array(type)
-
found_type = valid_types.find do |t|
-
value.is_a?(Sass::Script::Value.const_get(t)) ||
-
t == :Map && value.is_a?(Sass::Script::Value::List) && value.value.empty?
-
end
-
-
if found_type
-
value.check_deprecated_interp if found_type == :String
-
return
-
end
-
-
err = if valid_types.size == 1
-
"#{value.inspect} is not a #{TYPE_NAMES[type] || type.to_s.downcase}"
-
else
-
type_names = valid_types.map {|t| TYPE_NAMES[t] || t.to_s.downcase}
-
"#{value.inspect} is not any of #{type_names.join(', ')}"
-
end
-
err = "$#{name.to_s.tr('_', '-')}: " + err if name
-
raise ArgumentError.new(err)
-
end
-
-
# Asserts that the unit of the number is as expected.
-
#
-
# @example
-
# assert_unit number, "px"
-
# assert_unit number, nil
-
# @param number [Sass::Script::Value::Number] The number to be validated.
-
# @param unit [::String]
-
# The unit that the number must have.
-
# If nil, the number must be unitless.
-
# @param name [::String] The name of the parameter being validated.
-
# @raise [ArgumentError] if number is not of the correct unit or is not a number.
-
1
def assert_unit(number, unit, name = nil)
-
assert_type number, :Number, name
-
return if number.is_unit?(unit)
-
expectation = unit ? "have a unit of #{unit}" : "be unitless"
-
if name
-
raise ArgumentError.new("Expected $#{name} to #{expectation} but got #{number}")
-
else
-
raise ArgumentError.new("Expected #{number} to #{expectation}")
-
end
-
end
-
-
# Asserts that the value is an integer.
-
#
-
# @example
-
# assert_integer 2px
-
# assert_integer 2.5px
-
# => SyntaxError: "Expected 2.5px to be an integer"
-
# assert_integer 2.5px, "width"
-
# => SyntaxError: "Expected width to be an integer but got 2.5px"
-
# @param number [Sass::Script::Value::Base] The value to be validated.
-
# @param name [::String] The name of the parameter being validated.
-
# @raise [ArgumentError] if number is not an integer or is not a number.
-
1
def assert_integer(number, name = nil)
-
assert_type number, :Number, name
-
return if number.int?
-
if name
-
raise ArgumentError.new("Expected $#{name} to be an integer but got #{number}")
-
else
-
raise ArgumentError.new("Expected #{number} to be an integer")
-
end
-
end
-
-
# Performs a node that has been delayed for execution.
-
#
-
# @private
-
# @param node [Sass::Script::Tree::Node,
-
# Sass::Script::Value::Base] When this is a tree node, it's
-
# performed in the caller's environment. When it's a value
-
# (which can happen when the value had to be performed already
-
# -- like for a splat), it's returned as-is.
-
# @param env [Sass::Environment] The environment within which to perform the node.
-
# Defaults to the (read-only) environment of the caller.
-
1
def perform(node, env = environment.caller)
-
if node.is_a?(Sass::Script::Value::Base)
-
node
-
else
-
node.perform(env)
-
end
-
end
-
end
-
-
1
class << self
-
# Returns whether user function with a given name exists.
-
#
-
# @param function_name [String]
-
# @return [Boolean]
-
1
alias_method :callable?, :public_method_defined?
-
-
1
private
-
-
1
def include(*args)
-
1
r = super
-
# We have to re-include ourselves into EvaluationContext to work around
-
# an icky Ruby restriction.
-
1
EvaluationContext.send :include, self
-
1
r
-
end
-
end
-
-
# Creates a {Sass::Script::Value::Color Color} object from red, green, and
-
# blue values.
-
#
-
# @see #rgba
-
# @overload rgb($red, $green, $blue)
-
# @param $red [Sass::Script::Value::Number] The amount of red in the color.
-
# Must be between 0 and 255 inclusive, or between `0%` and `100%`
-
# inclusive
-
# @param $green [Sass::Script::Value::Number] The amount of green in the
-
# color. Must be between 0 and 255 inclusive, or between `0%` and `100%`
-
# inclusive
-
# @param $blue [Sass::Script::Value::Number] The amount of blue in the
-
# color. Must be between 0 and 255 inclusive, or between `0%` and `100%`
-
# inclusive
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out of bounds
-
1
def rgb(red, green, blue)
-
if special_number?(red) || special_number?(green) || special_number?(blue)
-
return unquoted_string("rgb(#{red}, #{green}, #{blue})")
-
end
-
assert_type red, :Number, :red
-
assert_type green, :Number, :green
-
assert_type blue, :Number, :blue
-
-
color_attrs = [red, green, blue].map do |c|
-
if c.is_unit?("%")
-
c.value * 255 / 100.0
-
elsif c.unitless?
-
c.value
-
else
-
raise ArgumentError.new("Expected #{c} to be unitless or have a unit of % but got #{c}")
-
end
-
end
-
-
# Don't store the string representation for function-created colors, both
-
# because it's not very useful and because some functions aren't supported
-
# on older browsers.
-
Sass::Script::Value::Color.new(color_attrs)
-
end
-
1
declare :rgb, [:red, :green, :blue]
-
-
# Creates a {Sass::Script::Value::Color Color} from red, green, blue, and
-
# alpha values.
-
# @see #rgb
-
#
-
# @overload rgba($red, $green, $blue, $alpha)
-
# @param $red [Sass::Script::Value::Number] The amount of red in the
-
# color. Must be between 0 and 255 inclusive or 0% and 100% inclusive
-
# @param $green [Sass::Script::Value::Number] The amount of green in the
-
# color. Must be between 0 and 255 inclusive or 0% and 100% inclusive
-
# @param $blue [Sass::Script::Value::Number] The amount of blue in the
-
# color. Must be between 0 and 255 inclusive or 0% and 100% inclusive
-
# @param $alpha [Sass::Script::Value::Number] The opacity of the color.
-
# Must be between 0 and 1 inclusive
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out of
-
# bounds
-
#
-
# @overload rgba($color, $alpha)
-
# Sets the opacity of an existing color.
-
#
-
# @example
-
# rgba(#102030, 0.5) => rgba(16, 32, 48, 0.5)
-
# rgba(blue, 0.2) => rgba(0, 0, 255, 0.2)
-
#
-
# @param $color [Sass::Script::Value::Color] The color whose opacity will
-
# be changed.
-
# @param $alpha [Sass::Script::Value::Number] The new opacity of the
-
# color. Must be between 0 and 1 inclusive
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$alpha` is out of bounds or either parameter
-
# is the wrong type
-
1
def rgba(*args)
-
case args.size
-
when 2
-
color, alpha = args
-
-
assert_type color, :Color, :color
-
if special_number?(alpha)
-
unquoted_string("rgba(#{color.red}, #{color.green}, #{color.blue}, #{alpha})")
-
else
-
assert_type alpha, :Number, :alpha
-
check_alpha_unit alpha, 'rgba'
-
color.with(:alpha => alpha.value)
-
end
-
when 4
-
red, green, blue, alpha = args
-
if special_number?(red) || special_number?(green) ||
-
special_number?(blue) || special_number?(alpha)
-
unquoted_string("rgba(#{red}, #{green}, #{blue}, #{alpha})")
-
else
-
rgba(rgb(red, green, blue), alpha)
-
end
-
else
-
raise ArgumentError.new("wrong number of arguments (#{args.size} for 4)")
-
end
-
end
-
1
declare :rgba, [:red, :green, :blue, :alpha]
-
1
declare :rgba, [:color, :alpha]
-
-
# Creates a {Sass::Script::Value::Color Color} from hue, saturation, and
-
# lightness values. Uses the algorithm from the [CSS3 spec][].
-
#
-
# [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @see #hsla
-
# @overload hsl($hue, $saturation, $lightness)
-
# @param $hue [Sass::Script::Value::Number] The hue of the color. Should be
-
# between 0 and 360 degrees, inclusive
-
# @param $saturation [Sass::Script::Value::Number] The saturation of the
-
# color. Must be between `0%` and `100%`, inclusive
-
# @param $lightness [Sass::Script::Value::Number] The lightness of the
-
# color. Must be between `0%` and `100%`, inclusive
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$saturation` or `$lightness` are out of bounds
-
# or any parameter is the wrong type
-
1
def hsl(hue, saturation, lightness)
-
if special_number?(hue) || special_number?(saturation) || special_number?(lightness)
-
unquoted_string("hsl(#{hue}, #{saturation}, #{lightness})")
-
else
-
hsla(hue, saturation, lightness, number(1))
-
end
-
end
-
1
declare :hsl, [:hue, :saturation, :lightness]
-
-
# Creates a {Sass::Script::Value::Color Color} from hue,
-
# saturation, lightness, and alpha values. Uses the algorithm from
-
# the [CSS3 spec][].
-
#
-
# [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @see #hsl
-
# @overload hsla($hue, $saturation, $lightness, $alpha)
-
# @param $hue [Sass::Script::Value::Number] The hue of the color. Should be
-
# between 0 and 360 degrees, inclusive
-
# @param $saturation [Sass::Script::Value::Number] The saturation of the
-
# color. Must be between `0%` and `100%`, inclusive
-
# @param $lightness [Sass::Script::Value::Number] The lightness of the
-
# color. Must be between `0%` and `100%`, inclusive
-
# @param $alpha [Sass::Script::Value::Number] The opacity of the color. Must
-
# be between 0 and 1, inclusive
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$saturation`, `$lightness`, or `$alpha` are out
-
# of bounds or any parameter is the wrong type
-
1
def hsla(hue, saturation, lightness, alpha)
-
if special_number?(hue) || special_number?(saturation) ||
-
special_number?(lightness) || special_number?(alpha)
-
return unquoted_string("hsla(#{hue}, #{saturation}, #{lightness}, #{alpha})")
-
end
-
assert_type hue, :Number, :hue
-
assert_type saturation, :Number, :saturation
-
assert_type lightness, :Number, :lightness
-
assert_type alpha, :Number, :alpha
-
check_alpha_unit alpha, 'hsla'
-
-
h = hue.value
-
s = saturation.value
-
l = lightness.value
-
-
# Don't store the string representation for function-created colors, both
-
# because it's not very useful and because some functions aren't supported
-
# on older browsers.
-
Sass::Script::Value::Color.new(
-
:hue => h, :saturation => s, :lightness => l, :alpha => alpha.value)
-
end
-
1
declare :hsla, [:hue, :saturation, :lightness, :alpha]
-
-
# Gets the red component of a color. Calculated from HSL where necessary via
-
# [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload red($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::Number] The red component, between 0 and 255
-
# inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def red(color)
-
assert_type color, :Color, :color
-
number(color.red)
-
end
-
1
declare :red, [:color]
-
-
# Gets the green component of a color. Calculated from HSL where necessary
-
# via [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload green($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::Number] The green component, between 0 and
-
# 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def green(color)
-
assert_type color, :Color, :color
-
number(color.green)
-
end
-
1
declare :green, [:color]
-
-
# Gets the blue component of a color. Calculated from HSL where necessary
-
# via [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload blue($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::Number] The blue component, between 0 and
-
# 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def blue(color)
-
assert_type color, :Color, :color
-
number(color.blue)
-
end
-
1
declare :blue, [:color]
-
-
# Returns the hue component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload hue($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::Number] The hue component, between 0deg and
-
# 360deg
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def hue(color)
-
assert_type color, :Color, :color
-
number(color.hue, "deg")
-
end
-
1
declare :hue, [:color]
-
-
# Returns the saturation component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload saturation($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::Number] The saturation component, between 0%
-
# and 100%
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def saturation(color)
-
assert_type color, :Color, :color
-
number(color.saturation, "%")
-
end
-
1
declare :saturation, [:color]
-
-
# Returns the lightness component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload lightness($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::Number] The lightness component, between 0%
-
# and 100%
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def lightness(color)
-
assert_type color, :Color, :color
-
number(color.lightness, "%")
-
end
-
1
declare :lightness, [:color]
-
-
# Returns the alpha component (opacity) of a color. This is 1 unless
-
# otherwise specified.
-
#
-
# This function also supports the proprietary Microsoft `alpha(opacity=20)`
-
# syntax as a special case.
-
#
-
# @overload alpha($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::Number] The alpha component, between 0 and 1
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def alpha(*args)
-
if args.all? do |a|
-
a.is_a?(Sass::Script::Value::String) && a.type == :identifier &&
-
a.value =~ /^[a-zA-Z]+\s*=/
-
end
-
# Support the proprietary MS alpha() function
-
return identifier("alpha(#{args.map {|a| a.to_s}.join(', ')})")
-
end
-
-
raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1
-
-
assert_type args.first, :Color, :color
-
number(args.first.alpha)
-
end
-
1
declare :alpha, [:color]
-
-
# Returns the alpha component (opacity) of a color. This is 1 unless
-
# otherwise specified.
-
#
-
# @overload opacity($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::Number] The alpha component, between 0 and 1
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def opacity(color)
-
if color.is_a?(Sass::Script::Value::Number)
-
return identifier("opacity(#{color})")
-
end
-
assert_type color, :Color, :color
-
number(color.alpha)
-
end
-
1
declare :opacity, [:color]
-
-
# Makes a color more opaque. Takes a color and a number between 0 and 1, and
-
# returns a color with the opacity increased by that amount.
-
#
-
# @see #transparentize
-
# @example
-
# opacify(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.6)
-
# opacify(rgba(0, 0, 17, 0.8), 0.2) => #001
-
# @overload opacify($color, $amount)
-
# @param $color [Sass::Script::Value::Color]
-
# @param $amount [Sass::Script::Value::Number] The amount to increase the
-
# opacity by, between 0 and 1
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def opacify(color, amount)
-
_adjust(color, amount, :alpha, 0..1, :+)
-
end
-
1
declare :opacify, [:color, :amount]
-
-
1
alias_method :fade_in, :opacify
-
1
declare :fade_in, [:color, :amount]
-
-
# Makes a color more transparent. Takes a color and a number between 0 and
-
# 1, and returns a color with the opacity decreased by that amount.
-
#
-
# @see #opacify
-
# @example
-
# transparentize(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.4)
-
# transparentize(rgba(0, 0, 0, 0.8), 0.2) => rgba(0, 0, 0, 0.6)
-
# @overload transparentize($color, $amount)
-
# @param $color [Sass::Script::Value::Color]
-
# @param $amount [Sass::Script::Value::Number] The amount to decrease the
-
# opacity by, between 0 and 1
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def transparentize(color, amount)
-
_adjust(color, amount, :alpha, 0..1, :-)
-
end
-
1
declare :transparentize, [:color, :amount]
-
-
1
alias_method :fade_out, :transparentize
-
1
declare :fade_out, [:color, :amount]
-
-
# Makes a color lighter. Takes a color and a number between `0%` and `100%`,
-
# and returns a color with the lightness increased by that amount.
-
#
-
# @see #darken
-
# @example
-
# lighten(hsl(0, 0%, 0%), 30%) => hsl(0, 0, 30)
-
# lighten(#800, 20%) => #e00
-
# @overload lighten($color, $amount)
-
# @param $color [Sass::Script::Value::Color]
-
# @param $amount [Sass::Script::Value::Number] The amount to increase the
-
# lightness by, between `0%` and `100%`
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def lighten(color, amount)
-
_adjust(color, amount, :lightness, 0..100, :+, "%")
-
end
-
1
declare :lighten, [:color, :amount]
-
-
# Makes a color darker. Takes a color and a number between 0% and 100%, and
-
# returns a color with the lightness decreased by that amount.
-
#
-
# @see #lighten
-
# @example
-
# darken(hsl(25, 100%, 80%), 30%) => hsl(25, 100%, 50%)
-
# darken(#800, 20%) => #200
-
# @overload darken($color, $amount)
-
# @param $color [Sass::Script::Value::Color]
-
# @param $amount [Sass::Script::Value::Number] The amount to decrease the
-
# lightness by, between `0%` and `100%`
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def darken(color, amount)
-
_adjust(color, amount, :lightness, 0..100, :-, "%")
-
end
-
1
declare :darken, [:color, :amount]
-
-
# Makes a color more saturated. Takes a color and a number between 0% and
-
# 100%, and returns a color with the saturation increased by that amount.
-
#
-
# @see #desaturate
-
# @example
-
# saturate(hsl(120, 30%, 90%), 20%) => hsl(120, 50%, 90%)
-
# saturate(#855, 20%) => #9e3f3f
-
# @overload saturate($color, $amount)
-
# @param $color [Sass::Script::Value::Color]
-
# @param $amount [Sass::Script::Value::Number] The amount to increase the
-
# saturation by, between `0%` and `100%`
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def saturate(color, amount = nil)
-
# Support the filter effects definition of saturate.
-
# https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html
-
return identifier("saturate(#{color})") if amount.nil?
-
_adjust(color, amount, :saturation, 0..100, :+, "%")
-
end
-
1
declare :saturate, [:color, :amount]
-
1
declare :saturate, [:amount]
-
-
# Makes a color less saturated. Takes a color and a number between 0% and
-
# 100%, and returns a color with the saturation decreased by that value.
-
#
-
# @see #saturate
-
# @example
-
# desaturate(hsl(120, 30%, 90%), 20%) => hsl(120, 10%, 90%)
-
# desaturate(#855, 20%) => #726b6b
-
# @overload desaturate($color, $amount)
-
# @param $color [Sass::Script::Value::Color]
-
# @param $amount [Sass::Script::Value::Number] The amount to decrease the
-
# saturation by, between `0%` and `100%`
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def desaturate(color, amount)
-
_adjust(color, amount, :saturation, 0..100, :-, "%")
-
end
-
1
declare :desaturate, [:color, :amount]
-
-
# Changes the hue of a color. Takes a color and a number of degrees (usually
-
# between `-360deg` and `360deg`), and returns a color with the hue rotated
-
# along the color wheel by that amount.
-
#
-
# @example
-
# adjust-hue(hsl(120, 30%, 90%), 60deg) => hsl(180, 30%, 90%)
-
# adjust-hue(hsl(120, 30%, 90%), -60deg) => hsl(60, 30%, 90%)
-
# adjust-hue(#811, 45deg) => #886a11
-
# @overload adjust_hue($color, $degrees)
-
# @param $color [Sass::Script::Value::Color]
-
# @param $degrees [Sass::Script::Value::Number] The number of degrees to
-
# rotate the hue
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if either parameter is the wrong type
-
1
def adjust_hue(color, degrees)
-
assert_type color, :Color, :color
-
assert_type degrees, :Number, :degrees
-
color.with(:hue => color.hue + degrees.value)
-
end
-
1
declare :adjust_hue, [:color, :degrees]
-
-
# Converts a color into the format understood by IE filters.
-
#
-
# @example
-
# ie-hex-str(#abc) => #FFAABBCC
-
# ie-hex-str(#3322BB) => #FF3322BB
-
# ie-hex-str(rgba(0, 255, 0, 0.5)) => #8000FF00
-
# @overload ie_hex_str($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::String] The IE-formatted string
-
# representation of the color
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def ie_hex_str(color)
-
assert_type color, :Color, :color
-
alpha = Sass::Util.round(color.alpha * 255).to_s(16).rjust(2, '0')
-
identifier("##{alpha}#{color.send(:hex_str)[1..-1]}".upcase)
-
end
-
1
declare :ie_hex_str, [:color]
-
-
# Increases or decreases one or more properties of a color. This can change
-
# the red, green, blue, hue, saturation, value, and alpha properties. The
-
# properties are specified as keyword arguments, and are added to or
-
# subtracted from the color's current value for that property.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$hue`, `$saturation`,
-
# `$value`) at the same time.
-
#
-
# @example
-
# adjust-color(#102030, $blue: 5) => #102035
-
# adjust-color(#102030, $red: -5, $blue: 5) => #0b2035
-
# adjust-color(hsl(25, 100%, 80%), $lightness: -30%, $alpha: -0.4) => hsla(25, 100%, 50%, 0.6)
-
# @overload adjust_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Sass::Script::Value::Color]
-
# @param $red [Sass::Script::Value::Number] The adjustment to make on the
-
# red component, between -255 and 255 inclusive
-
# @param $green [Sass::Script::Value::Number] The adjustment to make on the
-
# green component, between -255 and 255 inclusive
-
# @param $blue [Sass::Script::Value::Number] The adjustment to make on the
-
# blue component, between -255 and 255 inclusive
-
# @param $hue [Sass::Script::Value::Number] The adjustment to make on the
-
# hue component, in degrees
-
# @param $saturation [Sass::Script::Value::Number] The adjustment to make on
-
# the saturation component, between `-100%` and `100%` inclusive
-
# @param $lightness [Sass::Script::Value::Number] The adjustment to make on
-
# the lightness component, between `-100%` and `100%` inclusive
-
# @param $alpha [Sass::Script::Value::Number] The adjustment to make on the
-
# alpha component, between -1 and 1 inclusive
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
1
def adjust_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash(
-
"red" => [-255..255, ""],
-
"green" => [-255..255, ""],
-
"blue" => [-255..255, ""],
-
"hue" => nil,
-
"saturation" => [-100..100, "%"],
-
"lightness" => [-100..100, "%"],
-
"alpha" => [-1..1, ""]
-
) do |name, (range, units)|
-
val = kwargs.delete(name)
-
next unless val
-
assert_type val, :Number, name
-
Sass::Util.check_range("$#{name}: Amount", range, val, units) if range
-
adjusted = color.send(name) + val.value
-
adjusted = [0, Sass::Util.restrict(adjusted, range)].max if range
-
[name.to_sym, adjusted]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
1
declare :adjust_color, [:color], :var_kwargs => true
-
-
# Fluidly scales one or more properties of a color. Unlike
-
# \{#adjust_color adjust-color}, which changes a color's properties by fixed
-
# amounts, \{#scale_color scale-color} fluidly changes them based on how
-
# high or low they already are. That means that lightening an already-light
-
# color with \{#scale_color scale-color} won't change the lightness much,
-
# but lightening a dark color by the same amount will change it more
-
# dramatically. This has the benefit of making `scale-color($color, ...)`
-
# have a similar effect regardless of what `$color` is.
-
#
-
# For example, the lightness of a color can be anywhere between `0%` and
-
# `100%`. If `scale-color($color, $lightness: 40%)` is called, the resulting
-
# color's lightness will be 40% of the way between its original lightness
-
# and 100. If `scale-color($color, $lightness: -40%)` is called instead, the
-
# lightness will be 40% of the way between the original and 0.
-
#
-
# This can change the red, green, blue, saturation, value, and alpha
-
# properties. The properties are specified as keyword arguments. All
-
# arguments should be percentages between `0%` and `100%`.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$saturation`, `$value`)
-
# at the same time.
-
#
-
# @example
-
# scale-color(hsl(120, 70%, 80%), $lightness: 50%) => hsl(120, 70%, 90%)
-
# scale-color(rgb(200, 150%, 170%), $green: -40%, $blue: 70%) => rgb(200, 90, 229)
-
# scale-color(hsl(200, 70%, 80%), $saturation: -90%, $alpha: -30%) => hsla(200, 7%, 80%, 0.7)
-
# @overload scale_color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Sass::Script::Value::Color]
-
# @param $red [Sass::Script::Value::Number]
-
# @param $green [Sass::Script::Value::Number]
-
# @param $blue [Sass::Script::Value::Number]
-
# @param $saturation [Sass::Script::Value::Number]
-
# @param $lightness [Sass::Script::Value::Number]
-
# @param $alpha [Sass::Script::Value::Number]
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
1
def scale_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash(
-
"red" => 255,
-
"green" => 255,
-
"blue" => 255,
-
"saturation" => 100,
-
"lightness" => 100,
-
"alpha" => 1
-
) do |name, max|
-
val = kwargs.delete(name)
-
next unless val
-
assert_type val, :Number, name
-
assert_unit val, '%', name
-
Sass::Util.check_range("$#{name}: Amount", -100..100, val, '%')
-
-
current = color.send(name)
-
scale = val.value / 100.0
-
diff = scale > 0 ? max - current : current
-
[name.to_sym, current + diff * scale]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
1
declare :scale_color, [:color], :var_kwargs => true
-
-
# Changes one or more properties of a color. This can change the red, green,
-
# blue, hue, saturation, value, and alpha properties. The properties are
-
# specified as keyword arguments, and replace the color's current value for
-
# that property.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$hue`, `$saturation`,
-
# `$value`) at the same time.
-
#
-
# @example
-
# change-color(#102030, $blue: 5) => #102005
-
# change-color(#102030, $red: 120, $blue: 5) => #782005
-
# change-color(hsl(25, 100%, 80%), $lightness: 40%, $alpha: 0.8) => hsla(25, 100%, 40%, 0.8)
-
# @overload change_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Sass::Script::Value::Color]
-
# @param $red [Sass::Script::Value::Number] The new red component for the
-
# color, within 0 and 255 inclusive
-
# @param $green [Sass::Script::Value::Number] The new green component for
-
# the color, within 0 and 255 inclusive
-
# @param $blue [Sass::Script::Value::Number] The new blue component for the
-
# color, within 0 and 255 inclusive
-
# @param $hue [Sass::Script::Value::Number] The new hue component for the
-
# color, in degrees
-
# @param $saturation [Sass::Script::Value::Number] The new saturation
-
# component for the color, between `0%` and `100%` inclusive
-
# @param $lightness [Sass::Script::Value::Number] The new lightness
-
# component for the color, within `0%` and `100%` inclusive
-
# @param $alpha [Sass::Script::Value::Number] The new alpha component for
-
# the color, within 0 and 1 inclusive
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
1
def change_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash(
-
'red' => ['Red value', 0..255],
-
'green' => ['Green value', 0..255],
-
'blue' => ['Blue value', 0..255],
-
'hue' => [],
-
'saturation' => ['Saturation', 0..100, '%'],
-
'lightness' => ['Lightness', 0..100, '%'],
-
'alpha' => ['Alpha channel', 0..1]
-
) do |name, (desc, range, unit)|
-
val = kwargs.delete(name)
-
next unless val
-
assert_type val, :Number, name
-
-
if range
-
val = Sass::Util.check_range(desc, range, val, unit)
-
else
-
val = val.value
-
end
-
-
[name.to_sym, val]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
1
declare :change_color, [:color], :var_kwargs => true
-
-
# Mixes two colors together. Specifically, takes the average of each of the
-
# RGB components, optionally weighted by the given percentage. The opacity
-
# of the colors is also considered when weighting the components.
-
#
-
# The weight specifies the amount of the first color that should be included
-
# in the returned color. The default, `50%`, means that half the first color
-
# and half the second color should be used. `25%` means that a quarter of
-
# the first color and three quarters of the second color should be used.
-
#
-
# @example
-
# mix(#f00, #00f) => #7f007f
-
# mix(#f00, #00f, 25%) => #3f00bf
-
# mix(rgba(255, 0, 0, 0.5), #00f) => rgba(63, 0, 191, 0.75)
-
# @overload mix($color1, $color2, $weight: 50%)
-
# @param $color1 [Sass::Script::Value::Color]
-
# @param $color2 [Sass::Script::Value::Color]
-
# @param $weight [Sass::Script::Value::Number] The relative weight of each
-
# color. Closer to `100%` gives more weight to `$color1`, closer to `0%`
-
# gives more weight to `$color2`
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$weight` is out of bounds or any parameter is
-
# the wrong type
-
1
def mix(color1, color2, weight = number(50))
-
assert_type color1, :Color, :color1
-
assert_type color2, :Color, :color2
-
assert_type weight, :Number, :weight
-
-
Sass::Util.check_range("Weight", 0..100, weight, '%')
-
-
# This algorithm factors in both the user-provided weight (w) and the
-
# difference between the alpha values of the two colors (a) to decide how
-
# to perform the weighted average of the two RGB values.
-
#
-
# It works by first normalizing both parameters to be within [-1, 1],
-
# where 1 indicates "only use color1", -1 indicates "only use color2", and
-
# all values in between indicated a proportionately weighted average.
-
#
-
# Once we have the normalized variables w and a, we apply the formula
-
# (w + a)/(1 + w*a) to get the combined weight (in [-1, 1]) of color1.
-
# This formula has two especially nice properties:
-
#
-
# * When either w or a are -1 or 1, the combined weight is also that number
-
# (cases where w * a == -1 are undefined, and handled as a special case).
-
#
-
# * When a is 0, the combined weight is w, and vice versa.
-
#
-
# Finally, the weight of color1 is renormalized to be within [0, 1]
-
# and the weight of color2 is given by 1 minus the weight of color1.
-
p = (weight.value / 100.0).to_f
-
w = p * 2 - 1
-
a = color1.alpha - color2.alpha
-
-
w1 = ((w * a == -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0
-
w2 = 1 - w1
-
-
rgba = color1.rgb.zip(color2.rgb).map {|v1, v2| v1 * w1 + v2 * w2}
-
rgba << color1.alpha * p + color2.alpha * (1 - p)
-
rgb_color(*rgba)
-
end
-
1
declare :mix, [:color1, :color2]
-
1
declare :mix, [:color1, :color2, :weight]
-
-
# Converts a color to grayscale. This is identical to `desaturate(color,
-
# 100%)`.
-
#
-
# @see #desaturate
-
# @overload grayscale($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def grayscale(color)
-
if color.is_a?(Sass::Script::Value::Number)
-
return identifier("grayscale(#{color})")
-
end
-
desaturate color, number(100)
-
end
-
1
declare :grayscale, [:color]
-
-
# Returns the complement of a color. This is identical to `adjust-hue(color,
-
# 180deg)`.
-
#
-
# @see #adjust_hue #adjust-hue
-
# @overload complement($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def complement(color)
-
adjust_hue color, number(180)
-
end
-
1
declare :complement, [:color]
-
-
# Returns the inverse (negative) of a color. The red, green, and blue values
-
# are inverted, while the opacity is left alone.
-
#
-
# @overload invert($color)
-
# @param $color [Sass::Script::Value::Color]
-
# @overload invert($color, $weight: 100%)
-
# @param $color [Sass::Script::Value::Color]
-
# @param $weight [Sass::Script::Value::Number] The relative weight of the
-
# color color's inverse
-
# @return [Sass::Script::Value::Color]
-
# @raise [ArgumentError] if `$color` isn't a color or `$weight`
-
# isn't a percentage between 0% and 100%
-
1
def invert(color, weight = number(100))
-
if color.is_a?(Sass::Script::Value::Number)
-
return identifier("invert(#{color})")
-
end
-
-
assert_type color, :Color, :color
-
inv = color.with(
-
:red => (255 - color.red),
-
:green => (255 - color.green),
-
:blue => (255 - color.blue))
-
-
mix(inv, color, weight)
-
end
-
1
declare :invert, [:color]
-
1
declare :invert, [:color, :weight]
-
-
# Removes quotes from a string. If the string is already unquoted, this will
-
# return it unmodified.
-
#
-
# @see #quote
-
# @example
-
# unquote("foo") => foo
-
# unquote(foo) => foo
-
# @overload unquote($string)
-
# @param $string [Sass::Script::Value::String]
-
# @return [Sass::Script::Value::String]
-
# @raise [ArgumentError] if `$string` isn't a string
-
1
def unquote(string)
-
unless string.is_a?(Sass::Script::Value::String)
-
# Don't warn multiple times for the same source line.
-
# rubocop:disable GlobalVars
-
$_sass_warned_for_unquote ||= Set.new
-
frame = environment.stack.frames.last
-
key = [frame.filename, frame.line] if frame
-
return string if frame && $_sass_warned_for_unquote.include?(key)
-
$_sass_warned_for_unquote << key if frame
-
# rubocop:enable GlobalVars
-
-
Sass::Util.sass_warn(<<MESSAGE.strip)
-
DEPRECATION WARNING: Passing #{string.to_sass}, a non-string value, to unquote()
-
will be an error in future versions of Sass.
-
#{environment.stack.to_s.gsub(/^/, ' ' * 8)}
-
MESSAGE
-
return string
-
end
-
-
string.check_deprecated_interp
-
return string if string.type == :identifier
-
identifier(string.value)
-
end
-
1
declare :unquote, [:string]
-
-
# Add quotes to a string if the string isn't quoted,
-
# or returns the same string if it is.
-
#
-
# @see #unquote
-
# @example
-
# quote("foo") => "foo"
-
# quote(foo) => "foo"
-
# @overload quote($string)
-
# @param $string [Sass::Script::Value::String]
-
# @return [Sass::Script::Value::String]
-
# @raise [ArgumentError] if `$string` isn't a string
-
1
def quote(string)
-
assert_type string, :String, :string
-
if string.type != :string
-
quoted_string(string.value)
-
else
-
string
-
end
-
end
-
1
declare :quote, [:string]
-
-
# Returns the number of characters in a string.
-
#
-
# @example
-
# str-length("foo") => 3
-
# @overload str_length($string)
-
# @param $string [Sass::Script::Value::String]
-
# @return [Sass::Script::Value::Number]
-
# @raise [ArgumentError] if `$string` isn't a string
-
1
def str_length(string)
-
assert_type string, :String, :string
-
number(string.value.size)
-
end
-
1
declare :str_length, [:string]
-
-
# Inserts `$insert` into `$string` at `$index`.
-
#
-
# Note that unlike some languages, the first character in a Sass string is
-
# number 1, the second number 2, and so forth.
-
#
-
# @example
-
# str-insert("abcd", "X", 1) => "Xabcd"
-
# str-insert("abcd", "X", 4) => "abcXd"
-
# str-insert("abcd", "X", 5) => "abcdX"
-
#
-
# @overload str_insert($string, $insert, $index)
-
# @param $string [Sass::Script::Value::String]
-
# @param $insert [Sass::Script::Value::String]
-
# @param $index [Sass::Script::Value::Number] The position at which
-
# `$insert` will be inserted. Negative indices count from the end of
-
# `$string`. An index that's outside the bounds of the string will insert
-
# `$insert` at the front or back of the string
-
# @return [Sass::Script::Value::String] The result string. This will be
-
# quoted if and only if `$string` was quoted
-
# @raise [ArgumentError] if any parameter is the wrong type
-
1
def str_insert(original, insert, index)
-
assert_type original, :String, :string
-
assert_type insert, :String, :insert
-
assert_integer index, :index
-
assert_unit index, nil, :index
-
insertion_point = if index.to_i > 0
-
[index.to_i - 1, original.value.size].min
-
else
-
[index.to_i, -original.value.size - 1].max
-
end
-
result = original.value.dup.insert(insertion_point, insert.value)
-
Sass::Script::Value::String.new(result, original.type)
-
end
-
1
declare :str_insert, [:string, :insert, :index]
-
-
# Returns the index of the first occurrence of `$substring` in `$string`. If
-
# there is no such occurrence, returns `null`.
-
#
-
# Note that unlike some languages, the first character in a Sass string is
-
# number 1, the second number 2, and so forth.
-
#
-
# @example
-
# str-index(abcd, a) => 1
-
# str-index(abcd, ab) => 1
-
# str-index(abcd, X) => null
-
# str-index(abcd, c) => 3
-
#
-
# @overload str_index($string, $substring)
-
# @param $string [Sass::Script::Value::String]
-
# @param $substring [Sass::Script::Value::String]
-
# @return [Sass::Script::Value::Number, Sass::Script::Value::Null]
-
# @raise [ArgumentError] if any parameter is the wrong type
-
1
def str_index(string, substring)
-
assert_type string, :String, :string
-
assert_type substring, :String, :substring
-
index = string.value.index(substring.value)
-
index ? number(index + 1) : null
-
end
-
1
declare :str_index, [:string, :substring]
-
-
# Extracts a substring from `$string`. The substring will begin at index
-
# `$start-at` and ends at index `$end-at`.
-
#
-
# Note that unlike some languages, the first character in a Sass string is
-
# number 1, the second number 2, and so forth.
-
#
-
# @example
-
# str-slice("abcd", 2, 3) => "bc"
-
# str-slice("abcd", 2) => "bcd"
-
# str-slice("abcd", -3, -2) => "bc"
-
# str-slice("abcd", 2, -2) => "bc"
-
#
-
# @overload str_slice($string, $start-at, $end-at: -1)
-
# @param $start-at [Sass::Script::Value::Number] The index of the first
-
# character of the substring. If this is negative, it counts from the end
-
# of `$string`
-
# @param $end-at [Sass::Script::Value::Number] The index of the last
-
# character of the substring. If this is negative, it counts from the end
-
# of `$string`. Defaults to -1
-
# @return [Sass::Script::Value::String] The substring. This will be quoted
-
# if and only if `$string` was quoted
-
# @raise [ArgumentError] if any parameter is the wrong type
-
1
def str_slice(string, start_at, end_at = nil)
-
assert_type string, :String, :string
-
assert_unit start_at, nil, "start-at"
-
-
end_at = number(-1) if end_at.nil?
-
assert_unit end_at, nil, "end-at"
-
-
return Sass::Script::Value::String.new("", string.type) if end_at.value == 0
-
s = start_at.value > 0 ? start_at.value - 1 : start_at.value
-
e = end_at.value > 0 ? end_at.value - 1 : end_at.value
-
s = string.value.length + s if s < 0
-
s = 0 if s < 0
-
e = string.value.length + e if e < 0
-
return Sass::Script::Value::String.new("", string.type) if e < 0
-
extracted = string.value.slice(s..e)
-
Sass::Script::Value::String.new(extracted || "", string.type)
-
end
-
1
declare :str_slice, [:string, :start_at]
-
1
declare :str_slice, [:string, :start_at, :end_at]
-
-
# Converts a string to upper case.
-
#
-
# @example
-
# to-upper-case(abcd) => ABCD
-
#
-
# @overload to_upper_case($string)
-
# @param $string [Sass::Script::Value::String]
-
# @return [Sass::Script::Value::String]
-
# @raise [ArgumentError] if `$string` isn't a string
-
1
def to_upper_case(string)
-
assert_type string, :String, :string
-
Sass::Script::Value::String.new(Sass::Util.upcase(string.value), string.type)
-
end
-
1
declare :to_upper_case, [:string]
-
-
# Convert a string to lower case,
-
#
-
# @example
-
# to-lower-case(ABCD) => abcd
-
#
-
# @overload to_lower_case($string)
-
# @param $string [Sass::Script::Value::String]
-
# @return [Sass::Script::Value::String]
-
# @raise [ArgumentError] if `$string` isn't a string
-
1
def to_lower_case(string)
-
assert_type string, :String, :string
-
Sass::Script::Value::String.new(Sass::Util.downcase(string.value), string.type)
-
end
-
1
declare :to_lower_case, [:string]
-
-
# Returns the type of a value.
-
#
-
# @example
-
# type-of(100px) => number
-
# type-of(asdf) => string
-
# type-of("asdf") => string
-
# type-of(true) => bool
-
# type-of(#fff) => color
-
# type-of(blue) => color
-
# type-of(null) => null
-
# type-of(a b c) => list
-
# type-of((a: 1, b: 2)) => map
-
# type-of(get-function("foo")) => function
-
#
-
# @overload type_of($value)
-
# @param $value [Sass::Script::Value::Base] The value to inspect
-
# @return [Sass::Script::Value::String] The unquoted string name of the
-
# value's type
-
1
def type_of(value)
-
value.check_deprecated_interp if value.is_a?(Sass::Script::Value::String)
-
identifier(value.class.name.gsub(/Sass::Script::Value::/, '').downcase)
-
end
-
1
declare :type_of, [:value]
-
-
# Returns whether a feature exists in the current Sass runtime.
-
#
-
# The following features are supported:
-
#
-
# * `global-variable-shadowing` indicates that a local variable will shadow
-
# a global variable unless `!global` is used.
-
#
-
# * `extend-selector-pseudoclass` indicates that `@extend` will reach into
-
# selector pseudoclasses like `:not`.
-
#
-
# * `units-level-3` indicates full support for unit arithmetic using units
-
# defined in the [Values and Units Level 3][] spec.
-
#
-
# [Values and Units Level 3]: http://www.w3.org/TR/css3-values/
-
#
-
# * `at-error` indicates that the Sass `@error` directive is supported.
-
#
-
# * `custom-property` indicates that the [Custom Properties Level 1][] spec
-
# is supported. This means that custom properties are parsed statically,
-
# with only interpolation treated as SassScript.
-
#
-
# [Custom Properties Level 1]: https://www.w3.org/TR/css-variables-1/
-
#
-
# @example
-
# feature-exists(some-feature-that-exists) => true
-
# feature-exists(what-is-this-i-dont-know) => false
-
#
-
# @overload feature_exists($feature)
-
# @param $feature [Sass::Script::Value::String] The name of the feature
-
# @return [Sass::Script::Value::Bool] Whether the feature is supported in this version of Sass
-
# @raise [ArgumentError] if `$feature` isn't a string
-
1
def feature_exists(feature)
-
assert_type feature, :String, :feature
-
bool(Sass.has_feature?(feature.value))
-
end
-
1
declare :feature_exists, [:feature]
-
-
# Returns a reference to a function for later invocation with the `call()` function.
-
#
-
# If `$css` is `false`, the function reference may refer to a function
-
# defined in your stylesheet or built-in to the host environment. If it's
-
# `true` it will refer to a plain-CSS function.
-
#
-
# @example
-
# get-function("rgb")
-
#
-
# @function myfunc { @return "something"; }
-
# get-function("myfunc")
-
#
-
# @overload get_function($name, $css: false)
-
# @param name [Sass::Script::Value::String] The name of the function being referenced.
-
# @param css [Sass::Script::Value::Bool] Whether to get a plain CSS function.
-
#
-
# @return [Sass::Script::Value::Function] A function reference.
-
1
def get_function(name, kwargs = {})
-
assert_type name, :String, :name
-
-
css = if kwargs.has_key?("css")
-
v = kwargs.delete("css")
-
assert_type v, :Bool, :css
-
v.value
-
else
-
false
-
end
-
-
if kwargs.any?
-
raise ArgumentError.new("Illegal keyword argument '#{kwargs.keys.first}'")
-
end
-
-
if css
-
return Sass::Script::Value::Function.new(
-
Sass::Callable.new(name.value, nil, nil, nil, nil, nil, "function", :css))
-
end
-
-
callable = environment.caller.function(name.value) ||
-
(Sass::Script::Functions.callable?(name.value.tr("-", "_")) &&
-
Sass::Callable.new(name.value, nil, nil, nil, nil, nil, "function", :builtin))
-
-
if callable
-
Sass::Script::Value::Function.new(callable)
-
else
-
raise Sass::SyntaxError.new("Function not found: #{name}")
-
end
-
end
-
1
declare :get_function, [:name], :var_kwargs => true
-
-
# Returns the unit(s) associated with a number. Complex units are sorted in
-
# alphabetical order by numerator and denominator.
-
#
-
# @example
-
# unit(100) => ""
-
# unit(100px) => "px"
-
# unit(3em) => "em"
-
# unit(10px * 5em) => "em*px"
-
# unit(10px * 5em / 30cm / 1rem) => "em*px/cm*rem"
-
# @overload unit($number)
-
# @param $number [Sass::Script::Value::Number]
-
# @return [Sass::Script::Value::String] The unit(s) of the number, as a
-
# quoted string
-
# @raise [ArgumentError] if `$number` isn't a number
-
1
def unit(number)
-
assert_type number, :Number, :number
-
quoted_string(number.unit_str)
-
end
-
1
declare :unit, [:number]
-
-
# Returns whether a number has units.
-
#
-
# @example
-
# unitless(100) => true
-
# unitless(100px) => false
-
# @overload unitless($number)
-
# @param $number [Sass::Script::Value::Number]
-
# @return [Sass::Script::Value::Bool]
-
# @raise [ArgumentError] if `$number` isn't a number
-
1
def unitless(number)
-
assert_type number, :Number, :number
-
bool(number.unitless?)
-
end
-
1
declare :unitless, [:number]
-
-
# Returns whether two numbers can added, subtracted, or compared.
-
#
-
# @example
-
# comparable(2px, 1px) => true
-
# comparable(100px, 3em) => false
-
# comparable(10cm, 3mm) => true
-
# @overload comparable($number1, $number2)
-
# @param $number1 [Sass::Script::Value::Number]
-
# @param $number2 [Sass::Script::Value::Number]
-
# @return [Sass::Script::Value::Bool]
-
# @raise [ArgumentError] if either parameter is the wrong type
-
1
def comparable(number1, number2)
-
assert_type number1, :Number, :number1
-
assert_type number2, :Number, :number2
-
bool(number1.comparable_to?(number2))
-
end
-
1
declare :comparable, [:number1, :number2]
-
-
# Converts a unitless number to a percentage.
-
#
-
# @example
-
# percentage(0.2) => 20%
-
# percentage(100px / 50px) => 200%
-
# @overload percentage($number)
-
# @param $number [Sass::Script::Value::Number]
-
# @return [Sass::Script::Value::Number]
-
# @raise [ArgumentError] if `$number` isn't a unitless number
-
1
def percentage(number)
-
unless number.is_a?(Sass::Script::Value::Number) && number.unitless?
-
raise ArgumentError.new("$number: #{number.inspect} is not a unitless number")
-
end
-
number(number.value * 100, '%')
-
end
-
1
declare :percentage, [:number]
-
-
# Rounds a number to the nearest whole number.
-
#
-
# @example
-
# round(10.4px) => 10px
-
# round(10.6px) => 11px
-
# @overload round($number)
-
# @param $number [Sass::Script::Value::Number]
-
# @return [Sass::Script::Value::Number]
-
# @raise [ArgumentError] if `$number` isn't a number
-
1
def round(number)
-
numeric_transformation(number) {|n| Sass::Util.round(n)}
-
end
-
1
declare :round, [:number]
-
-
# Rounds a number up to the next whole number.
-
#
-
# @example
-
# ceil(10.4px) => 11px
-
# ceil(10.6px) => 11px
-
# @overload ceil($number)
-
# @param $number [Sass::Script::Value::Number]
-
# @return [Sass::Script::Value::Number]
-
# @raise [ArgumentError] if `$number` isn't a number
-
1
def ceil(number)
-
numeric_transformation(number) {|n| n.ceil}
-
end
-
1
declare :ceil, [:number]
-
-
# Rounds a number down to the previous whole number.
-
#
-
# @example
-
# floor(10.4px) => 10px
-
# floor(10.6px) => 10px
-
# @overload floor($number)
-
# @param $number [Sass::Script::Value::Number]
-
# @return [Sass::Script::Value::Number]
-
# @raise [ArgumentError] if `$number` isn't a number
-
1
def floor(number)
-
numeric_transformation(number) {|n| n.floor}
-
end
-
1
declare :floor, [:number]
-
-
# Returns the absolute value of a number.
-
#
-
# @example
-
# abs(10px) => 10px
-
# abs(-10px) => 10px
-
# @overload abs($number)
-
# @param $number [Sass::Script::Value::Number]
-
# @return [Sass::Script::Value::Number]
-
# @raise [ArgumentError] if `$number` isn't a number
-
1
def abs(number)
-
numeric_transformation(number) {|n| n.abs}
-
end
-
1
declare :abs, [:number]
-
-
# Finds the minimum of several numbers. This function takes any number of
-
# arguments.
-
#
-
# @example
-
# min(1px, 4px) => 1px
-
# min(5em, 3em, 4em) => 3em
-
# @overload min($numbers...)
-
# @param $numbers [[Sass::Script::Value::Number]]
-
# @return [Sass::Script::Value::Number]
-
# @raise [ArgumentError] if any argument isn't a number, or if not all of
-
# the arguments have comparable units
-
1
def min(*numbers)
-
numbers.each {|n| assert_type n, :Number}
-
numbers.inject {|min, num| min.lt(num).to_bool ? min : num}
-
end
-
1
declare :min, [], :var_args => :true
-
-
# Finds the maximum of several numbers. This function takes any number of
-
# arguments.
-
#
-
# @example
-
# max(1px, 4px) => 4px
-
# max(5em, 3em, 4em) => 5em
-
# @overload max($numbers...)
-
# @param $numbers [[Sass::Script::Value::Number]]
-
# @return [Sass::Script::Value::Number]
-
# @raise [ArgumentError] if any argument isn't a number, or if not all of
-
# the arguments have comparable units
-
1
def max(*values)
-
values.each {|v| assert_type v, :Number}
-
values.inject {|max, val| max.gt(val).to_bool ? max : val}
-
end
-
1
declare :max, [], :var_args => :true
-
-
# Return the length of a list.
-
#
-
# This can return the number of pairs in a map as well.
-
#
-
# @example
-
# length(10px) => 1
-
# length(10px 20px 30px) => 3
-
# length((width: 10px, height: 20px)) => 2
-
# @overload length($list)
-
# @param $list [Sass::Script::Value::Base]
-
# @return [Sass::Script::Value::Number]
-
1
def length(list)
-
number(list.to_a.size)
-
end
-
1
declare :length, [:list]
-
-
# Return a new list, based on the list provided, but with the nth
-
# element changed to the value given.
-
#
-
# Note that unlike some languages, the first item in a Sass list is number
-
# 1, the second number 2, and so forth.
-
#
-
# Negative index values address elements in reverse order, starting with the last element
-
# in the list.
-
#
-
# @example
-
# set-nth($list: 10px 20px 30px, $n: 2, $value: -20px) => 10px -20px 30px
-
# @overload set-nth($list, $n, $value)
-
# @param $list [Sass::Script::Value::Base] The list that will be copied, having the element
-
# at index `$n` changed.
-
# @param $n [Sass::Script::Value::Number] The index of the item to set.
-
# Negative indices count from the end of the list.
-
# @param $value [Sass::Script::Value::Base] The new value at index `$n`.
-
# @return [Sass::Script::Value::List]
-
# @raise [ArgumentError] if `$n` isn't an integer between 1 and the length
-
# of `$list`
-
1
def set_nth(list, n, value)
-
assert_type n, :Number, :n
-
Sass::Script::Value::List.assert_valid_index(list, n)
-
index = n.to_i > 0 ? n.to_i - 1 : n.to_i
-
new_list = list.to_a.dup
-
new_list[index] = value
-
list.with_contents(new_list)
-
end
-
1
declare :set_nth, [:list, :n, :value]
-
-
# Gets the nth item in a list.
-
#
-
# Note that unlike some languages, the first item in a Sass list is number
-
# 1, the second number 2, and so forth.
-
#
-
# This can return the nth pair in a map as well.
-
#
-
# Negative index values address elements in reverse order, starting with the last element in
-
# the list.
-
#
-
# @example
-
# nth(10px 20px 30px, 1) => 10px
-
# nth((Helvetica, Arial, sans-serif), 3) => sans-serif
-
# nth((width: 10px, length: 20px), 2) => length, 20px
-
# @overload nth($list, $n)
-
# @param $list [Sass::Script::Value::Base]
-
# @param $n [Sass::Script::Value::Number] The index of the item to get.
-
# Negative indices count from the end of the list.
-
# @return [Sass::Script::Value::Base]
-
# @raise [ArgumentError] if `$n` isn't an integer between 1 and the length
-
# of `$list`
-
1
def nth(list, n)
-
assert_type n, :Number, :n
-
Sass::Script::Value::List.assert_valid_index(list, n)
-
-
index = n.to_i > 0 ? n.to_i - 1 : n.to_i
-
list.to_a[index]
-
end
-
1
declare :nth, [:list, :n]
-
-
# Joins together two lists into one.
-
#
-
# Unless `$separator` is passed, if one list is comma-separated and one is
-
# space-separated, the first parameter's separator is used for the resulting
-
# list. If both lists have fewer than two items, spaces are used for the
-
# resulting list.
-
#
-
# Unless `$bracketed` is passed, the resulting list is bracketed if the
-
# first parameter is.
-
#
-
# Like all list functions, `join()` returns a new list rather than modifying
-
# its arguments in place.
-
#
-
# @example
-
# join(10px 20px, 30px 40px) => 10px 20px 30px 40px
-
# join((blue, red), (#abc, #def)) => blue, red, #abc, #def
-
# join(10px, 20px) => 10px 20px
-
# join(10px, 20px, comma) => 10px, 20px
-
# join((blue, red), (#abc, #def), space) => blue red #abc #def
-
# join([10px], 20px) => [10px 20px]
-
# @overload join($list1, $list2, $separator: auto, $bracketed: auto)
-
# @param $list1 [Sass::Script::Value::Base]
-
# @param $list2 [Sass::Script::Value::Base]
-
# @param $separator [Sass::Script::Value::String] The list separator to use.
-
# If this is `comma` or `space`, that separator will be used. If this is
-
# `auto` (the default), the separator is determined as explained above.
-
# @param $bracketed [Sass::Script::Value::Base] Whether the resulting list
-
# will be bracketed. If this is `auto` (the default), the separator is
-
# determined as explained above.
-
# @return [Sass::Script::Value::List]
-
# @comment
-
# rubocop:disable ParameterLists
-
1
def join(list1, list2,
-
separator = identifier("auto"), bracketed = identifier("auto"),
-
kwargs = nil, *rest)
-
# rubocop:enable ParameterLists
-
if separator.is_a?(Hash)
-
kwargs = separator
-
separator = identifier("auto")
-
elsif bracketed.is_a?(Hash)
-
kwargs = bracketed
-
bracketed = identifier("auto")
-
elsif rest.last.is_a?(Hash)
-
rest.unshift kwargs
-
kwargs = rest.pop
-
end
-
-
unless rest.empty?
-
# Add 4 to rest.length because we don't want to count the kwargs hash,
-
# which is always passed.
-
raise ArgumentError.new("wrong number of arguments (#{rest.length + 4} for 2..4)")
-
end
-
-
if kwargs
-
separator = kwargs.delete("separator") || separator
-
bracketed = kwargs.delete("bracketed") || bracketed
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
end
-
-
assert_type separator, :String, :separator
-
unless %w(auto space comma).include?(separator.value)
-
raise ArgumentError.new("Separator name must be space, comma, or auto")
-
end
-
-
list(list1.to_a + list2.to_a,
-
separator:
-
if separator.value == 'auto'
-
list1.separator || list2.separator || :space
-
else
-
separator.value.to_sym
-
end,
-
bracketed:
-
if bracketed.is_a?(Sass::Script::Value::String) && bracketed.value == 'auto'
-
list1.bracketed
-
else
-
bracketed.to_bool
-
end)
-
end
-
# We don't actually take variable arguments or keyword arguments, but this
-
# is the best way to take either `$separator` or `$bracketed` as keywords
-
# without complaining about the other missing.
-
1
declare :join, [:list1, :list2], :var_args => true, :var_kwargs => true
-
-
# Appends a single value onto the end of a list.
-
#
-
# Unless the `$separator` argument is passed, if the list had only one item,
-
# the resulting list will be space-separated.
-
#
-
# Like all list functions, `append()` returns a new list rather than
-
# modifying its argument in place.
-
#
-
# @example
-
# append(10px 20px, 30px) => 10px 20px 30px
-
# append((blue, red), green) => blue, red, green
-
# append(10px 20px, 30px 40px) => 10px 20px (30px 40px)
-
# append(10px, 20px, comma) => 10px, 20px
-
# append((blue, red), green, space) => blue red green
-
# @overload append($list, $val, $separator: auto)
-
# @param $list [Sass::Script::Value::Base]
-
# @param $val [Sass::Script::Value::Base]
-
# @param $separator [Sass::Script::Value::String] The list separator to use.
-
# If this is `comma` or `space`, that separator will be used. If this is
-
# `auto` (the default), the separator is determined as explained above.
-
# @return [Sass::Script::Value::List]
-
1
def append(list, val, separator = identifier("auto"))
-
assert_type separator, :String, :separator
-
unless %w(auto space comma).include?(separator.value)
-
raise ArgumentError.new("Separator name must be space, comma, or auto")
-
end
-
list.with_contents(list.to_a + [val],
-
separator:
-
if separator.value == 'auto'
-
list.separator || :space
-
else
-
separator.value.to_sym
-
end)
-
end
-
1
declare :append, [:list, :val]
-
1
declare :append, [:list, :val, :separator]
-
-
# Combines several lists into a single multidimensional list. The nth value
-
# of the resulting list is a space separated list of the source lists' nth
-
# values.
-
#
-
# The length of the resulting list is the length of the
-
# shortest list.
-
#
-
# @example
-
# zip(1px 1px 3px, solid dashed solid, red green blue)
-
# => 1px solid red, 1px dashed green, 3px solid blue
-
# @overload zip($lists...)
-
# @param $lists [[Sass::Script::Value::Base]]
-
# @return [Sass::Script::Value::List]
-
1
def zip(*lists)
-
length = nil
-
values = []
-
lists.each do |list|
-
array = list.to_a
-
values << array.dup
-
length = length.nil? ? array.length : [length, array.length].min
-
end
-
values.each do |value|
-
value.slice!(length)
-
end
-
new_list_value = values.first.zip(*values[1..-1])
-
list(new_list_value.map {|list| list(list, :space)}, :comma)
-
end
-
1
declare :zip, [], :var_args => true
-
-
# Returns the position of a value within a list. If the value isn't found,
-
# returns `null` instead.
-
#
-
# Note that unlike some languages, the first item in a Sass list is number
-
# 1, the second number 2, and so forth.
-
#
-
# This can return the position of a pair in a map as well.
-
#
-
# @example
-
# index(1px solid red, solid) => 2
-
# index(1px solid red, dashed) => null
-
# index((width: 10px, height: 20px), (height 20px)) => 2
-
# @overload index($list, $value)
-
# @param $list [Sass::Script::Value::Base]
-
# @param $value [Sass::Script::Value::Base]
-
# @return [Sass::Script::Value::Number, Sass::Script::Value::Null] The
-
# 1-based index of `$value` in `$list`, or `null`
-
1
def index(list, value)
-
index = list.to_a.index {|e| e.eq(value).to_bool}
-
index ? number(index + 1) : null
-
end
-
1
declare :index, [:list, :value]
-
-
# Returns the separator of a list. If the list doesn't have a separator due
-
# to having fewer than two elements, returns `space`.
-
#
-
# @example
-
# list-separator(1px 2px 3px) => space
-
# list-separator(1px, 2px, 3px) => comma
-
# list-separator('foo') => space
-
# @overload list_separator($list)
-
# @param $list [Sass::Script::Value::Base]
-
# @return [Sass::Script::Value::String] `comma` or `space`
-
1
def list_separator(list)
-
identifier((list.separator || :space).to_s)
-
end
-
1
declare :list_separator, [:list]
-
-
# Returns whether a list uses square brackets.
-
#
-
# @example
-
# is-bracketed(1px 2px 3px) => false
-
# is-bracketed([1px, 2px, 3px]) => true
-
# @overload is_bracketed($list)
-
# @param $list [Sass::Script::Value::Base]
-
# @return [Sass::Script::Value::Bool]
-
1
def is_bracketed(list)
-
bool(list.bracketed)
-
end
-
1
declare :is_bracketed, [:list]
-
-
# Returns the value in a map associated with the given key. If the map
-
# doesn't have such a key, returns `null`.
-
#
-
# @example
-
# map-get(("foo": 1, "bar": 2), "foo") => 1
-
# map-get(("foo": 1, "bar": 2), "bar") => 2
-
# map-get(("foo": 1, "bar": 2), "baz") => null
-
# @overload map_get($map, $key)
-
# @param $map [Sass::Script::Value::Map]
-
# @param $key [Sass::Script::Value::Base]
-
# @return [Sass::Script::Value::Base] The value indexed by `$key`, or `null`
-
# if the map doesn't contain the given key
-
# @raise [ArgumentError] if `$map` is not a map
-
1
def map_get(map, key)
-
assert_type map, :Map, :map
-
map.to_h[key] || null
-
end
-
1
declare :map_get, [:map, :key]
-
-
# Merges two maps together into a new map. Keys in `$map2` will take
-
# precedence over keys in `$map1`.
-
#
-
# This is the best way to add new values to a map.
-
#
-
# All keys in the returned map that also appear in `$map1` will have the
-
# same order as in `$map1`. New keys from `$map2` will be placed at the end
-
# of the map.
-
#
-
# Like all map functions, `map-merge()` returns a new map rather than
-
# modifying its arguments in place.
-
#
-
# @example
-
# map-merge(("foo": 1), ("bar": 2)) => ("foo": 1, "bar": 2)
-
# map-merge(("foo": 1, "bar": 2), ("bar": 3)) => ("foo": 1, "bar": 3)
-
# @overload map_merge($map1, $map2)
-
# @param $map1 [Sass::Script::Value::Map]
-
# @param $map2 [Sass::Script::Value::Map]
-
# @return [Sass::Script::Value::Map]
-
# @raise [ArgumentError] if either parameter is not a map
-
1
def map_merge(map1, map2)
-
assert_type map1, :Map, :map1
-
assert_type map2, :Map, :map2
-
map(map1.to_h.merge(map2.to_h))
-
end
-
1
declare :map_merge, [:map1, :map2]
-
-
# Returns a new map with keys removed.
-
#
-
# Like all map functions, `map-merge()` returns a new map rather than
-
# modifying its arguments in place.
-
#
-
# @example
-
# map-remove(("foo": 1, "bar": 2), "bar") => ("foo": 1)
-
# map-remove(("foo": 1, "bar": 2, "baz": 3), "bar", "baz") => ("foo": 1)
-
# map-remove(("foo": 1, "bar": 2), "baz") => ("foo": 1, "bar": 2)
-
# @overload map_remove($map, $keys...)
-
# @param $map [Sass::Script::Value::Map]
-
# @param $keys [[Sass::Script::Value::Base]]
-
# @return [Sass::Script::Value::Map]
-
# @raise [ArgumentError] if `$map` is not a map
-
1
def map_remove(map, *keys)
-
assert_type map, :Map, :map
-
hash = map.to_h.dup
-
hash.delete_if {|key, _| keys.include?(key)}
-
map(hash)
-
end
-
1
declare :map_remove, [:map, :key], :var_args => true
-
-
# Returns a list of all keys in a map.
-
#
-
# @example
-
# map-keys(("foo": 1, "bar": 2)) => "foo", "bar"
-
# @overload map_keys($map)
-
# @param $map [Map]
-
# @return [List] the list of keys, comma-separated
-
# @raise [ArgumentError] if `$map` is not a map
-
1
def map_keys(map)
-
assert_type map, :Map, :map
-
list(map.to_h.keys, :comma)
-
end
-
1
declare :map_keys, [:map]
-
-
# Returns a list of all values in a map. This list may include duplicate
-
# values, if multiple keys have the same value.
-
#
-
# @example
-
# map-values(("foo": 1, "bar": 2)) => 1, 2
-
# map-values(("foo": 1, "bar": 2, "baz": 1)) => 1, 2, 1
-
# @overload map_values($map)
-
# @param $map [Map]
-
# @return [List] the list of values, comma-separated
-
# @raise [ArgumentError] if `$map` is not a map
-
1
def map_values(map)
-
assert_type map, :Map, :map
-
list(map.to_h.values, :comma)
-
end
-
1
declare :map_values, [:map]
-
-
# Returns whether a map has a value associated with a given key.
-
#
-
# @example
-
# map-has-key(("foo": 1, "bar": 2), "foo") => true
-
# map-has-key(("foo": 1, "bar": 2), "baz") => false
-
# @overload map_has_key($map, $key)
-
# @param $map [Sass::Script::Value::Map]
-
# @param $key [Sass::Script::Value::Base]
-
# @return [Sass::Script::Value::Bool]
-
# @raise [ArgumentError] if `$map` is not a map
-
1
def map_has_key(map, key)
-
assert_type map, :Map, :map
-
bool(map.to_h.has_key?(key))
-
end
-
1
declare :map_has_key, [:map, :key]
-
-
# Returns the map of named arguments passed to a function or mixin that
-
# takes a variable argument list. The argument names are strings, and they
-
# do not contain the leading `$`.
-
#
-
# @example
-
# @mixin foo($args...) {
-
# @debug keywords($args); //=> (arg1: val, arg2: val)
-
# }
-
#
-
# @include foo($arg1: val, $arg2: val);
-
# @overload keywords($args)
-
# @param $args [Sass::Script::Value::ArgList]
-
# @return [Sass::Script::Value::Map]
-
# @raise [ArgumentError] if `$args` isn't a variable argument list
-
1
def keywords(args)
-
assert_type args, :ArgList, :args
-
map(Sass::Util.map_keys(args.keywords.as_stored) {|k| Sass::Script::Value::String.new(k)})
-
end
-
1
declare :keywords, [:args]
-
-
# Returns one of two values, depending on whether or not `$condition` is
-
# true. Just like in `@if`, all values other than `false` and `null` are
-
# considered to be true.
-
#
-
# @example
-
# if(true, 1px, 2px) => 1px
-
# if(false, 1px, 2px) => 2px
-
# @overload if($condition, $if-true, $if-false)
-
# @param $condition [Sass::Script::Value::Base] Whether the `$if-true` or
-
# `$if-false` will be returned
-
# @param $if-true [Sass::Script::Tree::Node]
-
# @param $if-false [Sass::Script::Tree::Node]
-
# @return [Sass::Script::Value::Base] `$if-true` or `$if-false`
-
1
def if(condition, if_true, if_false)
-
if condition.to_bool
-
perform(if_true)
-
else
-
perform(if_false)
-
end
-
end
-
1
declare :if, [:condition, :"&if_true", :"&if_false"]
-
-
# Returns a unique CSS identifier. The identifier is returned as an unquoted
-
# string. The identifier returned is only guaranteed to be unique within the
-
# scope of a single Sass run.
-
#
-
# @overload unique_id()
-
# @return [Sass::Script::Value::String]
-
1
def unique_id
-
generator = Sass::Script::Functions.random_number_generator
-
Thread.current[:sass_last_unique_id] ||= generator.rand(36**8)
-
# avoid the temptation of trying to guess the next unique value.
-
value = (Thread.current[:sass_last_unique_id] += (generator.rand(10) + 1))
-
# the u makes this a legal identifier if it would otherwise start with a number.
-
identifier("u" + value.to_s(36).rjust(8, '0'))
-
end
-
1
declare :unique_id, []
-
-
# Dynamically calls a function. This can call user-defined
-
# functions, built-in functions, or plain CSS functions. It will
-
# pass along all arguments, including keyword arguments, to the
-
# called function.
-
#
-
# @example
-
# call(rgb, 10, 100, 255) => #0a64ff
-
# call(scale-color, #0a64ff, $lightness: -10%) => #0058ef
-
#
-
# $fn: nth;
-
# call($fn, (a b c), 2) => b
-
#
-
# @overload call($function, $args...)
-
# @param $function [Sass::Script::Value::Function] The function to call.
-
1
def call(name, *args)
-
unless name.is_a?(Sass::Script::Value::String) ||
-
name.is_a?(Sass::Script::Value::Function)
-
assert_type name, :Function, :function
-
end
-
if name.is_a?(Sass::Script::Value::String)
-
name = if function_exists(name).to_bool
-
get_function(name)
-
else
-
get_function(name, "css" => bool(true))
-
end
-
Sass::Util.sass_warn(<<WARNING)
-
DEPRECATION WARNING: Passing a string to call() is deprecated and will be illegal
-
in Sass 4.0. Use call(#{name.to_sass}) instead.
-
WARNING
-
end
-
kwargs = args.last.is_a?(Hash) ? args.pop : {}
-
funcall = Sass::Script::Tree::Funcall.new(
-
name.value,
-
args.map {|a| Sass::Script::Tree::Literal.new(a)},
-
Sass::Util.map_vals(kwargs) {|v| Sass::Script::Tree::Literal.new(v)},
-
nil,
-
nil)
-
funcall.line = environment.stack.frames.last.line
-
funcall.filename = environment.stack.frames.last.filename
-
funcall.options = options
-
perform(funcall)
-
end
-
1
declare :call, [:name], :var_args => true, :var_kwargs => true
-
-
# This function only exists as a workaround for IE7's [`content:
-
# counter` bug](http://jes.st/2013/ie7s-css-breaking-content-counter-bug/).
-
# It works identically to any other plain-CSS function, except it
-
# avoids adding spaces between the argument commas.
-
#
-
# @example
-
# counter(item, ".") => counter(item,".")
-
# @overload counter($args...)
-
# @return [Sass::Script::Value::String]
-
1
def counter(*args)
-
identifier("counter(#{args.map {|a| a.to_s(options)}.join(',')})")
-
end
-
1
declare :counter, [], :var_args => true
-
-
# This function only exists as a workaround for IE7's [`content:
-
# counter` bug](http://jes.st/2013/ie7s-css-breaking-content-counter-bug/).
-
# It works identically to any other plain-CSS function, except it
-
# avoids adding spaces between the argument commas.
-
#
-
# @example
-
# counters(item, ".") => counters(item,".")
-
# @overload counters($args...)
-
# @return [Sass::Script::Value::String]
-
1
def counters(*args)
-
identifier("counters(#{args.map {|a| a.to_s(options)}.join(',')})")
-
end
-
1
declare :counters, [], :var_args => true
-
-
# Check whether a variable with the given name exists in the current
-
# scope or in the global scope.
-
#
-
# @example
-
# $a-false-value: false;
-
# variable-exists(a-false-value) => true
-
# variable-exists(a-null-value) => true
-
#
-
# variable-exists(nonexistent) => false
-
#
-
# @overload variable_exists($name)
-
# @param $name [Sass::Script::Value::String] The name of the variable to
-
# check. The name should not include the `$`.
-
# @return [Sass::Script::Value::Bool] Whether the variable is defined in
-
# the current scope.
-
1
def variable_exists(name)
-
assert_type name, :String, :name
-
bool(environment.caller.var(name.value))
-
end
-
1
declare :variable_exists, [:name]
-
-
# Check whether a variable with the given name exists in the global
-
# scope (at the top level of the file).
-
#
-
# @example
-
# $a-false-value: false;
-
# global-variable-exists(a-false-value) => true
-
# global-variable-exists(a-null-value) => true
-
#
-
# .foo {
-
# $some-var: false;
-
# @if global-variable-exists(some-var) { /* false, doesn't run */ }
-
# }
-
#
-
# @overload global_variable_exists($name)
-
# @param $name [Sass::Script::Value::String] The name of the variable to
-
# check. The name should not include the `$`.
-
# @return [Sass::Script::Value::Bool] Whether the variable is defined in
-
# the global scope.
-
1
def global_variable_exists(name)
-
assert_type name, :String, :name
-
bool(environment.global_env.var(name.value))
-
end
-
1
declare :global_variable_exists, [:name]
-
-
# Check whether a function with the given name exists.
-
#
-
# @example
-
# function-exists(lighten) => true
-
#
-
# @function myfunc { @return "something"; }
-
# function-exists(myfunc) => true
-
#
-
# @overload function_exists($name)
-
# @param name [Sass::Script::Value::String] The name of the function to
-
# check or a function reference.
-
# @return [Sass::Script::Value::Bool] Whether the function is defined.
-
1
def function_exists(name)
-
assert_type name, :String, :name
-
exists = Sass::Script::Functions.callable?(name.value.tr("-", "_"))
-
exists ||= environment.caller.function(name.value)
-
bool(exists)
-
end
-
1
declare :function_exists, [:name]
-
-
# Check whether a mixin with the given name exists.
-
#
-
# @example
-
# mixin-exists(nonexistent) => false
-
#
-
# @mixin red-text { color: red; }
-
# mixin-exists(red-text) => true
-
#
-
# @overload mixin_exists($name)
-
# @param name [Sass::Script::Value::String] The name of the mixin to
-
# check.
-
# @return [Sass::Script::Value::Bool] Whether the mixin is defined.
-
1
def mixin_exists(name)
-
assert_type name, :String, :name
-
bool(environment.mixin(name.value))
-
end
-
1
declare :mixin_exists, [:name]
-
-
# Check whether a mixin was passed a content block.
-
#
-
# Unless `content-exists()` is called directly from a mixin, an error will be raised.
-
#
-
# @example
-
# @mixin needs-content {
-
# @if not content-exists() {
-
# @error "You must pass a content block!"
-
# }
-
# @content;
-
# }
-
#
-
# @overload content_exists()
-
# @return [Sass::Script::Value::Bool] Whether a content block was passed to the mixin.
-
1
def content_exists
-
# frames.last is the stack frame for this function,
-
# so we use frames[-2] to get the frame before that.
-
mixin_frame = environment.stack.frames[-2]
-
unless mixin_frame && mixin_frame.type == :mixin
-
raise Sass::SyntaxError.new("Cannot call content-exists() except within a mixin.")
-
end
-
bool(!environment.caller.content.nil?)
-
end
-
1
declare :content_exists, []
-
-
# Return a string containing the value as its Sass representation.
-
#
-
# @overload inspect($value)
-
# @param $value [Sass::Script::Value::Base] The value to inspect.
-
# @return [Sass::Script::Value::String] A representation of the value as
-
# it would be written in Sass.
-
1
def inspect(value)
-
value.check_deprecated_interp if value.is_a?(Sass::Script::Value::String)
-
unquoted_string(value.to_sass)
-
end
-
1
declare :inspect, [:value]
-
-
# @overload random()
-
# Return a decimal between 0 and 1, inclusive of 0 but not 1.
-
# @return [Sass::Script::Value::Number] A decimal value.
-
# @overload random($limit)
-
# Return an integer between 1 and `$limit`, inclusive of both 1 and `$limit`.
-
# @param $limit [Sass::Script::Value::Number] The maximum of the random integer to be
-
# returned, a positive integer.
-
# @return [Sass::Script::Value::Number] An integer.
-
# @raise [ArgumentError] if the `$limit` is not 1 or greater
-
1
def random(limit = nil)
-
generator = Sass::Script::Functions.random_number_generator
-
if limit
-
assert_integer limit, "limit"
-
if limit.to_i < 1
-
raise ArgumentError.new("$limit #{limit} must be greater than or equal to 1")
-
end
-
number(1 + generator.rand(limit.to_i))
-
else
-
number(generator.rand)
-
end
-
end
-
1
declare :random, []
-
1
declare :random, [:limit]
-
-
# Parses a user-provided selector into a list of lists of strings
-
# as returned by `&`.
-
#
-
# @example
-
# selector-parse(".foo .bar, .baz .bang") => ('.foo' '.bar', '.baz' '.bang')
-
#
-
# @overload selector_parse($selector)
-
# @param $selector [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The selector to parse. This can be either a string, a list of
-
# strings, or a list of lists of strings as returned by `&`.
-
# @return [Sass::Script::Value::List]
-
# A list of lists of strings representing `$selector`. This is
-
# in the same format as a selector returned by `&`.
-
1
def selector_parse(selector)
-
parse_selector(selector, :selector).to_sass_script
-
end
-
1
declare :selector_parse, [:selector]
-
-
# Return a new selector with all selectors in `$selectors` nested beneath
-
# one another as though they had been nested in the stylesheet as
-
# `$selector1 { $selector2 { ... } }`.
-
#
-
# Unlike most selector functions, `selector-nest` allows the
-
# parent selector `&` to be used in any selector but the first.
-
#
-
# @example
-
# selector-nest(".foo", ".bar", ".baz") => .foo .bar .baz
-
# selector-nest(".a .foo", ".b .bar") => .a .foo .b .bar
-
# selector-nest(".foo", "&.bar") => .foo.bar
-
#
-
# @overload selector_nest($selectors...)
-
# @param $selectors [[Sass::Script::Value::String, Sass::Script::Value::List]]
-
# The selectors to nest. At least one selector must be passed. Each of
-
# these can be either a string, a list of strings, or a list of lists of
-
# strings as returned by `&`.
-
# @return [Sass::Script::Value::List]
-
# A list of lists of strings representing the result of nesting
-
# `$selectors`. This is in the same format as a selector returned by
-
# `&`.
-
1
def selector_nest(*selectors)
-
if selectors.empty?
-
raise ArgumentError.new("$selectors: At least one selector must be passed")
-
end
-
-
parsed = [parse_selector(selectors.first, :selectors)]
-
parsed += selectors[1..-1].map {|sel| parse_selector(sel, :selectors, true)}
-
parsed.inject {|result, child| child.resolve_parent_refs(result)}.to_sass_script
-
end
-
1
declare :selector_nest, [], :var_args => true
-
-
# Return a new selector with all selectors in `$selectors` appended one
-
# another as though they had been nested in the stylesheet as `$selector1 {
-
# &$selector2 { ... } }`.
-
#
-
# @example
-
# selector-append(".foo", ".bar", ".baz") => .foo.bar.baz
-
# selector-append(".a .foo", ".b .bar") => "a .foo.b .bar"
-
# selector-append(".foo", "-suffix") => ".foo-suffix"
-
#
-
# @overload selector_append($selectors...)
-
# @param $selectors [[Sass::Script::Value::String, Sass::Script::Value::List]]
-
# The selectors to append. At least one selector must be passed. Each of
-
# these can be either a string, a list of strings, or a list of lists of
-
# strings as returned by `&`.
-
# @return [Sass::Script::Value::List]
-
# A list of lists of strings representing the result of appending
-
# `$selectors`. This is in the same format as a selector returned by
-
# `&`.
-
# @raise [ArgumentError] if a selector could not be appended.
-
1
def selector_append(*selectors)
-
if selectors.empty?
-
raise ArgumentError.new("$selectors: At least one selector must be passed")
-
end
-
-
selectors.map {|sel| parse_selector(sel, :selectors)}.inject do |parent, child|
-
child.members.each do |seq|
-
sseq = seq.members.first
-
unless sseq.is_a?(Sass::Selector::SimpleSequence)
-
raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"")
-
end
-
-
base = sseq.base
-
case base
-
when Sass::Selector::Universal
-
raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"")
-
when Sass::Selector::Element
-
unless base.namespace.nil?
-
raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"")
-
end
-
sseq.members[0] = Sass::Selector::Parent.new(base.name)
-
else
-
sseq.members.unshift Sass::Selector::Parent.new
-
end
-
end
-
child.resolve_parent_refs(parent)
-
end.to_sass_script
-
end
-
1
declare :selector_append, [], :var_args => true
-
-
# Returns a new version of `$selector` with `$extendee` extended
-
# with `$extender`. This works just like the result of
-
#
-
# $selector { ... }
-
# $extender { @extend $extendee }
-
#
-
# @example
-
# selector-extend(".a .b", ".b", ".foo .bar") => .a .b, .a .foo .bar, .foo .a .bar
-
#
-
# @overload selector_extend($selector, $extendee, $extender)
-
# @param $selector [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The selector within which `$extendee` is extended with
-
# `$extender`. This can be either a string, a list of strings,
-
# or a list of lists of strings as returned by `&`.
-
# @param $extendee [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The selector being extended. This can be either a string, a
-
# list of strings, or a list of lists of strings as returned
-
# by `&`.
-
# @param $extender [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The selector being injected into `$selector`. This can be
-
# either a string, a list of strings, or a list of lists of
-
# strings as returned by `&`.
-
# @return [Sass::Script::Value::List]
-
# A list of lists of strings representing the result of the
-
# extension. This is in the same format as a selector returned
-
# by `&`.
-
# @raise [ArgumentError] if the extension fails
-
1
def selector_extend(selector, extendee, extender)
-
selector = parse_selector(selector, :selector)
-
extendee = parse_selector(extendee, :extendee)
-
extender = parse_selector(extender, :extender)
-
-
extends = Sass::Util::SubsetMap.new
-
begin
-
extender.populate_extends(extends, extendee, nil, [], true)
-
selector.do_extend(extends).to_sass_script
-
rescue Sass::SyntaxError => e
-
raise ArgumentError.new(e.to_s)
-
end
-
end
-
1
declare :selector_extend, [:selector, :extendee, :extender]
-
-
# Replaces all instances of `$original` with `$replacement` in `$selector`
-
#
-
# This works by using `@extend` and throwing away the original
-
# selector. This means that it can be used to do very advanced
-
# replacements; see the examples below.
-
#
-
# @example
-
# selector-replace(".foo .bar", ".bar", ".baz") => ".foo .baz"
-
# selector-replace(".foo.bar.baz", ".foo.baz", ".qux") => ".bar.qux"
-
#
-
# @overload selector_replace($selector, $original, $replacement)
-
# @param $selector [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The selector within which `$original` is replaced with
-
# `$replacement`. This can be either a string, a list of
-
# strings, or a list of lists of strings as returned by `&`.
-
# @param $original [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The selector being replaced. This can be either a string, a
-
# list of strings, or a list of lists of strings as returned
-
# by `&`.
-
# @param $replacement [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The selector that `$original` is being replaced with. This
-
# can be either a string, a list of strings, or a list of
-
# lists of strings as returned by `&`.
-
# @return [Sass::Script::Value::List]
-
# A list of lists of strings representing the result of the
-
# extension. This is in the same format as a selector returned
-
# by `&`.
-
# @raise [ArgumentError] if the replacement fails
-
1
def selector_replace(selector, original, replacement)
-
selector = parse_selector(selector, :selector)
-
original = parse_selector(original, :original)
-
replacement = parse_selector(replacement, :replacement)
-
-
extends = Sass::Util::SubsetMap.new
-
begin
-
replacement.populate_extends(extends, original, nil, [], true)
-
selector.do_extend(extends, [], true).to_sass_script
-
rescue Sass::SyntaxError => e
-
raise ArgumentError.new(e.to_s)
-
end
-
end
-
1
declare :selector_replace, [:selector, :original, :replacement]
-
-
# Unifies two selectors into a single selector that matches only
-
# elements matched by both input selectors. Returns `null` if
-
# there is no such selector.
-
#
-
# Like the selector unification done for `@extend`, this doesn't
-
# guarantee that the output selector will match *all* elements
-
# matched by both input selectors. For example, if `.a .b` is
-
# unified with `.x .y`, `.a .x .b.y, .x .a .b.y` will be returned,
-
# but `.a.x .b.y` will not. This avoids exponential output size
-
# while matching all elements that are likely to exist in
-
# practice.
-
#
-
# @example
-
# selector-unify(".a", ".b") => .a.b
-
# selector-unify(".a .b", ".x .y") => .a .x .b.y, .x .a .b.y
-
# selector-unify(".a.b", ".b.c") => .a.b.c
-
# selector-unify("#a", "#b") => null
-
#
-
# @overload selector_unify($selector1, $selector2)
-
# @param $selector1 [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The first selector to be unified. This can be either a
-
# string, a list of strings, or a list of lists of strings as
-
# returned by `&`.
-
# @param $selector2 [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The second selector to be unified. This can be either a
-
# string, a list of strings, or a list of lists of strings as
-
# returned by `&`.
-
# @return [Sass::Script::Value::List, Sass::Script::Value::Null]
-
# A list of lists of strings representing the result of the
-
# unification, or null if no unification exists. This is in
-
# the same format as a selector returned by `&`.
-
1
def selector_unify(selector1, selector2)
-
selector1 = parse_selector(selector1, :selector1)
-
selector2 = parse_selector(selector2, :selector2)
-
return null unless (unified = selector1.unify(selector2))
-
unified.to_sass_script
-
end
-
1
declare :selector_unify, [:selector1, :selector2]
-
-
# Returns the [simple
-
# selectors](http://dev.w3.org/csswg/selectors4/#simple) that
-
# comprise the compound selector `$selector`.
-
#
-
# Note that `$selector` **must be** a [compound
-
# selector](http://dev.w3.org/csswg/selectors4/#compound). That
-
# means it cannot contain commas or spaces. It also means that
-
# unlike other selector functions, this takes only strings, not
-
# lists.
-
#
-
# @example
-
# simple-selectors(".foo.bar") => ".foo", ".bar"
-
# simple-selectors(".foo.bar.baz") => ".foo", ".bar", ".baz"
-
#
-
# @overload simple_selectors($selector)
-
# @param $selector [Sass::Script::Value::String]
-
# The compound selector whose simple selectors will be extracted.
-
# @return [Sass::Script::Value::List]
-
# A list of simple selectors in the compound selector.
-
1
def simple_selectors(selector)
-
selector = parse_compound_selector(selector, :selector)
-
list(selector.members.map {|simple| unquoted_string(simple.to_s)}, :comma)
-
end
-
1
declare :simple_selectors, [:selector]
-
-
# Returns whether `$super` is a superselector of `$sub`. This means that
-
# `$super` matches all the elements that `$sub` matches, as well as possibly
-
# additional elements. In general, simpler selectors tend to be
-
# superselectors of more complex oned.
-
#
-
# @example
-
# is-superselector(".foo", ".foo.bar") => true
-
# is-superselector(".foo.bar", ".foo") => false
-
# is-superselector(".bar", ".foo .bar") => true
-
# is-superselector(".foo .bar", ".bar") => false
-
#
-
# @overload is_superselector($super, $sub)
-
# @param $super [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The potential superselector. This can be either a string, a list of
-
# strings, or a list of lists of strings as returned by `&`.
-
# @param $sub [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The potential subselector. This can be either a string, a list of
-
# strings, or a list of lists of strings as returned by `&`.
-
# @return [Sass::Script::Value::Bool]
-
# Whether `$selector1` is a superselector of `$selector2`.
-
1
def is_superselector(sup, sub)
-
sup = parse_selector(sup, :super)
-
sub = parse_selector(sub, :sub)
-
bool(sup.superselector?(sub))
-
end
-
1
declare :is_superselector, [:super, :sub]
-
-
1
private
-
-
# This method implements the pattern of transforming a numeric value into
-
# another numeric value with the same units.
-
# It yields a number to a block to perform the operation and return a number
-
1
def numeric_transformation(value)
-
assert_type value, :Number, :value
-
Sass::Script::Value::Number.new(
-
yield(value.value), value.numerator_units, value.denominator_units)
-
end
-
-
# @comment
-
# rubocop:disable ParameterLists
-
1
def _adjust(color, amount, attr, range, op, units = "")
-
# rubocop:enable ParameterLists
-
assert_type color, :Color, :color
-
assert_type amount, :Number, :amount
-
Sass::Util.check_range('Amount', range, amount, units)
-
-
color.with(attr => color.send(attr).send(op, amount.value))
-
end
-
-
1
def check_alpha_unit(alpha, function)
-
return if alpha.unitless?
-
-
if alpha.is_unit?("%")
-
Sass::Util.sass_warn(<<WARNING)
-
DEPRECATION WARNING: Passing a percentage as the alpha value to #{function}() will be
-
interpreted differently in future versions of Sass. For now, use #{alpha.value} instead.
-
WARNING
-
else
-
Sass::Util.sass_warn(<<WARNING)
-
DEPRECATION WARNING: Passing a number with units as the alpha value to #{function}() is
-
deprecated and will be an error in future versions of Sass. Use #{alpha.value} instead.
-
WARNING
-
end
-
end
-
end
-
end
-
1
require 'sass/scss/rx'
-
-
1
module Sass
-
1
module Script
-
# The lexical analyzer for SassScript.
-
# It takes a raw string and converts it to individual tokens
-
# that are easier to parse.
-
1
class Lexer
-
1
include Sass::SCSS::RX
-
-
# A struct containing information about an individual token.
-
#
-
# `type`: \[`Symbol`\]
-
# : The type of token.
-
#
-
# `value`: \[`Object`\]
-
# : The Ruby object corresponding to the value of the token.
-
#
-
# `source_range`: \[`Sass::Source::Range`\]
-
# : The range in the source file in which the token appeared.
-
#
-
# `pos`: \[`Integer`\]
-
# : The scanner position at which the SassScript token appeared.
-
1
Token = Struct.new(:type, :value, :source_range, :pos)
-
-
# The line number of the lexer's current position.
-
#
-
# @return [Integer]
-
1
def line
-
return @line unless @tok
-
@tok.source_range.start_pos.line
-
end
-
-
# The number of bytes into the current line
-
# of the lexer's current position (1-based).
-
#
-
# @return [Integer]
-
1
def offset
-
return @offset unless @tok
-
@tok.source_range.start_pos.offset
-
end
-
-
# A hash from operator strings to the corresponding token types.
-
1
OPERATORS = {
-
'+' => :plus,
-
'-' => :minus,
-
'*' => :times,
-
'/' => :div,
-
'%' => :mod,
-
'=' => :single_eq,
-
':' => :colon,
-
'(' => :lparen,
-
')' => :rparen,
-
'[' => :lsquare,
-
']' => :rsquare,
-
',' => :comma,
-
'and' => :and,
-
'or' => :or,
-
'not' => :not,
-
'==' => :eq,
-
'!=' => :neq,
-
'>=' => :gte,
-
'<=' => :lte,
-
'>' => :gt,
-
'<' => :lt,
-
'#{' => :begin_interpolation,
-
'}' => :end_interpolation,
-
';' => :semicolon,
-
'{' => :lcurly,
-
'...' => :splat,
-
}
-
-
27
OPERATORS_REVERSE = Sass::Util.map_hash(OPERATORS) {|k, v| [v, k]}
-
-
27
TOKEN_NAMES = Sass::Util.map_hash(OPERATORS_REVERSE) {|k, v| [k, v.inspect]}.merge(
-
:const => "variable (e.g. $foo)",
-
:ident => "identifier (e.g. middle)")
-
-
# A list of operator strings ordered with longer names first
-
# so that `>` and `<` don't clobber `>=` and `<=`.
-
27
OP_NAMES = OPERATORS.keys.sort_by {|o| -o.size}
-
-
# A sub-list of {OP_NAMES} that only includes operators
-
# with identifier names.
-
27
IDENT_OP_NAMES = OP_NAMES.select {|k, _v| k =~ /^\w+/}
-
-
1
PARSEABLE_NUMBER = /(?:(\d*\.\d+)|(\d+))(?:[eE]([+-]?\d+))?(#{UNIT})?/
-
-
# A hash of regular expressions that are used for tokenizing.
-
1
REGULAR_EXPRESSIONS = {
-
:whitespace => /\s+/,
-
:comment => COMMENT,
-
:single_line_comment => SINGLE_LINE_COMMENT,
-
:variable => /(\$)(#{IDENT})/,
-
:ident => /(#{IDENT})(\()?/,
-
:number => PARSEABLE_NUMBER,
-
:unary_minus_number => /-#{PARSEABLE_NUMBER}/,
-
:color => HEXCOLOR,
-
:id => /##{IDENT}/,
-
:selector => /&/,
-
:ident_op => /(#{Regexp.union(*IDENT_OP_NAMES.map do |s|
-
3
Regexp.new(Regexp.escape(s) + "(?!#{NMCHAR}|\Z)")
-
end)})/,
-
:op => /(#{Regexp.union(*OP_NAMES)})/,
-
}
-
-
1
class << self
-
1
private
-
-
1
def string_re(open, close)
-
4
/#{open}((?:\\.|\#(?!\{)|[^#{close}\\#])*)(#{close}|#\{)/m
-
end
-
end
-
-
# A hash of regular expressions that are used for tokenizing strings.
-
#
-
# The key is a `[Symbol, Boolean]` pair.
-
# The symbol represents which style of quotation to use,
-
# while the boolean represents whether or not the string
-
# is following an interpolated segment.
-
1
STRING_REGULAR_EXPRESSIONS = {
-
:double => {
-
false => string_re('"', '"'),
-
true => string_re('', '"')
-
},
-
:single => {
-
false => string_re("'", "'"),
-
true => string_re('', "'")
-
},
-
:uri => {
-
false => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
-
},
-
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
-
# non-standard version of http://www.w3.org/TR/css3-conditional/
-
:url_prefix => {
-
false => /url-prefix\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
-
},
-
:domain => {
-
false => /domain\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
-
}
-
}
-
-
# @param str [String, StringScanner] The source text to lex
-
# @param line [Integer] The 1-based line on which the SassScript appears.
-
# Used for error reporting and sourcemap building
-
# @param offset [Integer] The 1-based character (not byte) offset in the line in the source.
-
# Used for error reporting and sourcemap building
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#Options the Sass options documentation}
-
1
def initialize(str, line, offset, options)
-
@scanner = str.is_a?(StringScanner) ? str : Sass::Util::MultibyteStringScanner.new(str)
-
@line = line
-
@offset = offset
-
@options = options
-
@interpolation_stack = []
-
@prev = nil
-
@tok = nil
-
@next_tok = nil
-
end
-
-
# Moves the lexer forward one token.
-
#
-
# @return [Token] The token that was moved past
-
1
def next
-
@tok ||= read_token
-
@tok, tok = nil, @tok
-
@prev = tok
-
tok
-
end
-
-
# Returns whether or not there's whitespace before the next token.
-
#
-
# @return [Boolean]
-
1
def whitespace?(tok = @tok)
-
if tok
-
@scanner.string[0...tok.pos] =~ /\s\Z/
-
else
-
@scanner.string[@scanner.pos, 1] =~ /^\s/ ||
-
@scanner.string[@scanner.pos - 1, 1] =~ /\s\Z/
-
end
-
end
-
-
# Returns the given character.
-
#
-
# @return [String]
-
1
def char(pos = @scanner.pos)
-
@scanner.string[pos, 1]
-
end
-
-
# Returns the next token without moving the lexer forward.
-
#
-
# @return [Token] The next token
-
1
def peek
-
@tok ||= read_token
-
end
-
-
# Rewinds the underlying StringScanner
-
# to before the token returned by \{#peek}.
-
1
def unpeek!
-
return unless @tok
-
@scanner.pos = @tok.pos
-
@line = @tok.source_range.start_pos.line
-
@offset = @tok.source_range.start_pos.offset
-
end
-
-
# @return [Boolean] Whether or not there's more source text to lex.
-
1
def done?
-
return if @next_tok
-
whitespace unless after_interpolation? && !@interpolation_stack.empty?
-
@scanner.eos? && @tok.nil?
-
end
-
-
# @return [Boolean] Whether or not the last token lexed was `:end_interpolation`.
-
1
def after_interpolation?
-
@prev && @prev.type == :end_interpolation
-
end
-
-
# Raise an error to the effect that `name` was expected in the input stream
-
# and wasn't found.
-
#
-
# This calls \{#unpeek!} to rewind the scanner to immediately after
-
# the last returned token.
-
#
-
# @param name [String] The name of the entity that was expected but not found
-
# @raise [Sass::SyntaxError]
-
1
def expected!(name)
-
unpeek!
-
Sass::SCSS::Parser.expected(@scanner, name, @line)
-
end
-
-
# Records all non-comment text the lexer consumes within the block
-
# and returns it as a string.
-
#
-
# @yield A block in which text is recorded
-
# @return [String]
-
1
def str
-
old_pos = @tok ? @tok.pos : @scanner.pos
-
yield
-
new_pos = @tok ? @tok.pos : @scanner.pos
-
@scanner.string[old_pos...new_pos]
-
end
-
-
1
private
-
-
1
def read_token
-
if (tok = @next_tok)
-
@next_tok = nil
-
return tok
-
end
-
-
return if done?
-
start_pos = source_position
-
value = token
-
return unless value
-
type, val = value
-
Token.new(type, val, range(start_pos), @scanner.pos - @scanner.matched_size)
-
end
-
-
1
def whitespace
-
nil while scan(REGULAR_EXPRESSIONS[:whitespace]) ||
-
scan(REGULAR_EXPRESSIONS[:comment]) ||
-
scan(REGULAR_EXPRESSIONS[:single_line_comment])
-
end
-
-
1
def token
-
if after_interpolation? && (interp = @interpolation_stack.pop)
-
interp_type, interp_value = interp
-
if interp_type == :special_fun
-
return special_fun_body(interp_value)
-
else
-
raise "[BUG]: Unknown interp_type #{interp_type}" unless interp_type == :string
-
return string(interp_value, true)
-
end
-
end
-
-
variable || string(:double, false) || string(:single, false) || number || id || color ||
-
selector || string(:uri, false) || raw(UNICODERANGE) || special_fun || special_val ||
-
ident_op || ident || op
-
end
-
-
1
def variable
-
_variable(REGULAR_EXPRESSIONS[:variable])
-
end
-
-
1
def _variable(rx)
-
return unless scan(rx)
-
-
[:const, @scanner[2]]
-
end
-
-
1
def ident
-
return unless scan(REGULAR_EXPRESSIONS[:ident])
-
[@scanner[2] ? :funcall : :ident, @scanner[1]]
-
end
-
-
1
def string(re, open)
-
line, offset = @line, @offset
-
return unless scan(STRING_REGULAR_EXPRESSIONS[re][open])
-
if @scanner[0] =~ /([^\\]|^)\n/
-
filename = @options[:filename]
-
Sass::Util.sass_warn <<MESSAGE
-
DEPRECATION WARNING on line #{line}, column #{offset}#{" of #{filename}" if filename}:
-
Unescaped multiline strings are deprecated and will be removed in a future version of Sass.
-
To include a newline in a string, use "\\a" or "\\a " as in CSS.
-
MESSAGE
-
end
-
-
if @scanner[2] == '#{' # '
-
@interpolation_stack << [:string, re]
-
start_pos = Sass::Source::Position.new(@line, @offset - 2)
-
@next_tok = Token.new(:string_interpolation, range(start_pos), @scanner.pos - 2)
-
end
-
str =
-
if re == :uri
-
url = "#{'url(' unless open}#{@scanner[1]}#{')' unless @scanner[2] == '#{'}"
-
Script::Value::String.new(url)
-
else
-
Script::Value::String.new(Sass::Script::Value::String.value(@scanner[1]), :string)
-
end
-
[:string, str]
-
end
-
-
1
def number
-
# Handling unary minus is complicated by the fact that whitespace is an
-
# operator in SassScript. We want "1-2" to be parsed as "1 - 2", but we
-
# want "1 -2" to be parsed as "1 (-2)". To accomplish this, we only
-
# parse a unary minus as part of a number literal if there's whitespace
-
# before and not after it. Cases like "(-2)" are handled by the unary
-
# minus logic in the parser instead.
-
if @scanner.peek(1) == '-'
-
return if @scanner.pos == 0
-
unary_minus_allowed =
-
case @scanner.string[@scanner.pos - 1, 1]
-
when /\s/; true
-
when '/'; @scanner.pos != 1 && @scanner.string[@scanner.pos - 2, 1] == '*'
-
else; false
-
end
-
-
return unless unary_minus_allowed
-
return unless scan(REGULAR_EXPRESSIONS[:unary_minus_number])
-
minus = true
-
else
-
return unless scan(REGULAR_EXPRESSIONS[:number])
-
minus = false
-
end
-
-
value = (@scanner[1] ? @scanner[1].to_f : @scanner[2].to_i) * (minus ? -1 : 1)
-
value *= 10**@scanner[3].to_i if @scanner[3]
-
script_number = Script::Value::Number.new(value, Array(@scanner[4]))
-
[:number, script_number]
-
end
-
-
1
def id
-
# Colors and ids are tough to tell apart, because they overlap but
-
# neither is a superset of the other. "#xyz" is an id but not a color,
-
# "#000" is a color but not an id, "#abc" is both, and "#0" is neither.
-
# We need to handle all these cases correctly.
-
#
-
# To do so, we first try to parse something as an id. If this works and
-
# the id is also a valid color, we return the color. Otherwise, we
-
# return the id. If it didn't parse as an id, we then try to parse it as
-
# a color. If *this* works, we return the color, and if it doesn't we
-
# give up and throw an error.
-
#
-
# IDs in properties are used in the Basic User Interface Module
-
# (http://www.w3.org/TR/css3-ui/).
-
return unless scan(REGULAR_EXPRESSIONS[:id])
-
if @scanner[0] =~ /^\#[0-9a-fA-F]+$/
-
if @scanner[0].length == 4 || @scanner[0].length == 7
-
return [:color, Script::Value::Color.from_hex(@scanner[0])]
-
elsif @scanner[0].length == 5 || @scanner[0].length == 9
-
filename = @options[:filename]
-
Sass::Util.sass_warn <<MESSAGE
-
DEPRECATION WARNING on line #{line}, column #{offset}#{" of #{filename}" if filename}:
-
The value "#{@scanner[0]}" is currently parsed as a string, but it will be parsed as a color in
-
future versions of Sass. Use "unquote('#{@scanner[0]}')" to continue parsing it as a string.
-
MESSAGE
-
end
-
end
-
[:ident, @scanner[0]]
-
end
-
-
1
def color
-
return unless @scanner.match?(REGULAR_EXPRESSIONS[:color])
-
return unless @scanner[0].length == 4 || @scanner[0].length == 7
-
script_color = Script::Value::Color.from_hex(scan(REGULAR_EXPRESSIONS[:color]))
-
[:color, script_color]
-
end
-
-
1
def selector
-
start_pos = source_position
-
return unless scan(REGULAR_EXPRESSIONS[:selector])
-
script_selector = Script::Tree::Selector.new
-
script_selector.source_range = range(start_pos)
-
[:selector, script_selector]
-
end
-
-
1
def special_fun
-
prefix = scan(/((-[\w-]+-)?(calc|element)|expression|progid:[a-z\.]*)\(/i)
-
return unless prefix
-
special_fun_body(1, prefix)
-
end
-
-
1
def special_fun_body(parens, prefix = nil)
-
str = prefix || ''
-
while (scanned = scan(/.*?([()]|\#\{)/m))
-
str << scanned
-
if scanned[-1] == ?(
-
parens += 1
-
next
-
elsif scanned[-1] == ?)
-
parens -= 1
-
next unless parens == 0
-
else
-
raise "[BUG] Unreachable" unless @scanner[1] == '#{' # '
-
str.slice!(-2..-1)
-
@interpolation_stack << [:special_fun, parens]
-
start_pos = Sass::Source::Position.new(@line, @offset - 2)
-
@next_tok = Token.new(:string_interpolation, range(start_pos), @scanner.pos - 2)
-
end
-
-
return [:special_fun, Sass::Script::Value::String.new(str)]
-
end
-
-
scan(/.*/)
-
expected!('")"')
-
end
-
-
1
def special_val
-
return unless scan(/!#{W}important/i)
-
[:string, Script::Value::String.new("!important")]
-
end
-
-
1
def ident_op
-
op = scan(REGULAR_EXPRESSIONS[:ident_op])
-
return unless op
-
[OPERATORS[op]]
-
end
-
-
1
def op
-
op = scan(REGULAR_EXPRESSIONS[:op])
-
return unless op
-
name = OPERATORS[op]
-
@interpolation_stack << nil if name == :begin_interpolation
-
[name]
-
end
-
-
1
def raw(rx)
-
val = scan(rx)
-
return unless val
-
[:raw, val]
-
end
-
-
1
def scan(re)
-
str = @scanner.scan(re)
-
return unless str
-
c = str.count("\n")
-
@line += c
-
@offset = (c == 0 ? @offset + str.size : str.size - str.rindex("\n"))
-
str
-
end
-
-
1
def range(start_pos, end_pos = source_position)
-
Sass::Source::Range.new(start_pos, end_pos, @options[:filename], @options[:importer])
-
end
-
-
1
def source_position
-
Sass::Source::Position.new(@line, @offset)
-
end
-
end
-
end
-
end
-
1
require 'sass/script/lexer'
-
-
1
module Sass
-
1
module Script
-
# The parser for SassScript.
-
# It parses a string of code into a tree of {Script::Tree::Node}s.
-
1
class Parser
-
# The line number of the parser's current position.
-
#
-
# @return [Integer]
-
1
def line
-
@lexer.line
-
end
-
-
# The column number of the parser's current position.
-
#
-
# @return [Integer]
-
1
def offset
-
@lexer.offset
-
end
-
-
# @param str [String, StringScanner] The source text to parse
-
# @param line [Integer] The line on which the SassScript appears.
-
# Used for error reporting and sourcemap building
-
# @param offset [Integer] The character (not byte) offset where the script starts in the line.
-
# Used for error reporting and sourcemap building
-
# @param options [{Symbol => Object}] An options hash; see
-
# {file:SASS_REFERENCE.md#Options the Sass options documentation}.
-
# This supports an additional `:allow_extra_text` option that controls
-
# whether the parser throws an error when extra text is encountered
-
# after the parsed construct.
-
1
def initialize(str, line, offset, options = {})
-
@options = options
-
@allow_extra_text = options.delete(:allow_extra_text)
-
@lexer = lexer_class.new(str, line, offset, options)
-
@stop_at = nil
-
end
-
-
# Parses a SassScript expression within an interpolated segment (`#{}`).
-
# This means that it stops when it comes across an unmatched `}`,
-
# which signals the end of an interpolated segment,
-
# it returns rather than throwing an error.
-
#
-
# @param warn_for_color [Boolean] Whether raw color values passed to
-
# interoplation should cause a warning.
-
# @return [Script::Tree::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
1
def parse_interpolated(warn_for_color = false)
-
# Start two characters back to compensate for #{
-
start_pos = Sass::Source::Position.new(line, offset - 2)
-
expr = assert_expr :expr
-
assert_tok :end_interpolation
-
expr = Sass::Script::Tree::Interpolation.new(
-
nil, expr, nil, false, false, :warn_for_color => warn_for_color)
-
check_for_interpolation expr
-
expr.options = @options
-
node(expr, start_pos)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression.
-
#
-
# @return [Script::Tree::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
1
def parse
-
expr = assert_expr :expr
-
assert_done
-
expr.options = @options
-
check_for_interpolation expr
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression,
-
# ending it when it encounters one of the given identifier tokens.
-
#
-
# @param tokens [#include?(String)] A set of strings that delimit the expression.
-
# @return [Script::Tree::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
1
def parse_until(tokens)
-
@stop_at = tokens
-
expr = assert_expr :expr
-
assert_done
-
expr.options = @options
-
check_for_interpolation expr
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a mixin include.
-
#
-
# @return [(Array<Script::Tree::Node>,
-
# {String => Script::Tree::Node},
-
# Script::Tree::Node,
-
# Script::Tree::Node)]
-
# The root nodes of the positional arguments, keyword arguments, and
-
# splat argument(s). Keyword arguments are in a hash from names to values.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
1
def parse_mixin_include_arglist
-
args, keywords = [], {}
-
if try_tok(:lparen)
-
args, keywords, splat, kwarg_splat = mixin_arglist
-
assert_tok(:rparen)
-
end
-
assert_done
-
-
args.each do |a|
-
check_for_interpolation a
-
a.options = @options
-
end
-
-
keywords.each do |_, v|
-
check_for_interpolation v
-
v.options = @options
-
end
-
-
if splat
-
check_for_interpolation splat
-
splat.options = @options
-
end
-
-
if kwarg_splat
-
check_for_interpolation kwarg_splat
-
kwarg_splat.options = @options
-
end
-
-
return args, keywords, splat, kwarg_splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a mixin definition.
-
#
-
# @return [(Array<Script::Tree::Node>, Script::Tree::Node)]
-
# The root nodes of the arguments, and the splat argument.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
1
def parse_mixin_definition_arglist
-
args, splat = defn_arglist!(false)
-
assert_done
-
-
args.each do |k, v|
-
check_for_interpolation k
-
k.options = @options
-
-
if v
-
check_for_interpolation v
-
v.options = @options
-
end
-
end
-
-
if splat
-
check_for_interpolation splat
-
splat.options = @options
-
end
-
-
return args, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a function definition.
-
#
-
# @return [(Array<Script::Tree::Node>, Script::Tree::Node)]
-
# The root nodes of the arguments, and the splat argument.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
1
def parse_function_definition_arglist
-
args, splat = defn_arglist!(true)
-
assert_done
-
-
args.each do |k, v|
-
check_for_interpolation k
-
k.options = @options
-
-
if v
-
check_for_interpolation v
-
v.options = @options
-
end
-
end
-
-
if splat
-
check_for_interpolation splat
-
splat.options = @options
-
end
-
-
return args, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parse a single string value, possibly containing interpolation.
-
# Doesn't assert that the scanner is finished after parsing.
-
#
-
# @return [Script::Tree::Node] The root node of the parse tree.
-
# @raise [Sass::SyntaxError] if the string isn't valid SassScript
-
1
def parse_string
-
unless (peek = @lexer.peek) &&
-
(peek.type == :string ||
-
(peek.type == :funcall && peek.value.downcase == 'url'))
-
lexer.expected!("string")
-
end
-
-
expr = assert_expr :funcall
-
check_for_interpolation expr
-
expr.options = @options
-
@lexer.unpeek!
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression.
-
#
-
# @overload parse(str, line, offset, filename = nil)
-
# @return [Script::Tree::Node] The root node of the parse tree
-
# @see Parser#initialize
-
# @see Parser#parse
-
1
def self.parse(*args)
-
new(*args).parse
-
end
-
-
1
PRECEDENCE = [
-
:comma, :single_eq, :space, :or, :and,
-
[:eq, :neq],
-
[:gt, :gte, :lt, :lte],
-
[:plus, :minus],
-
[:times, :div, :mod],
-
]
-
-
1
ASSOCIATIVE = [:plus, :times]
-
-
1
class << self
-
# Returns an integer representing the precedence
-
# of the given operator.
-
# A lower integer indicates a looser binding.
-
#
-
# @private
-
1
def precedence_of(op)
-
PRECEDENCE.each_with_index do |e, i|
-
return i if Array(e).include?(op)
-
end
-
raise "[BUG] Unknown operator #{op.inspect}"
-
end
-
-
# Returns whether or not the given operation is associative.
-
#
-
# @private
-
1
def associative?(op)
-
ASSOCIATIVE.include?(op)
-
end
-
-
1
private
-
-
# Defines a simple left-associative production.
-
# name is the name of the production,
-
# sub is the name of the production beneath it,
-
# and ops is a list of operators for this precedence level
-
1
def production(name, sub, *ops)
-
8
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def #{name}
-
interp = try_ops_after_interp(#{ops.inspect}, #{name.inspect})
-
return interp if interp
-
return unless e = #{sub}
-
15
while tok = try_toks(#{ops.map {|o| o.inspect}.join(', ')})
-
if interp = try_op_before_interp(tok, e)
-
other_interp = try_ops_after_interp(#{ops.inspect}, #{name.inspect}, interp)
-
return interp unless other_interp
-
return other_interp
-
end
-
-
e = node(Tree::Operation.new(e, assert_expr(#{sub.inspect}), tok.type),
-
e.source_range.start_pos)
-
end
-
e
-
end
-
RUBY
-
end
-
-
1
def unary(op, sub)
-
4
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def unary_#{op}
-
return #{sub} unless tok = try_tok(:#{op})
-
interp = try_op_before_interp(tok)
-
return interp if interp
-
start_pos = source_position
-
node(Tree::UnaryOperation.new(assert_expr(:unary_#{op}), :#{op}), start_pos)
-
end
-
RUBY
-
end
-
end
-
-
1
private
-
-
1
def source_position
-
Sass::Source::Position.new(line, offset)
-
end
-
-
1
def range(start_pos, end_pos = source_position)
-
Sass::Source::Range.new(start_pos, end_pos, @options[:filename], @options[:importer])
-
end
-
-
# @private
-
1
def lexer_class; Lexer; end
-
-
1
def map
-
start_pos = source_position
-
e = interpolation
-
return unless e
-
return list e, start_pos unless @lexer.peek && @lexer.peek.type == :colon
-
-
pair = map_pair(e)
-
map = node(Sass::Script::Tree::MapLiteral.new([pair]), start_pos)
-
while try_tok(:comma)
-
pair = map_pair
-
return map unless pair
-
map.pairs << pair
-
end
-
map
-
end
-
-
1
def map_pair(key = nil)
-
return unless key ||= interpolation
-
assert_tok :colon
-
return key, assert_expr(:interpolation)
-
end
-
-
1
def expr
-
start_pos = source_position
-
e = interpolation
-
return unless e
-
list e, start_pos
-
end
-
-
1
def list(first, start_pos)
-
return first unless @lexer.peek && @lexer.peek.type == :comma
-
-
list = node(Sass::Script::Tree::ListLiteral.new([first], separator: :comma), start_pos)
-
while (tok = try_tok(:comma))
-
element_before_interp = list.elements.length == 1 ? list.elements.first : list
-
if (interp = try_op_before_interp(tok, element_before_interp))
-
other_interp = try_ops_after_interp([:comma], :expr, interp)
-
return interp unless other_interp
-
return other_interp
-
end
-
return list unless (e = interpolation)
-
list.elements << e
-
list.source_range.end_pos = list.elements.last.source_range.end_pos
-
end
-
list
-
end
-
-
1
production :equals, :interpolation, :single_eq
-
-
1
def try_op_before_interp(op, prev = nil, after_interp = false)
-
return unless @lexer.peek && @lexer.peek.type == :begin_interpolation
-
unary = !prev && !after_interp
-
wb = @lexer.whitespace?(op)
-
str = literal_node(Script::Value::String.new(Lexer::OPERATORS_REVERSE[op.type]),
-
op.source_range)
-
-
deprecation =
-
case op.type
-
when :comma; :potential
-
when :div, :single_eq; :none
-
when :plus; unary ? :none : :immediate
-
when :minus; @lexer.whitespace?(@lexer.peek) ? :immediate : :none
-
else; :immediate
-
end
-
-
interp = node(
-
Script::Tree::Interpolation.new(
-
prev, str, nil, wb, false, :originally_text => true, :deprecation => deprecation),
-
(prev || str).source_range.start_pos)
-
interpolation(first: interp)
-
end
-
-
1
def try_ops_after_interp(ops, name, prev = nil)
-
return unless @lexer.after_interpolation?
-
op = try_toks(*ops)
-
return unless op
-
interp = try_op_before_interp(op, prev, :after_interp)
-
return interp if interp
-
-
wa = @lexer.whitespace?
-
str = literal_node(Script::Value::String.new(Lexer::OPERATORS_REVERSE[op.type]),
-
op.source_range)
-
str.line = @lexer.line
-
-
deprecation =
-
case op.type
-
when :comma; :potential
-
when :div, :single_eq; :none
-
when :minus; @lexer.whitespace?(op) ? :immediate : :none
-
else; :immediate
-
end
-
interp = node(
-
Script::Tree::Interpolation.new(
-
prev, str, assert_expr(name), false, wa,
-
:originally_text => true, :deprecation => deprecation),
-
(prev || str).source_range.start_pos)
-
interp
-
end
-
-
1
def interpolation(first: nil, inner: :space)
-
e = first || send(inner)
-
while (interp = try_tok(:begin_interpolation))
-
wb = @lexer.whitespace?(interp)
-
char_before = @lexer.char(interp.pos - 1)
-
mid = assert_expr :expr
-
assert_tok :end_interpolation
-
wa = @lexer.whitespace?
-
char_after = @lexer.char
-
-
after = send(inner)
-
before_deprecation = e.is_a?(Script::Tree::Interpolation) ? e.deprecation : :none
-
after_deprecation = after.is_a?(Script::Tree::Interpolation) ? after.deprecation : :none
-
-
deprecation =
-
if before_deprecation == :immediate || after_deprecation == :immediate ||
-
# Warn for #{foo}$var and #{foo}(1) but not #{$foo}1.
-
(after && !wa && char_after =~ /[$(]/) ||
-
# Warn for $var#{foo} and (a)#{foo} but not a#{foo}.
-
(e && !wb && is_unsafe_before?(e, char_before))
-
:immediate
-
else
-
:potential
-
end
-
-
e = node(
-
Script::Tree::Interpolation.new(e, mid, after, wb, wa, :deprecation => deprecation),
-
(e || interp).source_range.start_pos)
-
end
-
e
-
end
-
-
# Returns whether `expr` is unsafe to include before an interpolation.
-
#
-
# @param expr [Node] The expression to check.
-
# @param char_before [String] The character immediately before the
-
# interpolation being checked (and presumably the last character of
-
# `expr`).
-
# @return [Boolean]
-
1
def is_unsafe_before?(expr, char_before)
-
return char_before == ')' if is_safe_value?(expr)
-
-
# Otherwise, it's only safe if it was another interpolation.
-
!expr.is_a?(Script::Tree::Interpolation)
-
end
-
-
# Returns whether `expr` is safe as the value immediately before an
-
# interpolation.
-
#
-
# It's safe as long as the previous expression is an identifier or number,
-
# or a list whose last element is also safe.
-
1
def is_safe_value?(expr)
-
return is_safe_value?(expr.elements.last) if expr.is_a?(Script::Tree::ListLiteral)
-
return false unless expr.is_a?(Script::Tree::Literal)
-
expr.value.is_a?(Script::Value::Number) ||
-
(expr.value.is_a?(Script::Value::String) && expr.value.type == :identifier)
-
end
-
-
1
def space
-
start_pos = source_position
-
e = or_expr
-
return unless e
-
arr = [e]
-
while (e = or_expr)
-
arr << e
-
end
-
if arr.size == 1
-
arr.first
-
else
-
node(Sass::Script::Tree::ListLiteral.new(arr, separator: :space), start_pos)
-
end
-
end
-
-
1
production :or_expr, :and_expr, :or
-
1
production :and_expr, :eq_or_neq, :and
-
1
production :eq_or_neq, :relational, :eq, :neq
-
1
production :relational, :plus_or_minus, :gt, :gte, :lt, :lte
-
1
production :plus_or_minus, :times_div_or_mod, :plus, :minus
-
1
production :times_div_or_mod, :unary_plus, :times, :div, :mod
-
-
1
unary :plus, :unary_minus
-
1
unary :minus, :unary_div
-
1
unary :div, :unary_not # For strings, so /foo/bar works
-
1
unary :not, :ident
-
-
1
def ident
-
return funcall unless @lexer.peek && @lexer.peek.type == :ident
-
return if @stop_at && @stop_at.include?(@lexer.peek.value)
-
-
name = @lexer.next
-
if (color = Sass::Script::Value::Color::COLOR_NAMES[name.value.downcase])
-
literal_node(Sass::Script::Value::Color.new(color, name.value), name.source_range)
-
elsif name.value == "true"
-
literal_node(Sass::Script::Value::Bool.new(true), name.source_range)
-
elsif name.value == "false"
-
literal_node(Sass::Script::Value::Bool.new(false), name.source_range)
-
elsif name.value == "null"
-
literal_node(Sass::Script::Value::Null.new, name.source_range)
-
else
-
literal_node(Sass::Script::Value::String.new(name.value, :identifier), name.source_range)
-
end
-
end
-
-
1
def funcall
-
tok = try_tok(:funcall)
-
return raw unless tok
-
args, keywords, splat, kwarg_splat = fn_arglist
-
assert_tok(:rparen)
-
node(Script::Tree::Funcall.new(tok.value, args, keywords, splat, kwarg_splat),
-
tok.source_range.start_pos, source_position)
-
end
-
-
1
def defn_arglist!(must_have_parens)
-
if must_have_parens
-
assert_tok(:lparen)
-
else
-
return [], nil unless try_tok(:lparen)
-
end
-
-
res = []
-
splat = nil
-
must_have_default = false
-
loop do
-
break if peek_tok(:rparen)
-
c = assert_tok(:const)
-
var = node(Script::Tree::Variable.new(c.value), c.source_range)
-
if try_tok(:colon)
-
val = assert_expr(:space)
-
must_have_default = true
-
elsif try_tok(:splat)
-
splat = var
-
break
-
elsif must_have_default
-
raise SyntaxError.new(
-
"Required argument #{var.inspect} must come before any optional arguments.")
-
end
-
res << [var, val]
-
break unless try_tok(:comma)
-
end
-
assert_tok(:rparen)
-
return res, splat
-
end
-
-
1
def fn_arglist
-
arglist(:equals, "function argument")
-
end
-
-
1
def mixin_arglist
-
arglist(:interpolation, "mixin argument")
-
end
-
-
1
def arglist(subexpr, description)
-
args = []
-
keywords = Sass::Util::NormalizedMap.new
-
splat = nil
-
while (e = send(subexpr))
-
if @lexer.peek && @lexer.peek.type == :colon
-
name = e
-
@lexer.expected!("comma") unless name.is_a?(Tree::Variable)
-
assert_tok(:colon)
-
value = assert_expr(subexpr, description)
-
-
if keywords[name.name]
-
raise SyntaxError.new("Keyword argument \"#{name.to_sass}\" passed more than once")
-
end
-
-
keywords[name.name] = value
-
else
-
if try_tok(:splat)
-
return args, keywords, splat, e if splat
-
splat, e = e, nil
-
elsif splat
-
raise SyntaxError.new("Only keyword arguments may follow variable arguments (...).")
-
elsif !keywords.empty?
-
raise SyntaxError.new("Positional arguments must come before keyword arguments.")
-
end
-
args << e if e
-
end
-
-
return args, keywords, splat unless try_tok(:comma)
-
end
-
return args, keywords
-
end
-
-
1
def raw
-
tok = try_tok(:raw)
-
return special_fun unless tok
-
literal_node(Script::Value::String.new(tok.value), tok.source_range)
-
end
-
-
1
def special_fun
-
first = try_tok(:special_fun)
-
return square_list unless first
-
str = literal_node(first.value, first.source_range)
-
return str unless try_tok(:string_interpolation)
-
mid = assert_expr :expr
-
assert_tok :end_interpolation
-
last = assert_expr(:special_fun)
-
node(
-
Tree::Interpolation.new(str, mid, last, false, false),
-
first.source_range.start_pos)
-
end
-
-
1
def square_list
-
start_pos = source_position
-
return paren unless try_tok(:lsquare)
-
-
space_start_pos = source_position
-
e = interpolation(inner: :or_expr)
-
separator = nil
-
if e
-
elements = [e]
-
while (e = interpolation(inner: :or_expr))
-
elements << e
-
end
-
-
# If there's a comma after a space-separated list, it's actually a
-
# space-separated list nested in a comma-separated list.
-
if try_tok(:comma)
-
e = if elements.length == 1
-
elements.first
-
else
-
node(
-
Sass::Script::Tree::ListLiteral.new(elements, separator: :space),
-
space_start_pos)
-
end
-
elements = [e]
-
-
while (e = space)
-
elements << e
-
break unless try_tok(:comma)
-
end
-
separator = :comma
-
else
-
separator = :space if elements.length > 1
-
end
-
else
-
elements = []
-
end
-
-
assert_tok(:rsquare)
-
end_pos = source_position
-
-
node(Sass::Script::Tree::ListLiteral.new(elements, separator: separator, bracketed: true),
-
start_pos, end_pos)
-
end
-
-
1
def paren
-
return variable unless try_tok(:lparen)
-
start_pos = source_position
-
e = map
-
e.force_division! if e
-
end_pos = source_position
-
assert_tok(:rparen)
-
e || node(Sass::Script::Tree::ListLiteral.new([]), start_pos, end_pos)
-
end
-
-
1
def variable
-
start_pos = source_position
-
c = try_tok(:const)
-
return string unless c
-
node(Tree::Variable.new(*c.value), start_pos)
-
end
-
-
1
def string
-
first = try_tok(:string)
-
return number unless first
-
str = literal_node(first.value, first.source_range)
-
return str unless try_tok(:string_interpolation)
-
mid = assert_expr :expr
-
assert_tok :end_interpolation
-
last = assert_expr(:string)
-
node(Tree::StringInterpolation.new(str, mid, last), first.source_range.start_pos)
-
end
-
-
1
def number
-
tok = try_tok(:number)
-
return selector unless tok
-
num = tok.value
-
num.options = @options
-
num.original = num.to_s
-
literal_node(num, tok.source_range.start_pos)
-
end
-
-
1
def selector
-
tok = try_tok(:selector)
-
return literal unless tok
-
node(tok.value, tok.source_range.start_pos)
-
end
-
-
1
def literal
-
t = try_tok(:color)
-
return literal_node(t.value, t.source_range) if t
-
end
-
-
# It would be possible to have unified #assert and #try methods,
-
# but detecting the method/token difference turns out to be quite expensive.
-
-
1
EXPR_NAMES = {
-
:string => "string",
-
:default => "expression (e.g. 1px, bold)",
-
:mixin_arglist => "mixin argument",
-
:fn_arglist => "function argument",
-
:splat => "...",
-
:special_fun => '")"',
-
}
-
-
1
def assert_expr(name, expected = nil)
-
e = send(name)
-
return e if e
-
@lexer.expected!(expected || EXPR_NAMES[name] || EXPR_NAMES[:default])
-
end
-
-
1
def assert_tok(name)
-
# Avoids an array allocation caused by argument globbing in assert_toks.
-
t = try_tok(name)
-
return t if t
-
@lexer.expected!(Lexer::TOKEN_NAMES[name] || name.to_s)
-
end
-
-
1
def assert_toks(*names)
-
t = try_toks(*names)
-
return t if t
-
@lexer.expected!(names.map {|tok| Lexer::TOKEN_NAMES[tok] || tok}.join(" or "))
-
end
-
-
1
def peek_tok(name)
-
# Avoids an array allocation caused by argument globbing in the try_toks method.
-
peeked = @lexer.peek
-
peeked && name == peeked.type
-
end
-
-
1
def try_tok(name)
-
peek_tok(name) && @lexer.next
-
end
-
-
1
def try_toks(*names)
-
peeked = @lexer.peek
-
peeked && names.include?(peeked.type) && @lexer.next
-
end
-
-
1
def assert_done
-
if @allow_extra_text
-
# If extra text is allowed, just rewind the lexer so that the
-
# StringScanner is pointing to the end of the parsed text.
-
@lexer.unpeek!
-
else
-
return if @lexer.done?
-
@lexer.expected!(EXPR_NAMES[:default])
-
end
-
end
-
-
# @overload node(value, source_range)
-
# @param value [Sass::Script::Value::Base]
-
# @param source_range [Sass::Source::Range]
-
# @overload node(value, start_pos, end_pos = source_position)
-
# @param value [Sass::Script::Value::Base]
-
# @param start_pos [Sass::Source::Position]
-
# @param end_pos [Sass::Source::Position]
-
1
def literal_node(value, source_range_or_start_pos, end_pos = source_position)
-
node(Sass::Script::Tree::Literal.new(value), source_range_or_start_pos, end_pos)
-
end
-
-
# @overload node(node, source_range)
-
# @param node [Sass::Script::Tree::Node]
-
# @param source_range [Sass::Source::Range]
-
# @overload node(node, start_pos, end_pos = source_position)
-
# @param node [Sass::Script::Tree::Node]
-
# @param start_pos [Sass::Source::Position]
-
# @param end_pos [Sass::Source::Position]
-
1
def node(node, source_range_or_start_pos, end_pos = source_position)
-
source_range =
-
if source_range_or_start_pos.is_a?(Sass::Source::Range)
-
source_range_or_start_pos
-
else
-
range(source_range_or_start_pos, end_pos)
-
end
-
-
node.line = source_range.start_pos.line
-
node.source_range = source_range
-
node.filename = @options[:filename]
-
node
-
end
-
-
# Checks a script node for any immediately-deprecated interpolations, and
-
# emits warnings for them.
-
#
-
# @param node [Sass::Script::Tree::Node]
-
1
def check_for_interpolation(node)
-
nodes = [node]
-
until nodes.empty?
-
node = nodes.pop
-
unless node.is_a?(Sass::Script::Tree::Interpolation) &&
-
node.deprecation == :immediate
-
nodes.concat node.children
-
next
-
end
-
-
interpolation_deprecation(node)
-
end
-
end
-
-
# Emits a deprecation warning for an interpolation node.
-
#
-
# @param node [Sass::Script::Tree::Node]
-
1
def interpolation_deprecation(interpolation)
-
return if @options[:_convert]
-
location = "on line #{interpolation.line}"
-
location << " of #{interpolation.filename}" if interpolation.filename
-
Sass::Util.sass_warn <<WARNING
-
DEPRECATION WARNING #{location}:
-
\#{} interpolation near operators will be simplified in a future version of Sass.
-
To preserve the current behavior, use quotes:
-
-
#{interpolation.to_quoted_equivalent.to_sass}
-
-
You can use the sass-convert command to automatically fix most cases.
-
WARNING
-
end
-
end
-
end
-
end
-
# The module containing nodes in the SassScript parse tree. These nodes are
-
# all subclasses of {Sass::Script::Tree::Node}.
-
1
module Sass::Script::Tree
-
end
-
-
1
require 'sass/script/tree/node'
-
1
require 'sass/script/tree/variable'
-
1
require 'sass/script/tree/funcall'
-
1
require 'sass/script/tree/operation'
-
1
require 'sass/script/tree/unary_operation'
-
1
require 'sass/script/tree/interpolation'
-
1
require 'sass/script/tree/string_interpolation'
-
1
require 'sass/script/tree/literal'
-
1
require 'sass/script/tree/list_literal'
-
1
require 'sass/script/tree/map_literal'
-
1
require 'sass/script/tree/selector'
-
1
require 'sass/script/functions'
-
1
require 'sass/util'
-
-
1
module Sass::Script::Tree
-
# A SassScript parse node representing a function call.
-
#
-
# A function call either calls one of the functions in
-
# {Sass::Script::Functions}, or if no function with the given name exists it
-
# returns a string representation of the function call.
-
1
class Funcall < Node
-
# The name of the function.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# The callable to be invoked
-
#
-
# @return [Sass::Callable] or nil if no callable is provided.
-
1
attr_reader :callable
-
-
# The arguments to the function.
-
#
-
# @return [Array<Node>]
-
1
attr_reader :args
-
-
# The keyword arguments to the function.
-
#
-
# @return [Sass::Util::NormalizedMap<Node>]
-
1
attr_reader :keywords
-
-
# The first splat argument for this function, if one exists.
-
#
-
# This could be a list of positional arguments, a map of keyword
-
# arguments, or an arglist containing both.
-
#
-
# @return [Node?]
-
1
attr_accessor :splat
-
-
# The second splat argument for this function, if one exists.
-
#
-
# If this exists, it's always a map of keyword arguments, and
-
# \{#splat} is always either a list or an arglist.
-
#
-
# @return [Node?]
-
1
attr_accessor :kwarg_splat
-
-
# @param name_or_callable [String, Sass::Callable] See \{#name}
-
# @param args [Array<Node>] See \{#args}
-
# @param keywords [Sass::Util::NormalizedMap<Node>] See \{#keywords}
-
# @param splat [Node] See \{#splat}
-
# @param kwarg_splat [Node] See \{#kwarg_splat}
-
1
def initialize(name_or_callable, args, keywords, splat, kwarg_splat)
-
if name_or_callable.is_a?(Sass::Callable)
-
@callable = name_or_callable
-
@name = name_or_callable.name
-
else
-
@callable = nil
-
@name = name_or_callable
-
end
-
@args = args
-
@keywords = keywords
-
@splat = splat
-
@kwarg_splat = kwarg_splat
-
super()
-
end
-
-
# @return [String] A string representation of the function call
-
1
def inspect
-
args = @args.map {|a| a.inspect}.join(', ')
-
keywords = @keywords.as_stored.to_a.map {|k, v| "$#{k}: #{v.inspect}"}.join(', ')
-
# rubocop:disable RedundantSelf
-
if self.splat
-
splat = args.empty? && keywords.empty? ? "" : ", "
-
splat = "#{splat}#{self.splat.inspect}..."
-
splat = "#{splat}, #{kwarg_splat.inspect}..." if kwarg_splat
-
end
-
# rubocop:enable RedundantSelf
-
"#{name}(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
arg_to_sass = lambda do |arg|
-
sass = arg.to_sass(opts)
-
sass = "(#{sass})" if arg.is_a?(Sass::Script::Tree::ListLiteral) && arg.separator == :comma
-
sass
-
end
-
-
args = @args.map(&arg_to_sass)
-
keywords = @keywords.as_stored.to_a.map {|k, v| "$#{dasherize(k, opts)}: #{arg_to_sass[v]}"}
-
-
# rubocop:disable RedundantSelf
-
if self.splat
-
splat = "#{arg_to_sass[self.splat]}..."
-
kwarg_splat = "#{arg_to_sass[self.kwarg_splat]}..." if self.kwarg_splat
-
end
-
# rubocop:enable RedundantSelf
-
-
arglist = [args, splat, keywords, kwarg_splat].flatten.compact.join(', ')
-
"#{dasherize(name, opts)}(#{arglist})"
-
end
-
-
# Returns the arguments to the function.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
1
def children
-
res = @args + @keywords.values
-
res << @splat if @splat
-
res << @kwarg_splat if @kwarg_splat
-
res
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@args', args.map {|a| a.deep_copy})
-
copied_keywords = Sass::Util::NormalizedMap.new
-
@keywords.as_stored.each {|k, v| copied_keywords[k] = v.deep_copy}
-
node.instance_variable_set('@keywords', copied_keywords)
-
node
-
end
-
-
1
protected
-
-
# Evaluates the function call.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::Value] The SassScript object that is the value of the function call
-
# @raise [Sass::SyntaxError] if the function call raises an ArgumentError
-
1
def _perform(environment)
-
args = @args.each_with_index.
-
map {|a, i| perform_arg(a, environment, signature && signature.args[i])}
-
keywords = Sass::Util.map_hash(@keywords) do |k, v|
-
[k, perform_arg(v, environment, k.tr('-', '_'))]
-
end
-
splat = Sass::Tree::Visitors::Perform.perform_splat(
-
@splat, keywords, @kwarg_splat, environment)
-
-
fn = @callable || environment.function(@name)
-
-
if fn && fn.origin == :stylesheet
-
environment.stack.with_function(filename, line, name) do
-
return without_original(perform_sass_fn(fn, args, splat, environment))
-
end
-
end
-
-
args = construct_ruby_args(ruby_name, args, splat, environment)
-
-
if Sass::Script::Functions.callable?(ruby_name) && (!fn || fn.origin == :builtin)
-
local_environment = Sass::Environment.new(environment.global_env, environment.options)
-
local_environment.caller = Sass::ReadOnlyEnvironment.new(environment, environment.options)
-
result = local_environment.stack.with_function(filename, line, name) do
-
opts(Sass::Script::Functions::EvaluationContext.new(
-
local_environment).send(ruby_name, *args))
-
end
-
without_original(result)
-
else
-
opts(to_literal(args))
-
end
-
rescue ArgumentError => e
-
reformat_argument_error(e)
-
end
-
-
# Compass historically overrode this before it changed name to {Funcall#to_value}.
-
# We should get rid of it in the future.
-
1
def to_literal(args)
-
to_value(args)
-
end
-
-
# This method is factored out from `_perform` so that compass can override
-
# it with a cross-browser implementation for functions that require vendor prefixes
-
# in the generated css.
-
1
def to_value(args)
-
Sass::Script::Value::String.new("#{name}(#{args.join(', ')})")
-
end
-
-
1
private
-
-
1
def ruby_name
-
@ruby_name ||= @name.tr('-', '_')
-
end
-
-
1
def perform_arg(argument, environment, name)
-
return argument if signature && signature.delayed_args.include?(name)
-
argument.perform(environment)
-
end
-
-
1
def signature
-
@signature ||= Sass::Script::Functions.signature(name.to_sym, @args.size, @keywords.size)
-
end
-
-
1
def without_original(value)
-
return value unless value.is_a?(Sass::Script::Value::Number)
-
value = value.dup
-
value.original = nil
-
value
-
end
-
-
1
def construct_ruby_args(name, args, splat, environment)
-
args += splat.to_a if splat
-
-
# All keywords are contained in splat.keywords for consistency,
-
# even if there were no splats passed in.
-
old_keywords_accessed = splat.keywords_accessed
-
keywords = splat.keywords
-
splat.keywords_accessed = old_keywords_accessed
-
-
unless (signature = Sass::Script::Functions.signature(name.to_sym, args.size, keywords.size))
-
return args if keywords.empty?
-
raise Sass::SyntaxError.new("Function #{name} doesn't support keyword arguments")
-
end
-
-
# If the user passes more non-keyword args than the function expects,
-
# but it does expect keyword args, Ruby's arg handling won't raise an error.
-
# Since we don't want to make functions think about this,
-
# we'll handle it for them here.
-
if signature.var_kwargs && !signature.var_args && args.size > signature.args.size
-
raise Sass::SyntaxError.new(
-
"#{args[signature.args.size].inspect} is not a keyword argument for `#{name}'")
-
elsif keywords.empty?
-
args << {} if signature.var_kwargs
-
return args
-
end
-
-
argnames = signature.args[args.size..-1] || []
-
deprecated_argnames = (signature.deprecated && signature.deprecated[args.size..-1]) || []
-
args += argnames.zip(deprecated_argnames).map do |(argname, deprecated_argname)|
-
if keywords.has_key?(argname)
-
keywords.delete(argname)
-
elsif deprecated_argname && keywords.has_key?(deprecated_argname)
-
deprecated_argname = keywords.denormalize(deprecated_argname)
-
Sass::Util.sass_warn("DEPRECATION WARNING: The `$#{deprecated_argname}' argument for " +
-
"`#{@name}()' has been renamed to `$#{argname}'.")
-
keywords.delete(deprecated_argname)
-
else
-
raise Sass::SyntaxError.new("Function #{name} requires an argument named $#{argname}")
-
end
-
end
-
-
if keywords.size > 0
-
if signature.var_kwargs
-
# Don't pass a NormalizedMap to a Ruby function.
-
args << keywords.to_hash
-
else
-
argname = keywords.keys.sort.first
-
if signature.args.include?(argname)
-
raise Sass::SyntaxError.new(
-
"Function #{name} was passed argument $#{argname} both by position and by name")
-
else
-
raise Sass::SyntaxError.new(
-
"Function #{name} doesn't have an argument named $#{argname}")
-
end
-
end
-
end
-
-
args
-
end
-
-
1
def perform_sass_fn(function, args, splat, environment)
-
Sass::Tree::Visitors::Perform.perform_arguments(function, args, splat, environment) do |env|
-
env.caller = Sass::Environment.new(environment)
-
-
val = catch :_sass_return do
-
function.tree.each {|c| Sass::Tree::Visitors::Perform.visit(c, env)}
-
raise Sass::SyntaxError.new("Function #{@name} finished without @return")
-
end
-
val
-
end
-
end
-
-
1
def reformat_argument_error(e)
-
message = e.message
-
-
# If this is a legitimate Ruby-raised argument error, re-raise it.
-
# Otherwise, it's an error in the user's stylesheet, so wrap it.
-
if Sass::Util.rbx?
-
# Rubinius has a different error report string than vanilla Ruby. It
-
# also doesn't put the actual method for which the argument error was
-
# thrown in the backtrace, nor does it include `send`, so we look for
-
# `_perform`.
-
if e.message =~ /^method '([^']+)': given (\d+), expected (\d+)/
-
error_name, given, expected = $1, $2, $3
-
raise e if error_name != ruby_name || e.backtrace[0] !~ /:in `_perform'$/
-
message = "wrong number of arguments (#{given} for #{expected})"
-
end
-
elsif Sass::Util.jruby?
-
should_maybe_raise =
-
e.message =~ /^wrong number of arguments calling `[^`]+` \((\d+) for (\d+)\)/
-
given, expected = $1, $2
-
-
if should_maybe_raise
-
# JRuby 1.7 includes __send__ before send and _perform.
-
trace = e.backtrace.dup
-
raise e if trace.shift !~ /:in `__send__'$/
-
-
# JRuby (as of 1.7.2) doesn't put the actual method
-
# for which the argument error was thrown in the backtrace, so we
-
# detect whether our send threw an argument error.
-
if !(trace[0] =~ /:in `send'$/ && trace[1] =~ /:in `_perform'$/)
-
raise e
-
else
-
# JRuby 1.7 doesn't use standard formatting for its ArgumentErrors.
-
message = "wrong number of arguments (#{given} for #{expected})"
-
end
-
end
-
elsif (md = /^wrong number of arguments \(given (\d+), expected (\d+)\)/.match(e.message)) &&
-
e.backtrace[0] =~ /:in `#{ruby_name}'$/
-
# Handle ruby 2.3 error formatting
-
message = "wrong number of arguments (#{md[1]} for #{md[2]})"
-
elsif e.message =~ /^wrong number of arguments/ &&
-
e.backtrace[0] !~ /:in `(block in )?#{ruby_name}'$/
-
raise e
-
end
-
raise Sass::SyntaxError.new("#{message} for `#{name}'")
-
end
-
end
-
end
-
1
module Sass::Script::Tree
-
# A SassScript object representing `#{}` interpolation outside a string.
-
#
-
# @see StringInterpolation
-
1
class Interpolation < Node
-
# @return [Node] The SassScript before the interpolation
-
1
attr_reader :before
-
-
# @return [Node] The SassScript within the interpolation
-
1
attr_reader :mid
-
-
# @return [Node] The SassScript after the interpolation
-
1
attr_reader :after
-
-
# @return [Boolean] Whether there was whitespace between `before` and `#{`
-
1
attr_reader :whitespace_before
-
-
# @return [Boolean] Whether there was whitespace between `}` and `after`
-
1
attr_reader :whitespace_after
-
-
# @return [Boolean] Whether the original format of the interpolation was
-
# plain text, not an interpolation. This is used when converting back to
-
# SassScript.
-
1
attr_reader :originally_text
-
-
# @return [Boolean] Whether a color value passed to the interpolation should
-
# generate a warning.
-
1
attr_reader :warn_for_color
-
-
# The type of interpolation deprecation for this node.
-
#
-
# This can be `:none`, indicating that the node doesn't use deprecated
-
# interpolation; `:immediate`, indicating that a deprecation warning should
-
# be emitted as soon as possible; or `:potential`, indicating that a
-
# deprecation warning should be emitted if the resulting string is used in a
-
# way that would distinguish it from a list.
-
#
-
# @return [Symbol]
-
1
attr_reader :deprecation
-
-
# Interpolation in a property is of the form `before #{mid} after`.
-
#
-
# @param before [Node] See {Interpolation#before}
-
# @param mid [Node] See {Interpolation#mid}
-
# @param after [Node] See {Interpolation#after}
-
# @param wb [Boolean] See {Interpolation#whitespace_before}
-
# @param wa [Boolean] See {Interpolation#whitespace_after}
-
# @param originally_text [Boolean] See {Interpolation#originally_text}
-
# @param warn_for_color [Boolean] See {Interpolation#warn_for_color}
-
# @comment
-
# rubocop:disable ParameterLists
-
1
def initialize(before, mid, after, wb, wa, opts = {})
-
# rubocop:enable ParameterLists
-
@before = before
-
@mid = mid
-
@after = after
-
@whitespace_before = wb
-
@whitespace_after = wa
-
@originally_text = opts[:originally_text] || false
-
@warn_for_color = opts[:warn_for_color] || false
-
@deprecation = opts[:deprecation] || :none
-
end
-
-
# @return [String] A human-readable s-expression representation of the interpolation
-
1
def inspect
-
"(interpolation #{@before.inspect} #{@mid.inspect} #{@after.inspect})"
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
return to_quoted_equivalent.to_sass if deprecation == :immediate
-
-
res = ""
-
res << @before.to_sass(opts) if @before
-
res << ' ' if @before && @whitespace_before
-
res << '#{' unless @originally_text
-
res << @mid.to_sass(opts)
-
res << '}' unless @originally_text
-
res << ' ' if @after && @whitespace_after
-
res << @after.to_sass(opts) if @after
-
res
-
end
-
-
# Returns an `unquote()` expression that will evaluate to the same value as
-
# this interpolation.
-
#
-
# @return [Sass::Script::Tree::Node]
-
1
def to_quoted_equivalent
-
Funcall.new(
-
"unquote",
-
[to_string_interpolation(self)],
-
Sass::Util::NormalizedMap.new,
-
nil,
-
nil)
-
end
-
-
# Returns the three components of the interpolation, `before`, `mid`, and `after`.
-
#
-
# @return [Array<Node>]
-
# @see #initialize
-
# @see Node#children
-
1
def children
-
[@before, @mid, @after].compact
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@before', @before.deep_copy) if @before
-
node.instance_variable_set('@mid', @mid.deep_copy)
-
node.instance_variable_set('@after', @after.deep_copy) if @after
-
node
-
end
-
-
1
protected
-
-
# Converts a script node into a corresponding string interpolation
-
# expression.
-
#
-
# @param node_or_interp [Sass::Script::Tree::Node]
-
# @return [Sass::Script::Tree::StringInterpolation]
-
1
def to_string_interpolation(node_or_interp)
-
unless node_or_interp.is_a?(Interpolation)
-
node = node_or_interp
-
return string_literal(node.value.to_s) if node.is_a?(Literal)
-
if node.is_a?(StringInterpolation)
-
return concat(string_literal(node.quote), concat(node, string_literal(node.quote)))
-
end
-
return StringInterpolation.new(string_literal(""), node, string_literal(""))
-
end
-
-
interp = node_or_interp
-
after_string_or_interp =
-
if interp.after
-
to_string_interpolation(interp.after)
-
else
-
string_literal("")
-
end
-
if interp.after && interp.whitespace_after
-
after_string_or_interp = concat(string_literal(' '), after_string_or_interp)
-
end
-
-
mid_string_or_interp = to_string_interpolation(interp.mid)
-
-
before_string_or_interp =
-
if interp.before
-
to_string_interpolation(interp.before)
-
else
-
string_literal("")
-
end
-
if interp.before && interp.whitespace_before
-
before_string_or_interp = concat(before_string_or_interp, string_literal(' '))
-
end
-
-
concat(before_string_or_interp, concat(mid_string_or_interp, after_string_or_interp))
-
end
-
-
1
private
-
-
# Evaluates the interpolation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::Value::String]
-
# The SassScript string that is the value of the interpolation
-
1
def _perform(environment)
-
res = ""
-
res << @before.perform(environment).to_s if @before
-
res << " " if @before && @whitespace_before
-
-
val = @mid.perform(environment)
-
if @warn_for_color && val.is_a?(Sass::Script::Value::Color) && val.name
-
alternative = Operation.new(Sass::Script::Value::String.new("", :string), @mid, :plus)
-
Sass::Util.sass_warn <<MESSAGE
-
WARNING on line #{line}, column #{source_range.start_pos.offset}#{" of #{filename}" if filename}:
-
You probably don't mean to use the color value `#{val}' in interpolation here.
-
It may end up represented as #{val.inspect}, which will likely produce invalid CSS.
-
Always quote color names when using them as strings (for example, "#{val}").
-
If you really want to use the color value here, use `#{alternative.to_sass}'.
-
MESSAGE
-
end
-
-
res << val.to_s(:quote => :none)
-
res << " " if @after && @whitespace_after
-
res << @after.perform(environment).to_s if @after
-
str = Sass::Script::Value::String.new(
-
res, :identifier,
-
(to_quoted_equivalent.to_sass if deprecation == :potential))
-
str.source_range = source_range
-
opts(str)
-
end
-
-
# Concatenates two string literals or string interpolation expressions.
-
#
-
# @param string_or_interp1 [Sass::Script::Tree::Literal|Sass::Script::Tree::StringInterpolation]
-
# @param string_or_interp2 [Sass::Script::Tree::Literal|Sass::Script::Tree::StringInterpolation]
-
# @return [Sass::Script::Tree::StringInterpolation]
-
1
def concat(string_or_interp1, string_or_interp2)
-
if string_or_interp1.is_a?(Literal) && string_or_interp2.is_a?(Literal)
-
return string_literal(string_or_interp1.value.value + string_or_interp2.value.value)
-
end
-
-
if string_or_interp1.is_a?(Literal)
-
string = string_or_interp1
-
interp = string_or_interp2
-
before = string_literal(string.value.value + interp.before.value.value)
-
return StringInterpolation.new(before, interp.mid, interp.after)
-
end
-
-
StringInterpolation.new(
-
string_or_interp1.before,
-
string_or_interp1.mid,
-
concat(string_or_interp1.after, string_or_interp2))
-
end
-
-
# Returns a string literal with the given contents.
-
#
-
# @param string [String]
-
# @return string [Sass::Script::Tree::Literal]
-
1
def string_literal(string)
-
Literal.new(Sass::Script::Value::String.new(string, :string))
-
end
-
end
-
end
-
1
module Sass::Script::Tree
-
# A parse tree node representing a list literal. When resolved, this returns a
-
# {Sass::Tree::Value::List}.
-
1
class ListLiteral < Node
-
# The parse nodes for members of this list.
-
#
-
# @return [Array<Node>]
-
1
attr_reader :elements
-
-
# The operator separating the values of the list. Either `:comma` or
-
# `:space`.
-
#
-
# @return [Symbol]
-
1
attr_reader :separator
-
-
# Whether the list is surrounded by square brackets.
-
#
-
# @return [Boolean]
-
1
attr_reader :bracketed
-
-
# Creates a new list literal.
-
#
-
# @param elements [Array<Node>] See \{#elements}
-
# @param separator [Symbol] See \{#separator}
-
# @param bracketed [Boolean] See \{#bracketed}
-
1
def initialize(elements, separator: nil, bracketed: false)
-
@elements = elements
-
@separator = separator
-
@bracketed = bracketed
-
end
-
-
# @see Node#children
-
1
def children; elements; end
-
-
# @see Value#to_sass
-
1
def to_sass(opts = {})
-
return bracketed ? "[]" : "()" if elements.empty?
-
members = elements.map do |v|
-
if element_needs_parens?(v)
-
"(#{v.to_sass(opts)})"
-
else
-
v.to_sass(opts)
-
end
-
end
-
-
if separator == :comma && members.length == 1
-
return "#{bracketed ? '[' : '('}#{members.first},#{bracketed ? ']' : ')'}"
-
end
-
-
contents = members.join(sep_str(nil))
-
bracketed ? "[#{contents}]" : contents
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@elements', elements.map {|e| e.deep_copy})
-
node
-
end
-
-
1
def inspect
-
(bracketed ? '[' : '(') +
-
elements.map {|e| e.inspect}.join(separator == :space ? ' ' : ', ') +
-
(bracketed ? ']' : ')')
-
end
-
-
1
def force_division!
-
# Do nothing. Lists prevent division propagation.
-
end
-
-
1
protected
-
-
1
def _perform(environment)
-
list = Sass::Script::Value::List.new(
-
elements.map {|e| e.perform(environment)},
-
separator: separator,
-
bracketed: bracketed)
-
list.source_range = source_range
-
list.options = options
-
list
-
end
-
-
1
private
-
-
# Returns whether an element in the list should be wrapped in parentheses
-
# when serialized to Sass.
-
1
def element_needs_parens?(element)
-
if element.is_a?(ListLiteral)
-
return false if element.elements.length < 2
-
return false if element.bracketed
-
return Sass::Script::Parser.precedence_of(element.separator || :space) <=
-
Sass::Script::Parser.precedence_of(separator || :space)
-
end
-
-
return false unless separator == :space
-
-
if element.is_a?(UnaryOperation)
-
return element.operator == :minus || element.operator == :plus
-
end
-
-
return false unless element.is_a?(Operation)
-
return true unless element.operator == :div
-
!(is_literal_number?(element.operand1) && is_literal_number?(element.operand2))
-
end
-
-
# Returns whether a value is a number literal that shouldn't be divided.
-
1
def is_literal_number?(value)
-
value.is_a?(Literal) &&
-
value.value.is_a?((Sass::Script::Value::Number)) &&
-
!value.value.original.nil?
-
end
-
-
1
def sep_str(opts = options)
-
return ' ' if separator == :space
-
return ',' if opts && opts[:style] == :compressed
-
', '
-
end
-
end
-
end
-
1
module Sass::Script::Tree
-
# The parse tree node for a literal scalar value. This wraps an instance of
-
# {Sass::Script::Value::Base}.
-
#
-
# List literals should use {ListLiteral} instead.
-
1
class Literal < Node
-
# The wrapped value.
-
#
-
# @return [Sass::Script::Value::Base]
-
1
attr_reader :value
-
-
# Creates a new literal value.
-
#
-
# @param value [Sass::Script::Value::Base]
-
# @see #value
-
1
def initialize(value)
-
@value = value
-
end
-
-
# @see Node#children
-
1
def children; []; end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {}); value.to_sass(opts); end
-
-
# @see Node#deep_copy
-
1
def deep_copy; dup; end
-
-
# @see Node#options=
-
1
def options=(options)
-
value.options = options
-
end
-
-
1
def inspect
-
value.inspect
-
end
-
-
1
def force_division!
-
value.original = nil if value.is_a?(Sass::Script::Value::Number)
-
end
-
-
1
protected
-
-
1
def _perform(environment)
-
value.source_range = source_range
-
value
-
end
-
end
-
end
-
1
module Sass::Script::Tree
-
# A class representing a map literal. When resolved, this returns a
-
# {Sass::Script::Node::Map}.
-
1
class MapLiteral < Node
-
# The key/value pairs that make up this map node. This isn't a Hash so that
-
# we can detect key collisions once all the keys have been performed.
-
#
-
# @return [Array<(Node, Node)>]
-
1
attr_reader :pairs
-
-
# Creates a new map literal.
-
#
-
# @param pairs [Array<(Node, Node)>] See \{#pairs}
-
1
def initialize(pairs)
-
@pairs = pairs
-
end
-
-
# @see Node#children
-
1
def children
-
@pairs.flatten
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
return "()" if pairs.empty?
-
-
to_sass = lambda do |value|
-
if value.is_a?(ListLiteral) && value.separator == :comma
-
"(#{value.to_sass(opts)})"
-
else
-
value.to_sass(opts)
-
end
-
end
-
-
"(" + pairs.map {|(k, v)| "#{to_sass[k]}: #{to_sass[v]}"}.join(', ') + ")"
-
end
-
1
alias_method :inspect, :to_sass
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@pairs',
-
pairs.map {|(k, v)| [k.deep_copy, v.deep_copy]})
-
node
-
end
-
-
1
protected
-
-
# @see Node#_perform
-
1
def _perform(environment)
-
keys = Set.new
-
map = Sass::Script::Value::Map.new(Hash[pairs.map do |(k, v)|
-
k, v = k.perform(environment), v.perform(environment)
-
if keys.include?(k)
-
raise Sass::SyntaxError.new("Duplicate key #{k.inspect} in map #{to_sass}.")
-
end
-
keys << k
-
[k, v]
-
end])
-
map.options = options
-
map
-
end
-
end
-
end
-
1
module Sass::Script::Tree
-
# A SassScript parse node representing a binary operation,
-
# such as `$a + $b` or `"foo" + 1`.
-
1
class Operation < Node
-
1
@@color_arithmetic_deprecation = Sass::Deprecation.new
-
1
@@unitless_equals_deprecation = Sass::Deprecation.new
-
-
1
attr_reader :operand1
-
1
attr_reader :operand2
-
1
attr_reader :operator
-
-
# @param operand1 [Sass::Script::Tree::Node] The parse-tree node
-
# for the right-hand side of the operator
-
# @param operand2 [Sass::Script::Tree::Node] The parse-tree node
-
# for the left-hand side of the operator
-
# @param operator [Symbol] The operator to perform.
-
# This should be one of the binary operator names in {Sass::Script::Lexer::OPERATORS}
-
1
def initialize(operand1, operand2, operator)
-
@operand1 = operand1
-
@operand2 = operand2
-
@operator = operator
-
super()
-
end
-
-
# @return [String] A human-readable s-expression representation of the operation
-
1
def inspect
-
"(#{@operator.inspect} #{@operand1.inspect} #{@operand2.inspect})"
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
o1 = operand_to_sass @operand1, :left, opts
-
o2 = operand_to_sass @operand2, :right, opts
-
sep =
-
case @operator
-
when :comma; ", "
-
when :space; " "
-
else; " #{Sass::Script::Lexer::OPERATORS_REVERSE[@operator]} "
-
end
-
"#{o1}#{sep}#{o2}"
-
end
-
-
# Returns the operands for this operation.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
1
def children
-
[@operand1, @operand2]
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@operand1', @operand1.deep_copy)
-
node.instance_variable_set('@operand2', @operand2.deep_copy)
-
node
-
end
-
-
1
protected
-
-
# Evaluates the operation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::Value] The SassScript object that is the value of the operation
-
# @raise [Sass::SyntaxError] if the operation is undefined for the operands
-
1
def _perform(environment)
-
value1 = @operand1.perform(environment)
-
-
# Special-case :and and :or to support short-circuiting.
-
if @operator == :and
-
return value1.to_bool ? @operand2.perform(environment) : value1
-
elsif @operator == :or
-
return value1.to_bool ? value1 : @operand2.perform(environment)
-
end
-
-
value2 = @operand2.perform(environment)
-
-
if (value1.is_a?(Sass::Script::Value::Null) || value2.is_a?(Sass::Script::Value::Null)) &&
-
@operator != :eq && @operator != :neq
-
raise Sass::SyntaxError.new(
-
"Invalid null operation: \"#{value1.inspect} #{@operator} #{value2.inspect}\".")
-
end
-
-
begin
-
result = opts(value1.send(@operator, value2))
-
rescue NoMethodError => e
-
raise e unless e.name.to_s == @operator.to_s
-
raise Sass::SyntaxError.new("Undefined operation: \"#{value1} #{@operator} #{value2}\".")
-
end
-
-
warn_for_color_arithmetic(value1, value2)
-
warn_for_unitless_equals(value1, value2, result)
-
-
result
-
end
-
-
1
private
-
-
1
def warn_for_color_arithmetic(value1, value2)
-
return unless @operator == :plus || @operator == :times || @operator == :minus ||
-
@operator == :div || @operator == :mod
-
-
if value1.is_a?(Sass::Script::Value::Number)
-
return unless value2.is_a?(Sass::Script::Value::Color)
-
elsif value1.is_a?(Sass::Script::Value::Color)
-
return unless value2.is_a?(Sass::Script::Value::Color) || value2.is_a?(Sass::Script::Value::Number)
-
else
-
return
-
end
-
-
@@color_arithmetic_deprecation.warn(filename, line, <<WARNING)
-
The operation `#{value1} #{@operator} #{value2}` is deprecated and will be an error in future versions.
-
Consider using Sass's color functions instead.
-
http://sass-lang.com/documentation/Sass/Script/Functions.html#other_color_functions
-
WARNING
-
end
-
-
1
def warn_for_unitless_equals(value1, value2, result)
-
return unless @operator == :eq || @operator == :neq
-
return unless value1.is_a?(Sass::Script::Value::Number)
-
return unless value2.is_a?(Sass::Script::Value::Number)
-
return unless value1.unitless? != value2.unitless?
-
return unless result == (if @operator == :eq
-
Sass::Script::Value::Bool::TRUE
-
else
-
Sass::Script::Value::Bool::FALSE
-
end)
-
-
operation = "#{value1.to_sass} #{@operator == :eq ? '==' : '!='} #{value2.to_sass}"
-
future_value = @operator == :neq
-
@@unitless_equals_deprecation.warn(filename, line, <<WARNING)
-
The result of `#{operation}` will be `#{future_value}` in future releases of Sass.
-
Unitless numbers will no longer be equal to the same numbers with units.
-
WARNING
-
end
-
-
1
def operand_to_sass(op, side, opts)
-
return "(#{op.to_sass(opts)})" if op.is_a?(Sass::Script::Tree::ListLiteral)
-
return op.to_sass(opts) unless op.is_a?(Operation)
-
-
pred = Sass::Script::Parser.precedence_of(@operator)
-
sub_pred = Sass::Script::Parser.precedence_of(op.operator)
-
assoc = Sass::Script::Parser.associative?(@operator)
-
return "(#{op.to_sass(opts)})" if sub_pred < pred ||
-
(side == :right && sub_pred == pred && !assoc)
-
op.to_sass(opts)
-
end
-
end
-
end
-
1
module Sass::Script::Tree
-
# A SassScript node that will resolve to the current selector.
-
1
class Selector < Node
-
1
def initialize; end
-
-
1
def children
-
[]
-
end
-
-
1
def to_sass(opts = {})
-
'&'
-
end
-
-
1
def deep_copy
-
dup
-
end
-
-
1
protected
-
-
1
def _perform(environment)
-
selector = environment.selector
-
return opts(Sass::Script::Value::Null.new) unless selector
-
opts(selector.to_sass_script)
-
end
-
end
-
end
-
1
module Sass::Script::Tree
-
# A SassScript object representing `#{}` interpolation within a string.
-
#
-
# @see Interpolation
-
1
class StringInterpolation < Node
-
# @return [Literal] The string literal before this interpolation.
-
1
attr_reader :before
-
-
# @return [Node] The SassScript within the interpolation
-
1
attr_reader :mid
-
-
# @return [StringInterpolation, Literal]
-
# The string literal or string interpolation before this interpolation.
-
1
attr_reader :after
-
-
# Whether this is a CSS string or a CSS identifier. The difference is that
-
# strings are written with double-quotes, while identifiers aren't.
-
#
-
# String interpolations are only ever identifiers if they're quote-like
-
# functions such as `url()`.
-
#
-
# @return [Symbol] `:string` or `:identifier`
-
1
def type
-
@before.value.type
-
end
-
-
# Returns the quote character that should be used to wrap a Sass
-
# representation of this interpolation.
-
1
def quote
-
quote_for(self) || '"'
-
end
-
-
# Interpolation in a string is of the form `"before #{mid} after"`,
-
# where `before` and `after` may include more interpolation.
-
#
-
# @param before [StringInterpolation, Literal] See {StringInterpolation#before}
-
# @param mid [Node] See {StringInterpolation#mid}
-
# @param after [Literal] See {StringInterpolation#after}
-
1
def initialize(before, mid, after)
-
@before = before
-
@mid = mid
-
@after = after
-
end
-
-
# @return [String] A human-readable s-expression representation of the interpolation
-
1
def inspect
-
"(string_interpolation #{@before.inspect} #{@mid.inspect} #{@after.inspect})"
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
quote = type == :string ? opts[:quote] || quote_for(self) || '"' : :none
-
opts = opts.merge(:quote => quote)
-
-
res = ""
-
res << quote if quote != :none
-
res << _to_sass(before, opts)
-
res << '#{' << @mid.to_sass(opts.merge(:quote => nil)) << '}'
-
res << _to_sass(after, opts)
-
res << quote if quote != :none
-
res
-
end
-
-
# Returns the three components of the interpolation, `before`, `mid`, and `after`.
-
#
-
# @return [Array<Node>]
-
# @see #initialize
-
# @see Node#children
-
1
def children
-
[@before, @mid, @after].compact
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@before', @before.deep_copy) if @before
-
node.instance_variable_set('@mid', @mid.deep_copy)
-
node.instance_variable_set('@after', @after.deep_copy) if @after
-
node
-
end
-
-
1
protected
-
-
# Evaluates the interpolation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::Value::String]
-
# The SassScript string that is the value of the interpolation
-
1
def _perform(environment)
-
res = ""
-
before = @before.perform(environment)
-
res << before.value
-
mid = @mid.perform(environment)
-
res << (mid.is_a?(Sass::Script::Value::String) ? mid.value : mid.to_s(:quote => :none))
-
res << @after.perform(environment).value
-
opts(Sass::Script::Value::String.new(res, before.type))
-
end
-
-
1
private
-
-
1
def _to_sass(string_or_interp, opts)
-
result = string_or_interp.to_sass(opts)
-
opts[:quote] == :none ? result : result.slice(1...-1)
-
end
-
-
1
def quote_for(string_or_interp)
-
if string_or_interp.is_a?(Sass::Script::Tree::Literal)
-
return nil if string_or_interp.value.value.empty?
-
return '"' if string_or_interp.value.value.include?("'")
-
return "'" if string_or_interp.value.value.include?('"')
-
return nil
-
end
-
-
# Double-quotes take precedence over single quotes.
-
before_quote = quote_for(string_or_interp.before)
-
return '"' if before_quote == '"'
-
after_quote = quote_for(string_or_interp.after)
-
return '"' if after_quote == '"'
-
-
# Returns "'" if either or both insist on single quotes, and nil
-
# otherwise.
-
before_quote || after_quote
-
end
-
end
-
end
-
1
module Sass::Script::Tree
-
# A SassScript parse node representing a unary operation,
-
# such as `-$b` or `not true`.
-
#
-
# Currently only `-`, `/`, and `not` are unary operators.
-
1
class UnaryOperation < Node
-
# @return [Symbol] The operation to perform
-
1
attr_reader :operator
-
-
# @return [Script::Node] The parse-tree node for the object of the operator
-
1
attr_reader :operand
-
-
# @param operand [Script::Node] See \{#operand}
-
# @param operator [Symbol] See \{#operator}
-
1
def initialize(operand, operator)
-
@operand = operand
-
@operator = operator
-
super()
-
end
-
-
# @return [String] A human-readable s-expression representation of the operation
-
1
def inspect
-
"(#{@operator.inspect} #{@operand.inspect})"
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
operand = @operand.to_sass(opts)
-
if @operand.is_a?(Operation) ||
-
(@operator == :minus &&
-
(operand =~ Sass::SCSS::RX::IDENT) == 0)
-
operand = "(#{@operand.to_sass(opts)})"
-
end
-
op = Sass::Script::Lexer::OPERATORS_REVERSE[@operator]
-
op + (op =~ /[a-z]/ ? " " : "") + operand
-
end
-
-
# Returns the operand of the operation.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
1
def children
-
[@operand]
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@operand', @operand.deep_copy)
-
node
-
end
-
-
1
protected
-
-
# Evaluates the operation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::Value] The SassScript object that is the value of the operation
-
# @raise [Sass::SyntaxError] if the operation is undefined for the operand
-
1
def _perform(environment)
-
operator = "unary_#{@operator}"
-
value = @operand.perform(environment)
-
value.send(operator)
-
rescue NoMethodError => e
-
raise e unless e.name.to_s == operator.to_s
-
raise Sass::SyntaxError.new("Undefined unary operation: \"#{@operator} #{value}\".")
-
end
-
end
-
end
-
1
module Sass::Script::Tree
-
# A SassScript parse node representing a variable.
-
1
class Variable < Node
-
# The name of the variable.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# The underscored name of the variable.
-
#
-
# @return [String]
-
1
attr_reader :underscored_name
-
-
# @param name [String] See \{#name}
-
1
def initialize(name)
-
@name = name
-
@underscored_name = name.tr("-", "_")
-
super()
-
end
-
-
# @return [String] A string representation of the variable
-
1
def inspect(opts = {})
-
"$#{dasherize(name, opts)}"
-
end
-
1
alias_method :to_sass, :inspect
-
-
# Returns an empty array.
-
#
-
# @return [Array<Node>] empty
-
# @see Node#children
-
1
def children
-
[]
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
dup
-
end
-
-
1
protected
-
-
# Evaluates the variable.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::Value] The SassScript object that is the value of the variable
-
# @raise [Sass::SyntaxError] if the variable is undefined
-
1
def _perform(environment)
-
val = environment.var(name)
-
raise Sass::SyntaxError.new("Undefined variable: \"$#{name}\".") unless val
-
if val.is_a?(Sass::Script::Value::Number) && val.original
-
val = val.dup
-
val.original = nil
-
end
-
val
-
end
-
end
-
end
-
1
module Sass::Script::Value; end
-
-
1
require 'sass/script/value/base'
-
1
require 'sass/script/value/string'
-
1
require 'sass/script/value/number'
-
1
require 'sass/script/value/color'
-
1
require 'sass/script/value/bool'
-
1
require 'sass/script/value/null'
-
1
require 'sass/script/value/list'
-
1
require 'sass/script/value/arg_list'
-
1
require 'sass/script/value/map'
-
1
require 'sass/script/value/callable'
-
1
require 'sass/script/value/function'
-
1
module Sass::Script::Value
-
# A SassScript object representing a variable argument list. This works just
-
# like a normal list, but can also contain keyword arguments.
-
#
-
# The keyword arguments attached to this list are unused except when this is
-
# passed as a glob argument to a function or mixin.
-
1
class ArgList < List
-
# Whether \{#keywords} has been accessed. If so, we assume that all keywords
-
# were valid for the function that created this ArgList.
-
#
-
# @return [Boolean]
-
1
attr_accessor :keywords_accessed
-
-
# Creates a new argument list.
-
#
-
# @param value [Array<Value>] See \{List#value}.
-
# @param keywords [Hash<String, Value>, NormalizedMap<Value>] See \{#keywords}
-
# @param separator [String] See \{List#separator}.
-
1
def initialize(value, keywords, separator)
-
super(value, separator: separator)
-
if keywords.is_a?(Sass::Util::NormalizedMap)
-
@keywords = keywords
-
else
-
@keywords = Sass::Util::NormalizedMap.new(keywords)
-
end
-
end
-
-
# The keyword arguments attached to this list.
-
#
-
# @return [NormalizedMap<Value>]
-
1
def keywords
-
@keywords_accessed = true
-
@keywords
-
end
-
end
-
end
-
1
module Sass::Script::Value
-
# The abstract superclass for SassScript objects.
-
#
-
# Many of these methods, especially the ones that correspond to SassScript operations,
-
# are designed to be overridden by subclasses which may change the semantics somewhat.
-
# The operations listed here are just the defaults.
-
1
class Base
-
# Returns the Ruby value of the value.
-
# The type of this value varies based on the subclass.
-
#
-
# @return [Object]
-
1
attr_reader :value
-
-
# The source range in the document on which this node appeared.
-
#
-
# @return [Sass::Source::Range]
-
1
attr_accessor :source_range
-
-
# Creates a new value.
-
#
-
# @param value [Object] The object for \{#value}
-
1
def initialize(value = nil)
-
3
value.freeze unless value.nil? || value == true || value == false
-
3
@value = value
-
3
@options = nil
-
end
-
-
# Sets the options hash for this node,
-
# as well as for all child nodes.
-
# See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
-
#
-
# @param options [{Symbol => Object}] The options
-
1
attr_writer :options
-
-
# Returns the options hash for this node.
-
#
-
# @return [{Symbol => Object}]
-
# @raise [Sass::SyntaxError] if the options hash hasn't been set.
-
# This should only happen when the value was created
-
# outside of the parser and \{#to\_s} was called on it
-
1
def options
-
return @options if @options
-
raise Sass::SyntaxError.new(<<MSG)
-
The #options attribute is not set on this #{self.class}.
-
This error is probably occurring because #to_s was called
-
on this value within a custom Sass function without first
-
setting the #options attribute.
-
MSG
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Value::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Sass::Script::Value::Bool] True if this value is the same as the other,
-
# false otherwise
-
1
def eq(other)
-
Sass::Script::Value::Bool.new(self.class == other.class && value == other.value)
-
end
-
-
# The SassScript `!=` operation.
-
# **Note that this returns a {Sass::Script::Value::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Sass::Script::Value::Bool] False if this value is the same as the other,
-
# true otherwise
-
1
def neq(other)
-
Sass::Script::Value::Bool.new(!eq(other).to_bool)
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Value::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Sass::Script::Value::Bool] True if this value is the same as the other,
-
# false otherwise
-
1
def unary_not
-
Sass::Script::Value::Bool.new(!to_bool)
-
end
-
-
# The SassScript `=` operation
-
# (used for proprietary MS syntax like `alpha(opacity=20)`).
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Script::Value::String] A string containing both values
-
# separated by `"="`
-
1
def single_eq(other)
-
Sass::Script::Value::String.new("#{self}=#{other}")
-
end
-
-
# The SassScript `+` operation.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Script::Value::String] A string containing both values
-
# without any separation
-
1
def plus(other)
-
type = other.is_a?(Sass::Script::Value::String) ? other.type : :identifier
-
Sass::Script::Value::String.new(to_s(:quote => :none) + other.to_s(:quote => :none), type)
-
end
-
-
# The SassScript `-` operation.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Script::Value::String] A string containing both values
-
# separated by `"-"`
-
1
def minus(other)
-
Sass::Script::Value::String.new("#{self}-#{other}")
-
end
-
-
# The SassScript `/` operation.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Script::Value::String] A string containing both values
-
# separated by `"/"`
-
1
def div(other)
-
Sass::Script::Value::String.new("#{self}/#{other}")
-
end
-
-
# The SassScript unary `+` operation (e.g. `+$a`).
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Script::Value::String] A string containing the value
-
# preceded by `"+"`
-
1
def unary_plus
-
Sass::Script::Value::String.new("+#{self}")
-
end
-
-
# The SassScript unary `-` operation (e.g. `-$a`).
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Script::Value::String] A string containing the value
-
# preceded by `"-"`
-
1
def unary_minus
-
Sass::Script::Value::String.new("-#{self}")
-
end
-
-
# The SassScript unary `/` operation (e.g. `/$a`).
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Script::Value::String] A string containing the value
-
# preceded by `"/"`
-
1
def unary_div
-
Sass::Script::Value::String.new("/#{self}")
-
end
-
-
# Returns the hash code of this value. Two objects' hash codes should be
-
# equal if the objects are equal.
-
#
-
# @return [Integer for Ruby 2.4.0+, Fixnum for earlier Ruby versions] The hash code.
-
1
def hash
-
value.hash
-
end
-
-
1
def eql?(other)
-
self == other
-
end
-
-
# @return [String] A readable representation of the value
-
1
def inspect
-
value.inspect
-
end
-
-
# @return [Boolean] `true` (the Ruby boolean value)
-
1
def to_bool
-
true
-
end
-
-
# Compares this object with another.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this value is equivalent to `other`
-
1
def ==(other)
-
eq(other).to_bool
-
end
-
-
# @return [Integer] The integer value of this value
-
# @raise [Sass::SyntaxError] if this value isn't an integer
-
1
def to_i
-
raise Sass::SyntaxError.new("#{inspect} is not an integer.")
-
end
-
-
# @raise [Sass::SyntaxError] if this value isn't an integer
-
1
def assert_int!; to_i; end
-
-
# Returns the separator for this value. For non-list-like values or the
-
# empty list, this will be `nil`. For lists or maps, it will be `:space` or
-
# `:comma`.
-
#
-
# @return [Symbol]
-
1
def separator; nil; end
-
-
# Whether the value is surrounded by square brackets. For non-list values,
-
# this will be `false`.
-
#
-
# @return [Boolean]
-
1
def bracketed; false; end
-
-
# Returns the value of this value as a list.
-
# Single values are considered the same as single-element lists.
-
#
-
# @return [Array<Value>] This value as a list
-
1
def to_a
-
[self]
-
end
-
-
# Returns the value of this value as a hash. Most values don't have hash
-
# representations, but [Map]s and empty [List]s do.
-
#
-
# @return [Hash<Value, Value>] This value as a hash
-
# @raise [Sass::SyntaxError] if this value doesn't have a hash representation
-
1
def to_h
-
raise Sass::SyntaxError.new("#{inspect} is not a map.")
-
end
-
-
# Returns the string representation of this value
-
# as it would be output to the CSS document.
-
#
-
# @options opts :quote [String]
-
# The preferred quote style for quoted strings. If `:none`, strings are
-
# always emitted unquoted.
-
# @return [String]
-
1
def to_s(opts = {})
-
Sass::Util.abstract(self)
-
end
-
1
alias_method :to_sass, :to_s
-
-
# Returns whether or not this object is null.
-
#
-
# @return [Boolean] `false`
-
1
def null?
-
false
-
end
-
-
# Creates a new list containing `contents` but with the same brackets and
-
# separators as this object, when interpreted as a list.
-
#
-
# @param contents [Array<Value>] The contents of the new list.
-
# @param separator [Symbol] The separator of the new list. Defaults to \{#separator}.
-
# @param bracketed [Boolean] Whether the new list is bracketed. Defaults to \{#bracketed}.
-
# @return [Sass::Script::Value::List]
-
1
def with_contents(contents, separator: self.separator, bracketed: self.bracketed)
-
Sass::Script::Value::List.new(contents, separator: separator, bracketed: bracketed)
-
end
-
-
1
protected
-
-
# Evaluates the value.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Value] This value
-
1
def _perform(environment)
-
self
-
end
-
end
-
end
-
1
module Sass::Script::Value
-
# A SassScript object representing a boolean (true or false) value.
-
1
class Bool < Base
-
# The true value in SassScript.
-
#
-
# This is assigned before new is overridden below so that we use the default implementation.
-
1
TRUE = new(true)
-
-
# The false value in SassScript.
-
#
-
# This is assigned before new is overridden below so that we use the default implementation.
-
1
FALSE = new(false)
-
-
# We override object creation so that users of the core API
-
# will not need to know that booleans are specific constants.
-
#
-
# @param value A ruby value that will be tested for truthiness.
-
# @return [Bool] TRUE if value is truthy, FALSE if value is falsey
-
1
def self.new(value)
-
value ? TRUE : FALSE
-
end
-
-
# The Ruby value of the boolean.
-
#
-
# @return [Boolean]
-
1
attr_reader :value
-
1
alias_method :to_bool, :value
-
-
# @return [String] "true" or "false"
-
1
def to_s(opts = {})
-
@value.to_s
-
end
-
1
alias_method :to_sass, :to_s
-
end
-
end
-
1
module Sass::Script::Value
-
# A SassScript object representing a null value.
-
1
class Callable < Base
-
# Constructs a Callable value for use in SassScript.
-
#
-
# @param callable [Sass::Callable] The callable to be used when the
-
# callable is called.
-
1
def initialize(callable)
-
super(callable)
-
end
-
-
1
def to_s(opts = {})
-
raise Sass::SyntaxError.new("#{to_sass} isn't a valid CSS value.")
-
end
-
-
1
def inspect
-
to_sass
-
end
-
-
# @abstract
-
1
def to_sass
-
Sass::Util.abstract(self)
-
end
-
end
-
end
-
1
module Sass::Script::Value
-
# A SassScript object representing a CSS color.
-
#
-
# A color may be represented internally as RGBA, HSLA, or both.
-
# It's originally represented as whatever its input is;
-
# if it's created with RGB values, it's represented as RGBA,
-
# and if it's created with HSL values, it's represented as HSLA.
-
# Once a property is accessed that requires the other representation --
-
# for example, \{#red} for an HSL color --
-
# that component is calculated and cached.
-
#
-
# The alpha channel of a color is independent of its RGB or HSL representation.
-
# It's always stored, as 1 if nothing else is specified.
-
# If only the alpha channel is modified using \{#with},
-
# the cached RGB and HSL values are retained.
-
1
class Color < Base
-
# @private
-
#
-
# Convert a ruby integer to a rgba components
-
# @param color [Integer]
-
# @return [Array<Integer>] Array of 4 numbers representing r,g,b and alpha
-
1
def self.int_to_rgba(color)
-
745
rgba = (0..3).map {|n| color >> (n << 3) & 0xff}.reverse
-
149
rgba[-1] = rgba[-1] / 255.0
-
149
rgba
-
end
-
-
1
ALTERNATE_COLOR_NAMES = Sass::Util.map_vals(
-
{
-
'aqua' => 0x00FFFFFF,
-
'darkgrey' => 0xA9A9A9FF,
-
'darkslategrey' => 0x2F4F4FFF,
-
'dimgrey' => 0x696969FF,
-
'fuchsia' => 0xFF00FFFF,
-
'grey' => 0x808080FF,
-
'lightgrey' => 0xD3D3D3FF,
-
'lightslategrey' => 0x778899FF,
-
'slategrey' => 0x708090FF,
-
}, &method(:int_to_rgba))
-
-
# A hash from color names to `[red, green, blue]` value arrays.
-
1
COLOR_NAMES = Sass::Util.map_vals(
-
{
-
'aliceblue' => 0xF0F8FFFF,
-
'antiquewhite' => 0xFAEBD7FF,
-
'aquamarine' => 0x7FFFD4FF,
-
'azure' => 0xF0FFFFFF,
-
'beige' => 0xF5F5DCFF,
-
'bisque' => 0xFFE4C4FF,
-
'black' => 0x000000FF,
-
'blanchedalmond' => 0xFFEBCDFF,
-
'blue' => 0x0000FFFF,
-
'blueviolet' => 0x8A2BE2FF,
-
'brown' => 0xA52A2AFF,
-
'burlywood' => 0xDEB887FF,
-
'cadetblue' => 0x5F9EA0FF,
-
'chartreuse' => 0x7FFF00FF,
-
'chocolate' => 0xD2691EFF,
-
'coral' => 0xFF7F50FF,
-
'cornflowerblue' => 0x6495EDFF,
-
'cornsilk' => 0xFFF8DCFF,
-
'crimson' => 0xDC143CFF,
-
'cyan' => 0x00FFFFFF,
-
'darkblue' => 0x00008BFF,
-
'darkcyan' => 0x008B8BFF,
-
'darkgoldenrod' => 0xB8860BFF,
-
'darkgray' => 0xA9A9A9FF,
-
'darkgreen' => 0x006400FF,
-
'darkkhaki' => 0xBDB76BFF,
-
'darkmagenta' => 0x8B008BFF,
-
'darkolivegreen' => 0x556B2FFF,
-
'darkorange' => 0xFF8C00FF,
-
'darkorchid' => 0x9932CCFF,
-
'darkred' => 0x8B0000FF,
-
'darksalmon' => 0xE9967AFF,
-
'darkseagreen' => 0x8FBC8FFF,
-
'darkslateblue' => 0x483D8BFF,
-
'darkslategray' => 0x2F4F4FFF,
-
'darkturquoise' => 0x00CED1FF,
-
'darkviolet' => 0x9400D3FF,
-
'deeppink' => 0xFF1493FF,
-
'deepskyblue' => 0x00BFFFFF,
-
'dimgray' => 0x696969FF,
-
'dodgerblue' => 0x1E90FFFF,
-
'firebrick' => 0xB22222FF,
-
'floralwhite' => 0xFFFAF0FF,
-
'forestgreen' => 0x228B22FF,
-
'gainsboro' => 0xDCDCDCFF,
-
'ghostwhite' => 0xF8F8FFFF,
-
'gold' => 0xFFD700FF,
-
'goldenrod' => 0xDAA520FF,
-
'gray' => 0x808080FF,
-
'green' => 0x008000FF,
-
'greenyellow' => 0xADFF2FFF,
-
'honeydew' => 0xF0FFF0FF,
-
'hotpink' => 0xFF69B4FF,
-
'indianred' => 0xCD5C5CFF,
-
'indigo' => 0x4B0082FF,
-
'ivory' => 0xFFFFF0FF,
-
'khaki' => 0xF0E68CFF,
-
'lavender' => 0xE6E6FAFF,
-
'lavenderblush' => 0xFFF0F5FF,
-
'lawngreen' => 0x7CFC00FF,
-
'lemonchiffon' => 0xFFFACDFF,
-
'lightblue' => 0xADD8E6FF,
-
'lightcoral' => 0xF08080FF,
-
'lightcyan' => 0xE0FFFFFF,
-
'lightgoldenrodyellow' => 0xFAFAD2FF,
-
'lightgreen' => 0x90EE90FF,
-
'lightgray' => 0xD3D3D3FF,
-
'lightpink' => 0xFFB6C1FF,
-
'lightsalmon' => 0xFFA07AFF,
-
'lightseagreen' => 0x20B2AAFF,
-
'lightskyblue' => 0x87CEFAFF,
-
'lightslategray' => 0x778899FF,
-
'lightsteelblue' => 0xB0C4DEFF,
-
'lightyellow' => 0xFFFFE0FF,
-
'lime' => 0x00FF00FF,
-
'limegreen' => 0x32CD32FF,
-
'linen' => 0xFAF0E6FF,
-
'magenta' => 0xFF00FFFF,
-
'maroon' => 0x800000FF,
-
'mediumaquamarine' => 0x66CDAAFF,
-
'mediumblue' => 0x0000CDFF,
-
'mediumorchid' => 0xBA55D3FF,
-
'mediumpurple' => 0x9370DBFF,
-
'mediumseagreen' => 0x3CB371FF,
-
'mediumslateblue' => 0x7B68EEFF,
-
'mediumspringgreen' => 0x00FA9AFF,
-
'mediumturquoise' => 0x48D1CCFF,
-
'mediumvioletred' => 0xC71585FF,
-
'midnightblue' => 0x191970FF,
-
'mintcream' => 0xF5FFFAFF,
-
'mistyrose' => 0xFFE4E1FF,
-
'moccasin' => 0xFFE4B5FF,
-
'navajowhite' => 0xFFDEADFF,
-
'navy' => 0x000080FF,
-
'oldlace' => 0xFDF5E6FF,
-
'olive' => 0x808000FF,
-
'olivedrab' => 0x6B8E23FF,
-
'orange' => 0xFFA500FF,
-
'orangered' => 0xFF4500FF,
-
'orchid' => 0xDA70D6FF,
-
'palegoldenrod' => 0xEEE8AAFF,
-
'palegreen' => 0x98FB98FF,
-
'paleturquoise' => 0xAFEEEEFF,
-
'palevioletred' => 0xDB7093FF,
-
'papayawhip' => 0xFFEFD5FF,
-
'peachpuff' => 0xFFDAB9FF,
-
'peru' => 0xCD853FFF,
-
'pink' => 0xFFC0CBFF,
-
'plum' => 0xDDA0DDFF,
-
'powderblue' => 0xB0E0E6FF,
-
'purple' => 0x800080FF,
-
'red' => 0xFF0000FF,
-
'rebeccapurple' => 0x663399FF,
-
'rosybrown' => 0xBC8F8FFF,
-
'royalblue' => 0x4169E1FF,
-
'saddlebrown' => 0x8B4513FF,
-
'salmon' => 0xFA8072FF,
-
'sandybrown' => 0xF4A460FF,
-
'seagreen' => 0x2E8B57FF,
-
'seashell' => 0xFFF5EEFF,
-
'sienna' => 0xA0522DFF,
-
'silver' => 0xC0C0C0FF,
-
'skyblue' => 0x87CEEBFF,
-
'slateblue' => 0x6A5ACDFF,
-
'slategray' => 0x708090FF,
-
'snow' => 0xFFFAFAFF,
-
'springgreen' => 0x00FF7FFF,
-
'steelblue' => 0x4682B4FF,
-
'tan' => 0xD2B48CFF,
-
'teal' => 0x008080FF,
-
'thistle' => 0xD8BFD8FF,
-
'tomato' => 0xFF6347FF,
-
'transparent' => 0x00000000,
-
'turquoise' => 0x40E0D0FF,
-
'violet' => 0xEE82EEFF,
-
'wheat' => 0xF5DEB3FF,
-
'white' => 0xFFFFFFFF,
-
'whitesmoke' => 0xF5F5F5FF,
-
'yellow' => 0xFFFF00FF,
-
'yellowgreen' => 0x9ACD32FF
-
}, &method(:int_to_rgba))
-
-
# A hash from `[red, green, blue, alpha]` value arrays to color names.
-
1
COLOR_NAMES_REVERSE = COLOR_NAMES.invert.freeze
-
-
# We add the alternate color names after inverting because
-
# different ruby implementations and versions vary on the ordering of the result of invert.
-
1
COLOR_NAMES.update(ALTERNATE_COLOR_NAMES).freeze
-
-
# The user's original representation of the color.
-
#
-
# @return [String]
-
1
attr_reader :representation
-
-
# Constructs an RGB or HSL color object,
-
# optionally with an alpha channel.
-
#
-
# RGB values are clipped within 0 and 255.
-
# Saturation and lightness values are clipped within 0 and 100.
-
# The alpha value is clipped within 0 and 1.
-
#
-
# @raise [Sass::SyntaxError] if any color value isn't in the specified range
-
#
-
# @overload initialize(attrs)
-
# The attributes are specified as a hash. This hash must contain either
-
# `:hue`, `:saturation`, and `:lightness` keys, or `:red`, `:green`, and
-
# `:blue` keys. It cannot contain both HSL and RGB keys. It may also
-
# optionally contain an `:alpha` key, and a `:representation` key
-
# indicating the original representation of the color that the user wrote
-
# in their stylesheet.
-
#
-
# @param attrs [{Symbol => Numeric}] A hash of color attributes to values
-
# @raise [ArgumentError] if not enough attributes are specified,
-
# or both RGB and HSL attributes are specified
-
#
-
# @overload initialize(rgba, [representation])
-
# The attributes are specified as an array.
-
# This overload only supports RGB or RGBA colors.
-
#
-
# @param rgba [Array<Numeric>] A three- or four-element array
-
# of the red, green, blue, and optionally alpha values (respectively)
-
# of the color
-
# @param representation [String] The original representation of the color
-
# that the user wrote in their stylesheet.
-
# @raise [ArgumentError] if not enough attributes are specified
-
1
def initialize(attrs, representation = nil, allow_both_rgb_and_hsl = false)
-
super(nil)
-
-
if attrs.is_a?(Array)
-
unless (3..4).include?(attrs.size)
-
raise ArgumentError.new("Color.new(array) expects a three- or four-element array")
-
end
-
-
red, green, blue = attrs[0...3].map {|c| Sass::Util.round(c)}
-
@attrs = {:red => red, :green => green, :blue => blue}
-
@attrs[:alpha] = attrs[3] ? attrs[3].to_f : 1
-
@representation = representation
-
else
-
attrs = attrs.reject {|_k, v| v.nil?}
-
hsl = [:hue, :saturation, :lightness] & attrs.keys
-
rgb = [:red, :green, :blue] & attrs.keys
-
if !allow_both_rgb_and_hsl && !hsl.empty? && !rgb.empty?
-
raise ArgumentError.new("Color.new(hash) may not have both HSL and RGB keys specified")
-
elsif hsl.empty? && rgb.empty?
-
raise ArgumentError.new("Color.new(hash) must have either HSL or RGB keys specified")
-
elsif !hsl.empty? && hsl.size != 3
-
raise ArgumentError.new("Color.new(hash) must have all three HSL values specified")
-
elsif !rgb.empty? && rgb.size != 3
-
raise ArgumentError.new("Color.new(hash) must have all three RGB values specified")
-
end
-
-
@attrs = attrs
-
@attrs[:hue] %= 360 if @attrs[:hue]
-
@attrs[:alpha] ||= 1
-
@representation = @attrs.delete(:representation)
-
end
-
-
[:red, :green, :blue].each do |k|
-
next if @attrs[k].nil?
-
@attrs[k] = Sass::Util.restrict(Sass::Util.round(@attrs[k]), 0..255)
-
end
-
-
[:saturation, :lightness].each do |k|
-
next if @attrs[k].nil?
-
@attrs[k] = Sass::Util.restrict(@attrs[k], 0..100)
-
end
-
-
@attrs[:alpha] = Sass::Util.restrict(@attrs[:alpha], 0..1)
-
end
-
-
# Create a new color from a valid CSS hex string.
-
#
-
# The leading hash is optional.
-
#
-
# @return [Color]
-
1
def self.from_hex(hex_string, alpha = nil)
-
unless hex_string =~ /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i ||
-
hex_string =~ /^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i
-
raise ArgumentError.new("#{hex_string.inspect} is not a valid hex color.")
-
end
-
red = $1.ljust(2, $1).to_i(16)
-
green = $2.ljust(2, $2).to_i(16)
-
blue = $3.ljust(2, $3).to_i(16)
-
-
hex_string = "##{hex_string}" unless hex_string[0] == ?#
-
attrs = {:red => red, :green => green, :blue => blue, :representation => hex_string}
-
attrs[:alpha] = alpha if alpha
-
new(attrs)
-
end
-
-
# The red component of the color.
-
#
-
# @return [Integer]
-
1
def red
-
hsl_to_rgb!
-
@attrs[:red]
-
end
-
-
# The green component of the color.
-
#
-
# @return [Integer]
-
1
def green
-
hsl_to_rgb!
-
@attrs[:green]
-
end
-
-
# The blue component of the color.
-
#
-
# @return [Integer]
-
1
def blue
-
hsl_to_rgb!
-
@attrs[:blue]
-
end
-
-
# The hue component of the color.
-
#
-
# @return [Numeric]
-
1
def hue
-
rgb_to_hsl!
-
@attrs[:hue]
-
end
-
-
# The saturation component of the color.
-
#
-
# @return [Numeric]
-
1
def saturation
-
rgb_to_hsl!
-
@attrs[:saturation]
-
end
-
-
# The lightness component of the color.
-
#
-
# @return [Numeric]
-
1
def lightness
-
rgb_to_hsl!
-
@attrs[:lightness]
-
end
-
-
# The alpha channel (opacity) of the color.
-
# This is 1 unless otherwise defined.
-
#
-
# @return [Integer]
-
1
def alpha
-
@attrs[:alpha].to_f
-
end
-
-
# Returns whether this color object is translucent;
-
# that is, whether the alpha channel is non-1.
-
#
-
# @return [Boolean]
-
1
def alpha?
-
alpha < 1
-
end
-
-
# Returns the red, green, and blue components of the color.
-
#
-
# @return [Array<Integer>] A frozen three-element array of the red, green, and blue
-
# values (respectively) of the color
-
1
def rgb
-
[red, green, blue].freeze
-
end
-
-
# Returns the red, green, blue, and alpha components of the color.
-
#
-
# @return [Array<Integer>] A frozen four-element array of the red, green,
-
# blue, and alpha values (respectively) of the color
-
1
def rgba
-
[red, green, blue, alpha].freeze
-
end
-
-
# Returns the hue, saturation, and lightness components of the color.
-
#
-
# @return [Array<Integer>] A frozen three-element array of the
-
# hue, saturation, and lightness values (respectively) of the color
-
1
def hsl
-
[hue, saturation, lightness].freeze
-
end
-
-
# Returns the hue, saturation, lightness, and alpha components of the color.
-
#
-
# @return [Array<Integer>] A frozen four-element array of the hue,
-
# saturation, lightness, and alpha values (respectively) of the color
-
1
def hsla
-
[hue, saturation, lightness, alpha].freeze
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Value::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Bool] True if this value is the same as the other,
-
# false otherwise
-
1
def eq(other)
-
Sass::Script::Value::Bool.new(
-
other.is_a?(Color) && rgb == other.rgb && alpha == other.alpha)
-
end
-
-
1
def hash
-
[rgb, alpha].hash
-
end
-
-
# Returns a copy of this color with one or more channels changed.
-
# RGB or HSL colors may be changed, but not both at once.
-
#
-
# For example:
-
#
-
# Color.new([10, 20, 30]).with(:blue => 40)
-
# #=> rgb(10, 40, 30)
-
# Color.new([126, 126, 126]).with(:red => 0, :green => 255)
-
# #=> rgb(0, 255, 126)
-
# Color.new([255, 0, 127]).with(:saturation => 60)
-
# #=> rgb(204, 51, 127)
-
# Color.new([1, 2, 3]).with(:alpha => 0.4)
-
# #=> rgba(1, 2, 3, 0.4)
-
#
-
# @param attrs [{Symbol => Numeric}]
-
# A map of channel names (`:red`, `:green`, `:blue`,
-
# `:hue`, `:saturation`, `:lightness`, or `:alpha`) to values
-
# @return [Color] The new Color object
-
# @raise [ArgumentError] if both RGB and HSL keys are specified
-
1
def with(attrs)
-
attrs = attrs.reject {|_k, v| v.nil?}
-
hsl = !([:hue, :saturation, :lightness] & attrs.keys).empty?
-
rgb = !([:red, :green, :blue] & attrs.keys).empty?
-
if hsl && rgb
-
raise ArgumentError.new("Cannot specify HSL and RGB values for a color at the same time")
-
end
-
-
if hsl
-
[:hue, :saturation, :lightness].each {|k| attrs[k] ||= send(k)}
-
elsif rgb
-
[:red, :green, :blue].each {|k| attrs[k] ||= send(k)}
-
else
-
# If we're just changing the alpha channel,
-
# keep all the HSL/RGB stuff we've calculated
-
attrs = @attrs.merge(attrs)
-
end
-
attrs[:alpha] ||= alpha
-
-
Color.new(attrs, nil, :allow_both_rgb_and_hsl)
-
end
-
-
# The SassScript `+` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Adds the number to each of the RGB color channels.
-
#
-
# {Color}
-
# : Adds each of the RGB color channels together.
-
#
-
# {Value}
-
# : See {Value::Base#plus}.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
1
def plus(other)
-
if other.is_a?(Sass::Script::Value::Number) || other.is_a?(Sass::Script::Value::Color)
-
piecewise(other, :+)
-
else
-
super
-
end
-
end
-
-
# The SassScript `-` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Subtracts the number from each of the RGB color channels.
-
#
-
# {Color}
-
# : Subtracts each of the other color's RGB color channels from this color's.
-
#
-
# {Value}
-
# : See {Value::Base#minus}.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
1
def minus(other)
-
if other.is_a?(Sass::Script::Value::Number) || other.is_a?(Sass::Script::Value::Color)
-
piecewise(other, :-)
-
else
-
super
-
end
-
end
-
-
# The SassScript `*` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Multiplies the number by each of the RGB color channels.
-
#
-
# {Color}
-
# : Multiplies each of the RGB color channels together.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
1
def times(other)
-
if other.is_a?(Sass::Script::Value::Number) || other.is_a?(Sass::Script::Value::Color)
-
piecewise(other, :*)
-
else
-
raise NoMethodError.new(nil, :times)
-
end
-
end
-
-
# The SassScript `/` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Divides each of the RGB color channels by the number.
-
#
-
# {Color}
-
# : Divides each of this color's RGB color channels by the other color's.
-
#
-
# {Value}
-
# : See {Value::Base#div}.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
1
def div(other)
-
if other.is_a?(Sass::Script::Value::Number) ||
-
other.is_a?(Sass::Script::Value::Color)
-
piecewise(other, :/)
-
else
-
super
-
end
-
end
-
-
# The SassScript `%` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Takes each of the RGB color channels module the number.
-
#
-
# {Color}
-
# : Takes each of this color's RGB color channels modulo the other color's.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
1
def mod(other)
-
if other.is_a?(Sass::Script::Value::Number) ||
-
other.is_a?(Sass::Script::Value::Color)
-
piecewise(other, :%)
-
else
-
raise NoMethodError.new(nil, :mod)
-
end
-
end
-
-
# Returns a string representation of the color.
-
# This is usually the color's hex value,
-
# but if the color has a name that's used instead.
-
#
-
# @return [String] The string representation
-
1
def to_s(opts = {})
-
return smallest if options[:style] == :compressed
-
return representation if representation
-
-
# IE10 doesn't properly support the color name "transparent", so we emit
-
# generated transparent colors as rgba(0, 0, 0, 0) in favor of that. See
-
# #1782.
-
return rgba_str if Number.basically_equal?(alpha, 0)
-
return name if name
-
alpha? ? rgba_str : hex_str
-
end
-
1
alias_method :to_sass, :to_s
-
-
# Returns a string representation of the color.
-
#
-
# @return [String] The hex value
-
1
def inspect
-
alpha? ? rgba_str : hex_str
-
end
-
-
# Returns the color's name, if it has one.
-
#
-
# @return [String, nil]
-
1
def name
-
COLOR_NAMES_REVERSE[rgba]
-
end
-
-
1
private
-
-
1
def smallest
-
small_explicit_str = alpha? ? rgba_str : hex_str.gsub(/^#(.)\1(.)\2(.)\3$/, '#\1\2\3')
-
[representation, COLOR_NAMES_REVERSE[rgba], small_explicit_str].
-
compact.min_by {|str| str.size}
-
end
-
-
1
def rgba_str
-
split = options[:style] == :compressed ? ',' : ', '
-
"rgba(#{rgb.join(split)}#{split}#{Number.round(alpha)})"
-
end
-
-
1
def hex_str
-
red, green, blue = rgb.map {|num| num.to_s(16).rjust(2, '0')}
-
"##{red}#{green}#{blue}"
-
end
-
-
1
def operation_name(operation)
-
case operation
-
when :+
-
"add"
-
when :-
-
"subtract"
-
when :*
-
"multiply"
-
when :/
-
"divide"
-
when :%
-
"modulo"
-
end
-
end
-
-
1
def piecewise(other, operation)
-
other_num = other.is_a? Number
-
if other_num && !other.unitless?
-
raise Sass::SyntaxError.new(
-
"Cannot #{operation_name(operation)} a number with units (#{other}) to a color (#{self})."
-
)
-
end
-
-
result = []
-
(0...3).each do |i|
-
res = rgb[i].to_f.send(operation, other_num ? other.value : other.rgb[i])
-
result[i] = [[res, 255].min, 0].max
-
end
-
-
if !other_num && other.alpha != alpha
-
raise Sass::SyntaxError.new("Alpha channels must be equal: #{self} #{operation} #{other}")
-
end
-
-
with(:red => result[0], :green => result[1], :blue => result[2])
-
end
-
-
1
def hsl_to_rgb!
-
return if @attrs[:red] && @attrs[:blue] && @attrs[:green]
-
-
h = @attrs[:hue] / 360.0
-
s = @attrs[:saturation] / 100.0
-
l = @attrs[:lightness] / 100.0
-
-
# Algorithm from the CSS3 spec: http://www.w3.org/TR/css3-color/#hsl-color.
-
m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s
-
m1 = l * 2 - m2
-
@attrs[:red], @attrs[:green], @attrs[:blue] = [
-
hue_to_rgb(m1, m2, h + 1.0 / 3),
-
hue_to_rgb(m1, m2, h),
-
hue_to_rgb(m1, m2, h - 1.0 / 3)
-
].map {|c| Sass::Util.round(c * 0xff)}
-
end
-
-
1
def hue_to_rgb(m1, m2, h)
-
h += 1 if h < 0
-
h -= 1 if h > 1
-
return m1 + (m2 - m1) * h * 6 if h * 6 < 1
-
return m2 if h * 2 < 1
-
return m1 + (m2 - m1) * (2.0 / 3 - h) * 6 if h * 3 < 2
-
m1
-
end
-
-
1
def rgb_to_hsl!
-
return if @attrs[:hue] && @attrs[:saturation] && @attrs[:lightness]
-
r, g, b = [:red, :green, :blue].map {|k| @attrs[k] / 255.0}
-
-
# Algorithm from http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
max = [r, g, b].max
-
min = [r, g, b].min
-
d = max - min
-
-
h =
-
case max
-
when min; 0
-
when r; 60 * (g - b) / d
-
when g; 60 * (b - r) / d + 120
-
when b; 60 * (r - g) / d + 240
-
end
-
-
l = (max + min) / 2.0
-
-
s =
-
if max == min
-
0
-
elsif l < 0.5
-
d / (2 * l)
-
else
-
d / (2 - 2 * l)
-
end
-
-
@attrs[:hue] = h % 360
-
@attrs[:saturation] = s * 100
-
@attrs[:lightness] = l * 100
-
end
-
end
-
end
-
1
module Sass::Script::Value
-
# A SassScript object representing a function.
-
1
class Function < Callable
-
# Constructs a Function value for use in SassScript.
-
#
-
# @param function [Sass::Callable] The callable to be used when the
-
# function is invoked.
-
1
def initialize(function)
-
unless function.type == "function"
-
raise ArgumentError.new("A callable of type function was expected.")
-
end
-
super
-
end
-
-
1
def to_sass
-
%{get-function("#{value.name}")}
-
end
-
end
-
end
-
1
module Sass::Script::Value
-
# Provides helper functions for creating sass values from within ruby methods.
-
# @since `3.3.0`
-
# @comment
-
# rubocop:disable ModuleLength
-
1
module Helpers
-
# Construct a Sass Boolean.
-
#
-
# @param value [Object] A ruby object that will be tested for truthiness.
-
# @return [Sass::Script::Value::Bool] whether the ruby value is truthy.
-
1
def bool(value)
-
Bool.new(value)
-
end
-
-
# Construct a Sass Color from a hex color string.
-
#
-
# @param value [::String] A string representing a hex color.
-
# The leading hash ("#") is optional.
-
# @param alpha [::Number] The alpha channel. A number between 0 and 1.
-
# @return [Sass::Script::Value::Color] the color object
-
1
def hex_color(value, alpha = nil)
-
Color.from_hex(value, alpha)
-
end
-
-
# Construct a Sass Color from hsl values.
-
#
-
# @param hue [::Number] The hue of the color in degrees.
-
# A non-negative number, usually less than 360.
-
# @param saturation [::Number] The saturation of the color.
-
# Must be between 0 and 100 inclusive.
-
# @param lightness [::Number] The lightness of the color.
-
# Must be between 0 and 100 inclusive.
-
# @param alpha [::Number] The alpha channel. A number between 0 and 1.
-
#
-
# @return [Sass::Script::Value::Color] the color object
-
1
def hsl_color(hue, saturation, lightness, alpha = nil)
-
attrs = {:hue => hue, :saturation => saturation, :lightness => lightness}
-
attrs[:alpha] = alpha if alpha
-
Color.new(attrs)
-
end
-
-
# Construct a Sass Color from rgb values.
-
#
-
# @param red [::Number] The red component. Must be between 0 and 255 inclusive.
-
# @param green [::Number] The green component. Must be between 0 and 255 inclusive.
-
# @param blue [::Number] The blue component. Must be between 0 and 255 inclusive.
-
# @param alpha [::Number] The alpha channel. A number between 0 and 1.
-
#
-
# @return [Sass::Script::Value::Color] the color object
-
1
def rgb_color(red, green, blue, alpha = nil)
-
attrs = {:red => red, :green => green, :blue => blue}
-
attrs[:alpha] = alpha if alpha
-
Color.new(attrs)
-
end
-
-
# Construct a Sass Number from a ruby number.
-
#
-
# @param number [::Number] A numeric value.
-
# @param unit_string [::String] A unit string of the form
-
# `numeral_unit1 * numeral_unit2 ... / denominator_unit1 * denominator_unit2 ...`
-
# this is the same format that is returned by
-
# {Sass::Script::Value::Number#unit_str the `unit_str` method}
-
#
-
# @see Sass::Script::Value::Number#unit_str
-
#
-
# @return [Sass::Script::Value::Number] The sass number representing the given ruby number.
-
1
def number(number, unit_string = nil)
-
Number.new(number, *parse_unit_string(unit_string))
-
end
-
-
# @overload list(*elements, separator:, bracketed: false)
-
# Create a space-separated list from the arguments given.
-
# @param elements [Array<Sass::Script::Value::Base>] Each argument will be a list element.
-
# @param separator [Symbol] Either :space or :comma.
-
# @param bracketed [Boolean] Whether the list uses square brackets.
-
# @return [Sass::Script::Value::List] The space separated list.
-
#
-
# @overload list(array, separator:, bracketed: false)
-
# Create a space-separated list from the array given.
-
# @param array [Array<Sass::Script::Value::Base>] A ruby array of Sass values
-
# to make into a list.
-
# @param separator [Symbol] Either :space or :comma.
-
# @param bracketed [Boolean] Whether the list uses square brackets.
-
# @return [Sass::Script::Value::List] The space separated list.
-
1
def list(*elements, separator: nil, bracketed: false)
-
# Support passing separator as the last value in elements for
-
# backwards-compatibility.
-
if separator.nil?
-
if elements.last.is_a?(Symbol)
-
separator = elements.pop
-
else
-
raise ArgumentError.new("A separator of :space or :comma must be specified.")
-
end
-
end
-
-
if elements.size == 1 && elements.first.is_a?(Array)
-
elements = elements.first
-
end
-
Sass::Script::Value::List.new(elements, separator: separator, bracketed: bracketed)
-
end
-
-
# Construct a Sass map.
-
#
-
# @param hash [Hash<Sass::Script::Value::Base,
-
# Sass::Script::Value::Base>] A Ruby map to convert to a Sass map.
-
# @return [Sass::Script::Value::Map] The map.
-
1
def map(hash)
-
Map.new(hash)
-
end
-
-
# Create a sass null value.
-
#
-
# @return [Sass::Script::Value::Null]
-
1
def null
-
Sass::Script::Value::Null.new
-
end
-
-
# Create a quoted string.
-
#
-
# @param str [::String] A ruby string.
-
# @return [Sass::Script::Value::String] A quoted string.
-
1
def quoted_string(str)
-
Sass::Script::String.new(str, :string)
-
end
-
-
# Create an unquoted string.
-
#
-
# @param str [::String] A ruby string.
-
# @return [Sass::Script::Value::String] An unquoted string.
-
1
def unquoted_string(str)
-
Sass::Script::String.new(str, :identifier)
-
end
-
1
alias_method :identifier, :unquoted_string
-
-
# Parses a user-provided selector.
-
#
-
# @param value [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The selector to parse. This can be either a string, a list of
-
# strings, or a list of lists of strings as returned by `&`.
-
# @param name [Symbol, nil]
-
# If provided, the name of the selector argument. This is used
-
# for error reporting.
-
# @param allow_parent_ref [Boolean]
-
# Whether the parsed selector should allow parent references.
-
# @return [Sass::Selector::CommaSequence] The parsed selector.
-
# @throw [ArgumentError] if the parse failed for any reason.
-
1
def parse_selector(value, name = nil, allow_parent_ref = false)
-
str = normalize_selector(value, name)
-
begin
-
Sass::SCSS::StaticParser.new(str, nil, nil, 1, 1, allow_parent_ref).parse_selector
-
rescue Sass::SyntaxError => e
-
err = "#{value.inspect} is not a valid selector: #{e}"
-
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
-
raise ArgumentError.new(err)
-
end
-
end
-
-
# Parses a user-provided complex selector.
-
#
-
# A complex selector can contain combinators but cannot contain commas.
-
#
-
# @param value [Sass::Script::Value::String, Sass::Script::Value::List]
-
# The selector to parse. This can be either a string or a list of
-
# strings.
-
# @param name [Symbol, nil]
-
# If provided, the name of the selector argument. This is used
-
# for error reporting.
-
# @param allow_parent_ref [Boolean]
-
# Whether the parsed selector should allow parent references.
-
# @return [Sass::Selector::Sequence] The parsed selector.
-
# @throw [ArgumentError] if the parse failed for any reason.
-
1
def parse_complex_selector(value, name = nil, allow_parent_ref = false)
-
selector = parse_selector(value, name, allow_parent_ref)
-
return seq if selector.members.length == 1
-
-
err = "#{value.inspect} is not a complex selector"
-
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
-
raise ArgumentError.new(err)
-
end
-
-
# Parses a user-provided compound selector.
-
#
-
# A compound selector cannot contain combinators or commas.
-
#
-
# @param value [Sass::Script::Value::String] The selector to parse.
-
# @param name [Symbol, nil]
-
# If provided, the name of the selector argument. This is used
-
# for error reporting.
-
# @param allow_parent_ref [Boolean]
-
# Whether the parsed selector should allow parent references.
-
# @return [Sass::Selector::SimpleSequence] The parsed selector.
-
# @throw [ArgumentError] if the parse failed for any reason.
-
1
def parse_compound_selector(value, name = nil, allow_parent_ref = false)
-
assert_type value, :String, name
-
selector = parse_selector(value, name, allow_parent_ref)
-
seq = selector.members.first
-
sseq = seq.members.first
-
if selector.members.length == 1 && seq.members.length == 1 &&
-
sseq.is_a?(Sass::Selector::SimpleSequence)
-
return sseq
-
end
-
-
err = "#{value.inspect} is not a compound selector"
-
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
-
raise ArgumentError.new(err)
-
end
-
-
# Returns true when the literal is a string containing a calc().
-
#
-
# Use \{#special_number?} in preference to this.
-
#
-
# @param literal [Sass::Script::Value::Base] The value to check
-
# @return Boolean
-
1
def calc?(literal)
-
literal.is_a?(Sass::Script::Value::String) && literal.value =~ /calc\(/
-
end
-
-
# Returns whether the literal is a special CSS value that may evaluate to a
-
# number, such as `calc()` or `var()`.
-
#
-
# @param literal [Sass::Script::Value::Base] The value to check
-
# @return Boolean
-
1
def special_number?(literal)
-
literal.is_a?(Sass::Script::Value::String) && literal.value =~ /(calc|var)\(/
-
end
-
-
1
private
-
-
# Converts a user-provided selector into string form or throws an
-
# ArgumentError if it's in an invalid format.
-
1
def normalize_selector(value, name)
-
if (str = selector_to_str(value))
-
return str
-
end
-
-
err = "#{value.inspect} is not a valid selector: it must be a string,\n" +
-
"a list of strings, or a list of lists of strings"
-
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
-
raise ArgumentError.new(err)
-
end
-
-
# Converts a user-provided selector into string form or returns
-
# `nil` if it's in an invalid format.
-
1
def selector_to_str(value)
-
return value.value if value.is_a?(Sass::Script::String)
-
return unless value.is_a?(Sass::Script::List)
-
-
if value.separator == :comma
-
return value.to_a.map do |complex|
-
next complex.value if complex.is_a?(Sass::Script::String)
-
return unless complex.is_a?(Sass::Script::List) && complex.separator == :space
-
return unless (str = selector_to_str(complex))
-
str
-
end.join(', ')
-
end
-
-
value.to_a.map do |compound|
-
return unless compound.is_a?(Sass::Script::String)
-
compound.value
-
end.join(' ')
-
end
-
-
# @private
-
1
VALID_UNIT = /#{Sass::SCSS::RX::NMSTART}#{Sass::SCSS::RX::NMCHAR}|%*/
-
-
# @example
-
# parse_unit_string("em*px/in*%") # => [["em", "px], ["in", "%"]]
-
#
-
# @param unit_string [String] A string adhering to the output of a number with complex
-
# units. E.g. "em*px/in*%"
-
# @return [Array<Array<String>>] A list of numerator units and a list of denominator units.
-
1
def parse_unit_string(unit_string)
-
denominator_units = numerator_units = Sass::Script::Value::Number::NO_UNITS
-
return numerator_units, denominator_units unless unit_string && unit_string.length > 0
-
num_over_denominator = unit_string.split(%r{ */ *})
-
unless (1..2).include?(num_over_denominator.size)
-
raise ArgumentError.new("Malformed unit string: #{unit_string}")
-
end
-
numerator_units = num_over_denominator[0].split(/ *\* */)
-
denominator_units = (num_over_denominator[1] || "").split(/ *\* */)
-
[[numerator_units, "numerator"], [denominator_units, "denominator"]].each do |units, name|
-
if unit_string =~ %r{/} && units.size == 0
-
raise ArgumentError.new("Malformed unit string: #{unit_string}")
-
end
-
if units.any? {|unit| unit !~ VALID_UNIT}
-
raise ArgumentError.new("Malformed #{name} in unit string: #{unit_string}")
-
end
-
end
-
[numerator_units, denominator_units]
-
end
-
end
-
end
-
1
module Sass::Script::Value
-
# A SassScript object representing a map from keys to values. Both keys and
-
# values can be any SassScript object.
-
1
class Map < Base
-
# The Ruby hash containing the contents of this map.
-
#
-
# @return [Hash<Node, Node>]
-
1
attr_reader :value
-
1
alias_method :to_h, :value
-
-
# Creates a new map.
-
#
-
# @param hash [Hash<Node, Node>]
-
1
def initialize(hash)
-
super(hash)
-
end
-
-
# @see Value#options=
-
1
def options=(options)
-
super
-
value.each do |k, v|
-
k.options = options
-
v.options = options
-
end
-
end
-
-
# @see Value#separator
-
1
def separator
-
:comma unless value.empty?
-
end
-
-
# @see Value#to_a
-
1
def to_a
-
value.map do |k, v|
-
list = List.new([k, v], separator: :space)
-
list.options = options
-
list
-
end
-
end
-
-
# @see Value#eq
-
1
def eq(other)
-
Bool.new(other.is_a?(Map) && value == other.value)
-
end
-
-
1
def hash
-
@hash ||= value.hash
-
end
-
-
# @see Value#to_s
-
1
def to_s(opts = {})
-
raise Sass::SyntaxError.new("#{inspect} isn't a valid CSS value.")
-
end
-
-
1
def to_sass(opts = {})
-
return "()" if value.empty?
-
-
to_sass = lambda do |value|
-
if value.is_a?(List) && value.separator == :comma
-
"(#{value.to_sass(opts)})"
-
else
-
value.to_sass(opts)
-
end
-
end
-
-
"(#{value.map {|(k, v)| "#{to_sass[k]}: #{to_sass[v]}"}.join(', ')})"
-
end
-
1
alias_method :inspect, :to_sass
-
end
-
end
-
1
module Sass::Script::Value
-
# A SassScript object representing a null value.
-
1
class Null < Base
-
# The null value in SassScript.
-
#
-
# This is assigned before new is overridden below so that we use the default implementation.
-
1
NULL = new(nil)
-
-
# We override object creation so that users of the core API
-
# will not need to know that null is a specific constant.
-
#
-
# @private
-
# @return [Null] the {NULL} constant.
-
1
def self.new
-
NULL
-
end
-
-
# @return [Boolean] `false` (the Ruby boolean value)
-
1
def to_bool
-
false
-
end
-
-
# @return [Boolean] `true`
-
1
def null?
-
true
-
end
-
-
# @return [String] '' (An empty string)
-
1
def to_s(opts = {})
-
''
-
end
-
-
1
def to_sass(opts = {})
-
'null'
-
end
-
-
# Returns a string representing a null value.
-
#
-
# @return [String]
-
1
def inspect
-
'null'
-
end
-
end
-
end
-
1
module Sass::Script::Value
-
# A SassScript object representing a number.
-
# SassScript numbers can have decimal values,
-
# and can also have units.
-
# For example, `12`, `1px`, and `10.45em`
-
# are all valid values.
-
#
-
# Numbers can also have more complex units, such as `1px*em/in`.
-
# These cannot be inputted directly in Sass code at the moment.
-
1
class Number < Base
-
# The Ruby value of the number.
-
#
-
# @return [Numeric]
-
1
attr_reader :value
-
-
# A list of units in the numerator of the number.
-
# For example, `1px*em/in*cm` would return `["px", "em"]`
-
# @return [Array<String>]
-
1
attr_reader :numerator_units
-
-
# A list of units in the denominator of the number.
-
# For example, `1px*em/in*cm` would return `["in", "cm"]`
-
# @return [Array<String>]
-
1
attr_reader :denominator_units
-
-
# The original representation of this number.
-
# For example, although the result of `1px/2px` is `0.5`,
-
# the value of `#original` is `"1px/2px"`.
-
#
-
# This is only non-nil when the original value should be used as the CSS value,
-
# as in `font: 1px/2px`.
-
#
-
# @return [Boolean, nil]
-
1
attr_accessor :original
-
-
1
def self.precision
-
Thread.current[:sass_numeric_precision] || Thread.main[:sass_numeric_precision] || 10
-
end
-
-
# Sets the number of digits of precision
-
# For example, if this is `3`,
-
# `3.1415926` will be printed as `3.142`.
-
# The numeric precision is stored as a thread local for thread safety reasons.
-
# To set for all threads, be sure to set the precision on the main thread.
-
1
def self.precision=(digits)
-
Thread.current[:sass_numeric_precision] = digits.round
-
Thread.current[:sass_numeric_precision_factor] = nil
-
Thread.current[:sass_numeric_epsilon] = nil
-
end
-
-
# the precision factor used in numeric output
-
# it is derived from the `precision` method.
-
1
def self.precision_factor
-
Thread.current[:sass_numeric_precision_factor] ||= 10.0**precision
-
end
-
-
# Used in checking equality of floating point numbers. Any
-
# numbers within an `epsilon` of each other are considered functionally equal.
-
# The value for epsilon is one tenth of the current numeric precision.
-
1
def self.epsilon
-
Thread.current[:sass_numeric_epsilon] ||= 1 / (precision_factor * 10)
-
end
-
-
# Used so we don't allocate two new arrays for each new number.
-
1
NO_UNITS = []
-
-
# @param value [Numeric] The value of the number
-
# @param numerator_units [::String, Array<::String>] See \{#numerator\_units}
-
# @param denominator_units [::String, Array<::String>] See \{#denominator\_units}
-
1
def initialize(value, numerator_units = NO_UNITS, denominator_units = NO_UNITS)
-
numerator_units = [numerator_units] if numerator_units.is_a?(::String)
-
denominator_units = [denominator_units] if denominator_units.is_a?(::String)
-
super(value)
-
@numerator_units = numerator_units
-
@denominator_units = denominator_units
-
@options = nil
-
normalize!
-
end
-
-
# The SassScript `+` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Adds the two numbers together, converting units if possible.
-
#
-
# {Color}
-
# : Adds this number to each of the RGB color channels.
-
#
-
# {Value}
-
# : See {Value::Base#plus}.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Value] The result of the operation
-
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
-
1
def plus(other)
-
if other.is_a? Number
-
operate(other, :+)
-
elsif other.is_a?(Color)
-
other.plus(self)
-
else
-
super
-
end
-
end
-
-
# The SassScript binary `-` operation (e.g. `$a - $b`).
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Subtracts this number from the other, converting units if possible.
-
#
-
# {Value}
-
# : See {Value::Base#minus}.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Value] The result of the operation
-
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
-
1
def minus(other)
-
if other.is_a? Number
-
operate(other, :-)
-
else
-
super
-
end
-
end
-
-
# The SassScript unary `+` operation (e.g. `+$a`).
-
#
-
# @return [Number] The value of this number
-
1
def unary_plus
-
self
-
end
-
-
# The SassScript unary `-` operation (e.g. `-$a`).
-
#
-
# @return [Number] The negative value of this number
-
1
def unary_minus
-
Number.new(-value, @numerator_units, @denominator_units)
-
end
-
-
# The SassScript `*` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Multiplies the two numbers together, converting units appropriately.
-
#
-
# {Color}
-
# : Multiplies each of the RGB color channels by this number.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Number, Color] The result of the operation
-
# @raise [NoMethodError] if `other` is an invalid type
-
1
def times(other)
-
if other.is_a? Number
-
operate(other, :*)
-
elsif other.is_a? Color
-
other.times(self)
-
else
-
raise NoMethodError.new(nil, :times)
-
end
-
end
-
-
# The SassScript `/` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Divides this number by the other, converting units appropriately.
-
#
-
# {Value}
-
# : See {Value::Base#div}.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Value] The result of the operation
-
1
def div(other)
-
if other.is_a? Number
-
res = operate(other, :/)
-
if original && other.original
-
res.original = "#{original}/#{other.original}"
-
end
-
res
-
else
-
super
-
end
-
end
-
-
# The SassScript `%` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Number] This number modulo the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
# @raise [Sass::UnitConversionError] if `other` has incompatible units
-
1
def mod(other)
-
if other.is_a?(Number)
-
operate(other, :%)
-
else
-
raise NoMethodError.new(nil, :mod)
-
end
-
end
-
-
# The SassScript `==` operation.
-
#
-
# @param other [Value] The right-hand side of the operator
-
# @return [Boolean] Whether this number is equal to the other object
-
1
def eq(other)
-
return Bool::FALSE unless other.is_a?(Sass::Script::Value::Number)
-
this = self
-
begin
-
if unitless?
-
this = this.coerce(other.numerator_units, other.denominator_units)
-
else
-
other = other.coerce(@numerator_units, @denominator_units)
-
end
-
rescue Sass::UnitConversionError
-
return Bool::FALSE
-
end
-
Bool.new(basically_equal?(this.value, other.value))
-
end
-
-
1
def hash
-
[value, numerator_units, denominator_units].hash
-
end
-
-
# Hash-equality works differently than `==` equality for numbers.
-
# Hash-equality must be transitive, so it just compares the exact value,
-
# numerator units, and denominator units.
-
1
def eql?(other)
-
basically_equal?(value, other.value) && numerator_units == other.numerator_units &&
-
denominator_units == other.denominator_units
-
end
-
-
# The SassScript `>` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is greater than the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
1
def gt(other)
-
raise NoMethodError.new(nil, :gt) unless other.is_a?(Number)
-
operate(other, :>)
-
end
-
-
# The SassScript `>=` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is greater than or equal to the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
1
def gte(other)
-
raise NoMethodError.new(nil, :gte) unless other.is_a?(Number)
-
operate(other, :>=)
-
end
-
-
# The SassScript `<` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is less than the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
1
def lt(other)
-
raise NoMethodError.new(nil, :lt) unless other.is_a?(Number)
-
operate(other, :<)
-
end
-
-
# The SassScript `<=` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is less than or equal to the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
1
def lte(other)
-
raise NoMethodError.new(nil, :lte) unless other.is_a?(Number)
-
operate(other, :<=)
-
end
-
-
# @return [String] The CSS representation of this number
-
# @raise [Sass::SyntaxError] if this number has units that can't be used in CSS
-
# (e.g. `px*in`)
-
1
def to_s(opts = {})
-
return original if original
-
raise Sass::SyntaxError.new("#{inspect} isn't a valid CSS value.") unless legal_units?
-
inspect
-
end
-
-
# Returns a readable representation of this number.
-
#
-
# This representation is valid CSS (and valid SassScript)
-
# as long as there is only one unit.
-
#
-
# @return [String] The representation
-
1
def inspect(opts = {})
-
return original if original
-
-
value = self.class.round(self.value)
-
str = value.to_s
-
-
# Ruby will occasionally print in scientific notation if the number is
-
# small enough. That's technically valid CSS, but it's not well-supported
-
# and confusing.
-
str = ("%0.#{self.class.precision}f" % value).gsub(/0*$/, '') if str.include?('e')
-
-
# Sometimes numeric formatting will result in a decimal number with a trailing zero (x.0)
-
if str =~ /(.*)\.0$/
-
str = $1
-
end
-
-
# We omit a leading zero before the decimal point in compressed mode.
-
if @options && options[:style] == :compressed
-
str.sub!(/^(-)?0\./, '\1.')
-
end
-
-
unitless? ? str : "#{str}#{unit_str}"
-
end
-
1
alias_method :to_sass, :inspect
-
-
# @return [Integer] The integer value of the number
-
# @raise [Sass::SyntaxError] if the number isn't an integer
-
1
def to_i
-
super unless int?
-
value.to_i
-
end
-
-
# @return [Boolean] Whether or not this number is an integer.
-
1
def int?
-
basically_equal?(value % 1, 0.0)
-
end
-
-
# @return [Boolean] Whether or not this number has no units.
-
1
def unitless?
-
@numerator_units.empty? && @denominator_units.empty?
-
end
-
-
# Checks whether the number has the numerator unit specified.
-
#
-
# @example
-
# number = Sass::Script::Value::Number.new(10, "px")
-
# number.is_unit?("px") => true
-
# number.is_unit?(nil) => false
-
#
-
# @param unit [::String, nil] The unit the number should have or nil if the number
-
# should be unitless.
-
# @see Number#unitless? The unitless? method may be more readable.
-
1
def is_unit?(unit)
-
if unit
-
denominator_units.size == 0 && numerator_units.size == 1 && numerator_units.first == unit
-
else
-
unitless?
-
end
-
end
-
-
# @return [Boolean] Whether or not this number has units that can be represented in CSS
-
# (that is, zero or one \{#numerator\_units}).
-
1
def legal_units?
-
(@numerator_units.empty? || @numerator_units.size == 1) && @denominator_units.empty?
-
end
-
-
# Returns this number converted to other units.
-
# The conversion takes into account the relationship between e.g. mm and cm,
-
# as well as between e.g. in and cm.
-
#
-
# If this number has no units, it will simply return itself
-
# with the given units.
-
#
-
# An incompatible coercion, e.g. between px and cm, will raise an error.
-
#
-
# @param num_units [Array<String>] The numerator units to coerce this number into.
-
# See {\#numerator\_units}
-
# @param den_units [Array<String>] The denominator units to coerce this number into.
-
# See {\#denominator\_units}
-
# @return [Number] The number with the new units
-
# @raise [Sass::UnitConversionError] if the given units are incompatible with the number's
-
# current units
-
1
def coerce(num_units, den_units)
-
Number.new(if unitless?
-
value
-
else
-
value * coercion_factor(@numerator_units, num_units) /
-
coercion_factor(@denominator_units, den_units)
-
end, num_units, den_units)
-
end
-
-
# @param other [Number] A number to decide if it can be compared with this number.
-
# @return [Boolean] Whether or not this number can be compared with the other.
-
1
def comparable_to?(other)
-
operate(other, :+)
-
true
-
rescue Sass::UnitConversionError
-
false
-
end
-
-
# Returns a human readable representation of the units in this number.
-
# For complex units this takes the form of:
-
# numerator_unit1 * numerator_unit2 / denominator_unit1 * denominator_unit2
-
# @return [String] a string that represents the units in this number
-
1
def unit_str
-
rv = @numerator_units.sort.join("*")
-
if @denominator_units.any?
-
rv << "/"
-
rv << @denominator_units.sort.join("*")
-
end
-
rv
-
end
-
-
1
private
-
-
# @private
-
# @see Sass::Script::Number.basically_equal?
-
1
def basically_equal?(num1, num2)
-
self.class.basically_equal?(num1, num2)
-
end
-
-
# Checks whether two numbers are within an epsilon of each other.
-
# @return [Boolean]
-
1
def self.basically_equal?(num1, num2)
-
(num1 - num2).abs < epsilon
-
end
-
-
# @private
-
1
def self.round(num)
-
if num.is_a?(Float) && (num.infinite? || num.nan?)
-
num
-
elsif basically_equal?(num % 1, 0.0)
-
num.round
-
else
-
((num * precision_factor).round / precision_factor).to_f
-
end
-
end
-
-
1
OPERATIONS = [:+, :-, :<=, :<, :>, :>=, :%]
-
-
1
def operate(other, operation)
-
this = self
-
if OPERATIONS.include?(operation)
-
if unitless?
-
this = this.coerce(other.numerator_units, other.denominator_units)
-
else
-
other = other.coerce(@numerator_units, @denominator_units)
-
end
-
end
-
# avoid integer division
-
value = :/ == operation ? this.value.to_f : this.value
-
result = value.send(operation, other.value)
-
-
if result.is_a?(Numeric)
-
Number.new(result, *compute_units(this, other, operation))
-
else # Boolean op
-
Bool.new(result)
-
end
-
end
-
-
1
def coercion_factor(from_units, to_units)
-
# get a list of unmatched units
-
from_units, to_units = sans_common_units(from_units, to_units)
-
-
if from_units.size != to_units.size || !convertable?(from_units | to_units)
-
raise Sass::UnitConversionError.new(
-
"Incompatible units: '#{from_units.join('*')}' and '#{to_units.join('*')}'.")
-
end
-
-
from_units.zip(to_units).inject(1) {|m, p| m * conversion_factor(p[0], p[1])}
-
end
-
-
1
def compute_units(this, other, operation)
-
case operation
-
when :*
-
[this.numerator_units + other.numerator_units,
-
this.denominator_units + other.denominator_units]
-
when :/
-
[this.numerator_units + other.denominator_units,
-
this.denominator_units + other.numerator_units]
-
else
-
[this.numerator_units, this.denominator_units]
-
end
-
end
-
-
1
def normalize!
-
return if unitless?
-
@numerator_units, @denominator_units =
-
sans_common_units(@numerator_units, @denominator_units)
-
-
@denominator_units.each_with_index do |d, i|
-
next unless convertable?(d) && (u = @numerator_units.find(&method(:convertable?)))
-
@value /= conversion_factor(d, u)
-
@denominator_units.delete_at(i)
-
@numerator_units.delete_at(@numerator_units.index(u))
-
end
-
end
-
-
# This is the source data for all the unit logic. It's pre-processed to make
-
# it efficient to figure out whether a set of units is mutually compatible
-
# and what the conversion ratio is between two units.
-
#
-
# These come from http://www.w3.org/TR/2012/WD-css3-values-20120308/.
-
1
relative_sizes = [
-
{
-
'in' => Rational(1),
-
'cm' => Rational(1, 2.54),
-
'pc' => Rational(1, 6),
-
'mm' => Rational(1, 25.4),
-
'q' => Rational(1, 101.6),
-
'pt' => Rational(1, 72),
-
'px' => Rational(1, 96)
-
},
-
{
-
'deg' => Rational(1, 360),
-
'grad' => Rational(1, 400),
-
'rad' => Rational(1, 2 * Math::PI),
-
'turn' => Rational(1)
-
},
-
{
-
's' => Rational(1),
-
'ms' => Rational(1, 1000)
-
},
-
{
-
'Hz' => Rational(1),
-
'kHz' => Rational(1000)
-
},
-
{
-
'dpi' => Rational(1),
-
'dpcm' => Rational(254, 100),
-
'dppx' => Rational(96)
-
}
-
]
-
-
# A hash from each known unit to the set of units that it's mutually
-
# convertible with.
-
1
MUTUALLY_CONVERTIBLE = {}
-
1
relative_sizes.map do |values|
-
5
set = values.keys.to_set
-
23
values.keys.each {|name| MUTUALLY_CONVERTIBLE[name] = set}
-
end
-
-
# A two-dimensional hash from two units to the conversion ratio between
-
# them. Multiply `X` by `CONVERSION_TABLE[X][Y]` to convert it to `Y`.
-
1
CONVERSION_TABLE = {}
-
1
relative_sizes.each do |values|
-
5
values.each do |(name1, value1)|
-
18
CONVERSION_TABLE[name1] ||= {}
-
18
values.each do |(name2, value2)|
-
82
value = value1 / value2
-
82
CONVERSION_TABLE[name1][name2] = value.denominator == 1 ? value.to_i : value.to_f
-
end
-
end
-
end
-
-
1
def conversion_factor(from_unit, to_unit)
-
CONVERSION_TABLE[from_unit][to_unit]
-
end
-
-
1
def convertable?(units)
-
units = Array(units).to_set
-
return true if units.empty?
-
return false unless (mutually_convertible = MUTUALLY_CONVERTIBLE[units.first])
-
units.subset?(mutually_convertible)
-
end
-
-
1
def sans_common_units(units1, units2)
-
units2 = units2.dup
-
# Can't just use -, because we want px*px to coerce properly to px*mm
-
units1 = units1.map do |u|
-
j = units2.index(u)
-
next u unless j
-
units2.delete_at(j)
-
nil
-
end
-
units1.compact!
-
return units1, units2
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
1
module Sass::Script::Value
-
# A SassScript object representing a CSS string *or* a CSS identifier.
-
1
class String < Base
-
1
@@interpolation_deprecation = Sass::Deprecation.new
-
-
# The Ruby value of the string.
-
#
-
# @return [String]
-
1
attr_reader :value
-
-
# Whether this is a CSS string or a CSS identifier.
-
# The difference is that strings are written with double-quotes,
-
# while identifiers aren't.
-
#
-
# @return [Symbol] `:string` or `:identifier`
-
1
attr_reader :type
-
-
1
def self.value(contents)
-
contents.gsub("\\\n", "").gsub(/\\(?:([0-9a-fA-F]{1,6})\s?|(.))/) do
-
next $2 if $2
-
# Handle unicode escapes as per CSS Syntax Level 3 section 4.3.8.
-
code_point = $1.to_i(16)
-
if code_point == 0 || code_point > 0x10FFFF ||
-
(code_point >= 0xD800 && code_point <= 0xDFFF)
-
'�'
-
else
-
[code_point].pack("U")
-
end
-
end
-
end
-
-
# Returns the quoted string representation of `contents`.
-
#
-
# @options opts :quote [String]
-
# The preferred quote style for quoted strings. If `:none`, strings are
-
# always emitted unquoted. If `nil`, quoting is determined automatically.
-
# @options opts :sass [String]
-
# Whether to quote strings for Sass source, as opposed to CSS. Defaults to `false`.
-
1
def self.quote(contents, opts = {})
-
quote = opts[:quote]
-
-
# Short-circuit if there are no characters that need quoting.
-
unless contents =~ /[\n\\"']|\#\{/
-
quote ||= '"'
-
return "#{quote}#{contents}#{quote}"
-
end
-
-
if quote.nil?
-
if contents.include?('"')
-
if contents.include?("'")
-
quote = '"'
-
else
-
quote = "'"
-
end
-
else
-
quote = '"'
-
end
-
end
-
-
# Replace single backslashes with multiples.
-
contents = contents.gsub("\\", "\\\\\\\\")
-
-
# Escape interpolation.
-
contents = contents.gsub('#{', "\\\#{") if opts[:sass]
-
-
if quote == '"'
-
contents = contents.gsub('"', "\\\"")
-
else
-
contents = contents.gsub("'", "\\'")
-
end
-
-
contents = contents.gsub(/\n(?![a-fA-F0-9\s])/, "\\a").gsub("\n", "\\a ")
-
"#{quote}#{contents}#{quote}"
-
end
-
-
# Creates a new string.
-
#
-
# @param value [String] See \{#value}
-
# @param type [Symbol] See \{#type}
-
# @param deprecated_interp_equivalent [String?]
-
# If this was created via a potentially-deprecated string interpolation,
-
# this is the replacement expression that should be suggested to the user.
-
1
def initialize(value, type = :identifier, deprecated_interp_equivalent = nil)
-
super(value)
-
@type = type
-
@deprecated_interp_equivalent = deprecated_interp_equivalent
-
end
-
-
# @see Value#plus
-
1
def plus(other)
-
other_value = if other.is_a?(Sass::Script::Value::String)
-
other.value
-
else
-
other.to_s(:quote => :none)
-
end
-
Sass::Script::Value::String.new(value + other_value, type)
-
end
-
-
# @see Value#to_s
-
1
def to_s(opts = {})
-
return @value.gsub(/\n\s*/, ' ') if opts[:quote] == :none || @type == :identifier
-
String.quote(value, opts)
-
end
-
-
# @see Value#to_sass
-
1
def to_sass(opts = {})
-
to_s(opts.merge(:sass => true))
-
end
-
-
1
def separator
-
check_deprecated_interp
-
super
-
end
-
-
1
def to_a
-
check_deprecated_interp
-
super
-
end
-
-
# Prints a warning if this string was created using potentially-deprecated
-
# interpolation.
-
1
def check_deprecated_interp
-
return unless @deprecated_interp_equivalent
-
-
@@interpolation_deprecation.warn(source_range.file, source_range.start_pos.line, <<WARNING)
-
\#{} interpolation near operators will be simplified in a future version of Sass.
-
To preserve the current behavior, use quotes:
-
-
#{@deprecated_interp_equivalent}
-
WARNING
-
end
-
-
1
def inspect
-
String.quote(value)
-
end
-
end
-
end
-
1
require 'sass/scss/rx'
-
1
require 'sass/scss/parser'
-
1
require 'sass/scss/static_parser'
-
1
require 'sass/scss/css_parser'
-
-
1
module Sass
-
# SCSS is the CSS syntax for Sass.
-
# It parses into the same syntax tree as Sass,
-
# and generates the same sort of output CSS.
-
#
-
# This module contains code for the parsing of SCSS.
-
# The evaluation is handled by the broader {Sass} module.
-
1
module SCSS; end
-
end
-
1
require 'sass/script/css_parser'
-
-
1
module Sass
-
1
module SCSS
-
# This is a subclass of {Parser} which only parses plain CSS.
-
# It doesn't support any Sass extensions, such as interpolation,
-
# parent references, nested selectors, and so forth.
-
# It does support all the same CSS hacks as the SCSS parser, though.
-
1
class CssParser < StaticParser
-
1
private
-
-
1
def placeholder_selector; nil; end
-
1
def parent_selector; nil; end
-
1
def interpolation(warn_for_color = false); nil; end
-
1
def use_css_import?; true; end
-
-
1
def block_contents(node, context)
-
if node.is_a?(Sass::Tree::DirectiveNode) && node.normalized_name == '@keyframes'
-
context = :keyframes
-
end
-
super(node, context)
-
end
-
-
1
def block_child(context)
-
case context
-
when :ruleset
-
declaration
-
when :stylesheet
-
directive || ruleset
-
when :directive
-
directive || declaration_or_ruleset
-
when :keyframes
-
keyframes_ruleset
-
end
-
end
-
-
1
def nested_properties!(node)
-
expected('expression (e.g. 1px, bold)')
-
end
-
-
1
def ruleset
-
start_pos = source_position
-
return unless (selector = selector_comma_sequence)
-
block(node(Sass::Tree::RuleNode.new(selector, range(start_pos)), start_pos), :ruleset)
-
end
-
-
1
def keyframes_ruleset
-
start_pos = source_position
-
return unless (selector = keyframes_selector)
-
block(node(Sass::Tree::KeyframeRuleNode.new(selector.strip), start_pos), :ruleset)
-
end
-
-
1
@sass_script_parser = Sass::Script::CssParser
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
1
require 'set'
-
-
1
module Sass
-
1
module SCSS
-
# The parser for SCSS.
-
# It parses a string of code into a tree of {Sass::Tree::Node}s.
-
1
class Parser
-
# Expose for the SASS parser.
-
1
attr_accessor :offset
-
-
# @param str [String, StringScanner] The source document to parse.
-
# Note that `Parser` *won't* raise a nice error message if this isn't properly parsed;
-
# for that, you should use the higher-level {Sass::Engine} or {Sass::CSS}.
-
# @param filename [String] The name of the file being parsed. Used for
-
# warnings and source maps.
-
# @param importer [Sass::Importers::Base] The importer used to import the
-
# file being parsed. Used for source maps.
-
# @param line [Integer] The 1-based line on which the source string appeared,
-
# if it's part of another document.
-
# @param offset [Integer] The 1-based character (not byte) offset in the line on
-
# which the source string starts. Used for error reporting and sourcemap
-
# building.
-
1
def initialize(str, filename, importer, line = 1, offset = 1)
-
@template = str
-
@filename = filename
-
@importer = importer
-
@line = line
-
@offset = offset
-
@strs = []
-
@expected = nil
-
@throw_error = false
-
end
-
-
# Parses an SCSS document.
-
#
-
# @return [Sass::Tree::RootNode] The root node of the document tree
-
# @raise [Sass::SyntaxError] if there's a syntax error in the document
-
1
def parse
-
init_scanner!
-
root = stylesheet
-
expected("selector or at-rule") unless root && @scanner.eos?
-
root
-
end
-
-
# Parses an identifier with interpolation.
-
# Note that this won't assert that the identifier takes up the entire input string;
-
# it's meant to be used with `StringScanner`s as part of other parsers.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>, nil]
-
# The interpolated identifier, or nil if none could be parsed
-
1
def parse_interp_ident
-
init_scanner!
-
interp_ident
-
end
-
-
# Parses a supports clause for an @import directive
-
1
def parse_supports_clause
-
init_scanner!
-
ss
-
clause = supports_clause
-
ss
-
clause
-
end
-
-
# Parses a media query list.
-
#
-
# @return [Sass::Media::QueryList] The parsed query list
-
# @raise [Sass::SyntaxError] if there's a syntax error in the query list,
-
# or if it doesn't take up the entire input string.
-
1
def parse_media_query_list
-
init_scanner!
-
ql = media_query_list
-
expected("media query list") unless ql && @scanner.eos?
-
ql
-
end
-
-
# Parses an at-root query.
-
#
-
# @return [Array<String, Sass::Script;:Tree::Node>] The interpolated query.
-
# @raise [Sass::SyntaxError] if there's a syntax error in the query,
-
# or if it doesn't take up the entire input string.
-
1
def parse_at_root_query
-
init_scanner!
-
query = at_root_query
-
expected("@at-root query list") unless query && @scanner.eos?
-
query
-
end
-
-
# Parses a supports query condition.
-
#
-
# @return [Sass::Supports::Condition] The parsed condition
-
# @raise [Sass::SyntaxError] if there's a syntax error in the condition,
-
# or if it doesn't take up the entire input string.
-
1
def parse_supports_condition
-
init_scanner!
-
condition = supports_condition
-
expected("supports condition") unless condition && @scanner.eos?
-
condition
-
end
-
-
# Parses a custom property value.
-
#
-
# @return [Array<String, Sass::Script;:Tree::Node>] The interpolated value.
-
# @raise [Sass::SyntaxError] if there's a syntax error in the value,
-
# or if it doesn't take up the entire input string.
-
1
def parse_declaration_value
-
init_scanner!
-
value = declaration_value
-
expected('"}"') unless value && @scanner.eos?
-
value
-
end
-
-
1
private
-
-
1
include Sass::SCSS::RX
-
-
1
def source_position
-
Sass::Source::Position.new(@line, @offset)
-
end
-
-
1
def range(start_pos, end_pos = source_position)
-
Sass::Source::Range.new(start_pos, end_pos, @filename, @importer)
-
end
-
-
1
def init_scanner!
-
@scanner =
-
if @template.is_a?(StringScanner)
-
@template
-
else
-
Sass::Util::MultibyteStringScanner.new(@template.tr("\r", ""))
-
end
-
end
-
-
1
def stylesheet
-
node = node(Sass::Tree::RootNode.new(@scanner.string), source_position)
-
block_contents(node, :stylesheet) {s(node)}
-
end
-
-
1
def s(node)
-
while tok(S) || tok(CDC) || tok(CDO) || (c = tok(SINGLE_LINE_COMMENT)) || (c = tok(COMMENT))
-
next unless c
-
process_comment c, node
-
c = nil
-
end
-
true
-
end
-
-
1
def ss
-
nil while tok(S) || tok(SINGLE_LINE_COMMENT) || tok(COMMENT)
-
true
-
end
-
-
1
def ss_comments(node)
-
while tok(S) || (c = tok(SINGLE_LINE_COMMENT)) || (c = tok(COMMENT))
-
next unless c
-
process_comment c, node
-
c = nil
-
end
-
-
true
-
end
-
-
1
def whitespace
-
return unless tok(S) || tok(SINGLE_LINE_COMMENT) || tok(COMMENT)
-
ss
-
end
-
-
1
def process_comment(text, node)
-
silent = text =~ %r{\A//}
-
loud = !silent && text =~ %r{\A/[/*]!}
-
line = @line - text.count("\n")
-
comment_start = @scanner.pos - text.length
-
index_before_line = @scanner.string.rindex("\n", comment_start) || -1
-
offset = comment_start - index_before_line
-
-
if silent
-
value = [text.sub(%r{\A\s*//}, '/*').gsub(%r{^\s*//}, ' *') + ' */']
-
else
-
value = Sass::Engine.parse_interp(text, line, offset, :filename => @filename)
-
line_before_comment = @scanner.string[index_before_line + 1...comment_start]
-
value.unshift(line_before_comment.gsub(/[^\s]/, ' '))
-
end
-
-
type = if silent
-
:silent
-
elsif loud
-
:loud
-
else
-
:normal
-
end
-
start_pos = Sass::Source::Position.new(line, offset)
-
comment = node(Sass::Tree::CommentNode.new(value, type), start_pos)
-
node << comment
-
end
-
-
1
DIRECTIVES = Set[:mixin, :include, :function, :return, :debug, :warn, :for,
-
:each, :while, :if, :else, :extend, :import, :media, :charset, :content,
-
:_moz_document, :at_root, :error]
-
-
1
PREFIXED_DIRECTIVES = Set[:supports]
-
-
1
def directive
-
start_pos = source_position
-
return unless tok(/@/)
-
name = tok!(IDENT)
-
ss
-
-
if (dir = special_directive(name, start_pos))
-
return dir
-
elsif (dir = prefixed_directive(name, start_pos))
-
return dir
-
end
-
-
val = almost_any_value
-
val = val ? ["@#{name} "] + Sass::Util.strip_string_array(val) : ["@#{name}"]
-
directive_body(val, start_pos)
-
end
-
-
1
def directive_body(value, start_pos)
-
node = Sass::Tree::DirectiveNode.new(value)
-
-
if tok(/\{/)
-
node.has_children = true
-
block_contents(node, :directive)
-
tok!(/\}/)
-
end
-
-
node(node, start_pos)
-
end
-
-
1
def special_directive(name, start_pos)
-
sym = name.tr('-', '_').to_sym
-
DIRECTIVES.include?(sym) && send("#{sym}_directive", start_pos)
-
end
-
-
1
def prefixed_directive(name, start_pos)
-
sym = deprefix(name).tr('-', '_').to_sym
-
PREFIXED_DIRECTIVES.include?(sym) && send("#{sym}_directive", name, start_pos)
-
end
-
-
1
def mixin_directive(start_pos)
-
name = tok! IDENT
-
args, splat = sass_script(:parse_mixin_definition_arglist)
-
ss
-
block(node(Sass::Tree::MixinDefNode.new(name, args, splat), start_pos), :directive)
-
end
-
-
1
def include_directive(start_pos)
-
name = tok! IDENT
-
args, keywords, splat, kwarg_splat = sass_script(:parse_mixin_include_arglist)
-
ss
-
include_node = node(
-
Sass::Tree::MixinNode.new(name, args, keywords, splat, kwarg_splat), start_pos)
-
if tok?(/\{/)
-
include_node.has_children = true
-
block(include_node, :directive)
-
else
-
include_node
-
end
-
end
-
-
1
def content_directive(start_pos)
-
ss
-
node(Sass::Tree::ContentNode.new, start_pos)
-
end
-
-
1
def function_directive(start_pos)
-
name = tok! IDENT
-
args, splat = sass_script(:parse_function_definition_arglist)
-
ss
-
block(node(Sass::Tree::FunctionNode.new(name, args, splat), start_pos), :function)
-
end
-
-
1
def return_directive(start_pos)
-
node(Sass::Tree::ReturnNode.new(sass_script(:parse)), start_pos)
-
end
-
-
1
def debug_directive(start_pos)
-
node(Sass::Tree::DebugNode.new(sass_script(:parse)), start_pos)
-
end
-
-
1
def warn_directive(start_pos)
-
node(Sass::Tree::WarnNode.new(sass_script(:parse)), start_pos)
-
end
-
-
1
def for_directive(start_pos)
-
tok!(/\$/)
-
var = tok! IDENT
-
ss
-
-
tok!(/from/)
-
from = sass_script(:parse_until, Set["to", "through"])
-
ss
-
-
@expected = '"to" or "through"'
-
exclusive = (tok(/to/) || tok!(/through/)) == 'to'
-
to = sass_script(:parse)
-
ss
-
-
block(node(Sass::Tree::ForNode.new(var, from, to, exclusive), start_pos), :directive)
-
end
-
-
1
def each_directive(start_pos)
-
tok!(/\$/)
-
vars = [tok!(IDENT)]
-
ss
-
while tok(/,/)
-
ss
-
tok!(/\$/)
-
vars << tok!(IDENT)
-
ss
-
end
-
-
tok!(/in/)
-
list = sass_script(:parse)
-
ss
-
-
block(node(Sass::Tree::EachNode.new(vars, list), start_pos), :directive)
-
end
-
-
1
def while_directive(start_pos)
-
expr = sass_script(:parse)
-
ss
-
block(node(Sass::Tree::WhileNode.new(expr), start_pos), :directive)
-
end
-
-
1
def if_directive(start_pos)
-
expr = sass_script(:parse)
-
ss
-
node = block(node(Sass::Tree::IfNode.new(expr), start_pos), :directive)
-
pos = @scanner.pos
-
line = @line
-
ss
-
-
else_block(node) ||
-
begin
-
# Backtrack in case there are any comments we want to parse
-
@scanner.pos = pos
-
@line = line
-
node
-
end
-
end
-
-
1
def else_block(node)
-
start_pos = source_position
-
return unless tok(/@else/)
-
ss
-
else_node = block(
-
node(Sass::Tree::IfNode.new((sass_script(:parse) if tok(/if/))), start_pos),
-
:directive)
-
node.add_else(else_node)
-
pos = @scanner.pos
-
line = @line
-
ss
-
-
else_block(node) ||
-
begin
-
# Backtrack in case there are any comments we want to parse
-
@scanner.pos = pos
-
@line = line
-
node
-
end
-
end
-
-
1
def else_directive(start_pos)
-
err("Invalid CSS: @else must come after @if")
-
end
-
-
1
def extend_directive(start_pos)
-
selector_start_pos = source_position
-
@expected = "selector"
-
selector = Sass::Util.strip_string_array(expr!(:almost_any_value))
-
optional = tok(OPTIONAL)
-
ss
-
node(Sass::Tree::ExtendNode.new(selector, !!optional, range(selector_start_pos)), start_pos)
-
end
-
-
1
def import_directive(start_pos)
-
values = []
-
-
loop do
-
values << expr!(:import_arg)
-
break if use_css_import?
-
break unless tok(/,/)
-
ss
-
end
-
-
values
-
end
-
-
1
def import_arg
-
start_pos = source_position
-
return unless (str = string) || (uri = tok?(/url\(/i))
-
if uri
-
str = sass_script(:parse_string)
-
ss
-
supports = supports_clause
-
ss
-
media = media_query_list
-
ss
-
return node(Tree::CssImportNode.new(str, media.to_a, supports), start_pos)
-
end
-
ss
-
-
supports = supports_clause
-
ss
-
media = media_query_list
-
if str =~ %r{^(https?:)?//} || media || supports || use_css_import?
-
return node(
-
Sass::Tree::CssImportNode.new(
-
Sass::Script::Value::String.quote(str), media.to_a, supports), start_pos)
-
end
-
-
node(Sass::Tree::ImportNode.new(str.strip), start_pos)
-
end
-
-
1
def use_css_import?; false; end
-
-
1
def media_directive(start_pos)
-
block(node(Sass::Tree::MediaNode.new(expr!(:media_query_list).to_a), start_pos), :directive)
-
end
-
-
# http://www.w3.org/TR/css3-mediaqueries/#syntax
-
1
def media_query_list
-
query = media_query
-
return unless query
-
queries = [query]
-
-
ss
-
while tok(/,/)
-
ss; queries << expr!(:media_query)
-
end
-
ss
-
-
Sass::Media::QueryList.new(queries)
-
end
-
-
1
def media_query
-
if (ident1 = interp_ident)
-
ss
-
ident2 = interp_ident
-
ss
-
if ident2 && ident2.length == 1 && ident2[0].is_a?(String) && ident2[0].downcase == 'and'
-
query = Sass::Media::Query.new([], ident1, [])
-
else
-
if ident2
-
query = Sass::Media::Query.new(ident1, ident2, [])
-
else
-
query = Sass::Media::Query.new([], ident1, [])
-
end
-
return query unless tok(/and/i)
-
ss
-
end
-
end
-
-
if query
-
expr = expr!(:media_expr)
-
else
-
expr = media_expr
-
return unless expr
-
end
-
query ||= Sass::Media::Query.new([], [], [])
-
query.expressions << expr
-
-
ss
-
while tok(/and/i)
-
ss; query.expressions << expr!(:media_expr)
-
end
-
-
query
-
end
-
-
1
def query_expr
-
interp = interpolation
-
return interp if interp
-
return unless tok(/\(/)
-
res = ['(']
-
ss
-
res << sass_script(:parse)
-
-
if tok(/:/)
-
res << ': '
-
ss
-
res << sass_script(:parse)
-
end
-
res << tok!(/\)/)
-
ss
-
res
-
end
-
-
# Aliases allow us to use different descriptions if the same
-
# expression fails in different contexts.
-
1
alias_method :media_expr, :query_expr
-
1
alias_method :at_root_query, :query_expr
-
-
1
def charset_directive(start_pos)
-
name = expr!(:string)
-
ss
-
node(Sass::Tree::CharsetNode.new(name), start_pos)
-
end
-
-
# The document directive is specified in
-
# http://www.w3.org/TR/css3-conditional/, but Gecko allows the
-
# `url-prefix` and `domain` functions to omit quotation marks, contrary to
-
# the standard.
-
#
-
# We could parse all document directives according to Mozilla's syntax,
-
# but if someone's using e.g. @-webkit-document we don't want them to
-
# think WebKit works sans quotes.
-
1
def _moz_document_directive(start_pos)
-
res = ["@-moz-document "]
-
loop do
-
res << str {ss} << expr!(:moz_document_function)
-
if (c = tok(/,/))
-
res << c
-
else
-
break
-
end
-
end
-
directive_body(res.flatten, start_pos)
-
end
-
-
1
def moz_document_function
-
val = interp_uri || _interp_string(:url_prefix) ||
-
_interp_string(:domain) || function(false) || interpolation
-
return unless val
-
ss
-
val
-
end
-
-
1
def at_root_directive(start_pos)
-
if tok?(/\(/) && (expr = at_root_query)
-
return block(node(Sass::Tree::AtRootNode.new(expr), start_pos), :directive)
-
end
-
-
at_root_node = node(Sass::Tree::AtRootNode.new, start_pos)
-
rule_node = ruleset
-
return block(at_root_node, :stylesheet) unless rule_node
-
at_root_node << rule_node
-
at_root_node
-
end
-
-
1
def at_root_directive_list
-
return unless (first = tok(IDENT))
-
arr = [first]
-
ss
-
while (e = tok(IDENT))
-
arr << e
-
ss
-
end
-
arr
-
end
-
-
1
def error_directive(start_pos)
-
node(Sass::Tree::ErrorNode.new(sass_script(:parse)), start_pos)
-
end
-
-
# http://www.w3.org/TR/css3-conditional/
-
1
def supports_directive(name, start_pos)
-
condition = expr!(:supports_condition)
-
node = Sass::Tree::SupportsNode.new(name, condition)
-
-
tok!(/\{/)
-
node.has_children = true
-
block_contents(node, :directive)
-
tok!(/\}/)
-
-
node(node, start_pos)
-
end
-
-
1
def supports_clause
-
return unless tok(/supports\(/i)
-
ss
-
supports = import_supports_condition
-
ss
-
tok!(/\)/)
-
supports
-
end
-
-
1
def supports_condition
-
supports_negation || supports_operator || supports_interpolation
-
end
-
-
1
def import_supports_condition
-
supports_condition || supports_declaration
-
end
-
-
1
def supports_negation
-
return unless tok(/not/i)
-
ss
-
Sass::Supports::Negation.new(expr!(:supports_condition_in_parens))
-
end
-
-
1
def supports_operator
-
cond = supports_condition_in_parens
-
return unless cond
-
re = /and|or/i
-
while (op = tok(re))
-
re = /#{op}/i
-
ss
-
cond = Sass::Supports::Operator.new(
-
cond, expr!(:supports_condition_in_parens), op)
-
end
-
cond
-
end
-
-
1
def supports_declaration
-
name = sass_script(:parse)
-
tok!(/:/); ss
-
value = sass_script(:parse)
-
Sass::Supports::Declaration.new(name, value)
-
end
-
-
1
def supports_condition_in_parens
-
interp = supports_interpolation
-
return interp if interp
-
return unless tok(/\(/); ss
-
if (cond = supports_condition)
-
tok!(/\)/); ss
-
cond
-
else
-
decl = supports_declaration
-
tok!(/\)/); ss
-
decl
-
end
-
end
-
-
1
def supports_interpolation
-
interp = interpolation
-
return unless interp
-
ss
-
Sass::Supports::Interpolation.new(interp)
-
end
-
-
1
def variable
-
return unless tok(/\$/)
-
start_pos = source_position
-
name = tok!(IDENT)
-
ss; tok!(/:/); ss
-
-
expr = sass_script(:parse)
-
while tok(/!/)
-
flag_name = tok!(IDENT)
-
if flag_name == 'default'
-
guarded ||= true
-
elsif flag_name == 'global'
-
global ||= true
-
else
-
raise Sass::SyntaxError.new("Invalid flag \"!#{flag_name}\".", :line => @line)
-
end
-
ss
-
end
-
-
result = Sass::Tree::VariableNode.new(name, expr, guarded, global)
-
node(result, start_pos)
-
end
-
-
1
def operator
-
# Many of these operators (all except / and ,)
-
# are disallowed by the CSS spec,
-
# but they're included here for compatibility
-
# with some proprietary MS properties
-
str {ss if tok(%r{[/,:.=]})}
-
end
-
-
1
def ruleset
-
start_pos = source_position
-
return unless (rules = almost_any_value)
-
block(
-
node(
-
Sass::Tree::RuleNode.new(rules, range(start_pos)), start_pos), :ruleset)
-
end
-
-
1
def block(node, context)
-
node.has_children = true
-
tok!(/\{/)
-
block_contents(node, context)
-
tok!(/\}/)
-
node
-
end
-
-
# A block may contain declarations and/or rulesets
-
1
def block_contents(node, context)
-
block_given? ? yield : ss_comments(node)
-
node << (child = block_child(context))
-
while tok(/;/) || has_children?(child)
-
block_given? ? yield : ss_comments(node)
-
node << (child = block_child(context))
-
end
-
node
-
end
-
-
1
def block_child(context)
-
return variable || directive if context == :function
-
return variable || directive || ruleset if context == :stylesheet
-
variable || directive || declaration_or_ruleset
-
end
-
-
1
def has_children?(child_or_array)
-
return false unless child_or_array
-
return child_or_array.last.has_children if child_or_array.is_a?(Array)
-
child_or_array.has_children
-
end
-
-
# When parsing the contents of a ruleset, it can be difficult to tell
-
# declarations apart from nested rulesets. Since we don't thoroughly parse
-
# selectors until after resolving interpolation, we can share a bunch of
-
# the parsing of the two, but we need to disambiguate them first. We use
-
# the following criteria:
-
#
-
# * If the entity doesn't start with an identifier followed by a colon,
-
# it's a selector. There are some additional mostly-unimportant cases
-
# here to support various declaration hacks.
-
#
-
# * If the colon is followed by another colon, it's a selector.
-
#
-
# * Otherwise, if the colon is followed by anything other than
-
# interpolation or a character that's valid as the beginning of an
-
# identifier, it's a declaration.
-
#
-
# * If the colon is followed by interpolation or a valid identifier, try
-
# parsing it as a declaration value. If this fails, backtrack and parse
-
# it as a selector.
-
#
-
# * If the declaration value value valid but is followed by "{", backtrack
-
# and parse it as a selector anyway. This ensures that ".foo:bar {" is
-
# always parsed as a selector and never as a property with nested
-
# properties beneath it.
-
1
def declaration_or_ruleset
-
start_pos = source_position
-
declaration = try_declaration
-
-
if declaration.nil?
-
return unless (selector = almost_any_value)
-
elsif declaration.is_a?(Array)
-
selector = declaration
-
else
-
# Declaration should be a PropNode.
-
return declaration
-
end
-
-
if (additional_selector = almost_any_value)
-
selector << additional_selector
-
end
-
-
block(
-
node(
-
Sass::Tree::RuleNode.new(merge(selector), range(start_pos)), start_pos), :ruleset)
-
end
-
-
# Tries to parse a declaration, and returns the value parsed so far if it
-
# fails.
-
#
-
# This has three possible return types. It can return `nil`, indicating
-
# that parsing failed completely and the scanner hasn't moved forward at
-
# all. It can return an Array, indicating that parsing failed after
-
# consuming some text (possibly containing interpolation), which is
-
# returned. Or it can return a PropNode, indicating that parsing
-
# succeeded.
-
1
def try_declaration
-
# This allows the "*prop: val", ":prop: val", "#prop: val", and ".prop:
-
# val" hacks.
-
name_start_pos = source_position
-
if (s = tok(/[:\*\.]|\#(?!\{)/))
-
name = [s, str {ss}]
-
return name unless (ident = interp_ident)
-
name << ident
-
else
-
return unless (name = interp_ident)
-
name = Array(name)
-
end
-
-
if (comment = tok(COMMENT))
-
name << comment
-
end
-
name_end_pos = source_position
-
-
mid = [str {ss}]
-
return name + mid unless tok(/:/)
-
mid << ':'
-
-
# If this is a CSS variable, parse it as a property no matter what.
-
if name.first.is_a?(String) && name.first.start_with?("--")
-
return css_variable_declaration(name, name_start_pos, name_end_pos)
-
end
-
-
return name + mid + [':'] if tok(/:/)
-
mid << str {ss}
-
post_colon_whitespace = !mid.last.empty?
-
could_be_selector = !post_colon_whitespace && (tok?(IDENT_START) || tok?(INTERP_START))
-
-
value_start_pos = source_position
-
value = nil
-
error = catch_error do
-
value = value!
-
if tok?(/\{/)
-
# Properties that are ambiguous with selectors can't have additional
-
# properties nested beneath them.
-
tok!(/;/) if could_be_selector
-
elsif !tok?(/[;{}]/)
-
# We want an exception if there's no valid end-of-property character
-
# exists, but we don't want to consume it if it does.
-
tok!(/[;{}]/)
-
end
-
end
-
-
if error
-
rethrow error unless could_be_selector
-
-
# If the value would be followed by a semicolon, it's definitely
-
# supposed to be a property, not a selector.
-
additional_selector = almost_any_value
-
rethrow error if tok?(/;/)
-
-
return name + mid + (additional_selector || [])
-
end
-
-
value_end_pos = source_position
-
ss
-
require_block = tok?(/\{/)
-
-
node = node(Sass::Tree::PropNode.new(name.flatten.compact, [value], :new),
-
name_start_pos, value_end_pos)
-
node.name_source_range = range(name_start_pos, name_end_pos)
-
node.value_source_range = range(value_start_pos, value_end_pos)
-
-
return node unless require_block
-
nested_properties! node
-
end
-
-
1
def css_variable_declaration(name, name_start_pos, name_end_pos)
-
value_start_pos = source_position
-
value = declaration_value
-
value_end_pos = source_position
-
-
node = node(Sass::Tree::PropNode.new(name.flatten.compact, value, :new),
-
name_start_pos, value_end_pos)
-
node.name_source_range = range(name_start_pos, name_end_pos)
-
node.value_source_range = range(value_start_pos, value_end_pos)
-
node
-
end
-
-
# This production consumes values that could be a selector, an expression,
-
# or a combination of both. It respects strings and comments and supports
-
# interpolation. It will consume up to "{", "}", ";", or "!".
-
#
-
# Values consumed by this production will usually be parsed more
-
# thoroughly once interpolation has been resolved.
-
1
def almost_any_value
-
return unless (tok = almost_any_value_token)
-
sel = [tok]
-
while (tok = almost_any_value_token)
-
sel << tok
-
end
-
merge(sel)
-
end
-
-
1
def almost_any_value_token
-
tok(%r{
-
(
-
\\.
-
|
-
(?!url\()
-
[^"'/\#!;\{\}] # "
-
|
-
# interp_uri will handle most url() calls, but not ones that take strings
-
url\(#{W}(?=")
-
|
-
/(?![/*])
-
|
-
\#(?!\{)
-
|
-
!(?![a-z]) # TODO: never consume "!" when issue 1126 is fixed.
-
)+
-
}xi) || tok(COMMENT) || tok(SINGLE_LINE_COMMENT) || interp_string || interp_uri ||
-
interpolation(:warn_for_color)
-
end
-
-
1
def declaration_value(top_level: true)
-
return unless (tok = declaration_value_token(top_level))
-
value = [tok]
-
while (tok = declaration_value_token(top_level))
-
value << tok
-
end
-
merge(value)
-
end
-
-
1
def declaration_value_token(top_level)
-
# This comes, more or less, from the [token consumption algorithm][].
-
# However, since we don't have to worry about the token semantics, we
-
# just consume everything until we come across a token with special
-
# semantics.
-
#
-
# [token consumption algorithm]: https://drafts.csswg.org/css-syntax-3/#consume-token.
-
result = tok(%r{
-
(
-
(?!
-
url\(
-
)
-
[^()\[\]{}"'#/ \t\r\n\f#{top_level ? ";!" : ""}]
-
|
-
\#(?!\{)
-
|
-
/(?!\*)
-
)+
-
}xi) || interp_string || interp_uri || interpolation || tok(COMMENT)
-
return result if result
-
-
# Fold together multiple characters of whitespace that don't include
-
# newlines. The value only cares about the tokenization, so this is safe
-
# as long as we don't delete whitespace entirely. It's important that we
-
# fold here rather than post-processing, since we aren't allowed to fold
-
# whitespace within strings and we lose that context later on.
-
if (ws = tok(S))
-
return ws.include?("\n") ? ws.gsub(/\A[^\n]*/, '') : ' '
-
end
-
-
if tok(/\(/)
-
value = declaration_value(top_level: false)
-
tok!(/\)/)
-
['(', *value, ')']
-
elsif tok(/\[/)
-
value = declaration_value(top_level: false)
-
tok!(/\]/)
-
['[', *value, ']']
-
elsif tok(/\{/)
-
value = declaration_value(top_level: false)
-
tok!(/\}/)
-
['{', *value, '}']
-
end
-
end
-
-
1
def declaration
-
# This allows the "*prop: val", ":prop: val", "#prop: val", and ".prop:
-
# val" hacks.
-
name_start_pos = source_position
-
if (s = tok(/[:\*\.]|\#(?!\{)/))
-
name = [s, str {ss}, *expr!(:interp_ident)]
-
else
-
return unless (name = interp_ident)
-
name = Array(name)
-
end
-
-
if (comment = tok(COMMENT))
-
name << comment
-
end
-
name_end_pos = source_position
-
ss
-
-
tok!(/:/)
-
ss
-
value_start_pos = source_position
-
value = value!
-
value_end_pos = source_position
-
ss
-
require_block = tok?(/\{/)
-
-
node = node(Sass::Tree::PropNode.new(name.flatten.compact, [value], :new),
-
name_start_pos, value_end_pos)
-
node.name_source_range = range(name_start_pos, name_end_pos)
-
node.value_source_range = range(value_start_pos, value_end_pos)
-
-
return node unless require_block
-
nested_properties! node
-
end
-
-
1
def value!
-
if tok?(/\{/)
-
str = Sass::Script::Tree::Literal.new(Sass::Script::Value::String.new(""))
-
str.line = source_position.line
-
str.source_range = range(source_position)
-
return str
-
end
-
-
start_pos = source_position
-
# This is a bit of a dirty trick:
-
# if the value is completely static,
-
# we don't parse it at all, and instead return a plain old string
-
# containing the value.
-
# This results in a dramatic speed increase.
-
if (val = tok(STATIC_VALUE))
-
str = Sass::Script::Tree::Literal.new(Sass::Script::Value::String.new(val.strip))
-
str.line = start_pos.line
-
str.source_range = range(start_pos)
-
return str
-
end
-
sass_script(:parse)
-
end
-
-
1
def nested_properties!(node)
-
@expected = 'expression (e.g. 1px, bold) or "{"'
-
block(node, :property)
-
end
-
-
1
def expr(allow_var = true)
-
t = term(allow_var)
-
return unless t
-
res = [t, str {ss}]
-
-
while (o = operator) && (t = term(allow_var))
-
res << o << t << str {ss}
-
end
-
-
res.flatten
-
end
-
-
1
def term(allow_var)
-
e = tok(NUMBER) ||
-
interp_uri ||
-
function(allow_var) ||
-
interp_string ||
-
tok(UNICODERANGE) ||
-
interp_ident ||
-
tok(HEXCOLOR) ||
-
(allow_var && var_expr)
-
return e if e
-
-
op = tok(/[+-]/)
-
return unless op
-
@expected = "number or function"
-
[op,
-
tok(NUMBER) || function(allow_var) || (allow_var && var_expr) || expr!(:interpolation)]
-
end
-
-
1
def function(allow_var)
-
name = tok(FUNCTION)
-
return unless name
-
if name == "expression(" || name == "calc("
-
str, _ = Sass::Shared.balance(@scanner, ?(, ?), 1)
-
[name, str]
-
else
-
[name, str {ss}, expr(allow_var), tok!(/\)/)]
-
end
-
end
-
-
1
def var_expr
-
return unless tok(/\$/)
-
line = @line
-
var = Sass::Script::Tree::Variable.new(tok!(IDENT))
-
var.line = line
-
var
-
end
-
-
1
def interpolation(warn_for_color = false)
-
return unless tok(INTERP_START)
-
sass_script(:parse_interpolated, warn_for_color)
-
end
-
-
1
def string
-
return unless tok(STRING)
-
Sass::Script::Value::String.value(@scanner[1] || @scanner[2])
-
end
-
-
1
def interp_string
-
_interp_string(:double) || _interp_string(:single)
-
end
-
-
1
def interp_uri
-
_interp_string(:uri)
-
end
-
-
1
def _interp_string(type)
-
start = tok(Sass::Script::Lexer::STRING_REGULAR_EXPRESSIONS[type][false])
-
return unless start
-
res = [start]
-
-
mid_re = Sass::Script::Lexer::STRING_REGULAR_EXPRESSIONS[type][true]
-
# @scanner[2].empty? means we've started an interpolated section
-
while @scanner[2] == '#{'
-
@scanner.pos -= 2 # Don't consume the #{
-
res.last.slice!(-2..-1)
-
res << expr!(:interpolation) << tok(mid_re)
-
end
-
res
-
end
-
-
1
def interp_ident(start = IDENT)
-
val = tok(start) || interpolation(:warn_for_color) || tok(IDENT_HYPHEN_INTERP)
-
return unless val
-
res = [val]
-
while (val = tok(NAME) || interpolation(:warn_for_color))
-
res << val
-
end
-
res
-
end
-
-
1
def interp_ident_or_var
-
id = interp_ident
-
return id if id
-
var = var_expr
-
return [var] if var
-
end
-
-
1
def str
-
@strs.push String.new("")
-
yield
-
@strs.last
-
ensure
-
@strs.pop
-
end
-
-
1
def str?
-
pos = @scanner.pos
-
line = @line
-
offset = @offset
-
@strs.push ""
-
throw_error {yield} && @strs.last
-
rescue Sass::SyntaxError
-
@scanner.pos = pos
-
@line = line
-
@offset = offset
-
nil
-
ensure
-
@strs.pop
-
end
-
-
1
def node(node, start_pos, end_pos = source_position)
-
node.line = start_pos.line
-
node.source_range = range(start_pos, end_pos)
-
node
-
end
-
-
1
@sass_script_parser = Sass::Script::Parser
-
-
1
class << self
-
# @private
-
1
attr_accessor :sass_script_parser
-
end
-
-
1
def sass_script(*args)
-
parser = self.class.sass_script_parser.new(@scanner, @line, @offset,
-
:filename => @filename, :importer => @importer, :allow_extra_text => true)
-
result = parser.send(*args)
-
unless @strs.empty?
-
# Convert to CSS manually so that comments are ignored.
-
src = result.to_sass
-
@strs.each {|s| s << src}
-
end
-
@line = parser.line
-
@offset = parser.offset
-
result
-
rescue Sass::SyntaxError => e
-
throw(:_sass_parser_error, true) if @throw_error
-
raise e
-
end
-
-
1
def merge(arr)
-
arr && Sass::Util.merge_adjacent_strings([arr].flatten)
-
end
-
-
1
EXPR_NAMES = {
-
:media_query => "media query (e.g. print, screen, print and screen)",
-
:media_query_list => "media query (e.g. print, screen, print and screen)",
-
:media_expr => "media expression (e.g. (min-device-width: 800px))",
-
:at_root_query => "@at-root query (e.g. (without: media))",
-
:at_root_directive_list => '* or identifier',
-
:declaration_value => "expression (e.g. fr, 2n+1)",
-
:interp_ident => "identifier",
-
:qualified_name => "identifier",
-
:expr => "expression (e.g. 1px, bold)",
-
:selector_comma_sequence => "selector",
-
:string => "string",
-
:import_arg => "file to import (string or url())",
-
:moz_document_function => "matching function (e.g. url-prefix(), domain())",
-
:supports_condition => "@supports condition (e.g. (display: flexbox))",
-
:supports_condition_in_parens => "@supports condition (e.g. (display: flexbox))",
-
:a_n_plus_b => "An+B expression",
-
:keyframes_selector_component => "from, to, or a percentage",
-
:keyframes_selector => "keyframes selector (e.g. 10%)"
-
}
-
-
1
TOK_NAMES = Hash[Sass::SCSS::RX.constants.map do |c|
-
54
[Sass::SCSS::RX.const_get(c), c.downcase]
-
end].merge(
-
IDENT => "identifier",
-
/[;{}]/ => '";"',
-
/\b(without|with)\b/ => '"with" or "without"'
-
)
-
-
1
def tok?(rx)
-
@scanner.match?(rx)
-
end
-
-
1
def expr!(name)
-
e = send(name)
-
return e if e
-
expected(EXPR_NAMES[name] || name.to_s)
-
end
-
-
1
def tok!(rx)
-
t = tok(rx)
-
return t if t
-
name = TOK_NAMES[rx]
-
-
unless name
-
# Display basic regexps as plain old strings
-
source = rx.source.gsub(%r{\\/}, '/')
-
string = rx.source.gsub(/\\(.)/, '\1')
-
name = source == Regexp.escape(string) ? string.inspect : rx.inspect
-
end
-
-
expected(name)
-
end
-
-
1
def expected(name)
-
throw(:_sass_parser_error, true) if @throw_error
-
self.class.expected(@scanner, @expected || name, @line)
-
end
-
-
1
def err(msg)
-
throw(:_sass_parser_error, true) if @throw_error
-
raise Sass::SyntaxError.new(msg, :line => @line)
-
end
-
-
1
def throw_error
-
old_throw_error, @throw_error = @throw_error, false
-
yield
-
ensure
-
@throw_error = old_throw_error
-
end
-
-
1
def catch_error(&block)
-
old_throw_error, @throw_error = @throw_error, true
-
pos = @scanner.pos
-
line = @line
-
offset = @offset
-
expected = @expected
-
-
logger = Sass::Logger::Delayed.install!
-
if catch(:_sass_parser_error) {yield; false}
-
@scanner.pos = pos
-
@line = line
-
@offset = offset
-
@expected = expected
-
{:pos => pos, :line => line, :expected => @expected, :block => block}
-
else
-
logger.flush
-
nil
-
end
-
ensure
-
logger.uninstall! if logger
-
@throw_error = old_throw_error
-
end
-
-
1
def rethrow(err)
-
if @throw_error
-
throw :_sass_parser_error, err
-
else
-
@scanner = Sass::Util::MultibyteStringScanner.new(@scanner.string)
-
@scanner.pos = err[:pos]
-
@line = err[:line]
-
@expected = err[:expected]
-
err[:block].call
-
end
-
end
-
-
# @private
-
1
def self.expected(scanner, expected, line)
-
pos = scanner.pos
-
-
after = scanner.string[0...pos]
-
# Get rid of whitespace between pos and the last token,
-
# but only if there's a newline in there
-
after.gsub!(/\s*\n\s*$/, '')
-
# Also get rid of stuff before the last newline
-
after.gsub!(/.*\n/, '')
-
after = "..." + after[-15..-1] if after.size > 18
-
-
was = scanner.rest.dup
-
# Get rid of whitespace between pos and the next token,
-
# but only if there's a newline in there
-
was.gsub!(/^\s*\n\s*/, '')
-
# Also get rid of stuff after the next newline
-
was.gsub!(/\n.*/, '')
-
was = was[0...15] + "..." if was.size > 18
-
-
raise Sass::SyntaxError.new(
-
"Invalid CSS after \"#{after}\": expected #{expected}, was \"#{was}\"",
-
:line => line)
-
end
-
-
# Avoid allocating lots of new strings for `#tok`.
-
# This is important because `#tok` is called all the time.
-
1
NEWLINE = "\n"
-
-
1
def tok(rx)
-
res = @scanner.scan(rx)
-
-
return unless res
-
-
newline_count = res.count(NEWLINE)
-
if newline_count > 0
-
@line += newline_count
-
@offset = res[res.rindex(NEWLINE)..-1].size
-
else
-
@offset += res.size
-
end
-
-
@expected = nil
-
if !@strs.empty? && rx != COMMENT && rx != SINGLE_LINE_COMMENT
-
@strs.each {|s| s << res}
-
end
-
res
-
end
-
-
# Remove a vendor prefix from `str`.
-
1
def deprefix(str)
-
str.gsub(/^-[a-zA-Z0-9]+-/, '')
-
end
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
1
module Sass
-
1
module SCSS
-
# A module containing regular expressions used
-
# for lexing tokens in an SCSS document.
-
# Most of these are taken from [the CSS3 spec](http://www.w3.org/TR/css3-syntax/#lexical),
-
# although some have been modified for various reasons.
-
1
module RX
-
# Takes a string and returns a CSS identifier
-
# that will have the value of the given string.
-
#
-
# @param str [String] The string to escape
-
# @return [String] The escaped string
-
1
def self.escape_ident(str)
-
return "" if str.empty?
-
return "\\#{str}" if str == '-' || str == '_'
-
out = ""
-
value = str.dup
-
out << value.slice!(0...1) if value =~ /^[-_]/
-
if value[0...1] =~ NMSTART
-
out << value.slice!(0...1)
-
else
-
out << escape_char(value.slice!(0...1))
-
end
-
out << value.gsub(/[^a-zA-Z0-9_-]/) {|c| escape_char c}
-
out
-
end
-
-
# Escapes a single character for a CSS identifier.
-
#
-
# @param c [String] The character to escape. Should have length 1
-
# @return [String] The escaped character
-
# @private
-
1
def self.escape_char(c)
-
return "\\%06x" % c.ord unless c =~ %r{[ -/:-~]}
-
"\\#{c}"
-
end
-
-
# Creates a Regexp from a plain text string,
-
# escaping all significant characters.
-
#
-
# @param str [String] The text of the regexp
-
# @param flags [Integer] Flags for the created regular expression
-
# @return [Regexp]
-
# @private
-
1
def self.quote(str, flags = 0)
-
8
Regexp.new(Regexp.quote(str), flags)
-
end
-
-
1
H = /[0-9a-fA-F]/
-
1
NL = /\n|\r\n|\r|\f/
-
1
UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/
-
1
s = '\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}'
-
1
NONASCII = /[#{s}]/
-
1
ESCAPE = /#{UNICODE}|\\[ -~#{s}]/
-
1
NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/
-
1
NMCHAR = /[a-zA-Z0-9_-]|#{NONASCII}|#{ESCAPE}/
-
1
STRING1 = /\"((?:[^\n\r\f\\"]|\\#{NL}|#{ESCAPE})*)\"/
-
1
STRING2 = /\'((?:[^\n\r\f\\']|\\#{NL}|#{ESCAPE})*)\'/
-
-
1
IDENT = /-*#{NMSTART}#{NMCHAR}*/
-
1
NAME = /#{NMCHAR}+/
-
1
STRING = /#{STRING1}|#{STRING2}/
-
1
URLCHAR = /[#%&*-~]|#{NONASCII}|#{ESCAPE}/
-
1
URL = /(#{URLCHAR}*)/
-
1
W = /[ \t\r\n\f]*/
-
1
VARIABLE = /(\$)(#{Sass::SCSS::RX::IDENT})/
-
-
# This is more liberal than the spec's definition,
-
# but that definition didn't work well with the greediness rules
-
1
RANGE = /(?:#{H}|\?){1,6}/
-
-
##
-
-
1
S = /[ \t\r\n\f]+/
-
-
1
COMMENT = %r{/\*([^*]|\*+[^/*])*\**\*/}
-
1
SINGLE_LINE_COMMENT = %r{//.*(\n[ \t]*//.*)*}
-
-
1
CDO = quote("<!--")
-
1
CDC = quote("-->")
-
1
INCLUDES = quote("~=")
-
1
DASHMATCH = quote("|=")
-
1
PREFIXMATCH = quote("^=")
-
1
SUFFIXMATCH = quote("$=")
-
1
SUBSTRINGMATCH = quote("*=")
-
-
1
HASH = /##{NAME}/
-
-
1
IMPORTANT = /!#{W}important/i
-
-
# A unit is like an IDENT, but disallows a hyphen followed by a digit.
-
# This allows "1px-2px" to be interpreted as subtraction rather than "1"
-
# with the unit "px-2px". It also allows "%".
-
1
UNIT = /-?#{NMSTART}(?:[a-zA-Z0-9_]|#{NONASCII}|#{ESCAPE}|-(?!\.?\d))*|%/
-
-
1
UNITLESS_NUMBER = /(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?\d+)?/
-
1
NUMBER = /#{UNITLESS_NUMBER}(?:#{UNIT})?/
-
1
PERCENTAGE = /#{UNITLESS_NUMBER}%/
-
-
1
URI = /url\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
1
FUNCTION = /#{IDENT}\(/
-
-
1
UNICODERANGE = /u\+(?:#{H}{1,6}-#{H}{1,6}|#{RANGE})/i
-
-
# Defined in http://www.w3.org/TR/css3-selectors/#lex
-
1
PLUS = /#{W}\+/
-
1
GREATER = /#{W}>/
-
1
TILDE = /#{W}~/
-
1
NOT = quote(":not(", Regexp::IGNORECASE)
-
-
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
-
# non-standard version of http://www.w3.org/TR/css3-conditional/
-
1
URL_PREFIX = /url-prefix\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
1
DOMAIN = /domain\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
-
# Custom
-
1
HEXCOLOR = /\#[0-9a-fA-F]+/
-
1
INTERP_START = /#\{/
-
1
ANY = /:(-[-\w]+-)?any\(/i
-
1
OPTIONAL = /!#{W}optional/i
-
1
IDENT_START = /-|#{NMSTART}/
-
-
1
IDENT_HYPHEN_INTERP = /-(?=#\{)/
-
1
STRING1_NOINTERP = /\"((?:[^\n\r\f\\"#]|#(?!\{)|#{ESCAPE})*)\"/
-
1
STRING2_NOINTERP = /\'((?:[^\n\r\f\\'#]|#(?!\{)|#{ESCAPE})*)\'/
-
1
STRING_NOINTERP = /#{STRING1_NOINTERP}|#{STRING2_NOINTERP}/
-
-
1
STATIC_COMPONENT = /#{IDENT}|#{STRING_NOINTERP}|#{HEXCOLOR}|[+-]?#{NUMBER}|\!important/i
-
1
STATIC_VALUE = %r(#{STATIC_COMPONENT}(\s*[\s,\/]\s*#{STATIC_COMPONENT})*(?=[;}]))i
-
1
STATIC_SELECTOR = /(#{NMCHAR}|[ \t]|[,>+*]|[:#.]#{NMSTART}){1,50}([{])/i
-
end
-
end
-
end
-
1
require 'sass/script/css_parser'
-
-
1
module Sass
-
1
module SCSS
-
# A parser for a static SCSS tree.
-
# Parses with SCSS extensions, like nested rules and parent selectors,
-
# but without dynamic SassScript.
-
# This is useful for e.g. \{#parse\_selector parsing selectors}
-
# after resolving the interpolation.
-
1
class StaticParser < Parser
-
# Parses the text as a selector.
-
#
-
# @param filename [String, nil] The file in which the selector appears,
-
# or nil if there is no such file.
-
# Used for error reporting.
-
# @return [Selector::CommaSequence] The parsed selector
-
# @raise [Sass::SyntaxError] if there's a syntax error in the selector
-
1
def parse_selector
-
init_scanner!
-
seq = expr!(:selector_comma_sequence)
-
expected("selector") unless @scanner.eos?
-
seq.line = @line
-
seq.filename = @filename
-
seq
-
end
-
-
# Parses a static at-root query.
-
#
-
# @return [(Symbol, Array<String>)] The type of the query
-
# (`:with` or `:without`) and the values that are being filtered.
-
# @raise [Sass::SyntaxError] if there's a syntax error in the query,
-
# or if it doesn't take up the entire input string.
-
1
def parse_static_at_root_query
-
init_scanner!
-
tok!(/\(/); ss
-
type = tok!(/\b(without|with)\b/).to_sym; ss
-
tok!(/:/); ss
-
directives = expr!(:at_root_directive_list); ss
-
tok!(/\)/)
-
expected("@at-root query list") unless @scanner.eos?
-
return type, directives
-
end
-
-
1
def parse_keyframes_selector
-
init_scanner!
-
sel = expr!(:keyframes_selector)
-
expected("keyframes selector") unless @scanner.eos?
-
sel
-
end
-
-
# @see Parser#initialize
-
# @param allow_parent_ref [Boolean] Whether to allow the
-
# parent-reference selector, `&`, when parsing the document.
-
# @comment
-
# rubocop:disable ParameterLists
-
1
def initialize(str, filename, importer, line = 1, offset = 1, allow_parent_ref = true)
-
# rubocop:enable ParameterLists
-
super(str, filename, importer, line, offset)
-
@allow_parent_ref = allow_parent_ref
-
end
-
-
1
private
-
-
1
def moz_document_function
-
val = tok(URI) || tok(URL_PREFIX) || tok(DOMAIN) || function(false)
-
return unless val
-
ss
-
[val]
-
end
-
-
1
def variable; nil; end
-
1
def script_value; nil; end
-
1
def interpolation(warn_for_color = false); nil; end
-
1
def var_expr; nil; end
-
1
def interp_string; (s = tok(STRING)) && [s]; end
-
1
def interp_uri; (s = tok(URI)) && [s]; end
-
1
def interp_ident(ident = IDENT); (s = tok(ident)) && [s]; end
-
1
def use_css_import?; true; end
-
-
1
def special_directive(name, start_pos)
-
return unless %w(media import charset -moz-document).include?(name)
-
super
-
end
-
-
1
def selector_comma_sequence
-
sel = selector
-
return unless sel
-
selectors = [sel]
-
ws = ''
-
while tok(/,/)
-
ws << str {ss}
-
next unless (sel = selector)
-
selectors << sel
-
if ws.include?("\n")
-
selectors[-1] = Selector::Sequence.new(["\n"] + selectors.last.members)
-
end
-
ws = ''
-
end
-
Selector::CommaSequence.new(selectors)
-
end
-
-
1
def selector_string
-
sel = selector
-
return unless sel
-
sel.to_s
-
end
-
-
1
def selector
-
start_pos = source_position
-
# The combinator here allows the "> E" hack
-
val = combinator || simple_selector_sequence
-
return unless val
-
nl = str {ss}.include?("\n")
-
res = []
-
res << val
-
res << "\n" if nl
-
-
while (val = combinator || simple_selector_sequence)
-
res << val
-
res << "\n" if str {ss}.include?("\n")
-
end
-
seq = Selector::Sequence.new(res.compact)
-
-
if seq.members.any? {|sseq| sseq.is_a?(Selector::SimpleSequence) && sseq.subject?}
-
location = " of #{@filename}" if @filename
-
Sass::Util.sass_warn <<MESSAGE
-
DEPRECATION WARNING on line #{start_pos.line}, column #{start_pos.offset}#{location}:
-
The subject selector operator "!" is deprecated and will be removed in a future release.
-
This operator has been replaced by ":has()" in the CSS spec.
-
For example: #{seq.subjectless}
-
MESSAGE
-
end
-
-
seq
-
end
-
-
1
def combinator
-
tok(PLUS) || tok(GREATER) || tok(TILDE) || reference_combinator
-
end
-
-
1
def reference_combinator
-
return unless tok(%r{/})
-
res = '/'
-
ns, name = expr!(:qualified_name)
-
res << ns << '|' if ns
-
res << name << tok!(%r{/})
-
-
location = " of #{@filename}" if @filename
-
Sass::Util.sass_warn <<MESSAGE
-
DEPRECATION WARNING on line #{@line}, column #{@offset}#{location}:
-
The reference combinator #{res} is deprecated and will be removed in a future release.
-
MESSAGE
-
-
res
-
end
-
-
1
def simple_selector_sequence
-
start_pos = source_position
-
e = element_name || id_selector || class_selector || placeholder_selector || attrib ||
-
pseudo || parent_selector
-
return unless e
-
res = [e]
-
-
# The tok(/\*/) allows the "E*" hack
-
while (v = id_selector || class_selector || placeholder_selector ||
-
attrib || pseudo || (tok(/\*/) && Selector::Universal.new(nil)))
-
res << v
-
end
-
-
pos = @scanner.pos
-
line = @line
-
if (sel = str? {simple_selector_sequence})
-
@scanner.pos = pos
-
@line = line
-
begin
-
# If we see "*E", don't force a throw because this could be the
-
# "*prop: val" hack.
-
expected('"{"') if res.length == 1 && res[0].is_a?(Selector::Universal)
-
throw_error {expected('"{"')}
-
rescue Sass::SyntaxError => e
-
e.message << "\n\n\"#{sel}\" may only be used at the beginning of a compound selector."
-
raise e
-
end
-
end
-
-
Selector::SimpleSequence.new(res, tok(/!/), range(start_pos))
-
end
-
-
1
def parent_selector
-
return unless @allow_parent_ref && tok(/&/)
-
Selector::Parent.new(tok(NAME))
-
end
-
-
1
def class_selector
-
return unless tok(/\./)
-
@expected = "class name"
-
Selector::Class.new(tok!(IDENT))
-
end
-
-
1
def id_selector
-
return unless tok(/#(?!\{)/)
-
@expected = "id name"
-
Selector::Id.new(tok!(NAME))
-
end
-
-
1
def placeholder_selector
-
return unless tok(/%/)
-
@expected = "placeholder name"
-
Selector::Placeholder.new(tok!(IDENT))
-
end
-
-
1
def element_name
-
ns, name = Sass::Util.destructure(qualified_name(:allow_star_name))
-
return unless ns || name
-
-
if name == '*'
-
Selector::Universal.new(ns)
-
else
-
Selector::Element.new(name, ns)
-
end
-
end
-
-
1
def qualified_name(allow_star_name = false)
-
name = tok(IDENT) || tok(/\*/) || (tok?(/\|/) && "")
-
return unless name
-
return nil, name unless tok(/\|/)
-
-
return name, tok!(IDENT) unless allow_star_name
-
@expected = "identifier or *"
-
return name, tok(IDENT) || tok!(/\*/)
-
end
-
-
1
def attrib
-
return unless tok(/\[/)
-
ss
-
ns, name = attrib_name!
-
ss
-
-
op = tok(/=/) ||
-
tok(INCLUDES) ||
-
tok(DASHMATCH) ||
-
tok(PREFIXMATCH) ||
-
tok(SUFFIXMATCH) ||
-
tok(SUBSTRINGMATCH)
-
if op
-
@expected = "identifier or string"
-
ss
-
val = tok(IDENT) || tok!(STRING)
-
ss
-
end
-
flags = tok(IDENT) || tok(STRING)
-
tok!(/\]/)
-
-
Selector::Attribute.new(name, ns, op, val, flags)
-
end
-
-
1
def attrib_name!
-
if (name_or_ns = tok(IDENT))
-
# E, E|E
-
if tok(/\|(?!=)/)
-
ns = name_or_ns
-
name = tok(IDENT)
-
else
-
name = name_or_ns
-
end
-
else
-
# *|E or |E
-
ns = tok(/\*/) || ""
-
tok!(/\|/)
-
name = tok!(IDENT)
-
end
-
return ns, name
-
end
-
-
1
SELECTOR_PSEUDO_CLASSES = %w(not matches current any has host host-context).to_set
-
-
1
PREFIXED_SELECTOR_PSEUDO_CLASSES = %w(nth-child nth-last-child).to_set
-
-
1
SELECTOR_PSEUDO_ELEMENTS = %w(slotted).to_set
-
-
1
def pseudo
-
s = tok(/::?/)
-
return unless s
-
@expected = "pseudoclass or pseudoelement"
-
name = tok!(IDENT)
-
if tok(/\(/)
-
ss
-
deprefixed = deprefix(name)
-
if s == ':' && SELECTOR_PSEUDO_CLASSES.include?(deprefixed)
-
sel = selector_comma_sequence
-
elsif s == ':' && PREFIXED_SELECTOR_PSEUDO_CLASSES.include?(deprefixed)
-
arg, sel = prefixed_selector_pseudo
-
elsif s == '::' && SELECTOR_PSEUDO_ELEMENTS.include?(deprefixed)
-
sel = selector_comma_sequence
-
else
-
arg = expr!(:declaration_value).join
-
end
-
-
tok!(/\)/)
-
end
-
Selector::Pseudo.new(s == ':' ? :class : :element, name, arg, sel)
-
end
-
-
1
def prefixed_selector_pseudo
-
prefix = str do
-
expr = str {expr!(:a_n_plus_b)}
-
ss
-
return expr, nil unless tok(/of/)
-
ss
-
end
-
return prefix, expr!(:selector_comma_sequence)
-
end
-
-
1
def a_n_plus_b
-
if (parity = tok(/even|odd/i))
-
return parity
-
end
-
-
if tok(/[+-]?[0-9]+/)
-
ss
-
return true unless tok(/n/)
-
else
-
return unless tok(/[+-]?n/i)
-
end
-
ss
-
-
return true unless tok(/[+-]/)
-
ss
-
@expected = "number"
-
tok!(/[0-9]+/)
-
true
-
end
-
-
1
def keyframes_selector
-
ss
-
str do
-
return unless keyframes_selector_component
-
ss
-
while tok(/,/)
-
ss
-
expr!(:keyframes_selector_component)
-
ss
-
end
-
end
-
end
-
-
1
def keyframes_selector_component
-
tok(IDENT) || tok(PERCENTAGE)
-
end
-
-
1
@sass_script_parser = Class.new(Sass::Script::CssParser)
-
end
-
end
-
end
-
1
require 'sass/selector/simple'
-
1
require 'sass/selector/abstract_sequence'
-
1
require 'sass/selector/comma_sequence'
-
1
require 'sass/selector/pseudo'
-
1
require 'sass/selector/sequence'
-
1
require 'sass/selector/simple_sequence'
-
-
1
module Sass
-
# A namespace for nodes in the parse tree for selectors.
-
#
-
# {CommaSequence} is the toplevel selector,
-
# representing a comma-separated sequence of {Sequence}s,
-
# such as `foo bar, baz bang`.
-
# {Sequence} is the next level,
-
# representing {SimpleSequence}s separated by combinators (e.g. descendant or child),
-
# such as `foo bar` or `foo > bar baz`.
-
# {SimpleSequence} is a sequence of selectors that all apply to a single element,
-
# such as `foo.bar[attr=val]`.
-
# Finally, {Simple} is the superclass of the simplest selectors,
-
# such as `.foo` or `#bar`.
-
1
module Selector
-
# The base used for calculating selector specificity. The spec says this
-
# should be "sufficiently high"; it's extremely unlikely that any single
-
# selector sequence will contain 1,000 simple selectors.
-
1
SPECIFICITY_BASE = 1_000
-
-
# A parent-referencing selector (`&` in Sass).
-
# The function of this is to be replaced by the parent selector
-
# in the nested hierarchy.
-
1
class Parent < Simple
-
# The identifier following the `&`. `nil` indicates no suffix.
-
#
-
# @return [String, nil]
-
1
attr_reader :suffix
-
-
# @param name [String, nil] See \{#suffix}
-
1
def initialize(suffix = nil)
-
@suffix = suffix
-
end
-
-
# @see Selector#to_s
-
1
def to_s(opts = {})
-
"&" + (@suffix || '')
-
end
-
-
# Always raises an exception.
-
#
-
# @raise [Sass::SyntaxError] Parent selectors should be resolved before unification
-
# @see Selector#unify
-
1
def unify(sels)
-
raise Sass::SyntaxError.new("[BUG] Cannot unify parent selectors.")
-
end
-
end
-
-
# A class selector (e.g. `.foo`).
-
1
class Class < Simple
-
# The class name.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# @param name [String] The class name
-
1
def initialize(name)
-
@name = name
-
end
-
-
# @see Selector#to_s
-
1
def to_s(opts = {})
-
"." + @name
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
-
# An id selector (e.g. `#foo`).
-
1
class Id < Simple
-
# The id name.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# @param name [String] The id name
-
1
def initialize(name)
-
@name = name
-
end
-
-
1
def unique?
-
true
-
end
-
-
# @see Selector#to_s
-
1
def to_s(opts = {})
-
"#" + @name
-
end
-
-
# Returns `nil` if `sels` contains an {Id} selector
-
# with a different name than this one.
-
#
-
# @see Selector#unify
-
1
def unify(sels)
-
return if sels.any? {|sel2| sel2.is_a?(Id) && name != sel2.name}
-
super
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
SPECIFICITY_BASE**2
-
end
-
end
-
-
# A placeholder selector (e.g. `%foo`).
-
# This exists to be replaced via `@extend`.
-
# Rulesets using this selector will not be printed, but can be extended.
-
# Otherwise, this acts just like a class selector.
-
1
class Placeholder < Simple
-
# The placeholder name.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# @param name [String] The placeholder name
-
1
def initialize(name)
-
@name = name
-
end
-
-
# @see Selector#to_s
-
1
def to_s(opts = {})
-
"%" + @name
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
-
# A universal selector (`*` in CSS).
-
1
class Universal < Simple
-
# The selector namespace. `nil` means the default namespace, `""` means no
-
# namespace, `"*"` means any namespace.
-
#
-
# @return [String, nil]
-
1
attr_reader :namespace
-
-
# @param namespace [String, nil] See \{#namespace}
-
1
def initialize(namespace)
-
@namespace = namespace
-
end
-
-
# @see Selector#to_s
-
1
def to_s(opts = {})
-
@namespace ? "#{@namespace}|*" : "*"
-
end
-
-
# Unification of a universal selector is somewhat complicated,
-
# especially when a namespace is specified.
-
# If there is no namespace specified
-
# or any namespace is specified (namespace `"*"`),
-
# then `sel` is returned without change
-
# (unless it's empty, in which case `"*"` is required).
-
#
-
# If a namespace is specified
-
# but `sel` does not specify a namespace,
-
# then the given namespace is applied to `sel`,
-
# either by adding this {Universal} selector
-
# or applying this namespace to an existing {Element} selector.
-
#
-
# If both this selector *and* `sel` specify namespaces,
-
# those namespaces are unified via {Simple#unify_namespaces}
-
# and the unified namespace is used, if possible.
-
#
-
# @todo There are lots of cases that this documentation specifies;
-
# make sure we thoroughly test **all of them**.
-
# @todo Keep track of whether a default namespace has been declared
-
# and handle namespace-unspecified selectors accordingly.
-
# @todo If any branch of a CommaSequence ends up being just `"*"`,
-
# then all other branches should be eliminated
-
#
-
# @see Selector#unify
-
1
def unify(sels)
-
name =
-
case sels.first
-
when Universal; :universal
-
when Element; sels.first.name
-
else
-
return [self] + sels unless namespace.nil? || namespace == '*'
-
return sels unless sels.empty?
-
return [self]
-
end
-
-
ns, accept = unify_namespaces(namespace, sels.first.namespace)
-
return unless accept
-
[name == :universal ? Universal.new(ns) : Element.new(name, ns)] + sels[1..-1]
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
0
-
end
-
end
-
-
# An element selector (e.g. `h1`).
-
1
class Element < Simple
-
# The element name.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# The selector namespace. `nil` means the default namespace, `""` means no
-
# namespace, `"*"` means any namespace.
-
#
-
# @return [String, nil]
-
1
attr_reader :namespace
-
-
# @param name [String] The element name
-
# @param namespace [String, nil] See \{#namespace}
-
1
def initialize(name, namespace)
-
@name = name
-
@namespace = namespace
-
end
-
-
# @see Selector#to_s
-
1
def to_s(opts = {})
-
@namespace ? "#{@namespace}|#{@name}" : @name
-
end
-
-
# Unification of an element selector is somewhat complicated,
-
# especially when a namespace is specified.
-
# First, if `sel` contains another {Element} with a different \{#name},
-
# then the selectors can't be unified and `nil` is returned.
-
#
-
# Otherwise, if `sel` doesn't specify a namespace,
-
# or it specifies any namespace (via `"*"`),
-
# then it's returned with this element selector
-
# (e.g. `.foo` becomes `a.foo` or `svg|a.foo`).
-
# Similarly, if this selector doesn't specify a namespace,
-
# the namespace from `sel` is used.
-
#
-
# If both this selector *and* `sel` specify namespaces,
-
# those namespaces are unified via {Simple#unify_namespaces}
-
# and the unified namespace is used, if possible.
-
#
-
# @todo There are lots of cases that this documentation specifies;
-
# make sure we thoroughly test **all of them**.
-
# @todo Keep track of whether a default namespace has been declared
-
# and handle namespace-unspecified selectors accordingly.
-
#
-
# @see Selector#unify
-
1
def unify(sels)
-
case sels.first
-
when Universal;
-
when Element; return unless name == sels.first.name
-
else return [self] + sels
-
end
-
-
ns, accept = unify_namespaces(namespace, sels.first.namespace)
-
return unless accept
-
[Element.new(name, ns)] + sels[1..-1]
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
1
-
end
-
end
-
-
# An attribute selector (e.g. `[href^="http://"]`).
-
1
class Attribute < Simple
-
# The attribute name.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_reader :name
-
-
# The attribute namespace. `nil` means the default namespace, `""` means
-
# no namespace, `"*"` means any namespace.
-
#
-
# @return [String, nil]
-
1
attr_reader :namespace
-
-
# The matching operator, e.g. `"="` or `"^="`.
-
#
-
# @return [String]
-
1
attr_reader :operator
-
-
# The right-hand side of the operator.
-
#
-
# @return [String]
-
1
attr_reader :value
-
-
# Flags for the attribute selector (e.g. `i`).
-
#
-
# @return [String]
-
1
attr_reader :flags
-
-
# @param name [String] The attribute name
-
# @param namespace [String, nil] See \{#namespace}
-
# @param operator [String] The matching operator, e.g. `"="` or `"^="`
-
# @param value [String] See \{#value}
-
# @param flags [String] See \{#flags}
-
1
def initialize(name, namespace, operator, value, flags)
-
@name = name
-
@namespace = namespace
-
@operator = operator
-
@value = value
-
@flags = flags
-
end
-
-
# @see Selector#to_s
-
1
def to_s(opts = {})
-
res = "["
-
res << @namespace << "|" if @namespace
-
res << @name
-
res << @operator << @value if @value
-
res << " " << @flags if @flags
-
res << "]"
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Selector
-
# A comma-separated sequence of selectors.
-
1
class CommaSequence < AbstractSequence
-
1
@@compound_extend_deprecation = Sass::Deprecation.new
-
-
# The comma-separated selector sequences
-
# represented by this class.
-
#
-
# @return [Array<Sequence>]
-
1
attr_reader :members
-
-
# @param seqs [Array<Sequence>] See \{#members}
-
1
def initialize(seqs)
-
@members = seqs
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_cseq [CommaSequence] The parent selector
-
# @param implicit_parent [Boolean] Whether the the parent
-
# selector should automatically be prepended to the resolved
-
# selector if it contains no parent refs.
-
# @return [CommaSequence] This selector, with parent references resolved
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
1
def resolve_parent_refs(super_cseq, implicit_parent = true)
-
if super_cseq.nil?
-
if contains_parent_ref?
-
raise Sass::SyntaxError.new(
-
"Base-level rules cannot contain the parent-selector-referencing character '&'.")
-
end
-
return self
-
end
-
-
CommaSequence.new(Sass::Util.flatten_vertically(@members.map do |seq|
-
seq.resolve_parent_refs(super_cseq, implicit_parent).members
-
end))
-
end
-
-
# Returns whether there's a {Parent} selector anywhere in this sequence.
-
#
-
# @return [Boolean]
-
1
def contains_parent_ref?
-
@members.any? {|sel| sel.contains_parent_ref?}
-
end
-
-
# Non-destrucively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @todo Link this to the reference documentation on `@extend`
-
# when such a thing exists.
-
#
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @param replace [Boolean]
-
# Whether to replace the original selector entirely or include
-
# it in the result.
-
# @param seen [Set<Array<Selector::Simple>>]
-
# The set of simple sequences that are currently being replaced.
-
# @param original [Boolean]
-
# Whether this is the original selector being extended, as opposed to
-
# the result of a previous extension that's being re-extended.
-
# @return [CommaSequence] A copy of this selector,
-
# with extensions made according to `extends`
-
1
def do_extend(extends, parent_directives = [], replace = false, seen = Set.new,
-
original = true)
-
CommaSequence.new(members.map do |seq|
-
seq.do_extend(extends, parent_directives, replace, seen, original)
-
end.flatten)
-
end
-
-
# Returns whether or not this selector matches all elements
-
# that the given selector matches (as well as possibly more).
-
#
-
# @example
-
# (.foo).superselector?(.foo.bar) #=> true
-
# (.foo).superselector?(.bar) #=> false
-
# @param cseq [CommaSequence]
-
# @return [Boolean]
-
1
def superselector?(cseq)
-
cseq.members.all? {|seq1| members.any? {|seq2| seq2.superselector?(seq1)}}
-
end
-
-
# Populates a subset map that can then be used to extend
-
# selectors. This registers an extension with this selector as
-
# the extender and `extendee` as the extendee.
-
#
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The subset map representing the extensions to perform.
-
# @param extendee [CommaSequence] The selector being extended.
-
# @param extend_node [Sass::Tree::ExtendNode]
-
# The node that caused this extension.
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The parent directives containing `extend_node`.
-
# @param allow_compound_target [Boolean]
-
# Whether `extendee` is allowed to contain compound selectors.
-
# @raise [Sass::SyntaxError] if this extension is invalid.
-
1
def populate_extends(extends, extendee, extend_node = nil, parent_directives = [],
-
allow_compound_target = false)
-
extendee.members.each do |seq|
-
if seq.members.size > 1
-
raise Sass::SyntaxError.new("Can't extend #{seq}: can't extend nested selectors")
-
end
-
-
sseq = seq.members.first
-
if !sseq.is_a?(Sass::Selector::SimpleSequence)
-
raise Sass::SyntaxError.new("Can't extend #{seq}: invalid selector")
-
elsif sseq.members.any? {|ss| ss.is_a?(Sass::Selector::Parent)}
-
raise Sass::SyntaxError.new("Can't extend #{seq}: can't extend parent selectors")
-
end
-
-
sel = sseq.members
-
if !allow_compound_target && sel.length > 1
-
@@compound_extend_deprecation.warn(sseq.filename, sseq.line, <<WARNING)
-
Extending a compound selector, #{sseq}, is deprecated and will not be supported in a future release.
-
See https://github.com/sass/sass/issues/1599 for details.
-
WARNING
-
end
-
-
members.each do |member|
-
unless member.members.last.is_a?(Sass::Selector::SimpleSequence)
-
raise Sass::SyntaxError.new("#{member} can't extend: invalid selector")
-
end
-
-
extends[sel] = Sass::Tree::Visitors::Cssize::Extend.new(
-
member, sel, extend_node, parent_directives, false)
-
end
-
end
-
end
-
-
# Unifies this with another comma selector to produce a selector
-
# that matches (a subset of) the intersection of the two inputs.
-
#
-
# @param other [CommaSequence]
-
# @return [CommaSequence, nil] The unified selector, or nil if unification failed.
-
# @raise [Sass::SyntaxError] If this selector cannot be unified.
-
# This will only ever occur when a dynamic selector,
-
# such as {Parent} or {Interpolation}, is used in unification.
-
# Since these selectors should be resolved
-
# by the time extension and unification happen,
-
# this exception will only ever be raised as a result of programmer error
-
1
def unify(other)
-
results = members.map {|seq1| other.members.map {|seq2| seq1.unify(seq2)}}.flatten.compact
-
results.empty? ? nil : CommaSequence.new(results.map {|cseq| cseq.members}.flatten)
-
end
-
-
# Returns a SassScript representation of this selector.
-
#
-
# @return [Sass::Script::Value::List]
-
1
def to_sass_script
-
Sass::Script::Value::List.new(members.map do |seq|
-
Sass::Script::Value::List.new(seq.members.map do |component|
-
next if component == "\n"
-
Sass::Script::Value::String.new(component.to_s)
-
end.compact, separator: :space)
-
end, separator: :comma)
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
1
def inspect
-
members.map {|m| m.inspect}.join(", ")
-
end
-
-
# @see AbstractSequence#to_s
-
1
def to_s(opts = {})
-
@members.map do |m|
-
next if opts[:placeholder] == false && m.invisible?
-
m.to_s(opts)
-
end.compact.
-
join(opts[:style] == :compressed ? "," : ", ").
-
gsub(", \n", ",\n")
-
end
-
-
1
private
-
-
1
def _hash
-
members.hash
-
end
-
-
1
def _eql?(other)
-
other.class == self.class && other.members.eql?(members)
-
end
-
end
-
end
-
end
-
# coding: utf-8
-
1
module Sass
-
1
module Selector
-
# A pseudoclass (e.g. `:visited`) or pseudoelement (e.g. `::first-line`)
-
# selector. It can have arguments (e.g. `:nth-child(2n+1)`) which can
-
# contain selectors (e.g. `:nth-child(2n+1 of .foo)`).
-
1
class Pseudo < Simple
-
# Some pseudo-class-syntax selectors are actually considered
-
# pseudo-elements and must be treated differently. This is a list of such
-
# selectors.
-
#
-
# @return [Set<String>]
-
1
ACTUALLY_ELEMENTS = %w(after before first-line first-letter).to_set
-
-
# Like \{#type}, but returns the type of selector this looks like, rather
-
# than the type it is semantically. This only differs from type for
-
# selectors in \{ACTUALLY\_ELEMENTS}.
-
#
-
# @return [Symbol]
-
1
attr_reader :syntactic_type
-
-
# The name of the selector.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# The argument to the selector,
-
# or `nil` if no argument was given.
-
#
-
# @return [String, nil]
-
1
attr_reader :arg
-
-
# The selector argument, or `nil` if no selector exists.
-
#
-
# If this and \{#arg\} are both set, \{#arg\} is considered a non-selector
-
# prefix.
-
#
-
# @return [CommaSequence]
-
1
attr_reader :selector
-
-
# @param syntactic_type [Symbol] See \{#syntactic_type}
-
# @param name [String] See \{#name}
-
# @param arg [nil, String] See \{#arg}
-
# @param selector [nil, CommaSequence] See \{#selector}
-
1
def initialize(syntactic_type, name, arg, selector)
-
@syntactic_type = syntactic_type
-
@name = name
-
@arg = arg
-
@selector = selector
-
end
-
-
1
def unique?
-
type == :class && normalized_name == 'root'
-
end
-
-
# Whether or not this selector should be hidden due to containing a
-
# placeholder.
-
1
def invisible?
-
# :not() is a special case—if you eliminate all the placeholders from
-
# it, it should match anything.
-
name != 'not' && @selector && @selector.members.all? {|s| s.invisible?}
-
end
-
-
# Returns a copy of this with \{#selector} set to \{#new\_selector}.
-
#
-
# @param new_selector [CommaSequence]
-
# @return [Array<Simple>]
-
1
def with_selector(new_selector)
-
result = Pseudo.new(syntactic_type, name, arg,
-
CommaSequence.new(new_selector.members.map do |seq|
-
next seq unless seq.members.length == 1
-
sseq = seq.members.first
-
next seq unless sseq.is_a?(SimpleSequence) && sseq.members.length == 1
-
sel = sseq.members.first
-
next seq unless sel.is_a?(Pseudo) && sel.selector
-
-
case normalized_name
-
when 'not'
-
# In theory, if there's a nested :not its contents should be
-
# unified with the return value. For example, if :not(.foo)
-
# extends .bar, :not(.bar) should become .foo:not(.bar). However,
-
# this is a narrow edge case and supporting it properly would make
-
# this code and the code calling it a lot more complicated, so
-
# it's not supported for now.
-
next [] unless sel.normalized_name == 'matches'
-
sel.selector.members
-
when 'matches', 'any', 'current', 'nth-child', 'nth-last-child'
-
# As above, we could theoretically support :not within :matches, but
-
# doing so would require this method and its callers to handle much
-
# more complex cases that likely aren't worth the pain.
-
next [] unless sel.name == name && sel.arg == arg
-
sel.selector.members
-
when 'has', 'host', 'host-context', 'slotted'
-
# We can't expand nested selectors here, because each layer adds an
-
# additional layer of semantics. For example, `:has(:has(img))`
-
# doesn't match `<div><img></div>` but `:has(img)` does.
-
sel
-
else
-
[]
-
end
-
end.flatten))
-
-
# Older browsers support :not but only with a single complex selector.
-
# In order to support those browsers, we break up the contents of a :not
-
# unless it originally contained a selector list.
-
return [result] unless normalized_name == 'not'
-
return [result] if selector.members.length > 1
-
result.selector.members.map do |seq|
-
Pseudo.new(syntactic_type, name, arg, CommaSequence.new([seq]))
-
end
-
end
-
-
# The type of the selector. `:class` if this is a pseudoclass selector,
-
# `:element` if it's a pseudoelement.
-
#
-
# @return [Symbol]
-
1
def type
-
ACTUALLY_ELEMENTS.include?(normalized_name) ? :element : syntactic_type
-
end
-
-
# Like \{#name\}, but without any vendor prefix.
-
#
-
# @return [String]
-
1
def normalized_name
-
@normalized_name ||= name.gsub(/^-[a-zA-Z0-9]+-/, '')
-
end
-
-
# @see Selector#to_s
-
1
def to_s(opts = {})
-
# :not() is a special case, because :not(<nothing>) should match
-
# everything.
-
return '' if name == 'not' && @selector && @selector.members.all? {|m| m.invisible?}
-
-
res = (syntactic_type == :class ? ":" : "::") + @name
-
if @arg || @selector
-
res << "("
-
res << @arg.strip if @arg
-
res << " " if @arg && @selector
-
res << @selector.to_s(opts) if @selector
-
res << ")"
-
end
-
res
-
end
-
-
# Returns `nil` if this is a pseudoelement selector
-
# and `sels` contains a pseudoelement selector different than this one.
-
#
-
# @see SimpleSequence#unify
-
1
def unify(sels)
-
return if type == :element && sels.any? do |sel|
-
sel.is_a?(Pseudo) && sel.type == :element &&
-
(sel.name != name || sel.arg != arg || sel.selector != selector)
-
end
-
super
-
end
-
-
# Returns whether or not this selector matches all elements
-
# that the given selector matches (as well as possibly more).
-
#
-
# @example
-
# (.foo).superselector?(.foo.bar) #=> true
-
# (.foo).superselector?(.bar) #=> false
-
# @param their_sseq [SimpleSequence]
-
# @param parents [Array<SimpleSequence, String>] The parent selectors of `their_sseq`, if any.
-
# @return [Boolean]
-
1
def superselector?(their_sseq, parents = [])
-
case normalized_name
-
when 'matches', 'any'
-
# :matches can be a superselector of another selector in one of two
-
# ways. Either its constituent selectors can be a superset of those of
-
# another :matches in the other selector, or any of its constituent
-
# selectors can individually be a superselector of the other selector.
-
(their_sseq.selector_pseudo_classes[normalized_name] || []).any? do |their_sel|
-
next false unless their_sel.is_a?(Pseudo)
-
next false unless their_sel.name == name
-
selector.superselector?(their_sel.selector)
-
end || selector.members.any? do |our_seq|
-
their_seq = Sequence.new(parents + [their_sseq])
-
our_seq.superselector?(their_seq)
-
end
-
when 'has', 'host', 'host-context', 'slotted'
-
# Like :matches, :has (et al) can be a superselector of another
-
# selector if its constituent selectors are a superset of those of
-
# another :has in the other selector. However, the :matches other case
-
# doesn't work, because :has refers to nested elements.
-
(their_sseq.selector_pseudo_classes[normalized_name] || []).any? do |their_sel|
-
next false unless their_sel.is_a?(Pseudo)
-
next false unless their_sel.name == name
-
selector.superselector?(their_sel.selector)
-
end
-
when 'not'
-
selector.members.all? do |our_seq|
-
their_sseq.members.any? do |their_sel|
-
if their_sel.is_a?(Element) || their_sel.is_a?(Id)
-
# `:not(a)` is a superselector of `h1` and `:not(#foo)` is a
-
# superselector of `#bar`.
-
our_sseq = our_seq.members.last
-
next false unless our_sseq.is_a?(SimpleSequence)
-
our_sseq.members.any? do |our_sel|
-
our_sel.class == their_sel.class && our_sel != their_sel
-
end
-
else
-
next false unless their_sel.is_a?(Pseudo)
-
next false unless their_sel.name == name
-
# :not(X) is a superselector of :not(Y) exactly when Y is a
-
# superselector of X.
-
their_sel.selector.superselector?(CommaSequence.new([our_seq]))
-
end
-
end
-
end
-
when 'current'
-
(their_sseq.selector_pseudo_classes['current'] || []).any? do |their_current|
-
next false if their_current.name != name
-
# Explicitly don't check for nested superselector relationships
-
# here. :current(.foo) isn't always a superselector of
-
# :current(.foo.bar), since it matches the *innermost* ancestor of
-
# the current element that matches the selector. For example:
-
#
-
# <div class="foo bar">
-
# <p class="foo">
-
# <span>current element</span>
-
# </p>
-
# </div>
-
#
-
# Here :current(.foo) would match the p element and *not* the div
-
# element, whereas :current(.foo.bar) would match the div and not
-
# the p.
-
selector == their_current.selector
-
end
-
when 'nth-child', 'nth-last-child'
-
their_sseq.members.any? do |their_sel|
-
# This misses a few edge cases. For example, `:nth-child(n of X)`
-
# is a superselector of `X`, and `:nth-child(2n of X)` is a
-
# superselector of `:nth-child(4n of X)`. These seem rare enough
-
# not to be worth worrying about, though.
-
next false unless their_sel.is_a?(Pseudo)
-
next false unless their_sel.name == name
-
next false unless their_sel.arg == arg
-
selector.superselector?(their_sel.selector)
-
end
-
else
-
throw "[BUG] Unknown selector pseudo class #{name}"
-
end
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
return 1 if type == :element
-
return SPECIFICITY_BASE unless selector
-
@specificity ||=
-
if normalized_name == 'not'
-
min = 0
-
max = 0
-
selector.members.each do |seq|
-
spec = seq.specificity
-
if spec.is_a?(Range)
-
min = Sass::Util.max(spec.begin, min)
-
max = Sass::Util.max(spec.end, max)
-
else
-
min = Sass::Util.max(spec, min)
-
max = Sass::Util.max(spec, max)
-
end
-
end
-
min == max ? max : (min..max)
-
else
-
min = 0
-
max = 0
-
selector.members.each do |seq|
-
spec = seq.specificity
-
if spec.is_a?(Range)
-
min = Sass::Util.min(spec.begin, min)
-
max = Sass::Util.max(spec.end, max)
-
else
-
min = Sass::Util.min(spec, min)
-
max = Sass::Util.max(spec, max)
-
end
-
end
-
min == max ? max : (min..max)
-
end
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Selector
-
# An operator-separated sequence of
-
# {SimpleSequence simple selector sequences}.
-
1
class Sequence < AbstractSequence
-
# Sets the line of the Sass template on which this selector was declared.
-
# This also sets the line for all child selectors.
-
#
-
# @param line [Integer]
-
# @return [Integer]
-
1
def line=(line)
-
members.each {|m| m.line = line if m.is_a?(SimpleSequence)}
-
@line = line
-
end
-
-
# Sets the name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
# This also sets the filename for all child selectors.
-
#
-
# @param filename [String, nil]
-
# @return [String, nil]
-
1
def filename=(filename)
-
members.each {|m| m.filename = filename if m.is_a?(SimpleSequence)}
-
filename
-
end
-
-
# The array of {SimpleSequence simple selector sequences}, operators, and
-
# newlines. The operators are strings such as `"+"` and `">"` representing
-
# the corresponding CSS operators, or interpolated SassScript. Newlines
-
# are also newline strings; these aren't semantically relevant, but they
-
# do affect formatting.
-
#
-
# @return [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>]
-
1
attr_reader :members
-
-
# @param seqs_and_ops [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>]
-
# See \{#members}
-
1
def initialize(seqs_and_ops)
-
@members = seqs_and_ops
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_cseq [CommaSequence] The parent selector
-
# @param implicit_parent [Boolean] Whether the the parent
-
# selector should automatically be prepended to the resolved
-
# selector if it contains no parent refs.
-
# @return [CommaSequence] This selector, with parent references resolved
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
1
def resolve_parent_refs(super_cseq, implicit_parent)
-
members = @members.dup
-
nl = (members.first == "\n" && members.shift)
-
contains_parent_ref = contains_parent_ref?
-
return CommaSequence.new([self]) if !implicit_parent && !contains_parent_ref
-
-
unless contains_parent_ref
-
old_members, members = members, []
-
members << nl if nl
-
members << SimpleSequence.new([Parent.new], false)
-
members += old_members
-
end
-
-
CommaSequence.new(Sass::Util.paths(members.map do |sseq_or_op|
-
next [sseq_or_op] unless sseq_or_op.is_a?(SimpleSequence)
-
sseq_or_op.resolve_parent_refs(super_cseq).members
-
end).map do |path|
-
path_members = path.map do |seq_or_op|
-
next seq_or_op unless seq_or_op.is_a?(Sequence)
-
seq_or_op.members
-
end
-
if path_members.length == 2 && path_members[1][0] == "\n"
-
path_members[0].unshift path_members[1].shift
-
end
-
Sequence.new(path_members.flatten)
-
end)
-
end
-
-
# Returns whether there's a {Parent} selector anywhere in this sequence.
-
#
-
# @return [Boolean]
-
1
def contains_parent_ref?
-
members.any? do |sseq_or_op|
-
next false unless sseq_or_op.is_a?(SimpleSequence)
-
next true if sseq_or_op.members.first.is_a?(Parent)
-
sseq_or_op.members.any? do |sel|
-
sel.is_a?(Pseudo) && sel.selector && sel.selector.contains_parent_ref?
-
end
-
end
-
end
-
-
# Non-destructively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @param replace [Boolean]
-
# Whether to replace the original selector entirely or include
-
# it in the result.
-
# @param seen [Set<Array<Selector::Simple>>]
-
# The set of simple sequences that are currently being replaced.
-
# @param original [Boolean]
-
# Whether this is the original selector being extended, as opposed to
-
# the result of a previous extension that's being re-extended.
-
# @return [Array<Sequence>] A list of selectors generated
-
# by extending this selector with `extends`.
-
# These correspond to a {CommaSequence}'s {CommaSequence#members members array}.
-
# @see CommaSequence#do_extend
-
1
def do_extend(extends, parent_directives, replace, seen, original)
-
extended_not_expanded = members.map do |sseq_or_op|
-
next [[sseq_or_op]] unless sseq_or_op.is_a?(SimpleSequence)
-
extended = sseq_or_op.do_extend(extends, parent_directives, replace, seen)
-
-
# The First Law of Extend says that the generated selector should have
-
# specificity greater than or equal to that of the original selector.
-
# In order to ensure that, we record the original selector's
-
# (`extended.first`) original specificity.
-
extended.first.add_sources!([self]) if original && !invisible?
-
-
extended.map {|seq| seq.members}
-
end
-
weaves = Sass::Util.paths(extended_not_expanded).map {|path| weave(path)}
-
trim(weaves).map {|p| Sequence.new(p)}
-
end
-
-
# Unifies this with another selector sequence to produce a selector
-
# that matches (a subset of) the intersection of the two inputs.
-
#
-
# @param other [Sequence]
-
# @return [CommaSequence, nil] The unified selector, or nil if unification failed.
-
# @raise [Sass::SyntaxError] If this selector cannot be unified.
-
# This will only ever occur when a dynamic selector,
-
# such as {Parent} or {Interpolation}, is used in unification.
-
# Since these selectors should be resolved
-
# by the time extension and unification happen,
-
# this exception will only ever be raised as a result of programmer error
-
1
def unify(other)
-
base = members.last
-
other_base = other.members.last
-
return unless base.is_a?(SimpleSequence) && other_base.is_a?(SimpleSequence)
-
return unless (unified = other_base.unify(base))
-
-
woven = weave([members[0...-1], other.members[0...-1] + [unified]])
-
CommaSequence.new(woven.map {|w| Sequence.new(w)})
-
end
-
-
# Returns whether or not this selector matches all elements
-
# that the given selector matches (as well as possibly more).
-
#
-
# @example
-
# (.foo).superselector?(.foo.bar) #=> true
-
# (.foo).superselector?(.bar) #=> false
-
# @param cseq [Sequence]
-
# @return [Boolean]
-
1
def superselector?(seq)
-
_superselector?(members, seq.members)
-
end
-
-
# @see AbstractSequence#to_s
-
1
def to_s(opts = {})
-
@members.map {|m| m.is_a?(String) ? m : m.to_s(opts)}.join(" ").gsub(/ ?\n ?/, "\n")
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
1
def inspect
-
members.map {|m| m.inspect}.join(" ")
-
end
-
-
# Add to the {SimpleSequence#sources} sets of the child simple sequences.
-
# This destructively modifies this sequence's members array, but not the
-
# child simple sequences.
-
#
-
# @param sources [Set<Sequence>]
-
1
def add_sources!(sources)
-
members.map! {|m| m.is_a?(SimpleSequence) ? m.with_more_sources(sources) : m}
-
end
-
-
# Converts the subject operator "!", if it exists, into a ":has()"
-
# selector.
-
#
-
# @retur [Sequence]
-
1
def subjectless
-
pre_subject = []
-
has = []
-
subject = nil
-
members.each do |sseq_or_op|
-
if subject
-
has << sseq_or_op
-
elsif sseq_or_op.is_a?(String) || !sseq_or_op.subject?
-
pre_subject << sseq_or_op
-
else
-
subject = sseq_or_op.dup
-
subject.members = sseq_or_op.members.dup
-
subject.subject = false
-
has = []
-
end
-
end
-
-
return self unless subject
-
-
unless has.empty?
-
subject.members << Pseudo.new(:class, 'has', nil, CommaSequence.new([Sequence.new(has)]))
-
end
-
Sequence.new(pre_subject + [subject])
-
end
-
-
1
private
-
-
# Conceptually, this expands "parenthesized selectors". That is, if we
-
# have `.A .B {@extend .C}` and `.D .C {...}`, this conceptually expands
-
# into `.D .C, .D (.A .B)`, and this function translates `.D (.A .B)` into
-
# `.D .A .B, .A .D .B`. For thoroughness, `.A.D .B` would also be
-
# required, but including merged selectors results in exponential output
-
# for very little gain.
-
#
-
# @param path [Array<Array<SimpleSequence or String>>]
-
# A list of parenthesized selector groups.
-
# @return [Array<Array<SimpleSequence or String>>] A list of fully-expanded selectors.
-
1
def weave(path)
-
# This function works by moving through the selector path left-to-right,
-
# building all possible prefixes simultaneously.
-
prefixes = [[]]
-
-
path.each do |current|
-
next if current.empty?
-
current = current.dup
-
last_current = [current.pop]
-
prefixes = prefixes.map do |prefix|
-
sub = subweave(prefix, current)
-
next [] unless sub
-
sub.map {|seqs| seqs + last_current}
-
end.flatten(1)
-
end
-
prefixes
-
end
-
-
# This interweaves two lists of selectors,
-
# returning all possible orderings of them (including using unification)
-
# that maintain the relative ordering of the input arrays.
-
#
-
# For example, given `.foo .bar` and `.baz .bang`,
-
# this would return `.foo .bar .baz .bang`, `.foo .bar.baz .bang`,
-
# `.foo .baz .bar .bang`, `.foo .baz .bar.bang`, `.foo .baz .bang .bar`,
-
# and so on until `.baz .bang .foo .bar`.
-
#
-
# Semantically, for selectors A and B, this returns all selectors `AB_i`
-
# such that the union over all i of elements matched by `AB_i X` is
-
# identical to the intersection of all elements matched by `A X` and all
-
# elements matched by `B X`. Some `AB_i` are elided to reduce the size of
-
# the output.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<Array<SimpleSequence or String>>]
-
1
def subweave(seq1, seq2)
-
return [seq2] if seq1.empty?
-
return [seq1] if seq2.empty?
-
-
seq1, seq2 = seq1.dup, seq2.dup
-
return unless (init = merge_initial_ops(seq1, seq2))
-
return unless (fin = merge_final_ops(seq1, seq2))
-
-
# Make sure there's only one root selector in the output.
-
root1 = has_root?(seq1.first) && seq1.shift
-
root2 = has_root?(seq2.first) && seq2.shift
-
if root1 && root2
-
return unless (root = root1.unify(root2))
-
seq1.unshift root
-
seq2.unshift root
-
elsif root1
-
seq2.unshift root1
-
elsif root2
-
seq1.unshift root2
-
end
-
-
seq1 = group_selectors(seq1)
-
seq2 = group_selectors(seq2)
-
lcs = Sass::Util.lcs(seq2, seq1) do |s1, s2|
-
next s1 if s1 == s2
-
next unless s1.first.is_a?(SimpleSequence) && s2.first.is_a?(SimpleSequence)
-
next s2 if parent_superselector?(s1, s2)
-
next s1 if parent_superselector?(s2, s1)
-
next unless must_unify?(s1, s2)
-
next unless (unified = Sequence.new(s1).unify(Sequence.new(s2)))
-
unified.members.first.members if unified.members.length == 1
-
end
-
-
diff = [[init]]
-
-
until lcs.empty?
-
diff << chunks(seq1, seq2) {|s| parent_superselector?(s.first, lcs.first)} << [lcs.shift]
-
seq1.shift
-
seq2.shift
-
end
-
diff << chunks(seq1, seq2) {|s| s.empty?}
-
diff += fin.map {|sel| sel.is_a?(Array) ? sel : [sel]}
-
diff.reject! {|c| c.empty?}
-
-
Sass::Util.paths(diff).map {|p| p.flatten}.reject {|p| path_has_two_subjects?(p)}
-
end
-
-
# Extracts initial selector combinators (`"+"`, `">"`, `"~"`, and `"\n"`)
-
# from two sequences and merges them together into a single array of
-
# selector combinators.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<String>, nil] If there are no operators in the merged
-
# sequence, this will be the empty array. If the operators cannot be
-
# merged, this will be nil.
-
1
def merge_initial_ops(seq1, seq2)
-
ops1, ops2 = [], []
-
ops1 << seq1.shift while seq1.first.is_a?(String)
-
ops2 << seq2.shift while seq2.first.is_a?(String)
-
-
newline = false
-
newline ||= !!ops1.shift if ops1.first == "\n"
-
newline ||= !!ops2.shift if ops2.first == "\n"
-
-
# If neither sequence is a subsequence of the other, they cannot be
-
# merged successfully
-
lcs = Sass::Util.lcs(ops1, ops2)
-
return unless lcs == ops1 || lcs == ops2
-
(newline ? ["\n"] : []) + (ops1.size > ops2.size ? ops1 : ops2)
-
end
-
-
# Extracts final selector combinators (`"+"`, `">"`, `"~"`) and the
-
# selectors to which they apply from two sequences and merges them
-
# together into a single array.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<SimpleSequence or String or
-
# Array<Array<SimpleSequence or String>>]
-
# If there are no trailing combinators to be merged, this will be the
-
# empty array. If the trailing combinators cannot be merged, this will
-
# be nil. Otherwise, this will contained the merged selector. Array
-
# elements are [Sass::Util#paths]-style options; conceptually, an "or"
-
# of multiple selectors.
-
# @comment
-
# rubocop:disable MethodLength
-
1
def merge_final_ops(seq1, seq2, res = [])
-
ops1, ops2 = [], []
-
ops1 << seq1.pop while seq1.last.is_a?(String)
-
ops2 << seq2.pop while seq2.last.is_a?(String)
-
-
# Not worth the headache of trying to preserve newlines here. The most
-
# important use of newlines is at the beginning of the selector to wrap
-
# across lines anyway.
-
ops1.reject! {|o| o == "\n"}
-
ops2.reject! {|o| o == "\n"}
-
-
return res if ops1.empty? && ops2.empty?
-
if ops1.size > 1 || ops2.size > 1
-
# If there are multiple operators, something hacky's going on. If one
-
# is a supersequence of the other, use that, otherwise give up.
-
lcs = Sass::Util.lcs(ops1, ops2)
-
return unless lcs == ops1 || lcs == ops2
-
res.unshift(*(ops1.size > ops2.size ? ops1 : ops2).reverse)
-
return res
-
end
-
-
# This code looks complicated, but it's actually just a bunch of special
-
# cases for interactions between different combinators.
-
op1, op2 = ops1.first, ops2.first
-
if op1 && op2
-
sel1 = seq1.pop
-
sel2 = seq2.pop
-
if op1 == '~' && op2 == '~'
-
if sel1.superselector?(sel2)
-
res.unshift sel2, '~'
-
elsif sel2.superselector?(sel1)
-
res.unshift sel1, '~'
-
else
-
merged = sel1.unify(sel2)
-
res.unshift [
-
[sel1, '~', sel2, '~'],
-
[sel2, '~', sel1, '~'],
-
([merged, '~'] if merged)
-
].compact
-
end
-
elsif (op1 == '~' && op2 == '+') || (op1 == '+' && op2 == '~')
-
if op1 == '~'
-
tilde_sel, plus_sel = sel1, sel2
-
else
-
tilde_sel, plus_sel = sel2, sel1
-
end
-
-
if tilde_sel.superselector?(plus_sel)
-
res.unshift plus_sel, '+'
-
else
-
merged = plus_sel.unify(tilde_sel)
-
res.unshift [
-
[tilde_sel, '~', plus_sel, '+'],
-
([merged, '+'] if merged)
-
].compact
-
end
-
elsif op1 == '>' && %w(~ +).include?(op2)
-
res.unshift sel2, op2
-
seq1.push sel1, op1
-
elsif op2 == '>' && %w(~ +).include?(op1)
-
res.unshift sel1, op1
-
seq2.push sel2, op2
-
elsif op1 == op2
-
merged = sel1.unify(sel2)
-
return unless merged
-
res.unshift merged, op1
-
else
-
# Unknown selector combinators can't be unified
-
return
-
end
-
return merge_final_ops(seq1, seq2, res)
-
elsif op1
-
seq2.pop if op1 == '>' && seq2.last && seq2.last.superselector?(seq1.last)
-
res.unshift seq1.pop, op1
-
return merge_final_ops(seq1, seq2, res)
-
else # op2
-
seq1.pop if op2 == '>' && seq1.last && seq1.last.superselector?(seq2.last)
-
res.unshift seq2.pop, op2
-
return merge_final_ops(seq1, seq2, res)
-
end
-
end
-
# @comment
-
# rubocop:enable MethodLength
-
-
# Takes initial subsequences of `seq1` and `seq2` and returns all
-
# orderings of those subsequences. The initial subsequences are determined
-
# by a block.
-
#
-
# Destructively removes the initial subsequences of `seq1` and `seq2`.
-
#
-
# For example, given `(A B C | D E)` and `(1 2 | 3 4 5)` (with `|`
-
# denoting the boundary of the initial subsequence), this would return
-
# `[(A B C 1 2), (1 2 A B C)]`. The sequences would then be `(D E)` and
-
# `(3 4 5)`.
-
#
-
# @param seq1 [Array]
-
# @param seq2 [Array]
-
# @yield [a] Used to determine when to cut off the initial subsequences.
-
# Called repeatedly for each sequence until it returns true.
-
# @yieldparam a [Array] A final subsequence of one input sequence after
-
# cutting off some initial subsequence.
-
# @yieldreturn [Boolean] Whether or not to cut off the initial subsequence
-
# here.
-
# @return [Array<Array>] All possible orderings of the initial subsequences.
-
1
def chunks(seq1, seq2)
-
chunk1 = []
-
chunk1 << seq1.shift until yield seq1
-
chunk2 = []
-
chunk2 << seq2.shift until yield seq2
-
return [] if chunk1.empty? && chunk2.empty?
-
return [chunk2] if chunk1.empty?
-
return [chunk1] if chunk2.empty?
-
[chunk1 + chunk2, chunk2 + chunk1]
-
end
-
-
# Groups a sequence into subsequences. The subsequences are determined by
-
# strings; adjacent non-string elements will be put into separate groups,
-
# but any element adjacent to a string will be grouped with that string.
-
#
-
# For example, `(A B "C" D E "F" G "H" "I" J)` will become `[(A) (B "C" D)
-
# (E "F" G "H" "I" J)]`.
-
#
-
# @param seq [Array]
-
# @return [Array<Array>]
-
1
def group_selectors(seq)
-
newseq = []
-
tail = seq.dup
-
until tail.empty?
-
head = []
-
begin
-
head << tail.shift
-
end while !tail.empty? && head.last.is_a?(String) || tail.first.is_a?(String)
-
newseq << head
-
end
-
newseq
-
end
-
-
# Given two selector sequences, returns whether `seq1` is a
-
# superselector of `seq2`; that is, whether `seq1` matches every
-
# element `seq2` matches.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Boolean]
-
1
def _superselector?(seq1, seq2)
-
seq1 = seq1.reject {|e| e == "\n"}
-
seq2 = seq2.reject {|e| e == "\n"}
-
# Selectors with leading or trailing operators are neither
-
# superselectors nor subselectors.
-
return if seq1.last.is_a?(String) || seq2.last.is_a?(String) ||
-
seq1.first.is_a?(String) || seq2.first.is_a?(String)
-
# More complex selectors are never superselectors of less complex ones
-
return if seq1.size > seq2.size
-
return seq1.first.superselector?(seq2.last, seq2[0...-1]) if seq1.size == 1
-
-
_, si = seq2.each_with_index.find do |e, i|
-
return if i == seq2.size - 1
-
next if e.is_a?(String)
-
seq1.first.superselector?(e, seq2[0...i])
-
end
-
return unless si
-
-
if seq1[1].is_a?(String)
-
return unless seq2[si + 1].is_a?(String)
-
-
# .foo ~ .bar is a superselector of .foo + .bar
-
return unless seq1[1] == "~" ? seq2[si + 1] != ">" : seq1[1] == seq2[si + 1]
-
-
# .foo > .baz is not a superselector of .foo > .bar > .baz or .foo >
-
# .bar .baz, despite the fact that .baz is a superselector of .bar >
-
# .baz and .bar .baz. Same goes for + and ~.
-
return if seq1.length == 3 && seq2.length > 3
-
-
return _superselector?(seq1[2..-1], seq2[si + 2..-1])
-
elsif seq2[si + 1].is_a?(String)
-
return unless seq2[si + 1] == ">"
-
return _superselector?(seq1[1..-1], seq2[si + 2..-1])
-
else
-
return _superselector?(seq1[1..-1], seq2[si + 1..-1])
-
end
-
end
-
-
# Like \{#_superselector?}, but compares the selectors in the
-
# context of parent selectors, as though they shared an implicit
-
# base simple selector. For example, `B` is not normally a
-
# superselector of `B A`, since it doesn't match `A` elements.
-
# However, it is a parent superselector, since `B X` is a
-
# superselector of `B A X`.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Boolean]
-
1
def parent_superselector?(seq1, seq2)
-
base = Sass::Selector::SimpleSequence.new([Sass::Selector::Placeholder.new('<temp>')],
-
false)
-
_superselector?(seq1 + [base], seq2 + [base])
-
end
-
-
# Returns whether two selectors must be unified to produce a valid
-
# combined selector. This is true when both selectors contain the same
-
# unique simple selector such as an id.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Boolean]
-
1
def must_unify?(seq1, seq2)
-
unique_selectors = seq1.map do |sseq|
-
next [] if sseq.is_a?(String)
-
sseq.members.select {|sel| sel.unique?}
-
end.flatten.to_set
-
-
return false if unique_selectors.empty?
-
-
seq2.any? do |sseq|
-
next false if sseq.is_a?(String)
-
sseq.members.any? do |sel|
-
next unless sel.unique?
-
unique_selectors.include?(sel)
-
end
-
end
-
end
-
-
# Removes redundant selectors from between multiple lists of
-
# selectors. This takes a list of lists of selector sequences;
-
# each individual list is assumed to have no redundancy within
-
# itself. A selector is only removed if it's redundant with a
-
# selector in another list.
-
#
-
# "Redundant" here means that one selector is a superselector of
-
# the other. The more specific selector is removed.
-
#
-
# @param seqses [Array<Array<Array<SimpleSequence or String>>>]
-
# @return [Array<Array<SimpleSequence or String>>]
-
1
def trim(seqses)
-
# Avoid truly horrific quadratic behavior. TODO: I think there
-
# may be a way to get perfect trimming without going quadratic.
-
return seqses.flatten(1) if seqses.size > 100
-
-
# Keep the results in a separate array so we can be sure we aren't
-
# comparing against an already-trimmed selector. This ensures that two
-
# identical selectors don't mutually trim one another.
-
result = seqses.dup
-
-
# This is n^2 on the sequences, but only comparing between
-
# separate sequences should limit the quadratic behavior.
-
seqses.each_with_index do |seqs1, i|
-
result[i] = seqs1.reject do |seq1|
-
# The maximum specificity of the sources that caused [seq1] to be
-
# generated. In order for [seq1] to be removed, there must be
-
# another selector that's a superselector of it *and* that has
-
# specificity greater or equal to this.
-
max_spec = _sources(seq1).map do |seq|
-
spec = seq.specificity
-
spec.is_a?(Range) ? spec.max : spec
-
end.max || 0
-
-
result.any? do |seqs2|
-
next if seqs1.equal?(seqs2)
-
# Second Law of Extend: the specificity of a generated selector
-
# should never be less than the specificity of the extending
-
# selector.
-
#
-
# See https://github.com/nex3/sass/issues/324.
-
seqs2.any? do |seq2|
-
spec2 = _specificity(seq2)
-
spec2 = spec2.begin if spec2.is_a?(Range)
-
spec2 >= max_spec && _superselector?(seq2, seq1)
-
end
-
end
-
end
-
end
-
result.flatten(1)
-
end
-
-
1
def _hash
-
members.reject {|m| m == "\n"}.hash
-
end
-
-
1
def _eql?(other)
-
other.members.reject {|m| m == "\n"}.eql?(members.reject {|m| m == "\n"})
-
end
-
-
1
def path_has_two_subjects?(path)
-
subject = false
-
path.each do |sseq_or_op|
-
next unless sseq_or_op.is_a?(SimpleSequence)
-
next unless sseq_or_op.subject?
-
return true if subject
-
subject = true
-
end
-
false
-
end
-
-
1
def _sources(seq)
-
s = Set.new
-
seq.map {|sseq_or_op| s.merge sseq_or_op.sources if sseq_or_op.is_a?(SimpleSequence)}
-
s
-
end
-
-
1
def extended_not_expanded_to_s(extended_not_expanded)
-
extended_not_expanded.map do |choices|
-
choices = choices.map do |sel|
-
next sel.first.to_s if sel.size == 1
-
"#{sel.join ' '}"
-
end
-
next choices.first if choices.size == 1 && !choices.include?(' ')
-
"(#{choices.join ', '})"
-
end.join ' '
-
end
-
-
1
def has_root?(sseq)
-
sseq.is_a?(SimpleSequence) &&
-
sseq.members.any? {|sel| sel.is_a?(Pseudo) && sel.normalized_name == "root"}
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Selector
-
# The abstract superclass for simple selectors
-
# (that is, those that don't compose multiple selectors).
-
1
class Simple
-
# The line of the Sass template on which this selector was declared.
-
#
-
# @return [Integer]
-
1
attr_accessor :line
-
-
# The name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
#
-
# @return [String, nil]
-
1
attr_accessor :filename
-
-
# Whether only one instance of this simple selector is allowed in a given
-
# complex selector.
-
#
-
# @return [Boolean]
-
1
def unique?
-
false
-
end
-
-
# @see #to_s
-
#
-
# @return [String]
-
1
def inspect
-
to_s
-
end
-
-
# Returns the selector string.
-
#
-
# @param opts [Hash] rendering options.
-
# @option opts [Symbol] :style The css rendering style.
-
# @return [String]
-
1
def to_s(opts = {})
-
Sass::Util.abstract(self)
-
end
-
-
# Returns a hash code for this selector object.
-
#
-
# By default, this is based on the value of \{#to\_a},
-
# so if that contains information irrelevant to the identity of the selector,
-
# this should be overridden.
-
#
-
# @return [Integer]
-
1
def hash
-
@_hash ||= equality_key.hash
-
end
-
-
# Checks equality between this and another object.
-
#
-
# By default, this is based on the value of \{#to\_a},
-
# so if that contains information irrelevant to the identity of the selector,
-
# this should be overridden.
-
#
-
# @param other [Object] The object to test equality against
-
# @return [Boolean] Whether or not this is equal to `other`
-
1
def eql?(other)
-
other.class == self.class && other.hash == hash && other.equality_key == equality_key
-
end
-
1
alias_method :==, :eql?
-
-
# Unifies this selector with a {SimpleSequence}'s {SimpleSequence#members members array},
-
# returning another `SimpleSequence` members array
-
# that matches both this selector and the input selector.
-
#
-
# By default, this just appends this selector to the end of the array
-
# (or returns the original array if this selector already exists in it).
-
#
-
# @param sels [Array<Simple>] A {SimpleSequence}'s {SimpleSequence#members members array}
-
# @return [Array<Simple>, nil] A {SimpleSequence} {SimpleSequence#members members array}
-
# matching both `sels` and this selector,
-
# or `nil` if this is impossible (e.g. unifying `#foo` and `#bar`)
-
# @raise [Sass::SyntaxError] If this selector cannot be unified.
-
# This will only ever occur when a dynamic selector,
-
# such as {Parent} or {Interpolation}, is used in unification.
-
# Since these selectors should be resolved
-
# by the time extension and unification happen,
-
# this exception will only ever be raised as a result of programmer error
-
1
def unify(sels)
-
return sels.first.unify([self]) if sels.length == 1 && sels.first.is_a?(Universal)
-
return sels if sels.any? {|sel2| eql?(sel2)}
-
if !is_a?(Pseudo) || (sels.last.is_a?(Pseudo) && sels.last.type == :element)
-
_, i = sels.each_with_index.find {|sel, _| sel.is_a?(Pseudo)}
-
end
-
return sels + [self] unless i
-
sels[0...i] + [self] + sels[i..-1]
-
end
-
-
1
protected
-
-
# Returns the key used for testing whether selectors are equal.
-
#
-
# This is a cached version of \{#to\_s}.
-
#
-
# @return [String]
-
1
def equality_key
-
@equality_key ||= to_s
-
end
-
-
# Unifies two namespaces,
-
# returning a namespace that works for both of them if possible.
-
#
-
# @param ns1 [String, nil] The first namespace.
-
# `nil` means none specified, e.g. `foo`.
-
# The empty string means no namespace specified, e.g. `|foo`.
-
# `"*"` means any namespace is allowed, e.g. `*|foo`.
-
# @param ns2 [String, nil] The second namespace. See `ns1`.
-
# @return [Array(String or nil, Boolean)]
-
# The first value is the unified namespace, or `nil` for no namespace.
-
# The second value is whether or not a namespace that works for both inputs
-
# could be found at all.
-
# If the second value is `false`, the first should be ignored.
-
1
def unify_namespaces(ns1, ns2)
-
return ns2, true if ns1 == '*'
-
return ns1, true if ns2 == '*'
-
return nil, false unless ns1 == ns2
-
[ns1, true]
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Selector
-
# A unseparated sequence of selectors
-
# that all apply to a single element.
-
# For example, `.foo#bar[attr=baz]` is a simple sequence
-
# of the selectors `.foo`, `#bar`, and `[attr=baz]`.
-
1
class SimpleSequence < AbstractSequence
-
# The array of individual selectors.
-
#
-
# @return [Array<Simple>]
-
1
attr_accessor :members
-
-
# The extending selectors that caused this selector sequence to be
-
# generated. For example:
-
#
-
# a.foo { ... }
-
# b.bar {@extend a}
-
# c.baz {@extend b}
-
#
-
# The generated selector `b.foo.bar` has `{b.bar}` as its `sources` set,
-
# and the generated selector `c.foo.bar.baz` has `{b.bar, c.baz}` as its
-
# `sources` set.
-
#
-
# This is populated during the {Sequence#do_extend} process.
-
#
-
# @return {Set<Sequence>}
-
1
attr_accessor :sources
-
-
# This sequence source range.
-
#
-
# @return [Sass::Source::Range]
-
1
attr_accessor :source_range
-
-
# @see \{#subject?}
-
1
attr_writer :subject
-
-
# Returns the element or universal selector in this sequence,
-
# if it exists.
-
#
-
# @return [Element, Universal, nil]
-
1
def base
-
@base ||= (members.first if members.first.is_a?(Element) || members.first.is_a?(Universal))
-
end
-
-
1
def pseudo_elements
-
@pseudo_elements ||= members.select {|sel| sel.is_a?(Pseudo) && sel.type == :element}
-
end
-
-
1
def selector_pseudo_classes
-
@selector_pseudo_classes ||= members.
-
select {|sel| sel.is_a?(Pseudo) && sel.type == :class && sel.selector}.
-
group_by {|sel| sel.normalized_name}
-
end
-
-
# Returns the non-base, non-pseudo-element selectors in this sequence.
-
#
-
# @return [Set<Simple>]
-
1
def rest
-
@rest ||= Set.new(members - [base] - pseudo_elements)
-
end
-
-
# Whether or not this compound selector is the subject of the parent
-
# selector; that is, whether it is prepended with `$` and represents the
-
# actual element that will be selected.
-
#
-
# @return [Boolean]
-
1
def subject?
-
@subject
-
end
-
-
# @param selectors [Array<Simple>] See \{#members}
-
# @param subject [Boolean] See \{#subject?}
-
# @param source_range [Sass::Source::Range]
-
1
def initialize(selectors, subject, source_range = nil)
-
@members = selectors
-
@subject = subject
-
@sources = Set.new
-
@source_range = source_range
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_cseq [CommaSequence] The parent selector
-
# @return [CommaSequence] This selector, with parent references resolved
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
1
def resolve_parent_refs(super_cseq)
-
resolved_members = @members.map do |sel|
-
next sel unless sel.is_a?(Pseudo) && sel.selector
-
sel.with_selector(sel.selector.resolve_parent_refs(super_cseq, false))
-
end.flatten
-
-
# Parent selector only appears as the first selector in the sequence
-
unless (parent = resolved_members.first).is_a?(Parent)
-
return CommaSequence.new([Sequence.new([SimpleSequence.new(resolved_members, subject?)])])
-
end
-
-
return super_cseq if @members.size == 1 && parent.suffix.nil?
-
-
CommaSequence.new(super_cseq.members.map do |super_seq|
-
members = super_seq.members.dup
-
newline = members.pop if members.last == "\n"
-
unless members.last.is_a?(SimpleSequence)
-
raise Sass::SyntaxError.new("Invalid parent selector for \"#{self}\": \"" +
-
super_seq.to_s + '"')
-
end
-
-
parent_sub = members.last.members
-
unless parent.suffix.nil?
-
parent_sub = parent_sub.dup
-
parent_sub[-1] = parent_sub.last.dup
-
case parent_sub.last
-
when Sass::Selector::Class, Sass::Selector::Id, Sass::Selector::Placeholder
-
parent_sub[-1] = parent_sub.last.class.new(parent_sub.last.name + parent.suffix)
-
when Sass::Selector::Element
-
parent_sub[-1] = parent_sub.last.class.new(
-
parent_sub.last.name + parent.suffix,
-
parent_sub.last.namespace)
-
when Sass::Selector::Pseudo
-
if parent_sub.last.arg || parent_sub.last.selector
-
raise Sass::SyntaxError.new("Invalid parent selector for \"#{self}\": \"" +
-
super_seq.to_s + '"')
-
end
-
parent_sub[-1] = Sass::Selector::Pseudo.new(
-
parent_sub.last.type,
-
parent_sub.last.name + parent.suffix,
-
nil, nil)
-
else
-
raise Sass::SyntaxError.new("Invalid parent selector for \"#{self}\": \"" +
-
super_seq.to_s + '"')
-
end
-
end
-
-
Sequence.new(members[0...-1] +
-
[SimpleSequence.new(parent_sub + resolved_members[1..-1], subject?)] +
-
[newline].compact)
-
end)
-
end
-
-
# Non-destructively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @param extends [{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @param seen [Set<Array<Selector::Simple>>]
-
# The set of simple sequences that are currently being replaced.
-
# @param original [Boolean]
-
# Whether this is the original selector being extended, as opposed to
-
# the result of a previous extension that's being re-extended.
-
# @return [Array<Sequence>] A list of selectors generated
-
# by extending this selector with `extends`.
-
# @see CommaSequence#do_extend
-
1
def do_extend(extends, parent_directives, replace, seen)
-
seen_with_pseudo_selectors = seen.dup
-
-
modified_original = false
-
members = self.members.map do |sel|
-
next sel unless sel.is_a?(Pseudo) && sel.selector
-
next sel if seen.include?([sel])
-
extended = sel.selector.do_extend(extends, parent_directives, replace, seen, false)
-
next sel if extended == sel.selector
-
extended.members.reject! {|seq| seq.invisible?}
-
-
# For `:not()`, we usually want to get rid of any complex
-
# selectors because that will cause the selector to fail to
-
# parse on all browsers at time of writing. We can keep them
-
# if either the original selector had a complex selector, or
-
# the result of extending has only complex selectors,
-
# because either way we aren't breaking anything that isn't
-
# already broken.
-
if sel.normalized_name == 'not' &&
-
(sel.selector.members.none? {|seq| seq.members.length > 1} &&
-
extended.members.any? {|seq| seq.members.length == 1})
-
extended.members.reject! {|seq| seq.members.length > 1}
-
end
-
-
modified_original = true
-
result = sel.with_selector(extended)
-
result.each {|new_sel| seen_with_pseudo_selectors << [new_sel]}
-
result
-
end.flatten
-
-
groups = extends[members.to_set].group_by {|ex| ex.extender}.to_a
-
groups.map! do |seq, group|
-
sels = group.map {|e| e.target}.flatten
-
# If A {@extend B} and C {...},
-
# seq is A, sels is B, and self is C
-
-
self_without_sel = Sass::Util.array_minus(members, sels)
-
group.each {|e| e.success = true}
-
unified = seq.members.last.unify(SimpleSequence.new(self_without_sel, subject?))
-
next unless unified
-
group.each {|e| check_directives_match!(e, parent_directives)}
-
new_seq = Sequence.new(seq.members[0...-1] + [unified])
-
new_seq.add_sources!(sources + [seq])
-
[sels, new_seq]
-
end
-
groups.compact!
-
groups.map! do |sels, seq|
-
next [] if seen.include?(sels)
-
seq.do_extend(
-
extends, parent_directives, false, seen_with_pseudo_selectors + [sels], false)
-
end
-
groups.flatten!
-
-
if modified_original || !replace || groups.empty?
-
# First Law of Extend: the result of extending a selector should
-
# (almost) always contain the base selector.
-
#
-
# See https://github.com/nex3/sass/issues/324.
-
original = Sequence.new([SimpleSequence.new(members, @subject, source_range)])
-
original.add_sources! sources
-
groups.unshift original
-
end
-
groups.uniq!
-
groups
-
end
-
-
# Unifies this selector with another {SimpleSequence}, returning
-
# another `SimpleSequence` that is a subselector of both input
-
# selectors.
-
#
-
# @param other [SimpleSequence]
-
# @return [SimpleSequence, nil] A {SimpleSequence} matching both `sels` and this selector,
-
# or `nil` if this is impossible (e.g. unifying `#foo` and `#bar`)
-
# @raise [Sass::SyntaxError] If this selector cannot be unified.
-
# This will only ever occur when a dynamic selector,
-
# such as {Parent} or {Interpolation}, is used in unification.
-
# Since these selectors should be resolved
-
# by the time extension and unification happen,
-
# this exception will only ever be raised as a result of programmer error
-
1
def unify(other)
-
sseq = members.inject(other.members) do |member, sel|
-
return unless member
-
sel.unify(member)
-
end
-
return unless sseq
-
SimpleSequence.new(sseq, other.subject? || subject?)
-
end
-
-
# Returns whether or not this selector matches all elements
-
# that the given selector matches (as well as possibly more).
-
#
-
# @example
-
# (.foo).superselector?(.foo.bar) #=> true
-
# (.foo).superselector?(.bar) #=> false
-
# @param their_sseq [SimpleSequence]
-
# @param parents [Array<SimpleSequence, String>] The parent selectors of `their_sseq`, if any.
-
# @return [Boolean]
-
1
def superselector?(their_sseq, parents = [])
-
return false unless base.nil? || base.eql?(their_sseq.base)
-
return false unless pseudo_elements.eql?(their_sseq.pseudo_elements)
-
our_spcs = selector_pseudo_classes
-
their_spcs = their_sseq.selector_pseudo_classes
-
-
# Some psuedo-selectors can be subselectors of non-pseudo selectors.
-
# Pull those out here so we can efficiently check against them below.
-
their_subselector_pseudos = %w(matches any nth-child nth-last-child).
-
map {|name| their_spcs[name] || []}.flatten
-
-
# If `self`'s non-pseudo simple selectors aren't a subset of `their_sseq`'s,
-
# it's definitely not a superselector. This also considers being matched
-
# by `:matches` or `:any`.
-
return false unless rest.all? do |our_sel|
-
next true if our_sel.is_a?(Pseudo) && our_sel.selector
-
next true if their_sseq.rest.include?(our_sel)
-
their_subselector_pseudos.any? do |their_pseudo|
-
their_pseudo.selector.members.all? do |their_seq|
-
next false unless their_seq.members.length == 1
-
their_sseq = their_seq.members.first
-
next false unless their_sseq.is_a?(SimpleSequence)
-
their_sseq.rest.include?(our_sel)
-
end
-
end
-
end
-
-
our_spcs.all? do |_name, pseudos|
-
pseudos.all? {|pseudo| pseudo.superselector?(their_sseq, parents)}
-
end
-
end
-
-
# @see Simple#to_s
-
1
def to_s(opts = {})
-
res = @members.map {|m| m.to_s(opts)}.join
-
-
# :not(%foo) may resolve to the empty string, but it should match every
-
# selector so we replace it with "*".
-
res = '*' if res.empty?
-
-
res << '!' if subject?
-
res
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
1
def inspect
-
res = members.map {|m| m.inspect}.join
-
res << '!' if subject?
-
res
-
end
-
-
# Return a copy of this simple sequence with `sources` merged into the
-
# {SimpleSequence#sources} set.
-
#
-
# @param sources [Set<Sequence>]
-
# @return [SimpleSequence]
-
1
def with_more_sources(sources)
-
sseq = dup
-
sseq.members = members.dup
-
sseq.sources = self.sources | sources
-
sseq
-
end
-
-
1
private
-
-
1
def check_directives_match!(extend, parent_directives)
-
dirs1 = extend.directives.map {|d| d.resolved_value}
-
dirs2 = parent_directives.map {|d| d.resolved_value}
-
return if Sass::Util.subsequence?(dirs1, dirs2)
-
line = extend.node.line
-
filename = extend.node.filename
-
-
# TODO(nweiz): this should use the Sass stack trace of the extend node,
-
# not the selector.
-
raise Sass::SyntaxError.new(<<MESSAGE)
-
You may not @extend an outer selector from within #{extend.directives.last.name}.
-
You may only @extend selectors within the same directive.
-
From "@extend #{extend.target.join(', ')}" on line #{line}#{" of #{filename}" if filename}.
-
MESSAGE
-
end
-
-
1
def _hash
-
[base, rest.hash].hash
-
end
-
-
1
def _eql?(other)
-
other.base.eql?(base) && other.pseudo_elements == pseudo_elements &&
-
other.rest.eql?(rest) && other.subject? == subject?
-
end
-
end
-
end
-
end
-
1
module Sass
-
# This module contains functionality that's shared between Haml and Sass.
-
1
module Shared
-
1
extend self
-
-
# Scans through a string looking for the interoplation-opening `#{`
-
# and, when it's found, yields the scanner to the calling code
-
# so it can handle it properly.
-
#
-
# The scanner will have any backslashes immediately in front of the `#{`
-
# as the second capture group (`scan[2]`),
-
# and the text prior to that as the first (`scan[1]`).
-
#
-
# @yieldparam scan [StringScanner] The scanner scanning through the string
-
# @return [String] The text remaining in the scanner after all `#{`s have been processed
-
1
def handle_interpolation(str)
-
scan = Sass::Util::MultibyteStringScanner.new(str)
-
yield scan while scan.scan(/(.*?)(\\*)\#\{/m)
-
scan.rest
-
end
-
-
# Moves a scanner through a balanced pair of characters.
-
# For example:
-
#
-
# Foo (Bar (Baz bang) bop) (Bang (bop bip))
-
# ^ ^
-
# from to
-
#
-
# @param scanner [StringScanner] The string scanner to move
-
# @param start [Character] The character opening the balanced pair.
-
# A `Fixnum` in 1.8, a `String` in 1.9
-
# @param finish [Character] The character closing the balanced pair.
-
# A `Fixnum` in 1.8, a `String` in 1.9
-
# @param count [Integer] The number of opening characters matched
-
# before calling this method
-
# @return [(String, String)] The string matched within the balanced pair
-
# and the rest of the string.
-
# `["Foo (Bar (Baz bang) bop)", " (Bang (bop bip))"]` in the example above.
-
1
def balance(scanner, start, finish, count = 0)
-
str = ''
-
scanner = Sass::Util::MultibyteStringScanner.new(scanner) unless scanner.is_a? StringScanner
-
regexp = Regexp.new("(.*?)[\\#{start.chr}\\#{finish.chr}]", Regexp::MULTILINE)
-
while scanner.scan(regexp)
-
str << scanner.matched
-
count += 1 if scanner.matched[-1] == start
-
count -= 1 if scanner.matched[-1] == finish
-
return [str, scanner.rest] if count == 0
-
end
-
end
-
-
# Formats a string for use in error messages about indentation.
-
#
-
# @param indentation [String] The string used for indentation
-
# @param was [Boolean] Whether or not to add `"was"` or `"were"`
-
# (depending on how many characters were in `indentation`)
-
# @return [String] The name of the indentation (e.g. `"12 spaces"`, `"1 tab"`)
-
1
def human_indentation(indentation, was = false)
-
if !indentation.include?(?\t)
-
noun = 'space'
-
elsif !indentation.include?(?\s)
-
noun = 'tab'
-
else
-
return indentation.inspect + (was ? ' was' : '')
-
end
-
-
singular = indentation.length == 1
-
if was
-
was = singular ? ' was' : ' were'
-
else
-
was = ''
-
end
-
-
"#{indentation.length} #{noun}#{'s' unless singular}#{was}"
-
end
-
end
-
end
-
1
module Sass::Source
-
1
class Map
-
# A mapping from one source range to another. Indicates that `input` was
-
# compiled to `output`.
-
#
-
# @!attribute input
-
# @return [Sass::Source::Range] The source range in the input document.
-
#
-
# @!attribute output
-
# @return [Sass::Source::Range] The source range in the output document.
-
1
class Mapping < Struct.new(:input, :output)
-
# @return [String] A string representation of the mapping.
-
1
def inspect
-
"#{input.inspect} => #{output.inspect}"
-
end
-
end
-
-
# The mapping data ordered by the location in the target.
-
#
-
# @return [Array<Mapping>]
-
1
attr_reader :data
-
-
1
def initialize
-
@data = []
-
end
-
-
# Adds a new mapping from one source range to another. Multiple invocations
-
# of this method should have each `output` range come after all previous ranges.
-
#
-
# @param input [Sass::Source::Range]
-
# The source range in the input document.
-
# @param output [Sass::Source::Range]
-
# The source range in the output document.
-
1
def add(input, output)
-
@data.push(Mapping.new(input, output))
-
end
-
-
# Shifts all output source ranges forward one or more lines.
-
#
-
# @param delta [Integer] The number of lines to shift the ranges forward.
-
1
def shift_output_lines(delta)
-
return if delta == 0
-
@data.each do |m|
-
m.output.start_pos.line += delta
-
m.output.end_pos.line += delta
-
end
-
end
-
-
# Shifts any output source ranges that lie on the first line forward one or
-
# more characters on that line.
-
#
-
# @param delta [Integer] The number of characters to shift the ranges
-
# forward.
-
1
def shift_output_offsets(delta)
-
return if delta == 0
-
@data.each do |m|
-
break if m.output.start_pos.line > 1
-
m.output.start_pos.offset += delta
-
m.output.end_pos.offset += delta if m.output.end_pos.line > 1
-
end
-
end
-
-
# Returns the standard JSON representation of the source map.
-
#
-
# If the `:css_uri` option isn't specified, the `:css_path` and
-
# `:sourcemap_path` options must both be specified. Any options may also be
-
# specified alongside the `:css_uri` option. If `:css_uri` isn't specified,
-
# it will be inferred from `:css_path` and `:sourcemap_path` using the
-
# assumption that the local file system has the same layout as the server.
-
#
-
# Regardless of which options are passed to this method, source stylesheets
-
# that are imported using a non-default importer will only be linked to in
-
# the source map if their importers implement
-
# \{Sass::Importers::Base#public\_url\}.
-
#
-
# @option options :css_uri [String]
-
# The publicly-visible URI of the CSS output file.
-
# @option options :css_path [String]
-
# The local path of the CSS output file.
-
# @option options :sourcemap_path [String]
-
# The (eventual) local path of the sourcemap file.
-
# @option options :type [Symbol]
-
# `:auto` (default), `:file`, or `:inline`.
-
# @return [String] The JSON string.
-
# @raise [ArgumentError] If neither `:css_uri` nor `:css_path` and
-
# `:sourcemap_path` are specified.
-
# @comment
-
# rubocop:disable MethodLength
-
1
def to_json(options)
-
css_uri, css_path, sourcemap_path =
-
options[:css_uri], options[:css_path], options[:sourcemap_path]
-
unless css_uri || (css_path && sourcemap_path)
-
raise ArgumentError.new("Sass::Source::Map#to_json requires either " \
-
"the :css_uri option or both the :css_path and :soucemap_path options.")
-
end
-
css_path &&= Sass::Util.pathname(File.absolute_path(css_path))
-
sourcemap_path &&= Sass::Util.pathname(File.absolute_path(sourcemap_path))
-
css_uri ||= Sass::Util.file_uri_from_path(
-
Sass::Util.relative_path_from(css_path, sourcemap_path.dirname))
-
-
result = "{\n"
-
write_json_field(result, "version", 3, true)
-
-
source_uri_to_id = {}
-
id_to_source_uri = {}
-
id_to_contents = {} if options[:type] == :inline
-
next_source_id = 0
-
line_data = []
-
segment_data_for_line = []
-
-
# These track data necessary for the delta coding.
-
previous_target_line = nil
-
previous_target_offset = 1
-
previous_source_line = 1
-
previous_source_offset = 1
-
previous_source_id = 0
-
-
@data.each do |m|
-
file, importer = m.input.file, m.input.importer
-
-
next unless importer
-
-
if options[:type] == :inline
-
source_uri = file
-
else
-
sourcemap_dir = sourcemap_path && sourcemap_path.dirname.to_s
-
sourcemap_dir = nil if options[:type] == :file
-
source_uri = importer.public_url(file, sourcemap_dir)
-
next unless source_uri
-
end
-
-
current_source_id = source_uri_to_id[source_uri]
-
unless current_source_id
-
current_source_id = next_source_id
-
next_source_id += 1
-
-
source_uri_to_id[source_uri] = current_source_id
-
id_to_source_uri[current_source_id] = source_uri
-
-
if options[:type] == :inline
-
id_to_contents[current_source_id] =
-
importer.find(file, {}).instance_variable_get('@template')
-
end
-
end
-
-
[
-
[m.input.start_pos, m.output.start_pos],
-
[m.input.end_pos, m.output.end_pos]
-
].each do |source_pos, target_pos|
-
if previous_target_line != target_pos.line
-
line_data.push(segment_data_for_line.join(",")) unless segment_data_for_line.empty?
-
(target_pos.line - 1 - (previous_target_line || 0)).times {line_data.push("")}
-
previous_target_line = target_pos.line
-
previous_target_offset = 1
-
segment_data_for_line = []
-
end
-
-
# `segment` is a data chunk for a single position mapping.
-
segment = ""
-
-
# Field 1: zero-based starting offset.
-
segment << Sass::Util.encode_vlq(target_pos.offset - previous_target_offset)
-
previous_target_offset = target_pos.offset
-
-
# Field 2: zero-based index into the "sources" list.
-
segment << Sass::Util.encode_vlq(current_source_id - previous_source_id)
-
previous_source_id = current_source_id
-
-
# Field 3: zero-based starting line in the original source.
-
segment << Sass::Util.encode_vlq(source_pos.line - previous_source_line)
-
previous_source_line = source_pos.line
-
-
# Field 4: zero-based starting offset in the original source.
-
segment << Sass::Util.encode_vlq(source_pos.offset - previous_source_offset)
-
previous_source_offset = source_pos.offset
-
-
segment_data_for_line.push(segment)
-
-
previous_target_line = target_pos.line
-
end
-
end
-
line_data.push(segment_data_for_line.join(","))
-
write_json_field(result, "mappings", line_data.join(";"))
-
-
source_names = []
-
(0...next_source_id).each {|id| source_names.push(id_to_source_uri[id].to_s)}
-
write_json_field(result, "sources", source_names)
-
-
if options[:type] == :inline
-
write_json_field(result, "sourcesContent",
-
(0...next_source_id).map {|id| id_to_contents[id]})
-
end
-
-
write_json_field(result, "names", [])
-
write_json_field(result, "file", css_uri)
-
-
result << "\n}"
-
result
-
end
-
# @comment
-
# rubocop:enable MethodLength
-
-
1
private
-
-
1
def write_json_field(out, name, value, is_first = false)
-
out << (is_first ? "" : ",\n") <<
-
"\"" <<
-
Sass::Util.json_escape_string(name) <<
-
"\": " <<
-
Sass::Util.json_value_of(value)
-
end
-
end
-
end
-
1
module Sass::Source
-
1
class Position
-
# The one-based line of the document associated with the position.
-
#
-
# @return [Integer]
-
1
attr_accessor :line
-
-
# The one-based offset in the line of the document associated with the
-
# position.
-
#
-
# @return [Integer]
-
1
attr_accessor :offset
-
-
# @param line [Integer] The source line
-
# @param offset [Integer] The source offset
-
1
def initialize(line, offset)
-
@line = line
-
@offset = offset
-
end
-
-
# @return [String] A string representation of the source position.
-
1
def inspect
-
"#{line.inspect}:#{offset.inspect}"
-
end
-
-
# @param str [String] The string to move through.
-
# @return [Position] The source position after proceeding forward through
-
# `str`.
-
1
def after(str)
-
newlines = str.count("\n")
-
Position.new(line + newlines,
-
if newlines == 0
-
offset + str.length
-
else
-
str.length - str.rindex("\n") - 1
-
end)
-
end
-
end
-
end
-
1
module Sass::Source
-
1
class Range
-
# The starting position of the range in the document (inclusive).
-
#
-
# @return [Sass::Source::Position]
-
1
attr_accessor :start_pos
-
-
# The ending position of the range in the document (exclusive).
-
#
-
# @return [Sass::Source::Position]
-
1
attr_accessor :end_pos
-
-
# The file in which this source range appears. This can be nil if the file
-
# is unknown or not yet generated.
-
#
-
# @return [String]
-
1
attr_accessor :file
-
-
# The importer that imported the file in which this source range appears.
-
# This is nil for target ranges.
-
#
-
# @return [Sass::Importers::Base]
-
1
attr_accessor :importer
-
-
# @param start_pos [Sass::Source::Position] See \{#start_pos}
-
# @param end_pos [Sass::Source::Position] See \{#end_pos}
-
# @param file [String] See \{#file}
-
# @param importer [Sass::Importers::Base] See \{#importer}
-
1
def initialize(start_pos, end_pos, file, importer = nil)
-
@start_pos = start_pos
-
@end_pos = end_pos
-
@file = file
-
@importer = importer
-
end
-
-
# @return [String] A string representation of the source range.
-
1
def inspect
-
"(#{start_pos.inspect} to #{end_pos.inspect}#{" in #{@file}" if @file})"
-
end
-
end
-
end
-
1
module Sass
-
# A class representing the stack when compiling a Sass file.
-
1
class Stack
-
# TODO: use this to generate stack information for Sass::SyntaxErrors.
-
-
# A single stack frame.
-
1
class Frame
-
# The filename of the file in which this stack frame was created.
-
#
-
# @return [String]
-
1
attr_reader :filename
-
-
# The line number on which this stack frame was created.
-
#
-
# @return [String]
-
1
attr_reader :line
-
-
# The type of this stack frame. This can be `:import`, `:mixin`, or
-
# `:base`.
-
#
-
# `:base` indicates that this is the bottom-most frame, meaning that it
-
# represents a single line of code rather than a nested context. The stack
-
# will only ever have one base frame, and it will always be the most
-
# deeply-nested frame.
-
#
-
# @return [Symbol?]
-
1
attr_reader :type
-
-
# The name of the stack frame. For mixin frames, this is the mixin name;
-
# otherwise, it's `nil`.
-
#
-
# @return [String?]
-
1
attr_reader :name
-
-
1
def initialize(filename, line, type, name = nil)
-
@filename = filename
-
@line = line
-
@type = type
-
@name = name
-
end
-
-
# Whether this frame represents an import.
-
#
-
# @return [Boolean]
-
1
def is_import?
-
type == :import
-
end
-
-
# Whether this frame represents a mixin.
-
#
-
# @return [Boolean]
-
1
def is_mixin?
-
type == :mixin
-
end
-
-
# Whether this is the base frame.
-
#
-
# @return [Boolean]
-
1
def is_base?
-
type == :base
-
end
-
end
-
-
# The stack frames. The last frame is the most deeply-nested.
-
#
-
# @return [Array<Frame>]
-
1
attr_reader :frames
-
-
1
def initialize
-
@frames = []
-
end
-
-
# Pushes a base frame onto the stack.
-
#
-
# @param filename [String] See \{Frame#filename}.
-
# @param line [String] See \{Frame#line}.
-
# @yield [] A block in which the new frame is on the stack.
-
1
def with_base(filename, line)
-
with_frame(filename, line, :base) {yield}
-
end
-
-
# Pushes an import frame onto the stack.
-
#
-
# @param filename [String] See \{Frame#filename}.
-
# @param line [String] See \{Frame#line}.
-
# @yield [] A block in which the new frame is on the stack.
-
1
def with_import(filename, line)
-
with_frame(filename, line, :import) {yield}
-
end
-
-
# Pushes a mixin frame onto the stack.
-
#
-
# @param filename [String] See \{Frame#filename}.
-
# @param line [String] See \{Frame#line}.
-
# @param name [String] See \{Frame#name}.
-
# @yield [] A block in which the new frame is on the stack.
-
1
def with_mixin(filename, line, name)
-
with_frame(filename, line, :mixin, name) {yield}
-
end
-
-
# Pushes a function frame onto the stack.
-
#
-
# @param filename [String] See \{Frame#filename}.
-
# @param line [String] See \{Frame#line}.
-
# @param name [String] See \{Frame#name}.
-
# @yield [] A block in which the new frame is on the stack.
-
1
def with_function(filename, line, name)
-
with_frame(filename, line, :function, name) {yield}
-
end
-
-
# Pushes a function frame onto the stack.
-
#
-
# @param filename [String] See \{Frame#filename}.
-
# @param line [String] See \{Frame#line}.
-
# @param name [String] See \{Frame#name}.
-
# @yield [] A block in which the new frame is on the stack.
-
1
def with_directive(filename, line, name)
-
with_frame(filename, line, :directive, name) {yield}
-
end
-
-
1
def to_s
-
(frames.reverse + [nil]).each_cons(2).each_with_index.
-
map do |(frame, caller), i|
-
"#{i == 0 ? 'on' : 'from'} line #{frame.line}" +
-
" of #{frame.filename || 'an unknown file'}" +
-
(caller && caller.name ? ", in `#{caller.name}'" : "")
-
end.join("\n")
-
end
-
-
1
private
-
-
1
def with_frame(filename, line, type, name = nil)
-
@frames.pop if @frames.last && @frames.last.type == :base
-
@frames.push(Frame.new(filename, line, type, name))
-
yield
-
ensure
-
@frames.pop unless type == :base && @frames.last && @frames.last.type != :base
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing an `@at-root` directive.
-
#
-
# An `@at-root` directive with a selector is converted to an \{AtRootNode}
-
# containing a \{RuleNode} at parse time.
-
#
-
# @see Sass::Tree
-
1
class AtRootNode < Node
-
# The query for this node (e.g. `(without: media)`),
-
# interspersed with {Sass::Script::Tree::Node}s representing
-
# `#{}`-interpolation. Any adjacent strings will be merged
-
# together.
-
#
-
# This will be nil if the directive didn't have a query. In this
-
# case, {#resolved\_type} will automatically be set to
-
# `:without` and {#resolved\_rule} will automatically be set to `["rule"]`.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :query
-
-
# The resolved type of this directive. `:with` or `:without`.
-
#
-
# @return [Symbol]
-
1
attr_accessor :resolved_type
-
-
# The resolved value of this directive -- a list of directives
-
# to either include or exclude.
-
#
-
# @return [Array<String>]
-
1
attr_accessor :resolved_value
-
-
# The number of additional tabs that the contents of this node
-
# should be indented.
-
#
-
# @return [Number]
-
1
attr_accessor :tabs
-
-
# Whether the last child of this node should be considered the
-
# end of a group.
-
#
-
# @return [Boolean]
-
1
attr_accessor :group_end
-
-
1
def initialize(query = nil)
-
super()
-
@query = Sass::Util.strip_string_array(Sass::Util.merge_adjacent_strings(query)) if query
-
@tabs = 0
-
end
-
-
# Returns whether or not the given directive is excluded by this
-
# node. `directive` may be "rule", which indicates whether
-
# normal CSS rules should be excluded.
-
#
-
# @param directive [String]
-
# @return [Boolean]
-
1
def exclude?(directive)
-
if resolved_type == :with
-
return false if resolved_value.include?('all')
-
!resolved_value.include?(directive)
-
else # resolved_type == :without
-
return true if resolved_value.include?('all')
-
resolved_value.include?(directive)
-
end
-
end
-
-
# Returns whether the given node is excluded by this node.
-
#
-
# @param node [Sass::Tree::Node]
-
# @return [Boolean]
-
1
def exclude_node?(node)
-
return exclude?(node.name.gsub(/^@/, '')) if node.is_a?(Sass::Tree::DirectiveNode)
-
return exclude?('keyframes') if node.is_a?(Sass::Tree::KeyframeRuleNode)
-
exclude?('rule') && node.is_a?(Sass::Tree::RuleNode)
-
end
-
-
# @see Node#bubbles?
-
1
def bubbles?
-
true
-
end
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A static node representing an unprocessed Sass `@charset` directive.
-
#
-
# @see Sass::Tree
-
1
class CharsetNode < Node
-
# The name of the charset.
-
#
-
# @return [String]
-
1
attr_accessor :name
-
-
# @param name [String] see \{#name}
-
1
def initialize(name)
-
@name = name
-
super()
-
end
-
-
# @see Node#invisible?
-
1
def invisible?
-
true
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A static node representing a Sass comment (silent or loud).
-
#
-
# @see Sass::Tree
-
1
class CommentNode < Node
-
# The text of the comment, not including `/*` and `*/`.
-
# Interspersed with {Sass::Script::Tree::Node}s representing `#{}`-interpolation
-
# if this is a loud comment.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :value
-
-
# The text of the comment
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_value
-
-
# The type of the comment. `:silent` means it's never output to CSS,
-
# `:normal` means it's output in every compile mode except `:compressed`,
-
# and `:loud` means it's output even in `:compressed`.
-
#
-
# @return [Symbol]
-
1
attr_accessor :type
-
-
# @param value [Array<String, Sass::Script::Tree::Node>] See \{#value}
-
# @param type [Symbol] See \{#type}
-
1
def initialize(value, type)
-
@value = Sass::Util.with_extracted_values(value) {|str| normalize_indentation str}
-
@type = type
-
super()
-
end
-
-
# Compares the contents of two comments.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
1
def ==(other)
-
self.class == other.class && value == other.value && type == other.type
-
end
-
-
# Returns `true` if this is a silent comment
-
# or the current style doesn't render comments.
-
#
-
# Comments starting with ! are never invisible (and the ! is removed from the output.)
-
#
-
# @return [Boolean]
-
1
def invisible?
-
case @type
-
when :loud; false
-
when :silent; true
-
else; style == :compressed
-
end
-
end
-
-
# Returns the number of lines in the comment.
-
#
-
# @return [Integer]
-
1
def lines
-
@value.inject(0) do |s, e|
-
next s + e.count("\n") if e.is_a?(String)
-
next s
-
end
-
end
-
-
1
private
-
-
1
def normalize_indentation(str)
-
ind = str.split("\n").inject(str[/^[ \t]*/].split("")) do |pre, line|
-
line[/^[ \t]*/].split("").zip(pre).inject([]) do |arr, (a, b)|
-
break arr if a != b
-
arr << a
-
end
-
end.join
-
str.gsub(/^#{ind}/, '')
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A node representing the placement within a mixin of the include statement's content.
-
#
-
# @see Sass::Tree
-
1
class ContentNode < Node
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A node representing an `@import` rule that's importing plain CSS.
-
#
-
# @see Sass::Tree
-
1
class CssImportNode < DirectiveNode
-
# The URI being imported, either as a plain string or an interpolated
-
# script string.
-
#
-
# @return [String, Sass::Script::Tree::Node]
-
1
attr_accessor :uri
-
-
# The text of the URI being imported after any interpolated SassScript has
-
# been resolved. Only set once {Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_uri
-
-
# The supports condition for this import.
-
#
-
# @return [Sass::Supports::Condition]
-
1
attr_accessor :supports_condition
-
-
# The media query for this rule, interspersed with
-
# {Sass::Script::Tree::Node}s representing `#{}`-interpolation. Any adjacent
-
# strings will be merged together.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :query
-
-
# The media query for this rule, without any unresolved interpolation.
-
# It's only set once {Tree::Visitors::Perform} has been run.
-
#
-
# @return [Sass::Media::QueryList]
-
1
attr_accessor :resolved_query
-
-
# @param uri [String, Sass::Script::Tree::Node] See \{#uri}
-
# @param query [Array<String, Sass::Script::Tree::Node>] See \{#query}
-
# @param supports_condition [Sass::Supports::Condition] See \{#supports_condition}
-
1
def initialize(uri, query = [], supports_condition = nil)
-
@uri = uri
-
@query = query
-
@supports_condition = supports_condition
-
super('')
-
end
-
-
# @param uri [String] See \{#resolved_uri}
-
# @return [CssImportNode]
-
1
def self.resolved(uri)
-
node = new(uri)
-
node.resolved_uri = uri
-
node
-
end
-
-
# @see DirectiveNode#value
-
1
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#resolved_value
-
1
def resolved_value
-
@resolved_value ||=
-
begin
-
str = "@import #{resolved_uri}"
-
str << " supports(#{supports_condition.to_css})" if supports_condition
-
str << " #{resolved_query.to_css}" if resolved_query
-
str
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a Sass `@debug` statement.
-
#
-
# @see Sass::Tree
-
1
class DebugNode < Node
-
# The expression to print.
-
# @return [Script::Tree::Node]
-
1
attr_accessor :expr
-
-
# @param expr [Script::Tree::Node] The expression to print
-
1
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A static node representing an unprocessed Sass `@`-directive.
-
# Directives known to Sass, like `@for` and `@debug`,
-
# are handled by their own nodes;
-
# only CSS directives like `@media` and `@font-face` become {DirectiveNode}s.
-
#
-
# `@import` and `@charset` are special cases;
-
# they become {ImportNode}s and {CharsetNode}s, respectively.
-
#
-
# @see Sass::Tree
-
1
class DirectiveNode < Node
-
# The text of the directive, `@` and all, with interpolation included.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :value
-
-
# The text of the directive after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_value
-
-
# @see RuleNode#tabs
-
1
attr_accessor :tabs
-
-
# @see RuleNode#group_end
-
1
attr_accessor :group_end
-
-
# @param value [Array<String, Sass::Script::Tree::Node>] See \{#value}
-
1
def initialize(value)
-
@value = value
-
@tabs = 0
-
super()
-
end
-
-
# @param value [String] See \{#resolved_value}
-
# @return [DirectiveNode]
-
1
def self.resolved(value)
-
node = new([value])
-
node.resolved_value = value
-
node
-
end
-
-
# @return [String] The name of the directive, including `@`.
-
1
def name
-
@name ||= value.first.gsub(/ .*$/, '')
-
end
-
-
# Strips out any vendor prefixes and downcases the directive name.
-
# @return [String] The normalized name of the directive.
-
1
def normalized_name
-
@normalized_name ||= name.gsub(/^(@)(?:-[a-zA-Z0-9]+-)?/, '\1').downcase
-
end
-
-
1
def bubbles?
-
has_children
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A dynamic node representing a Sass `@each` loop.
-
#
-
# @see Sass::Tree
-
1
class EachNode < Node
-
# The names of the loop variables.
-
# @return [Array<String>]
-
1
attr_reader :vars
-
-
# The parse tree for the list.
-
# @return [Script::Tree::Node]
-
1
attr_accessor :list
-
-
# @param vars [Array<String>] The names of the loop variables
-
# @param list [Script::Tree::Node] The parse tree for the list
-
1
def initialize(vars, list)
-
@vars = vars
-
@list = list
-
super()
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a Sass `@error` statement.
-
#
-
# @see Sass::Tree
-
1
class ErrorNode < Node
-
# The expression to print.
-
# @return [Script::Tree::Node]
-
1
attr_accessor :expr
-
-
# @param expr [Script::Tree::Node] The expression to print
-
1
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A static node representing an `@extend` directive.
-
#
-
# @see Sass::Tree
-
1
class ExtendNode < Node
-
# The parsed selector after interpolation has been resolved.
-
# Only set once {Tree::Visitors::Perform} has been run.
-
#
-
# @return [Selector::CommaSequence]
-
1
attr_accessor :resolved_selector
-
-
# The CSS selector to extend, interspersed with {Sass::Script::Tree::Node}s
-
# representing `#{}`-interpolation.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :selector
-
-
# The extended selector source range.
-
#
-
# @return [Sass::Source::Range]
-
1
attr_accessor :selector_source_range
-
-
# Whether the `@extend` is allowed to match no selectors or not.
-
#
-
# @return [Boolean]
-
1
def optional?; @optional; end
-
-
# @param selector [Array<String, Sass::Script::Tree::Node>]
-
# The CSS selector to extend,
-
# interspersed with {Sass::Script::Tree::Node}s
-
# representing `#{}`-interpolation.
-
# @param optional [Boolean] See \{ExtendNode#optional?}
-
# @param selector_source_range [Sass::Source::Range] The extended selector source range.
-
1
def initialize(selector, optional, selector_source_range)
-
@selector = selector
-
@optional = optional
-
@selector_source_range = selector_source_range
-
super()
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A dynamic node representing a Sass `@for` loop.
-
#
-
# @see Sass::Tree
-
1
class ForNode < Node
-
# The name of the loop variable.
-
# @return [String]
-
1
attr_reader :var
-
-
# The parse tree for the initial expression.
-
# @return [Script::Tree::Node]
-
1
attr_accessor :from
-
-
# The parse tree for the final expression.
-
# @return [Script::Tree::Node]
-
1
attr_accessor :to
-
-
# Whether to include `to` in the loop or stop just before.
-
# @return [Boolean]
-
1
attr_reader :exclusive
-
-
# @param var [String] See \{#var}
-
# @param from [Script::Tree::Node] See \{#from}
-
# @param to [Script::Tree::Node] See \{#to}
-
# @param exclusive [Boolean] See \{#exclusive}
-
1
def initialize(var, from, to, exclusive)
-
@var = var
-
@from = from
-
@to = to
-
@exclusive = exclusive
-
super()
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a function definition.
-
#
-
# @see Sass::Tree
-
1
class FunctionNode < Node
-
# The name of the function.
-
# @return [String]
-
1
attr_reader :name
-
-
# The arguments to the function. Each element is a tuple
-
# containing the variable for argument and the parse tree for
-
# the default value of the argument
-
#
-
# @return [Array<Script::Tree::Node>]
-
1
attr_accessor :args
-
-
# The splat argument for this function, if one exists.
-
#
-
# @return [Script::Tree::Node?]
-
1
attr_accessor :splat
-
-
# Strips out any vendor prefixes.
-
# @return [String] The normalized name of the directive.
-
1
def normalized_name
-
@normalized_name ||= name.gsub(/^(?:-[a-zA-Z0-9]+-)?/, '\1')
-
end
-
-
# @param name [String] The function name
-
# @param args [Array<(Script::Tree::Node, Script::Tree::Node)>]
-
# The arguments for the function.
-
# @param splat [Script::Tree::Node] See \{#splat}
-
1
def initialize(name, args, splat)
-
@name = name
-
@args = args
-
@splat = splat
-
super()
-
-
return unless %w(and or not).include?(name)
-
raise Sass::SyntaxError.new("Invalid function name \"#{name}\".")
-
end
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A dynamic node representing a Sass `@if` statement.
-
#
-
# {IfNode}s are a little odd, in that they also represent `@else` and `@else if`s.
-
# This is done as a linked list:
-
# each {IfNode} has a link (\{#else}) to the next {IfNode}.
-
#
-
# @see Sass::Tree
-
1
class IfNode < Node
-
# The conditional expression.
-
# If this is nil, this is an `@else` node, not an `@else if`.
-
#
-
# @return [Script::Expr]
-
1
attr_accessor :expr
-
-
# The next {IfNode} in the if-else list, or `nil`.
-
#
-
# @return [IfNode]
-
1
attr_accessor :else
-
-
# @param expr [Script::Expr] See \{#expr}
-
1
def initialize(expr)
-
@expr = expr
-
@last_else = self
-
super()
-
end
-
-
# Append an `@else` node to the end of the list.
-
#
-
# @param node [IfNode] The `@else` node to append
-
1
def add_else(node)
-
@last_else.else = node
-
@last_else = node
-
end
-
-
1
def _dump(f)
-
Marshal.dump([expr, self.else, children])
-
end
-
-
1
def self._load(data)
-
expr, else_, children = Marshal.load(data)
-
node = IfNode.new(expr)
-
node.else = else_
-
node.children = children
-
node.instance_variable_set('@last_else',
-
node.else ? node.else.instance_variable_get('@last_else') : node)
-
node
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A static node that wraps the {Sass::Tree} for an `@import`ed file.
-
# It doesn't have a functional purpose other than to add the `@import`ed file
-
# to the backtrace if an error occurs.
-
1
class ImportNode < RootNode
-
# The name of the imported file as it appears in the Sass document.
-
#
-
# @return [String]
-
1
attr_reader :imported_filename
-
-
# Sets the imported file.
-
1
attr_writer :imported_file
-
-
# @param imported_filename [String] The name of the imported file
-
1
def initialize(imported_filename)
-
@imported_filename = imported_filename
-
super(nil)
-
end
-
-
1
def invisible?; to_s.empty?; end
-
-
# Returns the imported file.
-
#
-
# @return [Sass::Engine]
-
# @raise [Sass::SyntaxError] If no file could be found to import.
-
1
def imported_file
-
@imported_file ||= import
-
end
-
-
# Returns whether or not this import should emit a CSS @import declaration
-
#
-
# @return [Boolean] Whether or not this is a simple CSS @import declaration.
-
1
def css_import?
-
if @imported_filename =~ /\.css$/
-
@imported_filename
-
elsif imported_file.is_a?(String) && imported_file =~ /\.css$/
-
imported_file
-
end
-
end
-
-
1
private
-
-
1
def import
-
paths = @options[:load_paths]
-
-
if @options[:importer]
-
f = @options[:importer].find_relative(
-
@imported_filename, @options[:filename], options_for_importer)
-
return f if f
-
end
-
-
paths.each do |p|
-
f = p.find(@imported_filename, options_for_importer)
-
return f if f
-
end
-
-
lines = ["File to import not found or unreadable: #{@imported_filename}."]
-
-
if paths.size == 1
-
lines << "Load path: #{paths.first}"
-
elsif !paths.empty?
-
lines << "Load paths:\n #{paths.join("\n ")}"
-
end
-
raise SyntaxError.new(lines.join("\n"))
-
rescue SyntaxError => e
-
raise SyntaxError.new(e.message, :line => line, :filename => @filename)
-
end
-
-
1
def options_for_importer
-
@options.merge(:_from_import_node => true)
-
end
-
end
-
end
-
end
-
1
module Sass::Tree
-
1
class KeyframeRuleNode < Node
-
# The text of the directive after any interpolated SassScript has been resolved.
-
# Since this is only a static node, this is the only value property.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_value
-
-
# @param resolved_value [String] See \{#resolved_value}
-
1
def initialize(resolved_value)
-
@resolved_value = resolved_value
-
super()
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A static node representing a `@media` rule.
-
# `@media` rules behave differently from other directives
-
# in that when they're nested within rules,
-
# they bubble up to top-level.
-
#
-
# @see Sass::Tree
-
1
class MediaNode < DirectiveNode
-
# TODO: parse and cache the query immediately if it has no dynamic elements
-
-
# The media query for this rule, interspersed with {Sass::Script::Tree::Node}s
-
# representing `#{}`-interpolation. Any adjacent strings will be merged
-
# together.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :query
-
-
# The media query for this rule, without any unresolved interpolation. It's
-
# only set once {Tree::Visitors::Perform} has been run.
-
#
-
# @return [Sass::Media::QueryList]
-
1
attr_accessor :resolved_query
-
-
# @param query [Array<String, Sass::Script::Tree::Node>] See \{#query}
-
1
def initialize(query)
-
@query = query
-
super('')
-
end
-
-
# @see DirectiveNode#value
-
1
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#name
-
1
def name; '@media'; end
-
-
# @see DirectiveNode#resolved_value
-
1
def resolved_value
-
@resolved_value ||= "@media #{resolved_query.to_css}"
-
end
-
-
# True when the directive has no visible children.
-
#
-
# @return [Boolean]
-
1
def invisible?
-
children.all? {|c| c.invisible?}
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a mixin definition.
-
#
-
# @see Sass::Tree
-
1
class MixinDefNode < Node
-
# The mixin name.
-
# @return [String]
-
1
attr_reader :name
-
-
# The arguments for the mixin.
-
# Each element is a tuple containing the variable for argument
-
# and the parse tree for the default value of the argument.
-
#
-
# @return [Array<(Script::Tree::Node, Script::Tree::Node)>]
-
1
attr_accessor :args
-
-
# The splat argument for this mixin, if one exists.
-
#
-
# @return [Script::Tree::Node?]
-
1
attr_accessor :splat
-
-
# Whether the mixin uses `@content`. Set during the nesting check phase.
-
# @return [Boolean]
-
1
attr_accessor :has_content
-
-
# @param name [String] The mixin name
-
# @param args [Array<(Script::Tree::Node, Script::Tree::Node)>] See \{#args}
-
# @param splat [Script::Tree::Node] See \{#splat}
-
1
def initialize(name, args, splat)
-
@name = name
-
@args = args
-
@splat = splat
-
super()
-
end
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A static node representing a mixin include.
-
# When in a static tree, the sole purpose is to wrap exceptions
-
# to add the mixin to the backtrace.
-
#
-
# @see Sass::Tree
-
1
class MixinNode < Node
-
# The name of the mixin.
-
# @return [String]
-
1
attr_reader :name
-
-
# The arguments to the mixin.
-
# @return [Array<Script::Tree::Node>]
-
1
attr_accessor :args
-
-
# A hash from keyword argument names to values.
-
# @return [Sass::Util::NormalizedMap<Script::Tree::Node>]
-
1
attr_accessor :keywords
-
-
# The first splat argument for this mixin, if one exists.
-
#
-
# This could be a list of positional arguments, a map of keyword
-
# arguments, or an arglist containing both.
-
#
-
# @return [Node?]
-
1
attr_accessor :splat
-
-
# The second splat argument for this mixin, if one exists.
-
#
-
# If this exists, it's always a map of keyword arguments, and
-
# \{#splat} is always either a list or an arglist.
-
#
-
# @return [Node?]
-
1
attr_accessor :kwarg_splat
-
-
# @param name [String] The name of the mixin
-
# @param args [Array<Script::Tree::Node>] See \{#args}
-
# @param splat [Script::Tree::Node] See \{#splat}
-
# @param kwarg_splat [Script::Tree::Node] See \{#kwarg_splat}
-
# @param keywords [Sass::Util::NormalizedMap<Script::Tree::Node>] See \{#keywords}
-
1
def initialize(name, args, keywords, splat, kwarg_splat)
-
@name = name
-
@args = args
-
@keywords = keywords
-
@splat = splat
-
@kwarg_splat = kwarg_splat
-
super()
-
end
-
end
-
end
-
1
module Sass
-
# A namespace for nodes in the Sass parse tree.
-
#
-
# The Sass parse tree has three states: dynamic, static Sass, and static CSS.
-
#
-
# When it's first parsed, a Sass document is in the dynamic state.
-
# It has nodes for mixin definitions and `@for` loops and so forth,
-
# in addition to nodes for CSS rules and properties.
-
# Nodes that only appear in this state are called **dynamic nodes**.
-
#
-
# {Tree::Visitors::Perform} creates a static Sass tree, which is
-
# different. It still has nodes for CSS rules and properties but it
-
# doesn't have any dynamic-generation-related nodes. The nodes in
-
# this state are in a similar structure to the Sass document: rules
-
# and properties are nested beneath one another, although the
-
# {Tree::RuleNode} selectors are already in their final state. Nodes
-
# that can be in this state or in the dynamic state are called
-
# **static nodes**; nodes that can only be in this state are called
-
# **solely static nodes**.
-
#
-
# {Tree::Visitors::Cssize} is then used to create a static CSS tree.
-
# This is like a static Sass tree,
-
# but the structure exactly mirrors that of the generated CSS.
-
# Rules and properties can't be nested beneath one another in this state.
-
#
-
# Finally, {Tree::Visitors::ToCss} can be called on a static CSS tree
-
# to get the actual CSS code as a string.
-
1
module Tree
-
# The abstract superclass of all parse-tree nodes.
-
1
class Node
-
1
include Enumerable
-
-
1
def self.inherited(base)
-
27
node_name = base.name.gsub(/.*::(.*?)Node$/, '\\1').downcase
-
27
base.instance_eval <<-METHODS
-
# @return [Symbol] The name that is used for this node when visiting.
-
def node_name
-
:#{node_name}
-
end
-
-
# @return [Symbol] The method that is used on the visitor to visit nodes of this type.
-
def visit_method
-
:visit_#{node_name}
-
end
-
-
# @return [Symbol] The method name that determines if the parent is invalid.
-
def invalid_child_method_name
-
:"invalid_#{node_name}_child?"
-
end
-
-
# @return [Symbol] The method name that determines if the node is an invalid parent.
-
def invalid_parent_method_name
-
:"invalid_#{node_name}_parent?"
-
end
-
METHODS
-
end
-
-
# The child nodes of this node.
-
#
-
# @return [Array<Tree::Node>]
-
1
attr_reader :children
-
-
# Whether or not this node has child nodes.
-
# This may be true even when \{#children} is empty,
-
# in which case this node has an empty block (e.g. `{}`).
-
#
-
# @return [Boolean]
-
1
attr_accessor :has_children
-
-
# The line of the document on which this node appeared.
-
#
-
# @return [Integer]
-
1
attr_accessor :line
-
-
# The source range in the document on which this node appeared.
-
#
-
# @return [Sass::Source::Range]
-
1
attr_accessor :source_range
-
-
# The name of the document on which this node appeared.
-
#
-
# @return [String]
-
1
attr_writer :filename
-
-
# The options hash for the node.
-
# See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
-
#
-
# @return [{Symbol => Object}]
-
1
attr_reader :options
-
-
1
def initialize
-
@children = []
-
@filename = nil
-
@options = nil
-
end
-
-
# Sets the options hash for the node and all its children.
-
#
-
# @param options [{Symbol => Object}] The options
-
# @see #options
-
1
def options=(options)
-
Sass::Tree::Visitors::SetOptions.visit(self, options)
-
end
-
-
# @private
-
1
def children=(children)
-
self.has_children ||= !children.empty?
-
@children = children
-
end
-
-
# The name of the document on which this node appeared.
-
#
-
# @return [String]
-
1
def filename
-
@filename || (@options && @options[:filename])
-
end
-
-
# Appends a child to the node.
-
#
-
# @param child [Tree::Node, Array<Tree::Node>] The child node or nodes
-
# @raise [Sass::SyntaxError] if `child` is invalid
-
1
def <<(child)
-
return if child.nil?
-
if child.is_a?(Array)
-
child.each {|c| self << c}
-
else
-
self.has_children = true
-
@children << child
-
end
-
end
-
-
# Compares this node and another object (only other {Tree::Node}s will be equal).
-
# This does a structural comparison;
-
# if the contents of the nodes and all the child nodes are equivalent,
-
# then the nodes are as well.
-
#
-
# Only static nodes need to override this.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
# @see Sass::Tree
-
1
def ==(other)
-
self.class == other.class && other.children == children
-
end
-
-
# True if \{#to\_s} will return `nil`;
-
# that is, if the node shouldn't be rendered.
-
# Should only be called in a static tree.
-
#
-
# @return [Boolean]
-
1
def invisible?; false; end
-
-
# The output style. See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
-
#
-
# @return [Symbol]
-
1
def style
-
@options[:style]
-
end
-
-
# Computes the CSS corresponding to this static CSS tree.
-
#
-
# @return [String] The resulting CSS
-
# @see Sass::Tree
-
1
def css
-
Sass::Tree::Visitors::ToCss.new.visit(self)
-
end
-
-
# Computes the CSS corresponding to this static CSS tree, along with
-
# the respective source map.
-
#
-
# @return [(String, Sass::Source::Map)] The resulting CSS and the source map
-
# @see Sass::Tree
-
1
def css_with_sourcemap
-
visitor = Sass::Tree::Visitors::ToCss.new(:build_source_mapping)
-
result = visitor.visit(self)
-
return result, visitor.source_mapping
-
end
-
-
# Returns a representation of the node for debugging purposes.
-
#
-
# @return [String]
-
1
def inspect
-
return self.class.to_s unless has_children
-
"(#{self.class} #{children.map {|c| c.inspect}.join(' ')})"
-
end
-
-
# Iterates through each node in the tree rooted at this node
-
# in a pre-order walk.
-
#
-
# @yield node
-
# @yieldparam node [Node] a node in the tree
-
1
def each
-
yield self
-
children.each {|c| c.each {|n| yield n}}
-
end
-
-
# Converts a node to Sass code that will generate it.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
-
# @return [String] The Sass code corresponding to the node
-
1
def to_sass(options = {})
-
Sass::Tree::Visitors::Convert.visit(self, options, :sass)
-
end
-
-
# Converts a node to SCSS code that will generate it.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
-
# @return [String] The Sass code corresponding to the node
-
1
def to_scss(options = {})
-
Sass::Tree::Visitors::Convert.visit(self, options, :scss)
-
end
-
-
# Return a deep clone of this node.
-
# The child nodes are cloned, but options are not.
-
#
-
# @return [Node]
-
1
def deep_copy
-
Sass::Tree::Visitors::DeepCopy.visit(self)
-
end
-
-
# Whether or not this node bubbles up through RuleNodes.
-
#
-
# @return [Boolean]
-
1
def bubbles?
-
false
-
end
-
-
1
protected
-
-
# @see Sass::Shared.balance
-
# @raise [Sass::SyntaxError] if the brackets aren't balanced
-
1
def balance(*args)
-
res = Sass::Shared.balance(*args)
-
return res if res
-
raise Sass::SyntaxError.new("Unbalanced brackets.", :line => line)
-
end
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A static node representing a CSS property.
-
#
-
# @see Sass::Tree
-
1
class PropNode < Node
-
# The name of the property,
-
# interspersed with {Sass::Script::Tree::Node}s
-
# representing `#{}`-interpolation.
-
# Any adjacent strings will be merged together.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :name
-
-
# The name of the property
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_name
-
-
# The value of the property.
-
#
-
# For most properties, this will just contain a single Node. However, for
-
# CSS variables, it will contain multiple strings and nodes representing
-
# interpolation. Any adjacent strings will be merged together.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :value
-
-
# The value of the property
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_value
-
-
# How deep this property is indented
-
# relative to a normal property.
-
# This is only greater than 0 in the case that:
-
#
-
# * This node is in a CSS tree
-
# * The style is :nested
-
# * This is a child property of another property
-
# * The parent property has a value, and thus will be rendered
-
#
-
# @return [Integer]
-
1
attr_accessor :tabs
-
-
# The source range in which the property name appears.
-
#
-
# @return [Sass::Source::Range]
-
1
attr_accessor :name_source_range
-
-
# The source range in which the property value appears.
-
#
-
# @return [Sass::Source::Range]
-
1
attr_accessor :value_source_range
-
-
# Whether this represents a CSS custom property.
-
#
-
# @return [Boolean]
-
1
def custom_property?
-
name.first.is_a?(String) && name.first.start_with?("--")
-
end
-
-
# @param name [Array<String, Sass::Script::Tree::Node>] See \{#name}
-
# @param value [Array<String, Sass::Script::Tree::Node>] See \{#value}
-
# @param prop_syntax [Symbol] `:new` if this property uses `a: b`-style syntax,
-
# `:old` if it uses `:a b`-style syntax
-
1
def initialize(name, value, prop_syntax)
-
@name = Sass::Util.strip_string_array(
-
Sass::Util.merge_adjacent_strings(name))
-
@value = Sass::Util.merge_adjacent_strings(value)
-
@value = Sass::Util.strip_string_array(@value) unless custom_property?
-
@tabs = 0
-
@prop_syntax = prop_syntax
-
super()
-
end
-
-
# Compares the names and values of two properties.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
1
def ==(other)
-
self.class == other.class && name == other.name && value == other.value && super
-
end
-
-
# Returns a appropriate message indicating how to escape pseudo-class selectors.
-
# This only applies for old-style properties with no value,
-
# so returns the empty string if this is new-style.
-
#
-
# @return [String] The message
-
1
def pseudo_class_selector_message
-
if @prop_syntax == :new ||
-
custom_property? ||
-
!value.first.is_a?(Sass::Script::Tree::Literal) ||
-
!value.first.value.is_a?(Sass::Script::Value::String) ||
-
!value.first.value.value.empty?
-
return ""
-
end
-
-
"\nIf #{declaration.dump} should be a selector, use \"\\#{declaration}\" instead."
-
end
-
-
# Computes the Sass or SCSS code for the variable declaration.
-
# This is like \{#to\_scss} or \{#to\_sass},
-
# except it doesn't print any child properties or a trailing semicolon.
-
#
-
# @param opts [{Symbol => Object}] The options hash for the tree.
-
# @param fmt [Symbol] `:scss` or `:sass`.
-
1
def declaration(opts = {:old => @prop_syntax == :old}, fmt = :sass)
-
name = self.name.map {|n| n.is_a?(String) ? n : n.to_sass(opts)}.join
-
value = self.value.map {|n| n.is_a?(String) ? n : n.to_sass(opts)}.join
-
value = "(#{value})" if value_needs_parens?
-
-
if name[0] == ?:
-
raise Sass::SyntaxError.new("The \"#{name}: #{value}\"" +
-
" hack is not allowed in the Sass indented syntax")
-
end
-
-
# The indented syntax doesn't support newlines in custom property values,
-
# but we can losslessly convert them to spaces instead.
-
value = value.tr("\n", " ") if fmt == :sass
-
-
old = opts[:old] && fmt == :sass
-
"#{old ? ':' : ''}#{name}#{old ? '' : ':'}#{custom_property? ? '' : ' '}#{value}".rstrip
-
end
-
-
# A property node is invisible if its value is empty.
-
#
-
# @return [Boolean]
-
1
def invisible?
-
!custom_property? && resolved_value.empty?
-
end
-
-
1
private
-
-
# Returns whether \{#value} neesd parentheses in order to be parsed
-
# properly as division.
-
1
def value_needs_parens?
-
return false if custom_property?
-
-
root = value.first
-
root.is_a?(Sass::Script::Tree::Operation) &&
-
root.operator == :div &&
-
root.operand1.is_a?(Sass::Script::Tree::Literal) &&
-
root.operand1.value.is_a?(Sass::Script::Value::Number) &&
-
root.operand1.value.original.nil? &&
-
root.operand2.is_a?(Sass::Script::Tree::Literal) &&
-
root.operand2.value.is_a?(Sass::Script::Value::Number) &&
-
root.operand2.value.original.nil?
-
end
-
-
1
def check!
-
return unless @options[:property_syntax] && @options[:property_syntax] != @prop_syntax
-
raise Sass::SyntaxError.new(
-
"Illegal property syntax: can't use #{@prop_syntax} syntax when " +
-
":property_syntax => #{@options[:property_syntax].inspect} is set.")
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing returning from a function.
-
#
-
# @see Sass::Tree
-
1
class ReturnNode < Node
-
# The expression to return.
-
#
-
# @return [Script::Tree::Node]
-
1
attr_accessor :expr
-
-
# @param expr [Script::Tree::Node] The expression to return
-
1
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A static node that is the root node of the Sass document.
-
1
class RootNode < Node
-
# The Sass template from which this node was created
-
#
-
# @param template [String]
-
1
attr_reader :template
-
-
# @param template [String] The Sass template from which this node was created
-
1
def initialize(template)
-
super()
-
@template = template
-
end
-
-
# Runs the dynamic Sass code and computes the CSS for the tree.
-
#
-
# @return [String] The compiled CSS.
-
1
def render
-
css_tree.css
-
end
-
-
# Runs the dynamic Sass code and computes the CSS for the tree, along with
-
# the sourcemap.
-
#
-
# @return [(String, Sass::Source::Map)] The compiled CSS, as well as
-
# the source map. @see #render
-
1
def render_with_sourcemap
-
css_tree.css_with_sourcemap
-
end
-
-
1
private
-
-
1
def css_tree
-
Visitors::CheckNesting.visit(self)
-
result = Visitors::Perform.visit(self)
-
Visitors::CheckNesting.visit(result) # Check again to validate mixins
-
result, extends = Visitors::Cssize.visit(result)
-
Visitors::Extend.visit(result, extends)
-
result
-
end
-
end
-
end
-
end
-
1
require 'pathname'
-
-
1
module Sass::Tree
-
# A static node representing a CSS rule.
-
#
-
# @see Sass::Tree
-
1
class RuleNode < Node
-
# The character used to include the parent selector
-
1
PARENT = '&'
-
-
# The CSS selector for this rule,
-
# interspersed with {Sass::Script::Tree::Node}s
-
# representing `#{}`-interpolation.
-
# Any adjacent strings will be merged together.
-
#
-
# @return [Array<String, Sass::Script::Tree::Node>]
-
1
attr_accessor :rule
-
-
# The CSS selector for this rule, without any unresolved
-
# interpolation but with parent references still intact. It's only
-
# guaranteed to be set once {Tree::Visitors::Perform} has been
-
# run, but it may be set before then for optimization reasons.
-
#
-
# @return [Selector::CommaSequence]
-
1
attr_accessor :parsed_rules
-
-
# The CSS selector for this rule, without any unresolved
-
# interpolation or parent references. It's only set once
-
# {Tree::Visitors::Perform} has been run.
-
#
-
# @return [Selector::CommaSequence]
-
1
attr_accessor :resolved_rules
-
-
# How deep this rule is indented
-
# relative to a base-level rule.
-
# This is only greater than 0 in the case that:
-
#
-
# * This node is in a CSS tree
-
# * The style is :nested
-
# * This is a child rule of another rule
-
# * The parent rule has properties, and thus will be rendered
-
#
-
# @return [Integer]
-
1
attr_accessor :tabs
-
-
# The entire selector source range for this rule.
-
# @return [Sass::Source::Range]
-
1
attr_accessor :selector_source_range
-
-
# Whether or not this rule is the last rule in a nested group.
-
# This is only set in a CSS tree.
-
#
-
# @return [Boolean]
-
1
attr_accessor :group_end
-
-
# The stack trace.
-
# This is only readable in a CSS tree as it is written during the perform step
-
# and only when the :trace_selectors option is set.
-
#
-
# @return [String]
-
1
attr_accessor :stack_trace
-
-
# @param rule [Array<String, Sass::Script::Tree::Node>, Sass::Selector::CommaSequence]
-
# The CSS rule, either unparsed or parsed.
-
# @param selector_source_range [Sass::Source::Range]
-
1
def initialize(rule, selector_source_range = nil)
-
if rule.is_a?(Sass::Selector::CommaSequence)
-
@rule = [rule.to_s]
-
@parsed_rules = rule
-
else
-
merged = Sass::Util.merge_adjacent_strings(rule)
-
@rule = Sass::Util.strip_string_array(merged)
-
try_to_parse_non_interpolated_rules
-
end
-
@selector_source_range = selector_source_range
-
@tabs = 0
-
super()
-
end
-
-
# If we've precached the parsed selector, set the line on it, too.
-
1
def line=(line)
-
@parsed_rules.line = line if @parsed_rules
-
super
-
end
-
-
# If we've precached the parsed selector, set the filename on it, too.
-
1
def filename=(filename)
-
@parsed_rules.filename = filename if @parsed_rules
-
super
-
end
-
-
# Compares the contents of two rules.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
1
def ==(other)
-
self.class == other.class && rule == other.rule && super
-
end
-
-
# Adds another {RuleNode}'s rules to this one's.
-
#
-
# @param node [RuleNode] The other node
-
1
def add_rules(node)
-
@rule = Sass::Util.strip_string_array(
-
Sass::Util.merge_adjacent_strings(@rule + ["\n"] + node.rule))
-
try_to_parse_non_interpolated_rules
-
end
-
-
# @return [Boolean] Whether or not this rule is continued on the next line
-
1
def continued?
-
last = @rule.last
-
last.is_a?(String) && last[-1] == ?,
-
end
-
-
# A hash that will be associated with this rule in the CSS document
-
# if the {file:SASS_REFERENCE.md#debug_info-option `:debug_info` option} is enabled.
-
# This data is used by e.g. [the FireSass Firebug
-
# extension](https://addons.mozilla.org/en-US/firefox/addon/103988).
-
#
-
# @return [{#to_s => #to_s}]
-
1
def debug_info
-
{:filename => filename &&
-
("file://" + URI::DEFAULT_PARSER.escape(File.expand_path(filename))),
-
:line => line}
-
end
-
-
# A rule node is invisible if it has only placeholder selectors.
-
1
def invisible?
-
resolved_rules.members.all? {|seq| seq.invisible?}
-
end
-
-
1
private
-
-
1
def try_to_parse_non_interpolated_rules
-
@parsed_rules = nil
-
return unless @rule.all? {|t| t.is_a?(String)}
-
-
# We don't use real filename/line info because we don't have it yet.
-
# When we get it, we'll set it on the parsed rules if possible.
-
parser = nil
-
warnings = Sass::Util.silence_warnings do
-
parser = Sass::SCSS::StaticParser.new(@rule.join.strip, nil, nil, 1)
-
# rubocop:disable RescueModifier
-
@parsed_rules = parser.parse_selector rescue nil
-
# rubocop:enable RescueModifier
-
-
$stderr.string
-
end
-
-
# If parsing produces a warning, throw away the result so we can parse
-
# later with the real filename info.
-
@parsed_rules = nil unless warnings.empty?
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A static node representing a `@supports` rule.
-
#
-
# @see Sass::Tree
-
1
class SupportsNode < DirectiveNode
-
# The name, which may include a browser prefix.
-
#
-
# @return [String]
-
1
attr_accessor :name
-
-
# The supports condition.
-
#
-
# @return [Sass::Supports::Condition]
-
1
attr_accessor :condition
-
-
# @param condition [Sass::Supports::Condition] See \{#condition}
-
1
def initialize(name, condition)
-
@name = name
-
@condition = condition
-
super('')
-
end
-
-
# @see DirectiveNode#value
-
1
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#resolved_value
-
1
def resolved_value
-
@resolved_value ||= "@#{name} #{condition.to_css}"
-
end
-
-
# True when the directive has no visible children.
-
#
-
# @return [Boolean]
-
1
def invisible?
-
children.all? {|c| c.invisible?}
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A solely static node left over after a mixin include or @content has been performed.
-
# Its sole purpose is to wrap exceptions to add to the backtrace.
-
#
-
# @see Sass::Tree
-
1
class TraceNode < Node
-
# The name of the trace entry to add.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# @param name [String] The name of the trace entry to add.
-
1
def initialize(name)
-
@name = name
-
self.has_children = true
-
super()
-
end
-
-
# Initializes this node from an existing node.
-
# @param name [String] The name of the trace entry to add.
-
# @param node [Node] The node to copy information from.
-
# @return [TraceNode]
-
1
def self.from_node(name, node)
-
trace = new(name)
-
trace.line = node.line
-
trace.filename = node.filename
-
trace.options = node.options
-
trace
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a variable definition.
-
#
-
# @see Sass::Tree
-
1
class VariableNode < Node
-
# The name of the variable.
-
# @return [String]
-
1
attr_reader :name
-
-
# The parse tree for the variable value.
-
# @return [Script::Tree::Node]
-
1
attr_accessor :expr
-
-
# Whether this is a guarded variable assignment (`!default`).
-
# @return [Boolean]
-
1
attr_reader :guarded
-
-
# Whether this is a global variable assignment (`!global`).
-
# @return [Boolean]
-
1
attr_reader :global
-
-
# @param name [String] The name of the variable
-
# @param expr [Script::Tree::Node] See \{#expr}
-
# @param guarded [Boolean] See \{#guarded}
-
# @param global [Boolean] See \{#global}
-
1
def initialize(name, expr, guarded, global)
-
@name = name
-
@expr = expr
-
@guarded = guarded
-
@global = global
-
super()
-
end
-
end
-
end
-
end
-
# Visitors are used to traverse the Sass parse tree.
-
# Visitors should extend {Visitors::Base},
-
# which provides a small amount of scaffolding for traversal.
-
1
module Sass::Tree::Visitors
-
# The abstract base class for Sass visitors.
-
# Visitors should extend this class,
-
# then implement `visit_*` methods for each node they care about
-
# (e.g. `visit_rule` for {RuleNode} or `visit_for` for {ForNode}).
-
# These methods take the node in question as argument.
-
# They may `yield` to visit the child nodes of the current node.
-
#
-
# *Note*: due to the unusual nature of {Sass::Tree::IfNode},
-
# special care must be taken to ensure that it is properly handled.
-
# In particular, there is no built-in scaffolding
-
# for dealing with the return value of `@else` nodes.
-
#
-
# @abstract
-
1
class Base
-
# Runs the visitor on a tree.
-
#
-
# @param root [Tree::Node] The root node of the Sass tree.
-
# @return [Object] The return value of \{#visit} for the root node.
-
1
def self.visit(root)
-
new.send(:visit, root)
-
end
-
-
1
protected
-
-
# Runs the visitor on the given node.
-
# This can be overridden by subclasses that need to do something for each node.
-
#
-
# @param node [Tree::Node] The node to visit.
-
# @return [Object] The return value of the `visit_*` method for this node.
-
1
def visit(node)
-
if respond_to?(node.class.visit_method, true)
-
send(node.class.visit_method, node) {visit_children(node)}
-
else
-
visit_children(node)
-
end
-
end
-
-
# Visit the child nodes for a given node.
-
# This can be overridden by subclasses that need to do something
-
# with the child nodes' return values.
-
#
-
# This method is run when `visit_*` methods `yield`,
-
# and its return value is returned from the `yield`.
-
#
-
# @param parent [Tree::Node] The parent node of the children to visit.
-
# @return [Array<Object>] The return values of the `visit_*` methods for the children.
-
1
def visit_children(parent)
-
parent.children.map {|c| visit(c)}
-
end
-
-
# Returns the name of a node as used in the `visit_*` method.
-
#
-
# @param [Tree::Node] node The node.
-
# @return [String] The name.
-
1
def self.node_name(node)
-
Sass::Util.deprecated(self, "Call node.class.node_name instead.")
-
node.class.node_name
-
end
-
-
# `yield`s, then runs the visitor on the `@else` clause if the node has one.
-
# This exists to ensure that the contents of the `@else` clause get visited.
-
1
def visit_if(node)
-
yield
-
visit(node.else) if node.else
-
node
-
end
-
end
-
end
-
# A visitor for checking that all nodes are properly nested.
-
1
class Sass::Tree::Visitors::CheckNesting < Sass::Tree::Visitors::Base
-
1
protected
-
-
1
def initialize
-
@parents = []
-
@parent = nil
-
@current_mixin_def = nil
-
end
-
-
1
def visit(node)
-
if (error = @parent && (
-
try_send(@parent.class.invalid_child_method_name, @parent, node) ||
-
try_send(node.class.invalid_parent_method_name, @parent, node)))
-
raise Sass::SyntaxError.new(error)
-
end
-
super
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
1
CONTROL_NODES = [Sass::Tree::EachNode, Sass::Tree::ForNode, Sass::Tree::IfNode,
-
Sass::Tree::WhileNode, Sass::Tree::TraceNode]
-
1
SCRIPT_NODES = [Sass::Tree::ImportNode] + CONTROL_NODES
-
1
def visit_children(parent)
-
old_parent = @parent
-
-
# When checking a static tree, resolve at-roots to be sure they won't send
-
# nodes where they don't belong.
-
if parent.is_a?(Sass::Tree::AtRootNode) && parent.resolved_value
-
old_parents = @parents
-
@parents = @parents.reject {|p| parent.exclude_node?(p)}
-
@parent = @parents.reverse.each_with_index.
-
find {|p, i| !transparent_parent?(p, @parents[-i - 2])}.first
-
-
begin
-
return super
-
ensure
-
@parents = old_parents
-
@parent = old_parent
-
end
-
end
-
-
unless transparent_parent?(parent, old_parent)
-
@parent = parent
-
end
-
-
@parents.push parent
-
begin
-
super
-
ensure
-
@parent = old_parent
-
@parents.pop
-
end
-
end
-
-
1
def visit_root(node)
-
yield
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
1
def visit_import(node)
-
yield
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.children.first.filename)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
1
def visit_mixindef(node)
-
@current_mixin_def, old_mixin_def = node, @current_mixin_def
-
yield
-
ensure
-
@current_mixin_def = old_mixin_def
-
end
-
-
1
def invalid_content_parent?(parent, child)
-
if @current_mixin_def
-
@current_mixin_def.has_content = true
-
nil
-
else
-
"@content may only be used within a mixin."
-
end
-
end
-
-
1
def invalid_charset_parent?(parent, child)
-
"@charset may only be used at the root of a document." unless parent.is_a?(Sass::Tree::RootNode)
-
end
-
-
1
VALID_EXTEND_PARENTS = [Sass::Tree::RuleNode, Sass::Tree::MixinDefNode, Sass::Tree::MixinNode]
-
1
def invalid_extend_parent?(parent, child)
-
return if is_any_of?(parent, VALID_EXTEND_PARENTS)
-
"Extend directives may only be used within rules."
-
end
-
-
1
INVALID_IMPORT_PARENTS = CONTROL_NODES +
-
[Sass::Tree::MixinDefNode, Sass::Tree::MixinNode]
-
1
def invalid_import_parent?(parent, child)
-
unless (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
return "Import directives may not be used within control directives or mixins."
-
end
-
return if parent.is_a?(Sass::Tree::RootNode)
-
return "CSS import directives may only be used at the root of a document." if child.css_import?
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => child.imported_file.options[:filename])
-
e.add_backtrace(:filename => child.filename, :line => child.line)
-
raise e
-
end
-
-
1
def invalid_mixindef_parent?(parent, child)
-
return if (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
"Mixins may not be defined within control directives or other mixins."
-
end
-
-
1
def invalid_function_parent?(parent, child)
-
return if (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
"Functions may not be defined within control directives or other mixins."
-
end
-
-
1
VALID_FUNCTION_CHILDREN = [
-
Sass::Tree::CommentNode, Sass::Tree::DebugNode, Sass::Tree::ReturnNode,
-
Sass::Tree::VariableNode, Sass::Tree::WarnNode, Sass::Tree::ErrorNode
-
] + CONTROL_NODES
-
1
def invalid_function_child?(parent, child)
-
return if is_any_of?(child, VALID_FUNCTION_CHILDREN)
-
"Functions can only contain variable declarations and control directives."
-
end
-
-
1
VALID_PROP_CHILDREN = CONTROL_NODES + [Sass::Tree::CommentNode,
-
Sass::Tree::PropNode,
-
Sass::Tree::MixinNode]
-
1
def invalid_prop_child?(parent, child)
-
return if is_any_of?(child, VALID_PROP_CHILDREN)
-
"Illegal nesting: Only properties may be nested beneath properties."
-
end
-
-
1
VALID_PROP_PARENTS = [Sass::Tree::RuleNode, Sass::Tree::KeyframeRuleNode, Sass::Tree::PropNode,
-
Sass::Tree::MixinDefNode, Sass::Tree::DirectiveNode, Sass::Tree::MixinNode]
-
1
def invalid_prop_parent?(parent, child)
-
return if is_any_of?(parent, VALID_PROP_PARENTS)
-
"Properties are only allowed within rules, directives, mixin includes, or other properties." +
-
child.pseudo_class_selector_message
-
end
-
-
1
def invalid_return_parent?(parent, child)
-
"@return may only be used within a function." unless parent.is_a?(Sass::Tree::FunctionNode)
-
end
-
-
1
private
-
-
# Whether `parent` should be assigned to `@parent`.
-
1
def transparent_parent?(parent, grandparent)
-
is_any_of?(parent, SCRIPT_NODES) ||
-
(parent.bubbles? &&
-
!grandparent.is_a?(Sass::Tree::RootNode) &&
-
!grandparent.is_a?(Sass::Tree::AtRootNode))
-
end
-
-
1
def is_any_of?(val, classes)
-
classes.each do |c|
-
return true if val.is_a?(c)
-
end
-
false
-
end
-
-
1
def try_send(method, *args)
-
return unless respond_to?(method, true)
-
send(method, *args)
-
end
-
end
-
# A visitor for converting a Sass tree into a source string.
-
1
class Sass::Tree::Visitors::Convert < Sass::Tree::Visitors::Base
-
# Runs the visitor on a tree.
-
#
-
# @param root [Tree::Node] The root node of the Sass tree.
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @param format [Symbol] `:sass` or `:scss`.
-
# @return [String] The Sass or SCSS source for the tree.
-
1
def self.visit(root, options, format)
-
new(options, format).send(:visit, root)
-
end
-
-
1
protected
-
-
1
def initialize(options, format)
-
@options = options
-
@format = format
-
@tabs = 0
-
# 2 spaces by default
-
@tab_chars = @options[:indent] || " "
-
@is_else = false
-
end
-
-
1
def visit_children(parent)
-
@tabs += 1
-
return @format == :sass ? "\n" : " {}\n" if parent.children.empty?
-
-
res = visit_rule_level(parent.children)
-
-
if @format == :sass
-
"\n" + res.rstrip + "\n"
-
else
-
" {\n" + res.rstrip + "\n#{@tab_chars * (@tabs - 1)}}\n"
-
end
-
ensure
-
@tabs -= 1
-
end
-
-
# Ensures proper spacing between top-level nodes.
-
1
def visit_root(node)
-
visit_rule_level(node.children)
-
end
-
-
1
def visit_charset(node)
-
"#{tab_str}@charset \"#{node.name}\"#{semi}\n"
-
end
-
-
1
def visit_comment(node)
-
value = interp_to_src(node.value)
-
if @format == :sass
-
content = value.gsub(%r{\*/$}, '').rstrip
-
if content =~ /\A[ \t]/
-
# Re-indent SCSS comments like this:
-
# /* foo
-
# bar
-
# baz */
-
content.gsub!(/^/, ' ')
-
content.sub!(%r{\A([ \t]*)/\*}, '/*\1')
-
end
-
-
if content.include?("\n")
-
content.gsub!(/\n \*/, "\n ")
-
spaces = content.scan(/\n( *)/).map {|s| s.first.size}.min
-
sep = node.type == :silent ? "\n//" : "\n *"
-
if spaces >= 2
-
content.gsub!(/\n /, sep)
-
else
-
content.gsub!(/\n#{' ' * spaces}/, sep)
-
end
-
end
-
-
content.gsub!(%r{\A/\*}, '//') if node.type == :silent
-
content.gsub!(/^/, tab_str)
-
content = content.rstrip + "\n"
-
else
-
spaces = (@tab_chars * [@tabs - value[/^ */].size, 0].max)
-
content = if node.type == :silent
-
value.gsub(%r{^[/ ]\*}, '//').gsub(%r{ *\*/$}, '')
-
else
-
value
-
end.gsub(/^/, spaces) + "\n"
-
end
-
content
-
end
-
-
1
def visit_debug(node)
-
"#{tab_str}@debug #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
1
def visit_error(node)
-
"#{tab_str}@error #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
1
def visit_directive(node)
-
res = "#{tab_str}#{interp_to_src(node.value)}"
-
res.gsub!(/^@import \#\{(.*)\}([^}]*)$/, '@import \1\2')
-
return res + "#{semi}\n" unless node.has_children
-
res + yield
-
end
-
-
1
def visit_each(node)
-
vars = node.vars.map {|var| "$#{dasherize(var)}"}.join(", ")
-
"#{tab_str}@each #{vars} in #{node.list.to_sass(@options)}#{yield}"
-
end
-
-
1
def visit_extend(node)
-
"#{tab_str}@extend #{selector_to_src(node.selector).lstrip}" +
-
"#{' !optional' if node.optional?}#{semi}\n"
-
end
-
-
1
def visit_for(node)
-
"#{tab_str}@for $#{dasherize(node.var)} from #{node.from.to_sass(@options)} " +
-
"#{node.exclusive ? 'to' : 'through'} #{node.to.to_sass(@options)}#{yield}"
-
end
-
-
1
def visit_function(node)
-
args = node.args.map do |v, d|
-
d ? "#{v.to_sass(@options)}: #{d.to_sass(@options)}" : v.to_sass(@options)
-
end.join(", ")
-
if node.splat
-
args << ", " unless node.args.empty?
-
args << node.splat.to_sass(@options) << "..."
-
end
-
-
"#{tab_str}@function #{dasherize(node.name)}(#{args})#{yield}"
-
end
-
-
1
def visit_if(node)
-
name =
-
if !@is_else
-
"if"
-
elsif node.expr
-
"else if"
-
else
-
"else"
-
end
-
@is_else = false
-
str = "#{tab_str}@#{name}"
-
str << " #{node.expr.to_sass(@options)}" if node.expr
-
str << yield
-
@is_else = true
-
str << visit(node.else) if node.else
-
str
-
ensure
-
@is_else = false
-
end
-
-
1
def visit_import(node)
-
quote = @format == :scss ? '"' : ''
-
"#{tab_str}@import #{quote}#{node.imported_filename}#{quote}#{semi}\n"
-
end
-
-
1
def visit_media(node)
-
"#{tab_str}@media #{query_interp_to_src(node.query)}#{yield}"
-
end
-
-
1
def visit_supports(node)
-
"#{tab_str}@#{node.name} #{node.condition.to_src(@options)}#{yield}"
-
end
-
-
1
def visit_cssimport(node)
-
if node.uri.is_a?(Sass::Script::Tree::Node)
-
str = "#{tab_str}@import #{node.uri.to_sass(@options)}"
-
else
-
str = "#{tab_str}@import #{node.uri}"
-
end
-
str << " supports(#{node.supports_condition.to_src(@options)})" if node.supports_condition
-
str << " #{interp_to_src(node.query)}" unless node.query.empty?
-
"#{str}#{semi}\n"
-
end
-
-
1
def visit_mixindef(node)
-
args =
-
if node.args.empty? && node.splat.nil?
-
""
-
else
-
str = '('
-
str << node.args.map do |v, d|
-
if d
-
"#{v.to_sass(@options)}: #{d.to_sass(@options)}"
-
else
-
v.to_sass(@options)
-
end
-
end.join(", ")
-
-
if node.splat
-
str << ", " unless node.args.empty?
-
str << node.splat.to_sass(@options) << '...'
-
end
-
-
str << ')'
-
end
-
-
"#{tab_str}#{@format == :sass ? '=' : '@mixin '}#{dasherize(node.name)}#{args}#{yield}"
-
end
-
-
1
def visit_mixin(node)
-
arg_to_sass = lambda do |arg|
-
sass = arg.to_sass(@options)
-
sass = "(#{sass})" if arg.is_a?(Sass::Script::Tree::ListLiteral) && arg.separator == :comma
-
sass
-
end
-
-
unless node.args.empty? && node.keywords.empty? && node.splat.nil?
-
args = node.args.map(&arg_to_sass)
-
keywords = node.keywords.as_stored.to_a.map {|k, v| "$#{dasherize(k)}: #{arg_to_sass[v]}"}
-
-
if node.splat
-
splat = "#{arg_to_sass[node.splat]}..."
-
kwarg_splat = "#{arg_to_sass[node.kwarg_splat]}..." if node.kwarg_splat
-
end
-
-
arglist = "(#{[args, splat, keywords, kwarg_splat].flatten.compact.join(', ')})"
-
end
-
"#{tab_str}#{@format == :sass ? '+' : '@include '}" +
-
"#{dasherize(node.name)}#{arglist}#{node.has_children ? yield : semi}\n"
-
end
-
-
1
def visit_content(node)
-
"#{tab_str}@content#{semi}\n"
-
end
-
-
1
def visit_prop(node)
-
res = tab_str + node.declaration(@options, @format)
-
return res + semi + "\n" if node.children.empty?
-
res + yield.rstrip + semi + "\n"
-
end
-
-
1
def visit_return(node)
-
"#{tab_str}@return #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
1
def visit_rule(node)
-
rule = node.parsed_rules ? [node.parsed_rules.to_s] : node.rule
-
if @format == :sass
-
name = selector_to_sass(rule)
-
name = "\\" + name if name[0] == ?:
-
name.gsub(/^/, tab_str) + yield
-
elsif @format == :scss
-
name = selector_to_scss(rule)
-
res = name + yield
-
if node.children.last.is_a?(Sass::Tree::CommentNode) && node.children.last.type == :silent
-
res.slice!(-3..-1)
-
res << "\n" << tab_str << "}\n"
-
end
-
res
-
end
-
end
-
-
1
def visit_variable(node)
-
"#{tab_str}$#{dasherize(node.name)}: #{node.expr.to_sass(@options)}" +
-
"#{' !global' if node.global}#{' !default' if node.guarded}#{semi}\n"
-
end
-
-
1
def visit_warn(node)
-
"#{tab_str}@warn #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
1
def visit_while(node)
-
"#{tab_str}@while #{node.expr.to_sass(@options)}#{yield}"
-
end
-
-
1
def visit_atroot(node)
-
if node.query
-
"#{tab_str}@at-root #{query_interp_to_src(node.query)}#{yield}"
-
elsif node.children.length == 1 && node.children.first.is_a?(Sass::Tree::RuleNode)
-
rule = node.children.first
-
"#{tab_str}@at-root #{selector_to_src(rule.rule).lstrip}#{visit_children(rule)}"
-
else
-
"#{tab_str}@at-root#{yield}"
-
end
-
end
-
-
1
def visit_keyframerule(node)
-
"#{tab_str}#{node.resolved_value}#{yield}"
-
end
-
-
1
private
-
-
# Visit rule-level nodes and return their conversion with appropriate
-
# whitespace added.
-
1
def visit_rule_level(nodes)
-
(nodes + [nil]).each_cons(2).map do |child, nxt|
-
visit(child) +
-
if nxt &&
-
(child.is_a?(Sass::Tree::CommentNode) && child.line + child.lines + 1 == nxt.line) ||
-
(child.is_a?(Sass::Tree::ImportNode) && nxt.is_a?(Sass::Tree::ImportNode) &&
-
child.line + 1 == nxt.line) ||
-
(child.is_a?(Sass::Tree::VariableNode) && nxt.is_a?(Sass::Tree::VariableNode) &&
-
child.line + 1 == nxt.line) ||
-
(child.is_a?(Sass::Tree::PropNode) && nxt.is_a?(Sass::Tree::PropNode)) ||
-
(child.is_a?(Sass::Tree::MixinNode) && nxt.is_a?(Sass::Tree::MixinNode) &&
-
child.line + 1 == nxt.line)
-
""
-
else
-
"\n"
-
end
-
end.join.rstrip + "\n"
-
end
-
-
1
def interp_to_src(interp)
-
interp.map {|r| r.is_a?(String) ? r : r.to_sass(@options)}.join
-
end
-
-
# Like interp_to_src, but removes the unnecessary `#{}` around the keys and
-
# values in query expressions.
-
1
def query_interp_to_src(interp)
-
interp = interp.map do |e|
-
next e unless e.is_a?(Sass::Script::Tree::Literal)
-
next e unless e.value.is_a?(Sass::Script::Value::String)
-
e.value.value
-
end
-
-
interp_to_src(interp)
-
end
-
-
1
def selector_to_src(sel)
-
@format == :sass ? selector_to_sass(sel) : selector_to_scss(sel)
-
end
-
-
1
def selector_to_sass(sel)
-
sel.map do |r|
-
if r.is_a?(String)
-
r.gsub(/(,)?([ \t]*)\n\s*/) {$1 ? "#{$1}#{$2}\n" : " "}
-
else
-
r.to_sass(@options)
-
end
-
end.join
-
end
-
-
1
def selector_to_scss(sel)
-
interp_to_src(sel).gsub(/^[ \t]*/, tab_str).gsub(/[ \t]*$/, '')
-
end
-
-
1
def semi
-
@format == :sass ? "" : ";"
-
end
-
-
1
def tab_str
-
@tab_chars * @tabs
-
end
-
-
1
def dasherize(s)
-
if @options[:dasherize]
-
s.tr('_', '-')
-
else
-
s
-
end
-
end
-
end
-
# A visitor for converting a static Sass tree into a static CSS tree.
-
1
class Sass::Tree::Visitors::Cssize < Sass::Tree::Visitors::Base
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @return [(Tree::Node, Sass::Util::SubsetMap)] The resulting tree of static nodes
-
# *and* the extensions defined for this tree
-
1
def self.visit(root); super; end
-
-
1
protected
-
-
# Returns the immediate parent of the current node.
-
# @return [Tree::Node]
-
1
def parent
-
@parents.last
-
end
-
-
1
def initialize
-
@parents = []
-
@extends = Sass::Util::SubsetMap.new
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
1
def visit(node)
-
super(node)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current parent node.
-
1
def visit_children(parent)
-
with_parent parent do
-
parent.children = visit_children_without_parent(parent)
-
parent
-
end
-
end
-
-
# Like {#visit\_children}, but doesn't set {#parent}.
-
#
-
# @param node [Sass::Tree::Node]
-
# @return [Array<Sass::Tree::Node>] the flattened results of
-
# visiting all the children of `node`
-
1
def visit_children_without_parent(node)
-
node.children.map {|c| visit(c)}.flatten
-
end
-
-
# Runs a block of code with the current parent node
-
# replaced with the given node.
-
#
-
# @param parent [Tree::Node] The new parent for the duration of the block.
-
# @yield A block in which the parent is set to `parent`.
-
# @return [Object] The return value of the block.
-
1
def with_parent(parent)
-
@parents.push parent
-
yield
-
ensure
-
@parents.pop
-
end
-
-
# Converts the entire document to CSS.
-
#
-
# @return [(Tree::Node, Sass::Util::SubsetMap)] The resulting tree of static nodes
-
# *and* the extensions defined for this tree
-
1
def visit_root(node)
-
yield
-
-
if parent.nil?
-
imports_to_move = []
-
import_limit = nil
-
i = -1
-
node.children.reject! do |n|
-
i += 1
-
if import_limit
-
next false unless n.is_a?(Sass::Tree::CssImportNode)
-
imports_to_move << n
-
next true
-
end
-
-
if !n.is_a?(Sass::Tree::CommentNode) &&
-
!n.is_a?(Sass::Tree::CharsetNode) &&
-
!n.is_a?(Sass::Tree::CssImportNode)
-
import_limit = i
-
end
-
-
false
-
end
-
-
if import_limit
-
node.children = node.children[0...import_limit] + imports_to_move +
-
node.children[import_limit..-1]
-
end
-
end
-
-
return node, @extends
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
# A simple struct wrapping up information about a single `@extend` instance. A
-
# single {ExtendNode} can have multiple Extends if either the parent node or
-
# the extended selector is a comma sequence.
-
#
-
# @attr extender [Sass::Selector::Sequence]
-
# The selector of the CSS rule containing the `@extend`.
-
# @attr target [Array<Sass::Selector::Simple>] The selector being `@extend`ed.
-
# @attr node [Sass::Tree::ExtendNode] The node that produced this extend.
-
# @attr directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing the `@extend`.
-
# @attr success [Boolean]
-
# Whether this extend successfully matched a selector.
-
1
Extend = Struct.new(:extender, :target, :node, :directives, :success)
-
-
# Registers an extension in the `@extends` subset map.
-
1
def visit_extend(node)
-
parent.resolved_rules.populate_extends(@extends, node.resolved_selector, node,
-
@parents.select {|p| p.is_a?(Sass::Tree::DirectiveNode)})
-
[]
-
end
-
-
# Modifies exception backtraces to include the imported file.
-
1
def visit_import(node)
-
visit_children_without_parent(node)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.children.first.filename)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Asserts that all the traced children are valid in their new location.
-
1
def visit_trace(node)
-
visit_children_without_parent(node)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:mixin => node.name, :filename => node.filename, :line => node.line)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Converts nested properties into flat properties
-
# and updates the indentation of the prop node based on the nesting level.
-
1
def visit_prop(node)
-
if parent.is_a?(Sass::Tree::PropNode)
-
node.resolved_name = "#{parent.resolved_name}-#{node.resolved_name}"
-
node.tabs = parent.tabs + (parent.resolved_value.empty? ? 0 : 1) if node.style == :nested
-
end
-
-
yield
-
-
result = node.children.dup
-
if !node.resolved_value.empty? || node.children.empty?
-
node.send(:check!)
-
result.unshift(node)
-
end
-
-
result
-
end
-
-
1
def visit_atroot(node)
-
# If there aren't any more directives or rules that this @at-root needs to
-
# exclude, we can get rid of it and just evaluate the children.
-
if @parents.none? {|n| node.exclude_node?(n)}
-
results = visit_children_without_parent(node)
-
results.each {|c| c.tabs += node.tabs if bubblable?(c)}
-
if !results.empty? && bubblable?(results.last)
-
results.last.group_end = node.group_end
-
end
-
return results
-
end
-
-
# If this @at-root excludes the immediate parent, return it as-is so that it
-
# can be bubbled up by the parent node.
-
return Bubble.new(node) if node.exclude_node?(parent)
-
-
# Otherwise, duplicate the current parent and move it into the @at-root
-
# node. As above, returning an @at-root node signals to the parent directive
-
# that it should be bubbled upwards.
-
bubble(node)
-
end
-
-
# The following directives are visible and have children. This means they need
-
# to be able to handle bubbling up nodes such as @at-root and @media.
-
-
# Updates the indentation of the rule node based on the nesting
-
# level. The selectors were resolved in {Perform}.
-
1
def visit_rule(node)
-
yield
-
-
rules = node.children.select {|c| bubblable?(c)}
-
props = node.children.reject {|c| bubblable?(c) || c.invisible?}
-
-
unless props.empty?
-
node.children = props
-
rules.each {|r| r.tabs += 1} if node.style == :nested
-
rules.unshift(node)
-
end
-
-
rules = debubble(rules)
-
unless parent.is_a?(Sass::Tree::RuleNode) || rules.empty? || !bubblable?(rules.last)
-
rules.last.group_end = true
-
end
-
rules
-
end
-
-
1
def visit_keyframerule(node)
-
return node unless node.has_children
-
-
yield
-
-
debubble(node.children, node)
-
end
-
-
# Bubbles a directive up through RuleNodes.
-
1
def visit_directive(node)
-
return node unless node.has_children
-
if parent.is_a?(Sass::Tree::RuleNode)
-
# @keyframes shouldn't include the rule nodes, so we manually create a
-
# bubble that doesn't have the parent's contents for them.
-
return node.normalized_name == '@keyframes' ? Bubble.new(node) : bubble(node)
-
end
-
-
yield
-
-
# Since we don't know if the mere presence of an unknown directive may be
-
# important, we should keep an empty version around even if all the contents
-
# are removed via @at-root. However, if the contents are just bubbled out,
-
# we don't need to do so.
-
directive_exists = node.children.any? do |child|
-
next true unless child.is_a?(Bubble)
-
next false unless child.node.is_a?(Sass::Tree::DirectiveNode)
-
child.node.resolved_value == node.resolved_value
-
end
-
-
# We know empty @keyframes directives do nothing.
-
if directive_exists || node.name == '@keyframes'
-
[]
-
else
-
empty_node = node.dup
-
empty_node.children = []
-
[empty_node]
-
end + debubble(node.children, node)
-
end
-
-
# Bubbles the `@media` directive up through RuleNodes
-
# and merges it with other `@media` directives.
-
1
def visit_media(node)
-
return bubble(node) if parent.is_a?(Sass::Tree::RuleNode)
-
return Bubble.new(node) if parent.is_a?(Sass::Tree::MediaNode)
-
-
yield
-
-
debubble(node.children, node) do |child|
-
next child unless child.is_a?(Sass::Tree::MediaNode)
-
# Copies of `node` can be bubbled, and we don't want to merge it with its
-
# own query.
-
next child if child.resolved_query == node.resolved_query
-
next child if child.resolved_query = child.resolved_query.merge(node.resolved_query)
-
end
-
end
-
-
# Bubbles the `@supports` directive up through RuleNodes.
-
1
def visit_supports(node)
-
return node unless node.has_children
-
return bubble(node) if parent.is_a?(Sass::Tree::RuleNode)
-
-
yield
-
-
debubble(node.children, node)
-
end
-
-
1
private
-
-
# "Bubbles" `node` one level by copying the parent and wrapping `node`'s
-
# children with it.
-
#
-
# @param node [Sass::Tree::Node].
-
# @return [Bubble]
-
1
def bubble(node)
-
new_rule = parent.dup
-
new_rule.children = node.children
-
node.children = [new_rule]
-
Bubble.new(node)
-
end
-
-
# Pops all bubbles in `children` and intersperses the results with the other
-
# values.
-
#
-
# If `parent` is passed, it's copied and used as the parent node for the
-
# nested portions of `children`.
-
#
-
# @param children [List<Sass::Tree::Node, Bubble>]
-
# @param parent [Sass::Tree::Node]
-
# @yield [node] An optional block for processing bubbled nodes. Each bubbled
-
# node will be passed to this block.
-
# @yieldparam node [Sass::Tree::Node] A bubbled node.
-
# @yieldreturn [Sass::Tree::Node?] A node to use in place of the bubbled node.
-
# This can be the node itself, or `nil` to indicate that the node should be
-
# omitted.
-
# @return [List<Sass::Tree::Node, Bubble>]
-
1
def debubble(children, parent = nil)
-
# Keep track of the previous parent so that we don't divide `parent`
-
# unnecessarily if the `@at-root` doesn't produce any new nodes (e.g.
-
# `@at-root {@extend %foo}`).
-
previous_parent = nil
-
-
Sass::Util.slice_by(children) {|c| c.is_a?(Bubble)}.map do |(is_bubble, slice)|
-
unless is_bubble
-
next slice unless parent
-
if previous_parent
-
previous_parent.children.push(*slice)
-
next []
-
else
-
previous_parent = new_parent = parent.dup
-
new_parent.children = slice
-
next new_parent
-
end
-
end
-
-
slice.map do |bubble|
-
next unless (node = block_given? ? yield(bubble.node) : bubble.node)
-
node.tabs += bubble.tabs
-
node.group_end = bubble.group_end
-
results = [visit(node)].flatten
-
previous_parent = nil unless results.empty?
-
results
-
end.compact
-
end.flatten
-
end
-
-
# Returns whether or not a node can be bubbled up through the syntax tree.
-
#
-
# @param node [Sass::Tree::Node]
-
# @return [Boolean]
-
1
def bubblable?(node)
-
node.is_a?(Sass::Tree::RuleNode) || node.bubbles?
-
end
-
-
# A wrapper class for a node that indicates to the parent that it should
-
# treat the wrapped node as a sibling rather than a child.
-
#
-
# Nodes should be wrapped before they're passed to \{Cssize.visit}. They will
-
# be automatically visited upon calling \{#pop}.
-
#
-
# This duck types as a [Sass::Tree::Node] for the purposes of
-
# tree-manipulation operations.
-
1
class Bubble
-
1
attr_accessor :node
-
1
attr_accessor :tabs
-
1
attr_accessor :group_end
-
-
1
def initialize(node)
-
@node = node
-
@tabs = 0
-
end
-
-
1
def bubbles?
-
true
-
end
-
-
1
def inspect
-
"(Bubble #{node.inspect})"
-
end
-
end
-
end
-
# A visitor for performing selector inheritance on a static CSS tree.
-
#
-
# Destructively modifies the tree.
-
1
class Sass::Tree::Visitors::Extend < Sass::Tree::Visitors::Base
-
# Performs the given extensions on the static CSS tree based in `root`, then
-
# validates that all extends matched some selector.
-
#
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this tree.
-
# @return [Object] The return value of \{#visit} for the root node.
-
1
def self.visit(root, extends)
-
return if extends.empty?
-
new(extends).send(:visit, root)
-
check_extends_fired! extends
-
end
-
-
1
protected
-
-
1
def initialize(extends)
-
@parent_directives = []
-
@extends = extends
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
1
def visit(node)
-
super(node)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current parent directives.
-
1
def visit_children(parent)
-
@parent_directives.push parent if parent.is_a?(Sass::Tree::DirectiveNode)
-
super
-
ensure
-
@parent_directives.pop if parent.is_a?(Sass::Tree::DirectiveNode)
-
end
-
-
# Applies the extend to a single rule's selector.
-
1
def visit_rule(node)
-
node.resolved_rules = node.resolved_rules.do_extend(@extends, @parent_directives)
-
end
-
-
1
class << self
-
1
private
-
-
1
def check_extends_fired!(extends)
-
extends.each_value do |ex|
-
next if ex.success || ex.node.optional?
-
message = "\"#{ex.extender}\" failed to @extend \"#{ex.target.join}\"."
-
-
# TODO(nweiz): this should use the Sass stack trace of the extend node.
-
raise Sass::SyntaxError.new(<<MESSAGE, :filename => ex.node.filename, :line => ex.node.line)
-
#{message}
-
The selector "#{ex.target.join}" was not found.
-
Use "@extend #{ex.target.join} !optional" if the extend should be able to fail.
-
MESSAGE
-
end
-
end
-
end
-
end
-
# A visitor for converting a dynamic Sass tree into a static Sass tree.
-
1
class Sass::Tree::Visitors::Perform < Sass::Tree::Visitors::Base
-
1
@@function_name_deprecation = Sass::Deprecation.new
-
-
1
class << self
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @param environment [Sass::Environment] The lexical environment.
-
# @return [Tree::Node] The resulting tree of static nodes.
-
1
def visit(root, environment = nil)
-
new(environment).send(:visit, root)
-
end
-
-
# @api private
-
# @comment
-
# rubocop:disable MethodLength
-
1
def perform_arguments(callable, args, splat, environment)
-
desc = "#{callable.type.capitalize} #{callable.name}"
-
downcase_desc = "#{callable.type} #{callable.name}"
-
-
# All keywords are contained in splat.keywords for consistency,
-
# even if there were no splats passed in.
-
old_keywords_accessed = splat.keywords_accessed
-
keywords = splat.keywords
-
splat.keywords_accessed = old_keywords_accessed
-
-
begin
-
unless keywords.empty?
-
unknown_args = Sass::Util.array_minus(keywords.keys,
-
callable.args.map {|var| var.first.underscored_name})
-
if callable.splat && unknown_args.include?(callable.splat.underscored_name)
-
raise Sass::SyntaxError.new("Argument $#{callable.splat.name} of #{downcase_desc} " +
-
"cannot be used as a named argument.")
-
elsif unknown_args.any?
-
description = unknown_args.length > 1 ? 'the following arguments:' : 'an argument named'
-
raise Sass::SyntaxError.new("#{desc} doesn't have #{description} " +
-
"#{unknown_args.map {|name| "$#{name}"}.join ', '}.")
-
end
-
end
-
rescue Sass::SyntaxError => keyword_exception
-
end
-
-
# If there's no splat, raise the keyword exception immediately. The actual
-
# raising happens in the ensure clause at the end of this function.
-
return if keyword_exception && !callable.splat
-
-
splat_sep = :comma
-
if splat
-
args += splat.to_a
-
splat_sep = splat.separator
-
end
-
-
if args.size > callable.args.size && !callable.splat
-
extra_args_because_of_splat = splat && args.size - splat.to_a.size <= callable.args.size
-
-
takes = callable.args.size
-
passed = args.size
-
message = "#{desc} takes #{takes} argument#{'s' unless takes == 1} " +
-
"but #{passed} #{passed == 1 ? 'was' : 'were'} passed."
-
raise Sass::SyntaxError.new(message) unless extra_args_because_of_splat
-
# TODO: when the deprecation period is over, make this an error.
-
Sass::Util.sass_warn("WARNING: #{message}\n" +
-
environment.stack.to_s.gsub(/^/m, " " * 8) + "\n" +
-
"This will be an error in future versions of Sass.")
-
end
-
-
env = Sass::Environment.new(callable.environment)
-
callable.args.zip(args[0...callable.args.length]) do |(var, default), value|
-
if value && keywords.has_key?(var.name)
-
raise Sass::SyntaxError.new("#{desc} was passed argument $#{var.name} " +
-
"both by position and by name.")
-
end
-
-
value ||= keywords.delete(var.name)
-
value ||= default && default.perform(env)
-
raise Sass::SyntaxError.new("#{desc} is missing argument #{var.inspect}.") unless value
-
env.set_local_var(var.name, value)
-
end
-
-
if callable.splat
-
rest = args[callable.args.length..-1] || []
-
arg_list = Sass::Script::Value::ArgList.new(rest, keywords, splat_sep)
-
arg_list.options = env.options
-
env.set_local_var(callable.splat.name, arg_list)
-
end
-
-
yield env
-
rescue StandardError => e
-
ensure
-
# If there's a keyword exception, we don't want to throw it immediately,
-
# because the invalid keywords may be part of a glob argument that should be
-
# passed on to another function. So we only raise it if we reach the end of
-
# this function *and* the keywords attached to the argument list glob object
-
# haven't been accessed.
-
#
-
# The keyword exception takes precedence over any Sass errors, but not over
-
# non-Sass exceptions.
-
if keyword_exception &&
-
!(arg_list && arg_list.keywords_accessed) &&
-
(e.nil? || e.is_a?(Sass::SyntaxError))
-
raise keyword_exception
-
elsif e
-
raise e
-
end
-
end
-
-
# @api private
-
# @return [Sass::Script::Value::ArgList]
-
1
def perform_splat(splat, performed_keywords, kwarg_splat, environment)
-
args, kwargs, separator = [], nil, :comma
-
-
if splat
-
splat = splat.perform(environment)
-
separator = splat.separator || separator
-
if splat.is_a?(Sass::Script::Value::ArgList)
-
args = splat.to_a
-
kwargs = splat.keywords
-
elsif splat.is_a?(Sass::Script::Value::Map)
-
kwargs = arg_hash(splat)
-
else
-
args = splat.to_a
-
end
-
end
-
kwargs ||= Sass::Util::NormalizedMap.new
-
kwargs.update(performed_keywords)
-
-
if kwarg_splat
-
kwarg_splat = kwarg_splat.perform(environment)
-
unless kwarg_splat.is_a?(Sass::Script::Value::Map)
-
raise Sass::SyntaxError.new("Variable keyword arguments must be a map " +
-
"(was #{kwarg_splat.inspect}).")
-
end
-
kwargs.update(arg_hash(kwarg_splat))
-
end
-
-
Sass::Script::Value::ArgList.new(args, kwargs, separator)
-
end
-
-
1
private
-
-
1
def arg_hash(map)
-
Sass::Util.map_keys(map.to_h) do |key|
-
next key.value if key.is_a?(Sass::Script::Value::String)
-
raise Sass::SyntaxError.new("Variable keyword argument map must have string keys.\n" +
-
"#{key.inspect} is not a string in #{map.inspect}.")
-
end
-
end
-
end
-
# @comment
-
# rubocop:enable MethodLength
-
-
1
protected
-
-
1
def initialize(env)
-
@environment = env
-
@in_keyframes = false
-
@at_root_without_rule = false
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
1
def visit(node)
-
return super(node.dup) unless @environment
-
@environment.stack.with_base(node.filename, node.line) {super(node.dup)}
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current environment.
-
1
def visit_children(parent)
-
with_environment Sass::Environment.new(@environment, parent.options) do
-
parent.children = super.flatten
-
parent
-
end
-
end
-
-
# Runs a block of code with the current environment replaced with the given one.
-
#
-
# @param env [Sass::Environment] The new environment for the duration of the block.
-
# @yield A block in which the environment is set to `env`.
-
# @return [Object] The return value of the block.
-
1
def with_environment(env)
-
old_env, @environment = @environment, env
-
yield
-
ensure
-
@environment = old_env
-
end
-
-
# Sets the options on the environment if this is the top-level root.
-
1
def visit_root(node)
-
yield
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
# Removes this node from the tree if it's a silent comment.
-
1
def visit_comment(node)
-
return [] if node.invisible?
-
node.resolved_value = run_interp_no_strip(node.value)
-
node.resolved_value.gsub!(/\\([\\#])/, '\1')
-
node
-
end
-
-
# Prints the expression to STDERR.
-
1
def visit_debug(node)
-
res = node.expr.perform(@environment)
-
if res.is_a?(Sass::Script::Value::String)
-
res = res.value
-
else
-
res = res.to_sass
-
end
-
if node.filename
-
Sass::Util.sass_warn "#{node.filename}:#{node.line} DEBUG: #{res}"
-
else
-
Sass::Util.sass_warn "Line #{node.line} DEBUG: #{res}"
-
end
-
[]
-
end
-
-
# Throws the expression as an error.
-
1
def visit_error(node)
-
res = node.expr.perform(@environment)
-
if res.is_a?(Sass::Script::Value::String)
-
res = res.value
-
else
-
res = res.to_sass
-
end
-
raise Sass::SyntaxError.new(res)
-
end
-
-
# Runs the child nodes once for each value in the list.
-
1
def visit_each(node)
-
list = node.list.perform(@environment)
-
-
with_environment Sass::SemiGlobalEnvironment.new(@environment) do
-
list.to_a.map do |value|
-
if node.vars.length == 1
-
@environment.set_local_var(node.vars.first, value)
-
else
-
node.vars.zip(value.to_a) do |(var, sub_value)|
-
@environment.set_local_var(var, sub_value || Sass::Script::Value::Null.new)
-
end
-
end
-
node.children.map {|c| visit(c)}
-
end.flatten
-
end
-
end
-
-
# Runs SassScript interpolation in the selector,
-
# and then parses the result into a {Sass::Selector::CommaSequence}.
-
1
def visit_extend(node)
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.selector),
-
node.filename, node.options[:importer], node.line)
-
node.resolved_selector = parser.parse_selector
-
node
-
end
-
-
# Runs the child nodes once for each time through the loop, varying the variable each time.
-
1
def visit_for(node)
-
from = node.from.perform(@environment)
-
to = node.to.perform(@environment)
-
from.assert_int!
-
to.assert_int!
-
-
to = to.coerce(from.numerator_units, from.denominator_units)
-
direction = from.to_i > to.to_i ? -1 : 1
-
range = Range.new(direction * from.to_i, direction * to.to_i, node.exclusive)
-
-
with_environment Sass::SemiGlobalEnvironment.new(@environment) do
-
range.map do |i|
-
@environment.set_local_var(node.var,
-
Sass::Script::Value::Number.new(direction * i,
-
from.numerator_units, from.denominator_units))
-
node.children.map {|c| visit(c)}
-
end.flatten
-
end
-
end
-
-
# Loads the function into the environment.
-
1
def visit_function(node)
-
env = Sass::Environment.new(@environment, node.options)
-
-
if node.normalized_name == 'calc' || node.normalized_name == 'element' ||
-
node.name == 'expression' || node.name == 'url'
-
@@function_name_deprecation.warn(node.filename, node.line, <<WARNING)
-
Naming a function "#{node.name}" is disallowed and will be an error in future versions of Sass.
-
This name conflicts with an existing CSS function with special parse rules.
-
WARNING
-
end
-
-
@environment.set_local_function(node.name,
-
Sass::Callable.new(node.name, node.args, node.splat, env,
-
node.children, false, "function", :stylesheet))
-
[]
-
end
-
-
# Runs the child nodes if the conditional expression is true;
-
# otherwise, tries the else nodes.
-
1
def visit_if(node)
-
if node.expr.nil? || node.expr.perform(@environment).to_bool
-
with_environment Sass::SemiGlobalEnvironment.new(@environment) do
-
node.children.map {|c| visit(c)}
-
end.flatten
-
elsif node.else
-
visit(node.else)
-
else
-
[]
-
end
-
end
-
-
# Returns a static DirectiveNode if this is importing a CSS file,
-
# or parses and includes the imported Sass file.
-
1
def visit_import(node)
-
if (path = node.css_import?)
-
resolved_node = Sass::Tree::CssImportNode.resolved("url(#{path})")
-
resolved_node.options = node.options
-
resolved_node.source_range = node.source_range
-
return resolved_node
-
end
-
file = node.imported_file
-
if @environment.stack.frames.any? {|f| f.is_import? && f.filename == file.options[:filename]}
-
handle_import_loop!(node)
-
end
-
-
begin
-
@environment.stack.with_import(node.filename, node.line) do
-
root = file.to_tree
-
Sass::Tree::Visitors::CheckNesting.visit(root)
-
node.children = root.children.map {|c| visit(c)}.flatten
-
node
-
end
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.imported_file.options[:filename])
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
end
-
-
# Loads a mixin into the environment.
-
1
def visit_mixindef(node)
-
env = Sass::Environment.new(@environment, node.options)
-
@environment.set_local_mixin(node.name,
-
Sass::Callable.new(node.name, node.args, node.splat, env,
-
node.children, node.has_content, "mixin", :stylesheet))
-
[]
-
end
-
-
# Runs a mixin.
-
1
def visit_mixin(node)
-
@environment.stack.with_mixin(node.filename, node.line, node.name) do
-
mixin = @environment.mixin(node.name)
-
raise Sass::SyntaxError.new("Undefined mixin '#{node.name}'.") unless mixin
-
-
if node.children.any? && !mixin.has_content
-
raise Sass::SyntaxError.new(%(Mixin "#{node.name}" does not accept a content block.))
-
end
-
-
args = node.args.map {|a| a.perform(@environment)}
-
keywords = Sass::Util.map_vals(node.keywords) {|v| v.perform(@environment)}
-
splat = self.class.perform_splat(node.splat, keywords, node.kwarg_splat, @environment)
-
-
self.class.perform_arguments(mixin, args, splat, @environment) do |env|
-
env.caller = Sass::Environment.new(@environment)
-
env.content = [node.children, @environment] if node.has_children
-
-
trace_node = Sass::Tree::TraceNode.from_node(node.name, node)
-
with_environment(env) {trace_node.children = mixin.tree.map {|c| visit(c)}.flatten}
-
trace_node
-
end
-
end
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:mixin => node.name, :line => node.line)
-
e.add_backtrace(:line => node.line)
-
raise e
-
end
-
-
1
def visit_content(node)
-
content, content_env = @environment.content
-
return [] unless content
-
@environment.stack.with_mixin(node.filename, node.line, '@content') do
-
trace_node = Sass::Tree::TraceNode.from_node('@content', node)
-
content_env = Sass::Environment.new(content_env)
-
content_env.caller = Sass::Environment.new(@environment)
-
with_environment(content_env) do
-
trace_node.children = content.map {|c| visit(c.dup)}.flatten
-
end
-
trace_node
-
end
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:mixin => '@content', :line => node.line)
-
e.add_backtrace(:line => node.line)
-
raise e
-
end
-
-
# Runs any SassScript that may be embedded in a property.
-
1
def visit_prop(node)
-
node.resolved_name = run_interp(node.name)
-
-
# If the node's value is just a variable or similar, we may get a useful
-
# source range from evaluating it.
-
if node.value.length == 1 && node.value.first.is_a?(Sass::Script::Tree::Node)
-
result = node.value.first.perform(@environment)
-
node.resolved_value = result.to_s
-
node.value_source_range = result.source_range if result.source_range
-
elsif node.custom_property?
-
node.resolved_value = run_interp_no_strip(node.value)
-
else
-
node.resolved_value = run_interp(node.value)
-
end
-
-
yield
-
end
-
-
# Returns the value of the expression.
-
1
def visit_return(node)
-
throw :_sass_return, node.expr.perform(@environment)
-
end
-
-
# Runs SassScript interpolation in the selector,
-
# and then parses the result into a {Sass::Selector::CommaSequence}.
-
1
def visit_rule(node)
-
old_at_root_without_rule = @at_root_without_rule
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.rule),
-
node.filename, node.options[:importer], node.line)
-
if @in_keyframes
-
keyframe_rule_node = Sass::Tree::KeyframeRuleNode.new(parser.parse_keyframes_selector)
-
keyframe_rule_node.options = node.options
-
keyframe_rule_node.line = node.line
-
keyframe_rule_node.filename = node.filename
-
keyframe_rule_node.source_range = node.source_range
-
keyframe_rule_node.has_children = node.has_children
-
with_environment Sass::Environment.new(@environment, node.options) do
-
keyframe_rule_node.children = node.children.map {|c| visit(c)}.flatten
-
end
-
keyframe_rule_node
-
else
-
@at_root_without_rule = false
-
node.parsed_rules ||= parser.parse_selector
-
node.resolved_rules = node.parsed_rules.resolve_parent_refs(
-
@environment.selector, !old_at_root_without_rule)
-
node.stack_trace = @environment.stack.to_s if node.options[:trace_selectors]
-
with_environment Sass::Environment.new(@environment, node.options) do
-
@environment.selector = node.resolved_rules
-
node.children = node.children.map {|c| visit(c)}.flatten
-
end
-
node
-
end
-
ensure
-
@at_root_without_rule = old_at_root_without_rule
-
end
-
-
# Sets a variable that indicates that the first level of rule nodes
-
# shouldn't include the parent selector by default.
-
1
def visit_atroot(node)
-
if node.query
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.query),
-
node.filename, node.options[:importer], node.line)
-
node.resolved_type, node.resolved_value = parser.parse_static_at_root_query
-
else
-
node.resolved_type, node.resolved_value = :without, ['rule']
-
end
-
-
old_at_root_without_rule = @at_root_without_rule
-
old_in_keyframes = @in_keyframes
-
@at_root_without_rule = true if node.exclude?('rule')
-
@in_keyframes = false if node.exclude?('keyframes')
-
yield
-
ensure
-
@in_keyframes = old_in_keyframes
-
@at_root_without_rule = old_at_root_without_rule
-
end
-
-
# Loads the new variable value into the environment.
-
1
def visit_variable(node)
-
env = @environment
-
env = env.global_env if node.global
-
if node.guarded
-
var = env.var(node.name)
-
return [] if var && !var.null?
-
end
-
-
val = node.expr.perform(@environment)
-
if node.expr.source_range
-
val.source_range = node.expr.source_range
-
else
-
val.source_range = node.source_range
-
end
-
env.set_var(node.name, val)
-
[]
-
end
-
-
# Prints the expression to STDERR with a stylesheet trace.
-
1
def visit_warn(node)
-
res = node.expr.perform(@environment)
-
res = res.value if res.is_a?(Sass::Script::Value::String)
-
@environment.stack.with_directive(node.filename, node.line, "@warn") do
-
msg = "WARNING: #{res}\n "
-
msg << @environment.stack.to_s.gsub("\n", "\n ") << "\n"
-
Sass::Util.sass_warn msg
-
end
-
[]
-
end
-
-
# Runs the child nodes until the continuation expression becomes false.
-
1
def visit_while(node)
-
children = []
-
with_environment Sass::SemiGlobalEnvironment.new(@environment) do
-
children += node.children.map {|c| visit(c)} while node.expr.perform(@environment).to_bool
-
end
-
children.flatten
-
end
-
-
1
def visit_directive(node)
-
node.resolved_value = run_interp(node.value)
-
old_in_keyframes, @in_keyframes = @in_keyframes, node.normalized_name == "@keyframes"
-
with_environment Sass::Environment.new(@environment) do
-
node.children = node.children.map {|c| visit(c)}.flatten
-
node
-
end
-
ensure
-
@in_keyframes = old_in_keyframes
-
end
-
-
1
def visit_media(node)
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.query),
-
node.filename, node.options[:importer], node.line)
-
node.resolved_query ||= parser.parse_media_query_list
-
yield
-
end
-
-
1
def visit_supports(node)
-
node.condition = node.condition.deep_copy
-
node.condition.perform(@environment)
-
yield
-
end
-
-
1
def visit_cssimport(node)
-
node.resolved_uri = run_interp([node.uri])
-
if node.query && !node.query.empty?
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.query),
-
node.filename, node.options[:importer], node.line)
-
node.resolved_query ||= parser.parse_media_query_list
-
end
-
if node.supports_condition
-
node.supports_condition.perform(@environment)
-
end
-
yield
-
end
-
-
1
private
-
-
1
def run_interp_no_strip(text)
-
text.map do |r|
-
next r if r.is_a?(String)
-
r.perform(@environment).to_s(:quote => :none)
-
end.join
-
end
-
-
1
def run_interp(text)
-
run_interp_no_strip(text).strip
-
end
-
-
1
def handle_import_loop!(node)
-
msg = "An @import loop has been found:"
-
files = @environment.stack.frames.select {|f| f.is_import?}.map {|f| f.filename}.compact
-
if node.filename == node.imported_file.options[:filename]
-
raise Sass::SyntaxError.new("#{msg} #{node.filename} imports itself")
-
end
-
-
files << node.filename << node.imported_file.options[:filename]
-
msg << "\n" << files.each_cons(2).map do |m1, m2|
-
" #{m1} imports #{m2}"
-
end.join("\n")
-
raise Sass::SyntaxError.new(msg)
-
end
-
end
-
# A visitor for converting a Sass tree into CSS.
-
1
class Sass::Tree::Visitors::ToCss < Sass::Tree::Visitors::Base
-
# The source mapping for the generated CSS file. This is only set if
-
# `build_source_mapping` is passed to the constructor and \{Sass::Engine#render} has been
-
# run.
-
1
attr_reader :source_mapping
-
-
# @param build_source_mapping [Boolean] Whether to build a
-
# \{Sass::Source::Map} while creating the CSS output. The mapping will
-
# be available from \{#source\_mapping} after the visitor has completed.
-
1
def initialize(build_source_mapping = false)
-
@tabs = 0
-
@line = 1
-
@offset = 1
-
@result = String.new("")
-
@source_mapping = build_source_mapping ? Sass::Source::Map.new : nil
-
@lstrip = nil
-
@in_directive = false
-
end
-
-
# Runs the visitor on `node`.
-
#
-
# @param node [Sass::Tree::Node] The root node of the tree to convert to CSS>
-
# @return [String] The CSS output.
-
1
def visit(node)
-
super
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
1
protected
-
-
1
def with_tabs(tabs)
-
old_tabs, @tabs = @tabs, tabs
-
yield
-
ensure
-
@tabs = old_tabs
-
end
-
-
# Associate all output produced in a block with a given node. Used for source
-
# mapping.
-
1
def for_node(node, attr_prefix = nil)
-
return yield unless @source_mapping
-
start_pos = Sass::Source::Position.new(@line, @offset)
-
yield
-
-
range_attr = attr_prefix ? :"#{attr_prefix}_source_range" : :source_range
-
return if node.invisible? || !node.send(range_attr)
-
source_range = node.send(range_attr)
-
target_end_pos = Sass::Source::Position.new(@line, @offset)
-
target_range = Sass::Source::Range.new(start_pos, target_end_pos, nil)
-
@source_mapping.add(source_range, target_range)
-
end
-
-
1
def trailing_semicolon?
-
@result.end_with?(";") && !@result.end_with?('\;')
-
end
-
-
# Move the output cursor back `chars` characters.
-
1
def erase!(chars)
-
return if chars == 0
-
str = @result.slice!(-chars..-1)
-
newlines = str.count("\n")
-
if newlines > 0
-
@line -= newlines
-
@offset = @result[@result.rindex("\n") || 0..-1].size
-
else
-
@offset -= chars
-
end
-
end
-
-
# Avoid allocating lots of new strings for `#output`. This is important
-
# because `#output` is called all the time.
-
1
NEWLINE = "\n"
-
-
# Add `s` to the output string and update the line and offset information
-
# accordingly.
-
1
def output(s)
-
if @lstrip
-
s = s.gsub(/\A\s+/, "")
-
@lstrip = false
-
end
-
-
newlines = s.count(NEWLINE)
-
if newlines > 0
-
@line += newlines
-
@offset = s[s.rindex(NEWLINE)..-1].size
-
else
-
@offset += s.size
-
end
-
-
@result << s
-
end
-
-
# Strip all trailing whitespace from the output string.
-
1
def rstrip!
-
erase! @result.length - 1 - (@result.rindex(/[^\s]/) || -1)
-
end
-
-
# lstrip the first output in the given block.
-
1
def lstrip
-
old_lstrip = @lstrip
-
@lstrip = true
-
yield
-
ensure
-
@lstrip &&= old_lstrip
-
end
-
-
# Prepend `prefix` to the output string.
-
1
def prepend!(prefix)
-
@result.insert 0, prefix
-
return unless @source_mapping
-
-
line_delta = prefix.count("\n")
-
offset_delta = prefix.gsub(/.*\n/, '').size
-
@source_mapping.shift_output_offsets(offset_delta)
-
@source_mapping.shift_output_lines(line_delta)
-
end
-
-
1
def visit_root(node)
-
node.children.each do |child|
-
next if child.invisible?
-
visit(child)
-
next if node.style == :compressed
-
output "\n"
-
next unless child.is_a?(Sass::Tree::DirectiveNode) && child.has_children && !child.bubbles?
-
output "\n"
-
end
-
rstrip!
-
if node.style == :compressed && trailing_semicolon?
-
erase! 1
-
end
-
return "" if @result.empty?
-
-
output "\n"
-
-
unless @result.ascii_only?
-
if node.style == :compressed
-
# A byte order mark is sufficient to tell browsers that this
-
# file is UTF-8 encoded, and will override any other detection
-
# methods as per http://encoding.spec.whatwg.org/#decode-and-encode.
-
prepend! "\uFEFF"
-
else
-
prepend! "@charset \"UTF-8\";\n"
-
end
-
end
-
-
@result
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
1
def visit_charset(node)
-
for_node(node) {output("@charset \"#{node.name}\";")}
-
end
-
-
1
def visit_comment(node)
-
return if node.invisible?
-
spaces = (' ' * [@tabs - node.resolved_value[/^ */].size, 0].max)
-
output(spaces)
-
-
content = node.resolved_value.split("\n").join("\n" + spaces)
-
if node.type == :silent
-
content.gsub!(%r{^(\s*)//(.*)$}) {"#{$1}/*#{$2} */"}
-
end
-
if (node.style == :compact || node.style == :compressed) && node.type != :loud
-
content.gsub!(%r{\n +(\* *(?!/))?}, ' ')
-
end
-
for_node(node) {output(content)}
-
end
-
-
# @comment
-
# rubocop:disable MethodLength
-
1
def visit_directive(node)
-
was_in_directive = @in_directive
-
tab_str = ' ' * @tabs
-
if !node.has_children || node.children.empty?
-
output(tab_str)
-
for_node(node) {output(node.resolved_value)}
-
if node.has_children
-
output("#{' ' unless node.style == :compressed}{}")
-
elsif node.children.empty?
-
output(";")
-
end
-
return
-
end
-
-
@in_directive ||= !node.is_a?(Sass::Tree::MediaNode)
-
output(tab_str) if node.style != :compressed
-
for_node(node) {output(node.resolved_value)}
-
output(node.style == :compressed ? "{" : " {")
-
output(node.style == :compact ? ' ' : "\n") if node.style != :compressed
-
-
had_children = true
-
first = true
-
node.children.each do |child|
-
next if child.invisible?
-
if node.style == :compact
-
if child.is_a?(Sass::Tree::PropNode)
-
with_tabs(first || !had_children ? 0 : @tabs + 1) do
-
visit(child)
-
output(' ')
-
end
-
else
-
unless had_children
-
erase! 1
-
output "\n"
-
end
-
-
if first
-
lstrip {with_tabs(@tabs + 1) {visit(child)}}
-
else
-
with_tabs(@tabs + 1) {visit(child)}
-
end
-
-
rstrip!
-
output "\n"
-
end
-
had_children = child.has_children
-
first = false
-
elsif node.style == :compressed
-
unless had_children
-
output(";") unless trailing_semicolon?
-
end
-
with_tabs(0) {visit(child)}
-
had_children = child.has_children
-
else
-
with_tabs(@tabs + 1) {visit(child)}
-
output "\n"
-
end
-
end
-
rstrip!
-
if node.style == :compressed && trailing_semicolon?
-
erase! 1
-
end
-
if node.style == :expanded
-
output("\n#{tab_str}")
-
elsif node.style != :compressed
-
output(" ")
-
end
-
output("}")
-
ensure
-
@in_directive = was_in_directive
-
end
-
# @comment
-
# rubocop:enable MethodLength
-
-
1
def visit_media(node)
-
with_tabs(@tabs + node.tabs) {visit_directive(node)}
-
output("\n") if node.style != :compressed && node.group_end
-
end
-
-
1
def visit_supports(node)
-
visit_media(node)
-
end
-
-
1
def visit_cssimport(node)
-
visit_directive(node)
-
end
-
-
1
def visit_prop(node)
-
return if node.resolved_value.empty? && !node.custom_property?
-
tab_str = ' ' * (@tabs + node.tabs)
-
output(tab_str)
-
for_node(node, :name) {output(node.resolved_name)}
-
output(":")
-
output(" ") unless node.style == :compressed || node.custom_property?
-
for_node(node, :value) do
-
output(if node.custom_property?
-
format_custom_property_value(node)
-
else
-
node.resolved_value
-
end)
-
end
-
output(";") unless node.style == :compressed
-
end
-
-
# @comment
-
# rubocop:disable MethodLength
-
1
def visit_rule(node)
-
with_tabs(@tabs + node.tabs) do
-
rule_separator = node.style == :compressed ? ',' : ', '
-
line_separator =
-
case node.style
-
when :nested, :expanded; "\n"
-
when :compressed; ""
-
else; " "
-
end
-
rule_indent = ' ' * @tabs
-
per_rule_indent, total_indent = if [:nested, :expanded].include?(node.style)
-
[rule_indent, '']
-
else
-
['', rule_indent]
-
end
-
-
joined_rules = node.resolved_rules.members.map do |seq|
-
next if seq.invisible?
-
rule_part = seq.to_s(style: node.style, placeholder: false)
-
if node.style == :compressed
-
rule_part.gsub!(/([^,])\s*\n\s*/m, '\1 ')
-
rule_part.gsub!(/\s*([+>])\s*/m, '\1')
-
rule_part.gsub!(/nth([^( ]*)\(([^)]*)\)/m) do |match|
-
match.tr(" \t\n", "")
-
end
-
rule_part.strip!
-
end
-
rule_part
-
end.compact.join(rule_separator)
-
-
joined_rules.lstrip!
-
joined_rules.gsub!(/\s*\n\s*/, "#{line_separator}#{per_rule_indent}")
-
-
old_spaces = ' ' * @tabs
-
if node.style != :compressed
-
if node.options[:debug_info] && !@in_directive
-
visit(debug_info_rule(node.debug_info, node.options))
-
output "\n"
-
elsif node.options[:trace_selectors]
-
output("#{old_spaces}/* ")
-
output(node.stack_trace.gsub("\n", "\n #{old_spaces}"))
-
output(" */\n")
-
elsif node.options[:line_comments]
-
output("#{old_spaces}/* line #{node.line}")
-
-
if node.filename
-
relative_filename =
-
if node.options[:css_filename]
-
begin
-
Sass::Util.relative_path_from(
-
node.filename, File.dirname(node.options[:css_filename])).to_s
-
rescue ArgumentError
-
nil
-
end
-
end
-
relative_filename ||= node.filename
-
output(", #{relative_filename}")
-
end
-
-
output(" */\n")
-
end
-
end
-
-
end_props, trailer, tabs = '', '', 0
-
if node.style == :compact
-
separator, end_props, bracket = ' ', ' ', ' { '
-
trailer = "\n" if node.group_end
-
elsif node.style == :compressed
-
separator, bracket = ';', '{'
-
else
-
tabs = @tabs + 1
-
separator, bracket = "\n", " {\n"
-
trailer = "\n" if node.group_end
-
end_props = (node.style == :expanded ? "\n" + old_spaces : ' ')
-
end
-
output(total_indent + per_rule_indent)
-
for_node(node, :selector) {output(joined_rules)}
-
output(bracket)
-
-
with_tabs(tabs) do
-
node.children.each_with_index do |child, i|
-
if i > 0
-
if separator.start_with?(";") && trailing_semicolon?
-
erase! 1
-
end
-
output(separator)
-
end
-
visit(child)
-
end
-
end
-
if node.style == :compressed && trailing_semicolon?
-
erase! 1
-
end
-
-
output(end_props)
-
output("}" + trailer)
-
end
-
end
-
# @comment
-
# rubocop:enable MethodLength
-
-
1
def visit_keyframerule(node)
-
visit_directive(node)
-
end
-
-
1
private
-
-
# Reformats the value of `node` so that it's nicely indented, preserving its
-
# existing relative indentation.
-
#
-
# @param node [Sass::Script::Tree::PropNode] A custom property node.
-
# @return [String]
-
1
def format_custom_property_value(node)
-
if node.style == :compact || node.style == :compressed || !node.resolved_value.include?("\n")
-
# Folding not involving newlines was done in the parser. We can safely
-
# fold newlines here because tokens like strings can't contain literal
-
# newlines, so we know any adjacent whitespace is tokenized as whitespace.
-
return node.resolved_value.gsub(/[ \t\r\f]*\n[ \t\r\f\n]*/, ' ')
-
end
-
-
# Find the smallest amount of indentation in the custom property and use
-
# that as the base indentation level.
-
lines = node.resolved_value.split("\n")
-
indented_lines = lines[1..-1]
-
min_indentation = indented_lines.
-
map {|line| line[/^[ \t]*/]}.
-
reject {|line| line.empty?}.
-
min_by {|line| line.length}
-
-
# Limit the base indentation to the same indentation level as the node name
-
# so that if *every* line is indented relative to the property name that's
-
# preserved.
-
if node.name_source_range
-
base_indentation = min_indentation[0...node.name_source_range.start_pos.offset - 1]
-
end
-
-
lines.first + "\n" + indented_lines.join("\n").gsub(/^#{base_indentation}/, ' ' * @tabs)
-
end
-
-
1
def debug_info_rule(debug_info, options)
-
node = Sass::Tree::DirectiveNode.resolved("@media -sass-debug-info")
-
debug_info.map {|k, v| [k.to_s, v.to_s]}.to_a.each do |k, v|
-
rule = Sass::Tree::RuleNode.new([""])
-
rule.resolved_rules = Sass::Selector::CommaSequence.new(
-
[Sass::Selector::Sequence.new(
-
[Sass::Selector::SimpleSequence.new(
-
[Sass::Selector::Element.new(k.to_s.gsub(/[^\w-]/, "\\\\\\0"), nil)],
-
false)
-
])
-
])
-
prop = Sass::Tree::PropNode.new([""], [""], :new)
-
prop.resolved_name = "font-family"
-
prop.resolved_value = Sass::SCSS::RX.escape_ident(v.to_s)
-
rule << prop
-
node << rule
-
end
-
node.options = options.merge(:debug_info => false,
-
:line_comments => false,
-
:style => :compressed)
-
node
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a Sass `@warn` statement.
-
#
-
# @see Sass::Tree
-
1
class WarnNode < Node
-
# The expression to print.
-
# @return [Script::Tree::Node]
-
1
attr_accessor :expr
-
-
# @param expr [Script::Tree::Node] The expression to print
-
1
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A dynamic node representing a Sass `@while` loop.
-
#
-
# @see Sass::Tree
-
1
class WhileNode < Node
-
# The parse tree for the continuation expression.
-
# @return [Script::Tree::Node]
-
1
attr_accessor :expr
-
-
# @param expr [Script::Tree::Node] See \{#expr}
-
1
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
1
require 'erb'
-
1
require 'set'
-
1
require 'enumerator'
-
1
require 'stringio'
-
1
require 'rbconfig'
-
1
require 'uri'
-
1
require 'thread'
-
1
require 'pathname'
-
-
1
require 'sass/root'
-
1
require 'sass/util/subset_map'
-
-
1
module Sass
-
# A module containing various useful functions.
-
# @comment
-
# rubocop:disable ModuleLength
-
1
module Util
-
1
extend self
-
-
# An array of ints representing the Ruby version number.
-
# @api public
-
4
RUBY_VERSION_COMPONENTS = RUBY_VERSION.split(".").map {|s| s.to_i}
-
-
# The Ruby engine we're running under. Defaults to `"ruby"`
-
# if the top-level constant is undefined.
-
# @api public
-
1
RUBY_ENGINE = defined?(::RUBY_ENGINE) ? ::RUBY_ENGINE : "ruby"
-
-
# Returns the path of a file relative to the Sass root directory.
-
#
-
# @param file [String] The filename relative to the Sass root
-
# @return [String] The filename relative to the the working directory
-
1
def scope(file)
-
7
File.join(Sass::ROOT_DIR, file)
-
end
-
-
# Maps the keys in a hash according to a block.
-
#
-
# @example
-
# map_keys({:foo => "bar", :baz => "bang"}) {|k| k.to_s}
-
# #=> {"foo" => "bar", "baz" => "bang"}
-
# @param hash [Hash] The hash to map
-
# @yield [key] A block in which the keys are transformed
-
# @yieldparam key [Object] The key that should be mapped
-
# @yieldreturn [Object] The new value for the key
-
# @return [Hash] The mapped hash
-
# @see #map_vals
-
# @see #map_hash
-
1
def map_keys(hash)
-
map_hash(hash) {|k, v| [yield(k), v]}
-
end
-
-
# Maps the values in a hash according to a block.
-
#
-
# @example
-
# map_values({:foo => "bar", :baz => "bang"}) {|v| v.to_sym}
-
# #=> {:foo => :bar, :baz => :bang}
-
# @param hash [Hash] The hash to map
-
# @yield [value] A block in which the values are transformed
-
# @yieldparam value [Object] The value that should be mapped
-
# @yieldreturn [Object] The new value for the value
-
# @return [Hash] The mapped hash
-
# @see #map_keys
-
# @see #map_hash
-
1
def map_vals(hash)
-
# We don't delegate to map_hash for performance here
-
# because map_hash does more than is necessary.
-
2
rv = hash.class.new
-
2
hash = hash.as_stored if hash.is_a?(NormalizedMap)
-
2
hash.each do |k, v|
-
149
rv[k] = yield(v)
-
end
-
2
rv
-
end
-
-
# Maps the key-value pairs of a hash according to a block.
-
#
-
# @example
-
# map_hash({:foo => "bar", :baz => "bang"}) {|k, v| [k.to_s, v.to_sym]}
-
# #=> {"foo" => :bar, "baz" => :bang}
-
# @param hash [Hash] The hash to map
-
# @yield [key, value] A block in which the key-value pairs are transformed
-
# @yieldparam [key] The hash key
-
# @yieldparam [value] The hash value
-
# @yieldreturn [(Object, Object)] The new value for the `[key, value]` pair
-
# @return [Hash] The mapped hash
-
# @see #map_keys
-
# @see #map_vals
-
1
def map_hash(hash)
-
# Copy and modify is more performant than mapping to an array and using
-
# to_hash on the result.
-
2
rv = hash.class.new
-
2
hash.each do |k, v|
-
52
new_key, new_value = yield(k, v)
-
52
new_key = hash.denormalize(new_key) if hash.is_a?(NormalizedMap) && new_key == k
-
52
rv[new_key] = new_value
-
end
-
2
rv
-
end
-
-
# Computes the powerset of the given array.
-
# This is the set of all subsets of the array.
-
#
-
# @example
-
# powerset([1, 2, 3]) #=>
-
# Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[1, 3], Set[1, 2, 3]]
-
# @param arr [Enumerable]
-
# @return [Set<Set>] The subsets of `arr`
-
1
def powerset(arr)
-
arr.inject([Set.new].to_set) do |powerset, el|
-
new_powerset = Set.new
-
powerset.each do |subset|
-
new_powerset << subset
-
new_powerset << subset + [el]
-
end
-
new_powerset
-
end
-
end
-
-
# Restricts a number to falling within a given range.
-
# Returns the number if it falls within the range,
-
# or the closest value in the range if it doesn't.
-
#
-
# @param value [Numeric]
-
# @param range [Range<Numeric>]
-
# @return [Numeric]
-
1
def restrict(value, range)
-
[[value, range.first].max, range.last].min
-
end
-
-
# Like [Fixnum.round], but leaves rooms for slight floating-point
-
# differences.
-
#
-
# @param value [Numeric]
-
# @return [Numeric]
-
1
def round(value)
-
# If the number is within epsilon of X.5, round up (or down for negative
-
# numbers).
-
return value.round if (value % 1) - 0.5 <= -1 * Script::Value::Number.epsilon
-
value > 0 ? value.ceil : value.floor
-
end
-
-
# Concatenates all strings that are adjacent in an array,
-
# while leaving other elements as they are.
-
#
-
# @example
-
# merge_adjacent_strings([1, "foo", "bar", 2, "baz"])
-
# #=> [1, "foobar", 2, "baz"]
-
# @param arr [Array]
-
# @return [Array] The enumerable with strings merged
-
1
def merge_adjacent_strings(arr)
-
# Optimize for the common case of one element
-
return arr if arr.size < 2
-
arr.inject([]) do |a, e|
-
if e.is_a?(String)
-
if a.last.is_a?(String)
-
a.last << e
-
else
-
a << e.dup
-
end
-
else
-
a << e
-
end
-
a
-
end
-
end
-
-
# Non-destructively replaces all occurrences of a subsequence in an array
-
# with another subsequence.
-
#
-
# @example
-
# replace_subseq([1, 2, 3, 4, 5], [2, 3], [:a, :b])
-
# #=> [1, :a, :b, 4, 5]
-
#
-
# @param arr [Array] The array whose subsequences will be replaced.
-
# @param subseq [Array] The subsequence to find and replace.
-
# @param replacement [Array] The sequence that `subseq` will be replaced with.
-
# @return [Array] `arr` with `subseq` replaced with `replacement`.
-
1
def replace_subseq(arr, subseq, replacement)
-
new = []
-
matched = []
-
i = 0
-
arr.each do |elem|
-
if elem != subseq[i]
-
new.push(*matched)
-
matched = []
-
i = 0
-
new << elem
-
next
-
end
-
-
if i == subseq.length - 1
-
matched = []
-
i = 0
-
new.push(*replacement)
-
else
-
matched << elem
-
i += 1
-
end
-
end
-
new.push(*matched)
-
new
-
end
-
-
# Intersperses a value in an enumerable, as would be done with `Array#join`
-
# but without concatenating the array together afterwards.
-
#
-
# @param enum [Enumerable]
-
# @param val
-
# @return [Array]
-
1
def intersperse(enum, val)
-
enum.inject([]) {|a, e| a << e << val}[0...-1]
-
end
-
-
1
def slice_by(enum)
-
results = []
-
enum.each do |value|
-
key = yield(value)
-
if !results.empty? && results.last.first == key
-
results.last.last << value
-
else
-
results << [key, [value]]
-
end
-
end
-
results
-
end
-
-
# Substitutes a sub-array of one array with another sub-array.
-
#
-
# @param ary [Array] The array in which to make the substitution
-
# @param from [Array] The sequence of elements to replace with `to`
-
# @param to [Array] The sequence of elements to replace `from` with
-
1
def substitute(ary, from, to)
-
res = ary.dup
-
i = 0
-
while i < res.size
-
if res[i...i + from.size] == from
-
res[i...i + from.size] = to
-
end
-
i += 1
-
end
-
res
-
end
-
-
# Destructively strips whitespace from the beginning and end
-
# of the first and last elements, respectively,
-
# in the array (if those elements are strings).
-
#
-
# @param arr [Array]
-
# @return [Array] `arr`
-
1
def strip_string_array(arr)
-
arr.first.lstrip! if arr.first.is_a?(String)
-
arr.last.rstrip! if arr.last.is_a?(String)
-
arr
-
end
-
-
# Return an array of all possible paths through the given arrays.
-
#
-
# @param arrs [Array<Array>]
-
# @return [Array<Arrays>]
-
#
-
# @example
-
# paths([[1, 2], [3, 4], [5]]) #=>
-
# # [[1, 3, 5],
-
# # [2, 3, 5],
-
# # [1, 4, 5],
-
# # [2, 4, 5]]
-
1
def paths(arrs)
-
arrs.inject([[]]) do |paths, arr|
-
arr.map {|e| paths.map {|path| path + [e]}}.flatten(1)
-
end
-
end
-
-
# Computes a single longest common subsequence for `x` and `y`.
-
# If there are more than one longest common subsequences,
-
# the one returned is that which starts first in `x`.
-
#
-
# @param x [Array]
-
# @param y [Array]
-
# @yield [a, b] An optional block to use in place of a check for equality
-
# between elements of `x` and `y`.
-
# @yieldreturn [Object, nil] If the two values register as equal,
-
# this will return the value to use in the LCS array.
-
# @return [Array] The LCS
-
1
def lcs(x, y, &block)
-
x = [nil, *x]
-
y = [nil, *y]
-
block ||= proc {|a, b| a == b && a}
-
lcs_backtrace(lcs_table(x, y, &block), x, y, x.size - 1, y.size - 1, &block)
-
end
-
-
# Like `String.upcase`, but only ever upcases ASCII letters.
-
1
def upcase(string)
-
return string.upcase unless ruby2_4?
-
string.upcase(:ascii)
-
end
-
-
# Like `String.downcase`, but only ever downcases ASCII letters.
-
1
def downcase(string)
-
return string.downcase unless ruby2_4?
-
string.downcase(:ascii)
-
end
-
-
# Returns a sub-array of `minuend` containing only elements that are also in
-
# `subtrahend`. Ensures that the return value has the same order as
-
# `minuend`, even on Rubinius where that's not guaranteed by `Array#-`.
-
#
-
# @param minuend [Array]
-
# @param subtrahend [Array]
-
# @return [Array]
-
1
def array_minus(minuend, subtrahend)
-
return minuend - subtrahend unless rbx?
-
set = Set.new(minuend) - subtrahend
-
minuend.select {|e| set.include?(e)}
-
end
-
-
# Returns the maximum of `val1` and `val2`. We use this over \{Array.max} to
-
# avoid unnecessary garbage collection.
-
1
def max(val1, val2)
-
val1 > val2 ? val1 : val2
-
end
-
-
# Returns the minimum of `val1` and `val2`. We use this over \{Array.min} to
-
# avoid unnecessary garbage collection.
-
1
def min(val1, val2)
-
val1 <= val2 ? val1 : val2
-
end
-
-
# Returns a string description of the character that caused an
-
# `Encoding::UndefinedConversionError`.
-
#
-
# @param e [Encoding::UndefinedConversionError]
-
# @return [String]
-
1
def undefined_conversion_error_char(e)
-
# Rubinius (as of 2.0.0.rc1) pre-quotes the error character.
-
return e.error_char if rbx?
-
# JRuby (as of 1.7.2) doesn't have an error_char field on
-
# Encoding::UndefinedConversionError.
-
return e.error_char.dump unless jruby?
-
e.message[/^"[^"]+"/] # "
-
end
-
-
# Asserts that `value` falls within `range` (inclusive), leaving
-
# room for slight floating-point errors.
-
#
-
# @param name [String] The name of the value. Used in the error message.
-
# @param range [Range] The allowed range of values.
-
# @param value [Numeric, Sass::Script::Value::Number] The value to check.
-
# @param unit [String] The unit of the value. Used in error reporting.
-
# @return [Numeric] `value` adjusted to fall within range, if it
-
# was outside by a floating-point margin.
-
1
def check_range(name, range, value, unit = '')
-
grace = (-0.00001..0.00001)
-
str = value.to_s
-
value = value.value if value.is_a?(Sass::Script::Value::Number)
-
return value if range.include?(value)
-
return range.first if grace.include?(value - range.first)
-
return range.last if grace.include?(value - range.last)
-
raise ArgumentError.new(
-
"#{name} #{str} must be between #{range.first}#{unit} and #{range.last}#{unit}")
-
end
-
-
# Returns whether or not `seq1` is a subsequence of `seq2`. That is, whether
-
# or not `seq2` contains every element in `seq1` in the same order (and
-
# possibly more elements besides).
-
#
-
# @param seq1 [Array]
-
# @param seq2 [Array]
-
# @return [Boolean]
-
1
def subsequence?(seq1, seq2)
-
i = j = 0
-
loop do
-
return true if i == seq1.size
-
return false if j == seq2.size
-
i += 1 if seq1[i] == seq2[j]
-
j += 1
-
end
-
end
-
-
# Returns information about the caller of the previous method.
-
#
-
# @param entry [String] An entry in the `#caller` list, or a similarly formatted string
-
# @return [[String, Integer, (String, nil)]]
-
# An array containing the filename, line, and method name of the caller.
-
# The method name may be nil
-
1
def caller_info(entry = nil)
-
# JRuby evaluates `caller` incorrectly when it's in an actual default argument.
-
entry ||= caller[1]
-
info = entry.scan(/^((?:[A-Za-z]:)?.*?):(-?.*?)(?::.*`(.+)')?$/).first
-
info[1] = info[1].to_i
-
# This is added by Rubinius to designate a block, but we don't care about it.
-
info[2].sub!(/ \{\}\Z/, '') if info[2]
-
info
-
end
-
-
# Returns whether one version string represents a more recent version than another.
-
#
-
# @param v1 [String] A version string.
-
# @param v2 [String] Another version string.
-
# @return [Boolean]
-
1
def version_gt(v1, v2)
-
# Construct an array to make sure the shorter version is padded with nil
-
1
Array.new([v1.length, v2.length].max).zip(v1.split("."), v2.split(".")) do |_, p1, p2|
-
1
p1 ||= "0"
-
1
p2 ||= "0"
-
1
release1 = p1 =~ /^[0-9]+$/
-
1
release2 = p2 =~ /^[0-9]+$/
-
1
if release1 && release2
-
# Integer comparison if both are full releases
-
1
p1, p2 = p1.to_i, p2.to_i
-
1
next if p1 == p2
-
1
return p1 > p2
-
elsif !release1 && !release2
-
# String comparison if both are prereleases
-
next if p1 == p2
-
return p1 > p2
-
else
-
# If only one is a release, that one is newer
-
return release1
-
end
-
end
-
end
-
-
# Returns whether one version string represents the same or a more
-
# recent version than another.
-
#
-
# @param v1 [String] A version string.
-
# @param v2 [String] Another version string.
-
# @return [Boolean]
-
1
def version_geq(v1, v2)
-
1
version_gt(v1, v2) || !version_gt(v2, v1)
-
end
-
-
# Throws a NotImplementedError for an abstract method.
-
#
-
# @param obj [Object] `self`
-
# @raise [NotImplementedError]
-
1
def abstract(obj)
-
raise NotImplementedError.new("#{obj.class} must implement ##{caller_info[2]}")
-
end
-
-
# Prints a deprecation warning for the caller method.
-
#
-
# @param obj [Object] `self`
-
# @param message [String] A message describing what to do instead.
-
1
def deprecated(obj, message = nil)
-
obj_class = obj.is_a?(Class) ? "#{obj}." : "#{obj.class}#"
-
full_message = "DEPRECATION WARNING: #{obj_class}#{caller_info[2]} " +
-
"will be removed in a future version of Sass.#{("\n" + message) if message}"
-
Sass::Util.sass_warn full_message
-
end
-
-
# Silence all output to STDERR within a block.
-
#
-
# @yield A block in which no output will be printed to STDERR
-
1
def silence_warnings
-
the_real_stderr, $stderr = $stderr, StringIO.new
-
yield
-
ensure
-
$stderr = the_real_stderr
-
end
-
-
# Silences all Sass warnings within a block.
-
#
-
# @yield A block in which no Sass warnings will be printed
-
1
def silence_sass_warnings
-
old_level, Sass.logger.log_level = Sass.logger.log_level, :error
-
yield
-
ensure
-
Sass.logger.log_level = old_level
-
end
-
-
# The same as `Kernel#warn`, but is silenced by \{#silence\_sass\_warnings}.
-
#
-
# @param msg [String]
-
1
def sass_warn(msg)
-
Sass.logger.warn("#{msg}\n")
-
end
-
-
## Cross Rails Version Compatibility
-
-
# Returns the root of the Rails application,
-
# if this is running in a Rails context.
-
# Returns `nil` if no such root is defined.
-
#
-
# @return [String, nil]
-
1
def rails_root
-
if defined?(::Rails.root)
-
return ::Rails.root.to_s if ::Rails.root
-
raise "ERROR: Rails.root is nil!"
-
end
-
return RAILS_ROOT.to_s if defined?(RAILS_ROOT)
-
nil
-
end
-
-
# Returns the environment of the Rails application,
-
# if this is running in a Rails context.
-
# Returns `nil` if no such environment is defined.
-
#
-
# @return [String, nil]
-
1
def rails_env
-
return ::Rails.env.to_s if defined?(::Rails.env)
-
return RAILS_ENV.to_s if defined?(RAILS_ENV)
-
nil
-
end
-
-
# Returns whether this environment is using ActionPack
-
# version 3.0.0 or greater.
-
#
-
# @return [Boolean]
-
1
def ap_geq_3?
-
ap_geq?("3.0.0.beta1")
-
end
-
-
# Returns whether this environment is using ActionPack
-
# of a version greater than or equal to that specified.
-
#
-
# @param version [String] The string version number to check against.
-
# Should be greater than or equal to Rails 3,
-
# because otherwise ActionPack::VERSION isn't autoloaded
-
# @return [Boolean]
-
1
def ap_geq?(version)
-
# The ActionPack module is always loaded automatically in Rails >= 3
-
1
return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) &&
-
defined?(ActionPack::VERSION::STRING)
-
-
1
version_geq(ActionPack::VERSION::STRING, version)
-
end
-
-
# Returns an ActionView::Template* class.
-
# In pre-3.0 versions of Rails, most of these classes
-
# were of the form `ActionView::TemplateFoo`,
-
# while afterwards they were of the form `ActionView;:Template::Foo`.
-
#
-
# @param name [#to_s] The name of the class to get.
-
# For example, `:Error` will return `ActionView::TemplateError`
-
# or `ActionView::Template::Error`.
-
1
def av_template_class(name)
-
return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}")
-
ActionView::Template.const_get(name.to_s)
-
end
-
-
## Cross-OS Compatibility
-
#
-
# These methods are cached because some of them are called quite frequently
-
# and even basic checks like String#== are too costly to be called repeatedly.
-
-
# Whether or not this is running on Windows.
-
#
-
# @return [Boolean]
-
1
def windows?
-
return @windows if defined?(@windows)
-
@windows = (RbConfig::CONFIG['host_os'] =~ /mswin|windows|mingw/i)
-
end
-
-
# Whether or not this is running on IronRuby.
-
#
-
# @return [Boolean]
-
1
def ironruby?
-
return @ironruby if defined?(@ironruby)
-
@ironruby = RUBY_ENGINE == "ironruby"
-
end
-
-
# Whether or not this is running on Rubinius.
-
#
-
# @return [Boolean]
-
1
def rbx?
-
1
return @rbx if defined?(@rbx)
-
1
@rbx = RUBY_ENGINE == "rbx"
-
end
-
-
# Whether or not this is running on JRuby.
-
#
-
# @return [Boolean]
-
1
def jruby?
-
return @jruby if defined?(@jruby)
-
@jruby = RUBY_PLATFORM =~ /java/
-
end
-
-
# Returns an array of ints representing the JRuby version number.
-
#
-
# @return [Array<Integer>]
-
1
def jruby_version
-
@jruby_version ||= ::JRUBY_VERSION.split(".").map {|s| s.to_i}
-
end
-
-
# Like `Dir.glob`, but works with backslash-separated paths on Windows.
-
#
-
# @param path [String]
-
1
def glob(path)
-
path = path.tr('\\', '/') if windows?
-
if block_given?
-
Dir.glob(path) {|f| yield(f)}
-
else
-
Dir.glob(path)
-
end
-
end
-
-
# Like `Pathname.new`, but normalizes Windows paths to always use backslash
-
# separators.
-
#
-
# `Pathname#relative_path_from` can break if the two pathnames aren't
-
# consistent in their slash style.
-
#
-
# @param path [String]
-
# @return [Pathname]
-
1
def pathname(path)
-
path = path.tr("/", "\\") if windows?
-
Pathname.new(path)
-
end
-
-
# Like `Pathname#cleanpath`, but normalizes Windows paths to always use
-
# backslash separators. Normally, `Pathname#cleanpath` actually does the
-
# reverse -- it will convert backslashes to forward slashes, which can break
-
# `Pathname#relative_path_from`.
-
#
-
# @param path [String, Pathname]
-
# @return [Pathname]
-
1
def cleanpath(path)
-
path = Pathname.new(path) unless path.is_a?(Pathname)
-
pathname(path.cleanpath.to_s)
-
end
-
-
# Returns `path` with all symlinks resolved.
-
#
-
# @param path [String, Pathname]
-
# @return [Pathname]
-
1
def realpath(path)
-
path = Pathname.new(path) unless path.is_a?(Pathname)
-
-
# Explicitly DON'T run #pathname here. We don't want to convert
-
# to Windows directory separators because we're comparing these
-
# against the paths returned by Listen, which use forward
-
# slashes everywhere.
-
begin
-
path.realpath
-
rescue SystemCallError
-
# If [path] doesn't actually exist, don't bail, just
-
# return the original.
-
path
-
end
-
end
-
-
# Returns `path` relative to `from`.
-
#
-
# This is like `Pathname#relative_path_from` except it accepts both strings
-
# and pathnames, it handles Windows path separators correctly, and it throws
-
# an error rather than crashing if the paths use different encodings
-
# (https://github.com/ruby/ruby/pull/713).
-
#
-
# @param path [String, Pathname]
-
# @param from [String, Pathname]
-
# @return [Pathname?]
-
1
def relative_path_from(path, from)
-
pathname(path.to_s).relative_path_from(pathname(from.to_s))
-
rescue NoMethodError => e
-
raise e unless e.name == :zero?
-
-
# Work around https://github.com/ruby/ruby/pull/713.
-
path = path.to_s
-
from = from.to_s
-
raise ArgumentError("Incompatible path encodings: #{path.inspect} is #{path.encoding}, " +
-
"#{from.inspect} is #{from.encoding}")
-
end
-
-
# Converts `path` to a "file:" URI. This handles Windows paths correctly.
-
#
-
# @param path [String, Pathname]
-
# @return [String]
-
1
def file_uri_from_path(path)
-
path = path.to_s if path.is_a?(Pathname)
-
path = path.tr('\\', '/') if windows?
-
path = URI::DEFAULT_PARSER.escape(path)
-
return path.start_with?('/') ? "file://" + path : path unless windows?
-
return "file:///" + path.tr("\\", "/") if path =~ %r{^[a-zA-Z]:[/\\]}
-
return "file:" + path.tr("\\", "/") if path =~ %r{\\\\[^\\]+\\[^\\/]+}
-
path.tr("\\", "/")
-
end
-
-
# Retries a filesystem operation if it fails on Windows. Windows
-
# has weird and flaky locking rules that can cause operations to fail.
-
#
-
# @yield [] The filesystem operation.
-
1
def retry_on_windows
-
return yield unless windows?
-
-
begin
-
yield
-
rescue SystemCallError
-
sleep 0.1
-
yield
-
end
-
end
-
-
# Prepare a value for a destructuring assignment (e.g. `a, b =
-
# val`). This works around a performance bug when using
-
# ActiveSupport, and only needs to be called when `val` is likely
-
# to be `nil` reasonably often.
-
#
-
# See [this bug report](http://redmine.ruby-lang.org/issues/4917).
-
#
-
# @param val [Object]
-
# @return [Object]
-
1
def destructure(val)
-
val || []
-
end
-
-
1
CHARSET_REGEXP = /\A@charset "([^"]+)"/
-
1
bom = "\uFEFF"
-
1
UTF_8_BOM = bom.encode("UTF-8").force_encoding('BINARY')
-
1
UTF_16BE_BOM = bom.encode("UTF-16BE").force_encoding('BINARY')
-
1
UTF_16LE_BOM = bom.encode("UTF-16LE").force_encoding('BINARY')
-
-
## Cross-Ruby-Version Compatibility
-
-
# Whether or not this is running under Ruby 2.4 or higher.
-
#
-
# @return [Boolean]
-
1
def ruby2_4?
-
return @ruby2_4 if defined?(@ruby2_4)
-
@ruby2_4 =
-
if RUBY_VERSION_COMPONENTS[0] == 2
-
RUBY_VERSION_COMPONENTS[1] >= 4
-
else
-
RUBY_VERSION_COMPONENTS[0] > 2
-
end
-
end
-
-
# Like {\#check\_encoding}, but also checks for a `@charset` declaration
-
# at the beginning of the file and uses that encoding if it exists.
-
#
-
# Sass follows CSS's decoding rules.
-
#
-
# @param str [String] The string of which to check the encoding
-
# @return [(String, Encoding)] The original string encoded as UTF-8,
-
# and the source encoding of the string
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
# @raise [Sass::SyntaxError] If the document declares an encoding that
-
# doesn't match its contents, or it doesn't declare an encoding and its
-
# contents are invalid in the native encoding.
-
1
def check_sass_encoding(str)
-
# Determine the fallback encoding following section 3.2 of CSS Syntax Level 3 and Encodings:
-
# http://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#determine-the-fallback-encoding
-
# http://encoding.spec.whatwg.org/#decode
-
binary = str.dup.force_encoding("BINARY")
-
if binary.start_with?(UTF_8_BOM)
-
binary.slice! 0, UTF_8_BOM.length
-
str = binary.force_encoding('UTF-8')
-
elsif binary.start_with?(UTF_16BE_BOM)
-
binary.slice! 0, UTF_16BE_BOM.length
-
str = binary.force_encoding('UTF-16BE')
-
elsif binary.start_with?(UTF_16LE_BOM)
-
binary.slice! 0, UTF_16LE_BOM.length
-
str = binary.force_encoding('UTF-16LE')
-
elsif binary =~ CHARSET_REGEXP
-
charset = $1.force_encoding('US-ASCII')
-
encoding = Encoding.find(charset)
-
if encoding.name == 'UTF-16' || encoding.name == 'UTF-16BE'
-
encoding = Encoding.find('UTF-8')
-
end
-
str = binary.force_encoding(encoding)
-
elsif str.encoding.name == "ASCII-8BIT"
-
# Normally we want to fall back on believing the Ruby string
-
# encoding, but if that's just binary we want to make sure
-
# it's valid UTF-8.
-
str = str.force_encoding('utf-8')
-
end
-
-
find_encoding_error(str) unless str.valid_encoding?
-
-
begin
-
# If the string is valid, preprocess it according to section 3.3 of CSS Syntax Level 3.
-
return str.encode("UTF-8").gsub(/\r\n?|\f/, "\n").tr("\u0000", "�"), str.encoding
-
rescue EncodingError
-
find_encoding_error(str)
-
end
-
end
-
-
# Destructively removes all elements from an array that match a block, and
-
# returns the removed elements.
-
#
-
# @param array [Array] The array from which to remove elements.
-
# @yield [el] Called for each element.
-
# @yieldparam el [*] The element to test.
-
# @yieldreturn [Boolean] Whether or not to extract the element.
-
# @return [Array] The extracted elements.
-
1
def extract!(array)
-
out = []
-
array.reject! do |e|
-
next false unless yield e
-
out << e
-
true
-
end
-
out
-
end
-
-
# Flattens the first level of nested arrays in `arrs`. Unlike
-
# `Array#flatten`, this orders the result by taking the first
-
# values from each array in order, then the second, and so on.
-
#
-
# @param arrs [Array] The array to flatten.
-
# @return [Array] The flattened array.
-
1
def flatten_vertically(arrs)
-
result = []
-
arrs = arrs.map {|sub| sub.is_a?(Array) ? sub.dup : Array(sub)}
-
until arrs.empty?
-
arrs.reject! do |arr|
-
result << arr.shift
-
arr.empty?
-
end
-
end
-
result
-
end
-
-
# Like `Object#inspect`, but preserves non-ASCII characters rather than
-
# escaping them under Ruby 1.9.2. This is necessary so that the
-
# precompiled Haml template can be `#encode`d into `@options[:encoding]`
-
# before being evaluated.
-
#
-
# @param obj {Object}
-
# @return {String}
-
1
def inspect_obj(obj)
-
return obj.inspect unless version_geq(RUBY_VERSION, "1.9.2")
-
return ':' + inspect_obj(obj.to_s) if obj.is_a?(Symbol)
-
return obj.inspect unless obj.is_a?(String)
-
'"' + obj.gsub(/[\x00-\x7F]+/) {|s| s.inspect[1...-1]} + '"'
-
end
-
-
# Extracts the non-string vlaues from an array containing both strings and non-strings.
-
# These values are replaced with escape sequences.
-
# This can be undone using \{#inject\_values}.
-
#
-
# This is useful e.g. when we want to do string manipulation
-
# on an interpolated string.
-
#
-
# The precise format of the resulting string is not guaranteed.
-
# However, it is guaranteed that newlines and whitespace won't be affected.
-
#
-
# @param arr [Array] The array from which values are extracted.
-
# @return [(String, Array)] The resulting string, and an array of extracted values.
-
1
def extract_values(arr)
-
values = []
-
mapped = arr.map do |e|
-
next e.gsub('{', '{{') if e.is_a?(String)
-
values << e
-
next "{#{values.count - 1}}"
-
end
-
return mapped.join, values
-
end
-
-
# Undoes \{#extract\_values} by transforming a string with escape sequences
-
# into an array of strings and non-string values.
-
#
-
# @param str [String] The string with escape sequences.
-
# @param values [Array] The array of values to inject.
-
# @return [Array] The array of strings and values.
-
1
def inject_values(str, values)
-
return [str.gsub('{{', '{')] if values.empty?
-
# Add an extra { so that we process the tail end of the string
-
result = (str + '{{').scan(/(.*?)(?:(\{\{)|\{(\d+)\})/m).map do |(pre, esc, n)|
-
[pre, esc ? '{' : '', n ? values[n.to_i] : '']
-
end.flatten(1)
-
result[-2] = '' # Get rid of the extra {
-
merge_adjacent_strings(result).reject {|s| s == ''}
-
end
-
-
# Allows modifications to be performed on the string form
-
# of an array containing both strings and non-strings.
-
#
-
# @param arr [Array] The array from which values are extracted.
-
# @yield [str] A block in which string manipulation can be done to the array.
-
# @yieldparam str [String] The string form of `arr`.
-
# @yieldreturn [String] The modified string.
-
# @return [Array] The modified, interpolated array.
-
1
def with_extracted_values(arr)
-
str, vals = extract_values(arr)
-
str = yield str
-
inject_values(str, vals)
-
end
-
-
# Builds a sourcemap file name given the generated CSS file name.
-
#
-
# @param css [String] The generated CSS file name.
-
# @return [String] The source map file name.
-
1
def sourcemap_name(css)
-
css + ".map"
-
end
-
-
# Escapes certain characters so that the result can be used
-
# as the JSON string value. Returns the original string if
-
# no escaping is necessary.
-
#
-
# @param s [String] The string to be escaped
-
# @return [String] The escaped string
-
1
def json_escape_string(s)
-
return s if s !~ /["\\\b\f\n\r\t]/
-
-
result = ""
-
s.split("").each do |c|
-
case c
-
when '"', "\\"
-
result << "\\" << c
-
when "\n" then result << "\\n"
-
when "\t" then result << "\\t"
-
when "\r" then result << "\\r"
-
when "\f" then result << "\\f"
-
when "\b" then result << "\\b"
-
else
-
result << c
-
end
-
end
-
result
-
end
-
-
# Converts the argument into a valid JSON value.
-
#
-
# @param v [Integer, String, Array, Boolean, nil]
-
# @return [String]
-
1
def json_value_of(v)
-
case v
-
when Integer
-
v.to_s
-
when String
-
"\"" + json_escape_string(v) + "\""
-
when Array
-
"[" + v.map {|x| json_value_of(x)}.join(",") + "]"
-
when NilClass
-
"null"
-
when TrueClass
-
"true"
-
when FalseClass
-
"false"
-
else
-
raise ArgumentError.new("Unknown type: #{v.class.name}")
-
end
-
end
-
-
1
VLQ_BASE_SHIFT = 5
-
1
VLQ_BASE = 1 << VLQ_BASE_SHIFT
-
1
VLQ_BASE_MASK = VLQ_BASE - 1
-
1
VLQ_CONTINUATION_BIT = VLQ_BASE
-
-
1
BASE64_DIGITS = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a + ['+', '/']
-
1
BASE64_DIGIT_MAP = begin
-
1
map = {}
-
1
BASE64_DIGITS.each_with_index.map do |digit, i|
-
64
map[digit] = i
-
end
-
1
map
-
end
-
-
# Encodes `value` as VLQ (http://en.wikipedia.org/wiki/VLQ).
-
#
-
# @param value [Integer]
-
# @return [String] The encoded value
-
1
def encode_vlq(value)
-
if value < 0
-
value = ((-value) << 1) | 1
-
else
-
value <<= 1
-
end
-
-
result = ''
-
begin
-
digit = value & VLQ_BASE_MASK
-
value >>= VLQ_BASE_SHIFT
-
if value > 0
-
digit |= VLQ_CONTINUATION_BIT
-
end
-
result << BASE64_DIGITS[digit]
-
end while value > 0
-
result
-
end
-
-
## Static Method Stuff
-
-
# The context in which the ERB for \{#def\_static\_method} will be run.
-
1
class StaticConditionalContext
-
# @param set [#include?] The set of variables that are defined for this context.
-
1
def initialize(set)
-
@set = set
-
end
-
-
# Checks whether or not a variable is defined for this context.
-
#
-
# @param name [Symbol] The name of the variable
-
# @return [Boolean]
-
1
def method_missing(name, *args)
-
super unless args.empty? && !block_given?
-
@set.include?(name)
-
end
-
end
-
-
# @private
-
1
ATOMIC_WRITE_MUTEX = Mutex.new
-
-
# This creates a temp file and yields it for writing. When the
-
# write is complete, the file is moved into the desired location.
-
# The atomicity of this operation is provided by the filesystem's
-
# rename operation.
-
#
-
# @param filename [String] The file to write to.
-
# @param perms [Integer] The permissions used for creating this file.
-
# Will be masked by the process umask. Defaults to readable/writeable
-
# by all users however the umask usually changes this to only be writable
-
# by the process's user.
-
# @yieldparam tmpfile [Tempfile] The temp file that can be written to.
-
# @return The value returned by the block.
-
1
def atomic_create_and_write_file(filename, perms = 0666)
-
require 'tempfile'
-
tmpfile = Tempfile.new(File.basename(filename), File.dirname(filename))
-
tmpfile.binmode if tmpfile.respond_to?(:binmode)
-
result = yield tmpfile
-
tmpfile.close
-
ATOMIC_WRITE_MUTEX.synchronize do
-
begin
-
File.chmod(perms & ~File.umask, tmpfile.path)
-
rescue Errno::EPERM
-
# If we don't have permissions to chmod the file, don't let that crash
-
# the compilation. See issue 1215.
-
end
-
File.rename tmpfile.path, filename
-
end
-
result
-
ensure
-
# close and remove the tempfile if it still exists,
-
# presumably due to an error during write
-
tmpfile.close if tmpfile
-
tmpfile.unlink if tmpfile
-
end
-
-
1
private
-
-
1
def find_encoding_error(str)
-
encoding = str.encoding
-
cr = Regexp.quote("\r".encode(encoding).force_encoding('BINARY'))
-
lf = Regexp.quote("\n".encode(encoding).force_encoding('BINARY'))
-
ff = Regexp.quote("\f".encode(encoding).force_encoding('BINARY'))
-
line_break = /#{cr}#{lf}?|#{ff}|#{lf}/
-
-
str.force_encoding("binary").split(line_break).each_with_index do |line, i|
-
begin
-
line.encode(encoding)
-
rescue Encoding::UndefinedConversionError => e
-
raise Sass::SyntaxError.new(
-
"Invalid #{encoding.name} character #{undefined_conversion_error_char(e)}",
-
:line => i + 1)
-
end
-
end
-
-
# We shouldn't get here, but it's possible some weird encoding stuff causes it.
-
return str, str.encoding
-
end
-
-
# Calculates the memoization table for the Least Common Subsequence algorithm.
-
# Algorithm from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Computing_the_length_of_the_LCS)
-
1
def lcs_table(x, y)
-
# This method does not take a block as an explicit parameter for performance reasons.
-
c = Array.new(x.size) {[]}
-
x.size.times {|i| c[i][0] = 0}
-
y.size.times {|j| c[0][j] = 0}
-
(1...x.size).each do |i|
-
(1...y.size).each do |j|
-
c[i][j] =
-
if yield x[i], y[j]
-
c[i - 1][j - 1] + 1
-
else
-
[c[i][j - 1], c[i - 1][j]].max
-
end
-
end
-
end
-
c
-
end
-
# rubocop:disable ParameterLists
-
-
# Computes a single longest common subsequence for arrays x and y.
-
# Algorithm from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Reading_out_an_LCS)
-
1
def lcs_backtrace(c, x, y, i, j, &block)
-
# rubocop:enable ParameterList
-
return [] if i == 0 || j == 0
-
if (v = yield(x[i], y[j]))
-
return lcs_backtrace(c, x, y, i - 1, j - 1, &block) << v
-
end
-
-
return lcs_backtrace(c, x, y, i, j - 1, &block) if c[i][j - 1] > c[i - 1][j]
-
lcs_backtrace(c, x, y, i - 1, j, &block)
-
end
-
-
63
singleton_methods.each {|method| module_function method}
-
end
-
end
-
-
1
require 'sass/util/multibyte_string_scanner'
-
1
require 'sass/util/normalized_map'
-
1
require 'strscan'
-
-
1
if Sass::Util.rbx?
-
# Rubinius's StringScanner class implements some of its methods in terms of
-
# others, which causes us to double-count bytes in some cases if we do
-
# straightforward inheritance. To work around this, we use a delegate class.
-
require 'delegate'
-
class Sass::Util::MultibyteStringScanner < DelegateClass(StringScanner)
-
def initialize(str)
-
super(StringScanner.new(str))
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
end
-
-
def is_a?(klass)
-
__getobj__.is_a?(klass) || super
-
end
-
end
-
else
-
1
class Sass::Util::MultibyteStringScanner < StringScanner
-
1
def initialize(str)
-
super
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
end
-
end
-
end
-
-
# A wrapper of the native StringScanner class that works correctly with
-
# multibyte character encodings. The native class deals only in bytes, not
-
# characters, for methods like [#pos] and [#matched_size]. This class deals
-
# only in characters, instead.
-
1
class Sass::Util::MultibyteStringScanner
-
1
def self.new(str)
-
return StringScanner.new(str) if str.ascii_only?
-
super
-
end
-
-
1
alias_method :byte_pos, :pos
-
1
alias_method :byte_matched_size, :matched_size
-
-
1
def check(pattern); _match super; end
-
1
def check_until(pattern); _matched super; end
-
1
def getch; _forward _match super; end
-
1
def match?(pattern); _size check(pattern); end
-
1
def matched_size; @mb_matched_size; end
-
1
def peek(len); string[@mb_pos, len]; end
-
1
alias_method :peep, :peek
-
1
def pos; @mb_pos; end
-
1
alias_method :pointer, :pos
-
1
def rest_size; rest.size; end
-
1
def scan(pattern); _forward _match super; end
-
1
def scan_until(pattern); _forward _matched super; end
-
1
def skip(pattern); _size scan(pattern); end
-
1
def skip_until(pattern); _matched _size scan_until(pattern); end
-
-
1
def get_byte
-
raise "MultibyteStringScanner doesn't support #get_byte."
-
end
-
-
1
def getbyte
-
raise "MultibyteStringScanner doesn't support #getbyte."
-
end
-
-
1
def pos=(n)
-
@mb_last_pos = nil
-
-
# We set position kind of a lot during parsing, so we want it to be as
-
# efficient as possible. This is complicated by the fact that UTF-8 is a
-
# variable-length encoding, so it's difficult to find the byte length that
-
# corresponds to a given character length.
-
#
-
# Our heuristic here is to try to count the fewest possible characters. So
-
# if the new position is close to the current one, just count the
-
# characters between the two; if the new position is closer to the
-
# beginning of the string, just count the characters from there.
-
if @mb_pos - n < @mb_pos / 2
-
# New position is close to old position
-
byte_delta = @mb_pos > n ? -string[n...@mb_pos].bytesize : string[@mb_pos...n].bytesize
-
super(byte_pos + byte_delta)
-
else
-
# New position is close to BOS
-
super(string[0...n].bytesize)
-
end
-
@mb_pos = n
-
end
-
-
1
def reset
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
-
1
def scan_full(pattern, advance_pointer_p, return_string_p)
-
res = _match super(pattern, advance_pointer_p, true)
-
_forward res if advance_pointer_p
-
return res if return_string_p
-
end
-
-
1
def search_full(pattern, advance_pointer_p, return_string_p)
-
res = super(pattern, advance_pointer_p, true)
-
_forward res if advance_pointer_p
-
_matched((res if return_string_p))
-
end
-
-
1
def string=(str)
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
-
1
def terminate
-
@mb_pos = string.size
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
1
alias_method :clear, :terminate
-
-
1
def unscan
-
super
-
@mb_pos = @mb_last_pos
-
@mb_last_pos = @mb_matched_size = nil
-
end
-
-
1
private
-
-
1
def _size(str)
-
str && str.size
-
end
-
-
1
def _match(str)
-
@mb_matched_size = str && str.size
-
str
-
end
-
-
1
def _matched(res)
-
_match matched
-
res
-
end
-
-
1
def _forward(str)
-
@mb_last_pos = @mb_pos
-
@mb_pos += str.size if str
-
str
-
end
-
end
-
1
require 'delegate'
-
-
1
module Sass
-
1
module Util
-
# A hash that normalizes its string keys while still allowing you to get back
-
# to the original keys that were stored. If several different values normalize
-
# to the same value, whichever is stored last wins.
-
1
class NormalizedMap
-
# Create a normalized map
-
1
def initialize(map = nil)
-
@key_strings = {}
-
@map = {}
-
-
map.each {|key, value| self[key] = value} if map
-
end
-
-
# Specifies how to transform the key.
-
#
-
# This can be overridden to create other normalization behaviors.
-
1
def normalize(key)
-
key.tr("-", "_")
-
end
-
-
# Returns the version of `key` as it was stored before
-
# normalization. If `key` isn't in the map, returns it as it was
-
# passed in.
-
#
-
# @return [String]
-
1
def denormalize(key)
-
@key_strings[normalize(key)] || key
-
end
-
-
# @private
-
1
def []=(k, v)
-
normalized = normalize(k)
-
@map[normalized] = v
-
@key_strings[normalized] = k
-
v
-
end
-
-
# @private
-
1
def [](k)
-
@map[normalize(k)]
-
end
-
-
# @private
-
1
def has_key?(k)
-
@map.has_key?(normalize(k))
-
end
-
-
# @private
-
1
def delete(k)
-
normalized = normalize(k)
-
@key_strings.delete(normalized)
-
@map.delete(normalized)
-
end
-
-
# @return [Hash] Hash with the keys as they were stored (before normalization).
-
1
def as_stored
-
Sass::Util.map_keys(@map) {|k| @key_strings[k]}
-
end
-
-
1
def empty?
-
@map.empty?
-
end
-
-
1
def values
-
@map.values
-
end
-
-
1
def keys
-
@map.keys
-
end
-
-
1
def each
-
@map.each {|k, v| yield(k, v)}
-
end
-
-
1
def size
-
@map.size
-
end
-
-
1
def to_hash
-
@map.dup
-
end
-
-
1
def to_a
-
@map.to_a
-
end
-
-
1
def map
-
@map.map {|k, v| yield(k, v)}
-
end
-
-
1
def dup
-
d = super
-
d.send(:instance_variable_set, "@map", @map.dup)
-
d
-
end
-
-
1
def sort_by
-
@map.sort_by {|k, v| yield k, v}
-
end
-
-
1
def update(map)
-
map = map.as_stored if map.is_a?(NormalizedMap)
-
map.each {|k, v| self[k] = v}
-
end
-
-
1
def method_missing(method, *args, &block)
-
if Sass.tests_running
-
raise ArgumentError.new("The method #{method} must be implemented explicitly")
-
end
-
@map.send(method, *args, &block)
-
end
-
-
1
def respond_to_missing?(method, include_private = false)
-
@map.respond_to?(method, include_private)
-
end
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Sass
-
1
module Util
-
# A map from sets to values.
-
# A value is \{#\[]= set} by providing a set (the "set-set") and a value,
-
# which is then recorded as corresponding to that set.
-
# Values are \{#\[] accessed} by providing a set (the "get-set")
-
# and returning all values that correspond to set-sets
-
# that are subsets of the get-set.
-
#
-
# SubsetMap preserves the order of values as they're inserted.
-
#
-
# @example
-
# ssm = SubsetMap.new
-
# ssm[Set[1, 2]] = "Foo"
-
# ssm[Set[2, 3]] = "Bar"
-
# ssm[Set[1, 2, 3]] = "Baz"
-
#
-
# ssm[Set[1, 2, 3]] #=> ["Foo", "Bar", "Baz"]
-
1
class SubsetMap
-
# Creates a new, empty SubsetMap.
-
1
def initialize
-
@hash = {}
-
@vals = []
-
end
-
-
# Whether or not this SubsetMap has any key-value pairs.
-
#
-
# @return [Boolean]
-
1
def empty?
-
@hash.empty?
-
end
-
-
# Associates a value with a set.
-
# When `set` or any of its supersets is accessed,
-
# `value` will be among the values returned.
-
#
-
# Note that if the same `set` is passed to this method multiple times,
-
# all given `value`s will be associated with that `set`.
-
#
-
# This runs in `O(n)` time, where `n` is the size of `set`.
-
#
-
# @param set [#to_set] The set to use as the map key. May not be empty.
-
# @param value [Object] The value to associate with `set`.
-
# @raise [ArgumentError] If `set` is empty.
-
1
def []=(set, value)
-
raise ArgumentError.new("SubsetMap keys may not be empty.") if set.empty?
-
-
index = @vals.size
-
@vals << value
-
set.each do |k|
-
@hash[k] ||= []
-
@hash[k] << [set, set.to_set, index]
-
end
-
end
-
-
# Returns all values associated with subsets of `set`.
-
#
-
# In the worst case, this runs in `O(m*max(n, log m))` time,
-
# where `n` is the size of `set`
-
# and `m` is the number of associations in the map.
-
# However, unless many keys in the map overlap with `set`,
-
# `m` will typically be much smaller.
-
#
-
# @param set [Set] The set to use as the map key.
-
# @return [Array<(Object, #to_set)>] An array of pairs,
-
# where the first value is the value associated with a subset of `set`,
-
# and the second value is that subset of `set`
-
# (or whatever `#to_set` object was used to set the value)
-
# This array is in insertion order.
-
# @see #[]
-
1
def get(set)
-
res = set.map do |k|
-
subsets = @hash[k]
-
next unless subsets
-
subsets.map do |subenum, subset, index|
-
next unless subset.subset?(set)
-
[index, subenum]
-
end
-
end.flatten(1)
-
res.compact!
-
res.uniq!
-
res.sort!
-
res.map! {|i, s| [@vals[i], s]}
-
res
-
end
-
-
# Same as \{#get}, but doesn't return the subsets of the argument
-
# for which values were found.
-
#
-
# @param set [Set] The set to use as the map key.
-
# @return [Array] The array of all values
-
# associated with subsets of `set`, in insertion order.
-
# @see #get
-
1
def [](set)
-
get(set).map {|v, _| v}
-
end
-
-
# Iterates over each value in the subset map. Ignores keys completely. If
-
# multiple keys have the same value, this will return them multiple times.
-
#
-
# @yield [Object] Each value in the map.
-
1
def each_value
-
@vals.each {|v| yield v}
-
end
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'sass/util'
-
-
1
module Sass
-
# Handles Sass version-reporting.
-
# Sass not only reports the standard three version numbers,
-
# but its Git revision hash as well,
-
# if it was installed from Git.
-
1
module Version
-
# Returns a hash representing the version of Sass.
-
# The `:major`, `:minor`, and `:teeny` keys have their respective numbers as Integers.
-
# The `:name` key has the name of the version.
-
# The `:string` key contains a human-readable string representation of the version.
-
# The `:number` key is the major, minor, and teeny keys separated by periods.
-
# The `:date` key, which is not guaranteed to be defined, is the `DateTime`
-
# at which this release was cut.
-
# If Sass is checked out from Git, the `:rev` key will have the revision hash.
-
# For example:
-
#
-
# {
-
# :string => "2.1.0.9616393",
-
# :rev => "9616393b8924ef36639c7e82aa88a51a24d16949",
-
# :number => "2.1.0",
-
# :date => DateTime.parse("Apr 30 13:52:01 2009 -0700"),
-
# :major => 2, :minor => 1, :teeny => 0
-
# }
-
#
-
# If a prerelease version of Sass is being used,
-
# the `:string` and `:number` fields will reflect the full version
-
# (e.g. `"2.2.beta.1"`), and the `:teeny` field will be `-1`.
-
# A `:prerelease` key will contain the name of the prerelease (e.g. `"beta"`),
-
# and a `:prerelease_number` key will contain the rerelease number.
-
# For example:
-
#
-
# {
-
# :string => "3.0.beta.1",
-
# :number => "3.0.beta.1",
-
# :date => DateTime.parse("Mar 31 00:38:04 2010 -0700"),
-
# :major => 3, :minor => 0, :teeny => -1,
-
# :prerelease => "beta",
-
# :prerelease_number => 1
-
# }
-
#
-
# @return [{Symbol => String/Integer}] The version hash
-
# @comment
-
1
def version
-
1
return @@version if defined?(@@version)
-
-
1
numbers = File.read(Sass::Util.scope('VERSION')).strip.split('.').
-
3
map {|n| n =~ /^[0-9]+$/ ? n.to_i : n}
-
1
name = File.read(Sass::Util.scope('VERSION_NAME')).strip
-
1
@@version = {
-
:major => numbers[0],
-
:minor => numbers[1],
-
:teeny => numbers[2],
-
:name => name
-
}
-
-
1
if (date = version_date)
-
1
@@version[:date] = date
-
end
-
-
1
if numbers[3].is_a?(String)
-
@@version[:teeny] = -1
-
@@version[:prerelease] = numbers[3]
-
@@version[:prerelease_number] = numbers[4]
-
end
-
-
1
@@version[:number] = numbers.join('.')
-
1
@@version[:string] = @@version[:number].dup
-
-
1
if (rev = revision_number)
-
@@version[:rev] = rev
-
unless rev[0] == ?(
-
@@version[:string] << "." << rev[0...7]
-
end
-
end
-
-
1
@@version[:string] << " (#{name})"
-
1
@@version
-
end
-
-
1
private
-
-
1
def revision_number
-
1
if File.exist?(Sass::Util.scope('REVISION'))
-
1
rev = File.read(Sass::Util.scope('REVISION')).strip
-
1
return rev unless rev =~ /^([a-f0-9]+|\(.*\))$/ || rev == '(unknown)'
-
end
-
-
1
return unless File.exist?(Sass::Util.scope('.git/HEAD'))
-
rev = File.read(Sass::Util.scope('.git/HEAD')).strip
-
return rev unless rev =~ /^ref: (.*)$/
-
-
ref_name = $1
-
ref_file = Sass::Util.scope(".git/#{ref_name}")
-
info_file = Sass::Util.scope(".git/info/refs")
-
return File.read(ref_file).strip if File.exist?(ref_file)
-
return unless File.exist?(info_file)
-
File.open(info_file) do |f|
-
f.each do |l|
-
sha, ref = l.strip.split("\t", 2)
-
next unless ref == ref_name
-
return sha
-
end
-
end
-
nil
-
end
-
-
1
def version_date
-
1
return unless File.exist?(Sass::Util.scope('VERSION_DATE'))
-
1
DateTime.parse(File.read(Sass::Util.scope('VERSION_DATE')).strip)
-
end
-
end
-
-
1
extend Sass::Version
-
-
# A string representing the version of Sass.
-
# A more fine-grained representation is available from Sass.version.
-
# @api public
-
1
VERSION = version[:string] unless defined?(Sass::VERSION)
-
end
-
1
module Sass
-
1
module Rails
-
1
autoload :Logger, 'sass/rails/logger'
-
end
-
end
-
-
1
require 'sass/rails/version'
-
1
require 'sass/rails/helpers'
-
1
require 'sass/rails/importer'
-
1
require 'sass/rails/template'
-
1
require 'sass/rails/railtie'
-
1
require 'sass'
-
-
1
module Sass
-
1
module Rails
-
1
class CacheStore < ::Sass::CacheStores::Base
-
1
attr_reader :environment
-
-
1
def initialize(environment)
-
@environment = environment
-
end
-
-
1
def _store(key, version, sha, contents)
-
environment.cache_set("sass/#{key}", {:version => version, :sha => sha, :contents => contents})
-
end
-
-
1
def _retrieve(key, version, sha)
-
if obj = environment.cache_get("sass/#{key}")
-
return unless obj[:version] == version
-
return unless obj[:sha] == sha
-
obj[:contents]
-
else
-
nil
-
end
-
end
-
-
1
def path_to(key)
-
key
-
end
-
end
-
end
-
end
-
1
require 'sass'
-
1
require 'sprockets/sass_functions'
-
-
1
module Sprockets
-
1
module SassFunctions
-
1
def asset_data_url(path)
-
Sass::Script::String.new("url(" + sprockets_context.asset_data_uri(path.value) + ")")
-
end
-
end
-
end
-
-
1
::Sass::Script::Functions.send :include, Sprockets::SassFunctions
-
1
require 'active_support/deprecation/reporting'
-
1
require 'sass'
-
1
require 'sprockets/sass_importer'
-
1
require 'tilt'
-
-
1
module Sass
-
1
module Rails
-
1
class SassImporter < Sass::Importers::Filesystem
-
1
module Globbing
-
1
GLOB = /(\A|\/)(\*|\*\*\/\*)\z/
-
-
1
def find_relative(name, base, options)
-
if options[:sprockets] && m = name.match(GLOB)
-
path = name.sub(m[0], "")
-
base = File.expand_path(path, File.dirname(base))
-
glob_imports(base, m[2], options)
-
else
-
super
-
end
-
end
-
-
1
def find(name, options)
-
# globs must be relative
-
return if name =~ GLOB
-
super
-
end
-
-
1
private
-
1
def glob_imports(base, glob, options)
-
contents = ""
-
context = options[:sprockets][:context]
-
each_globbed_file(base, glob, context) do |filename|
-
next if filename == options[:filename]
-
contents << "@import #{filename.inspect};\n"
-
end
-
return nil if contents == ""
-
Sass::Engine.new(contents, options.merge(
-
:filename => base,
-
:importer => self,
-
:syntax => :scss
-
))
-
end
-
-
1
def each_globbed_file(base, glob, context)
-
raise ArgumentError unless glob == "*" || glob == "**/*"
-
-
exts = extensions.keys.map { |ext| Regexp.escape(".#{ext}") }.join("|")
-
sass_re = Regexp.compile("(#{exts})$")
-
-
context.depend_on(base)
-
-
Dir["#{base}/#{glob}"].sort.each do |path|
-
if File.directory?(path)
-
context.depend_on(path)
-
elsif sass_re =~ path
-
yield path
-
end
-
end
-
end
-
end
-
-
1
module ERB
-
1
def extensions
-
{
-
'css.erb' => :scss_erb,
-
'scss.erb' => :scss_erb,
-
'sass.erb' => :sass_erb
-
}.merge(super)
-
end
-
-
1
def erb_extensions
-
{
-
:scss_erb => :scss,
-
:sass_erb => :sass
-
}
-
end
-
-
1
def find_relative(*args)
-
process_erb_engine(super)
-
end
-
-
1
def find(*args)
-
process_erb_engine(super)
-
end
-
-
1
private
-
1
def process_erb_engine(engine)
-
if engine && engine.options[:sprockets] && syntax = erb_extensions[engine.options[:syntax]]
-
template = Tilt::ERBTemplate.new(engine.options[:filename])
-
contents = template.render(engine.options[:sprockets][:context], {})
-
-
Sass::Engine.new(contents, engine.options.merge(:syntax => syntax))
-
else
-
engine
-
end
-
end
-
end
-
-
1
module Deprecated
-
1
def extensions
-
{
-
'css.scss' => :scss,
-
'css.sass' => :sass,
-
'css.scss.erb' => :scss_erb,
-
'css.sass.erb' => :sass_erb
-
}.merge(super)
-
end
-
-
1
def find_relative(*args)
-
deprecate_extra_css_extension(super)
-
end
-
-
1
def find(*args)
-
deprecate_extra_css_extension(super)
-
end
-
-
1
private
-
1
def deprecate_extra_css_extension(engine)
-
if engine && filename = engine.options[:filename]
-
if filename.end_with?('.css.scss')
-
msg = "Extra .css in SCSS file is unnecessary. Rename #{filename} to #{filename.sub('.css.scss', '.scss')}."
-
elsif filename.end_with?('.css.sass')
-
msg = "Extra .css in SASS file is unnecessary. Rename #{filename} to #{filename.sub('.css.sass', '.sass')}."
-
elsif filename.end_with?('.css.scss.erb')
-
msg = "Extra .css in SCSS/ERB file is unnecessary. Rename #{filename} to #{filename.sub('.css.scss.erb', '.scss.erb')}."
-
elsif filename.end_with?('.css.sass.erb')
-
msg = "Extra .css in SASS/ERB file is unnecessary. Rename #{filename} to #{filename.sub('.css.sass.erb', '.sass.erb')}."
-
end
-
-
ActiveSupport::Deprecation.warn(msg) if msg
-
end
-
-
engine
-
end
-
end
-
-
1
include Deprecated
-
1
include ERB
-
1
include Globbing
-
-
# Allow .css files to be @import'd
-
1
def extensions
-
{ 'css' => :scss }.merge(super)
-
end
-
end
-
end
-
end
-
1
require 'sass'
-
1
require 'sass/logger'
-
-
1
module Sass
-
1
module Rails
-
1
class Logger < Sass::Logger::Base
-
1
def _log(level, message)
-
-
case level
-
when :trace, :debug
-
::Rails.logger.debug message
-
when :warn
-
::Rails.logger.warn message
-
when :error
-
::Rails.logger.error message
-
when :info
-
::Rails.logger.info message
-
end
-
end
-
end
-
end
-
end
-
1
require 'sass'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'sprockets/railtie'
-
-
1
module Sass::Rails
-
1
class Railtie < ::Rails::Railtie
-
1
config.sass = ActiveSupport::OrderedOptions.new
-
-
# Establish static configuration defaults
-
# Emit scss files during stylesheet generation of scaffold
-
1
config.sass.preferred_syntax = :scss
-
# Write sass cache files for performance
-
1
config.sass.cache = true
-
# Read sass cache files for performance
-
1
config.sass.read_cache = true
-
# Display line comments above each selector as a debugging aid
-
1
config.sass.line_comments = true
-
# Initialize the load paths to an empty array
-
1
config.sass.load_paths = []
-
# Send Sass logs to Rails.logger
-
1
config.sass.logger = Sass::Rails::Logger.new
-
-
# Set the default stylesheet engine
-
# It can be overridden by passing:
-
# --stylesheet_engine=sass
-
# to the rails generate command
-
1
config.app_generators.stylesheet_engine config.sass.preferred_syntax
-
-
1
if config.respond_to?(:annotations)
-
config.annotations.register_extensions("scss", "sass") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ }
-
end
-
-
# Remove the sass middleware if it gets inadvertently enabled by applications.
-
1
config.after_initialize do |app|
-
1
app.config.middleware.delete(Sass::Plugin::Rack) if defined?(Sass::Plugin::Rack)
-
end
-
-
1
initializer :setup_sass, group: :all do |app|
-
# Only emit one kind of syntax because though we have registered two kinds of generators
-
1
syntax = app.config.sass.preferred_syntax.to_sym
-
1
alt_syntax = syntax == :sass ? "scss" : "sass"
-
1
app.config.generators.hide_namespace alt_syntax
-
-
# Override stylesheet engine to the preferred syntax
-
1
config.app_generators.stylesheet_engine syntax
-
-
# Set the sass cache location
-
1
config.sass.cache_location = File.join(Rails.root, "tmp/cache/sass")
-
-
# Establish configuration defaults that are evironmental in nature
-
1
if config.sass.full_exception.nil?
-
# Display a stack trace in the css output when in development-like environments.
-
1
config.sass.full_exception = app.config.consider_all_requests_local
-
end
-
-
1
config.assets.configure do |env|
-
1
if env.respond_to?(:register_engine)
-
1
args = ['.sass', Sass::Rails::SassTemplate]
-
1
args << { silence_deprecation: true } if env.method(:register_engine).arity.abs > 2
-
1
env.register_engine(*args)
-
-
1
args = ['.scss', Sass::Rails::ScssTemplate]
-
1
args << { silence_deprecation: true } if env.method(:register_engine).arity.abs > 2
-
1
env.register_engine(*args)
-
end
-
-
1
if env.respond_to?(:register_transformer)
-
1
env.register_transformer 'text/sass', 'text/css',
-
Sprockets::SassProcessor.new(importer: SassImporter, sass_config: app.config.sass)
-
1
env.register_transformer 'text/scss', 'text/css',
-
Sprockets::ScssProcessor.new(importer: SassImporter, sass_config: app.config.sass)
-
end
-
-
1
env.context_class.class_eval do
-
1
class_attribute :sass_config
-
1
self.sass_config = app.config.sass
-
end
-
end
-
-
1
Sass.logger = app.config.sass.logger
-
end
-
-
1
initializer :setup_compression, group: :all do |app|
-
1
if Rails.env.development?
-
# Use expanded output instead of the sass default of :nested unless specified
-
app.config.sass.style ||= :expanded
-
else
-
# config.assets.css_compressor may be set to nil in non-dev environments.
-
# otherwise, the default is sass compression.
-
1
app.config.assets.css_compressor = :sass unless app.config.assets.has_key?(:css_compressor)
-
end
-
end
-
end
-
end
-
1
require 'sass'
-
1
require 'sass/rails/cache_store'
-
1
require 'sass/rails/helpers'
-
1
require 'sprockets/sass_functions'
-
1
require 'tilt'
-
-
1
module Sass
-
1
module Rails
-
1
class SassTemplate < Tilt::Template
-
1
def self.default_mime_type
-
4
'text/css'
-
end
-
-
1
def self.engine_initialized?
-
true
-
end
-
-
1
def initialize_engine
-
end
-
-
1
def prepare
-
end
-
-
1
def syntax
-
:sass
-
end
-
-
1
def evaluate(context, locals, &block)
-
cache_store = CacheStore.new(context.environment)
-
-
options = {
-
:filename => eval_file,
-
:line => line,
-
:syntax => syntax,
-
:cache_store => cache_store,
-
:importer => importer_class.new(context.pathname.to_s),
-
:load_paths => context.environment.paths.map { |path| importer_class.new(path.to_s) },
-
:sprockets => {
-
:context => context,
-
:environment => context.environment
-
}
-
}
-
-
sass_config = context.sass_config.merge(options)
-
-
engine = ::Sass::Engine.new(data, sass_config)
-
css = engine.render
-
-
engine.dependencies.map do |dependency|
-
context.depend_on(dependency.options[:filename])
-
end
-
-
css
-
rescue ::Sass::SyntaxError => e
-
context.__LINE__ = e.sass_backtrace.first[:line]
-
raise e
-
end
-
-
1
private
-
-
1
def importer_class
-
SassImporter
-
end
-
end
-
-
1
class ScssTemplate < SassTemplate
-
1
def syntax
-
:scss
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Rails
-
1
VERSION = "5.0.6"
-
end
-
end
-
# encoding: utf-8
-
1
require 'sprockets/version'
-
1
require 'sprockets/cache'
-
1
require 'sprockets/environment'
-
1
require 'sprockets/errors'
-
1
require 'sprockets/manifest'
-
1
require 'sprockets/deprecation'
-
-
1
module Sprockets
-
1
require 'sprockets/processor_utils'
-
1
extend ProcessorUtils
-
-
# Extend Sprockets module to provide global registry
-
1
require 'sprockets/configuration'
-
1
require 'sprockets/context'
-
1
require 'digest/sha2'
-
1
extend Configuration
-
-
1
self.config = {
-
2
bundle_processors: Hash.new { |h, k| [].freeze }.freeze,
-
3
bundle_reducers: Hash.new { |h, k| {}.freeze }.freeze,
-
2
compressors: Hash.new { |h, k| {}.freeze }.freeze,
-
dependencies: Set.new.freeze,
-
dependency_resolvers: {}.freeze,
-
digest_class: Digest::SHA256,
-
engine_mime_types: {}.freeze,
-
engines: {}.freeze,
-
mime_exts: {}.freeze,
-
mime_types: {}.freeze,
-
paths: [].freeze,
-
pipelines: {}.freeze,
-
9
postprocessors: Hash.new { |h, k| [].freeze }.freeze,
-
2
preprocessors: Hash.new { |h, k| [].freeze }.freeze,
-
7
registered_transformers: Hash.new { |h, k| {}.freeze }.freeze,
-
root: File.expand_path('..', __FILE__).freeze,
-
transformers: Hash.new { |h, k| {}.freeze }.freeze,
-
version: "",
-
gzip_enabled: true
-
}.freeze
-
1
self.computed_config = {}
-
-
1
@context_class = Context
-
-
1
require 'logger'
-
1
@logger = Logger.new($stderr)
-
1
@logger.level = Logger::FATAL
-
-
# Common asset text types
-
1
register_mime_type 'application/javascript', extensions: ['.js'], charset: :unicode
-
1
register_mime_type 'application/json', extensions: ['.json'], charset: :unicode
-
1
register_mime_type 'application/xml', extensions: ['.xml']
-
1
register_mime_type 'text/css', extensions: ['.css'], charset: :css
-
1
register_mime_type 'text/html', extensions: ['.html', '.htm'], charset: :html
-
1
register_mime_type 'text/plain', extensions: ['.txt', '.text']
-
1
register_mime_type 'text/yaml', extensions: ['.yml', '.yaml'], charset: :unicode
-
-
# Common image types
-
1
register_mime_type 'image/x-icon', extensions: ['.ico']
-
1
register_mime_type 'image/bmp', extensions: ['.bmp']
-
1
register_mime_type 'image/gif', extensions: ['.gif']
-
1
register_mime_type 'image/webp', extensions: ['.webp']
-
1
register_mime_type 'image/png', extensions: ['.png']
-
1
register_mime_type 'image/jpeg', extensions: ['.jpg', '.jpeg']
-
1
register_mime_type 'image/tiff', extensions: ['.tiff', '.tif']
-
1
register_mime_type 'image/svg+xml', extensions: ['.svg']
-
-
# Common audio/video types
-
1
register_mime_type 'video/webm', extensions: ['.webm']
-
1
register_mime_type 'audio/basic', extensions: ['.snd', '.au']
-
1
register_mime_type 'audio/aiff', extensions: ['.aiff']
-
1
register_mime_type 'audio/mpeg', extensions: ['.mp3', '.mp2', '.m2a', '.m3a']
-
1
register_mime_type 'application/ogg', extensions: ['.ogx']
-
1
register_mime_type 'audio/midi', extensions: ['.midi', '.mid']
-
1
register_mime_type 'video/avi', extensions: ['.avi']
-
1
register_mime_type 'audio/wave', extensions: ['.wav', '.wave']
-
1
register_mime_type 'video/mp4', extensions: ['.mp4', '.m4v']
-
-
# Common font types
-
1
register_mime_type 'application/vnd.ms-fontobject', extensions: ['.eot']
-
1
register_mime_type 'application/x-font-opentype', extensions: ['.otf']
-
1
register_mime_type 'application/x-font-ttf', extensions: ['.ttf']
-
1
register_mime_type 'application/font-woff', extensions: ['.woff']
-
-
1
register_pipeline :source do |env|
-
[]
-
end
-
-
1
register_pipeline :self do |env, type, file_type, engine_extnames|
-
4
env.self_processors_for(type, file_type, engine_extnames)
-
end
-
-
1
register_pipeline :default do |env, type, file_type, engine_extnames|
-
2
env.default_processors_for(type, file_type, engine_extnames)
-
end
-
-
1
require 'sprockets/directive_processor'
-
1
register_preprocessor 'text/css', DirectiveProcessor.new(
-
comments: ["//", ["/*", "*/"]]
-
)
-
1
register_preprocessor 'application/javascript', DirectiveProcessor.new(
-
comments: ["//", ["/*", "*/"]] + ["#", ["###", "###"]]
-
)
-
-
1
require 'sprockets/bundle'
-
1
register_bundle_processor 'application/javascript', Bundle
-
1
register_bundle_processor 'text/css', Bundle
-
-
1
register_bundle_metadata_reducer '*/*', :data, proc { "" }, :concat
-
1
register_bundle_metadata_reducer 'application/javascript', :data, proc { "" }, Utils.method(:concat_javascript_sources)
-
1
register_bundle_metadata_reducer '*/*', :links, :+
-
-
1
require 'sprockets/closure_compressor'
-
1
require 'sprockets/sass_compressor'
-
1
require 'sprockets/uglifier_compressor'
-
1
require 'sprockets/yui_compressor'
-
1
register_compressor 'text/css', :sass, SassCompressor
-
1
register_compressor 'text/css', :scss, SassCompressor
-
1
register_compressor 'text/css', :yui, YUICompressor
-
1
register_compressor 'application/javascript', :closure, ClosureCompressor
-
1
register_compressor 'application/javascript', :uglifier, UglifierCompressor
-
1
register_compressor 'application/javascript', :uglify, UglifierCompressor
-
1
register_compressor 'application/javascript', :yui, YUICompressor
-
-
# Mmm, CoffeeScript
-
1
require 'sprockets/coffee_script_processor'
-
1
Deprecation.silence do
-
1
register_engine '.coffee', CoffeeScriptProcessor, mime_type: 'application/javascript', silence_deprecation: true
-
end
-
-
# JST engines
-
1
require 'sprockets/eco_processor'
-
1
require 'sprockets/ejs_processor'
-
1
require 'sprockets/jst_processor'
-
1
Deprecation.silence do
-
1
register_engine '.jst', JstProcessor, mime_type: 'application/javascript', silence_deprecation: true
-
1
register_engine '.eco', EcoProcessor, mime_type: 'application/javascript', silence_deprecation: true
-
1
register_engine '.ejs', EjsProcessor, mime_type: 'application/javascript', silence_deprecation: true
-
end
-
-
# CSS engines
-
1
require 'sprockets/sass_processor'
-
1
Deprecation.silence do
-
1
register_engine '.sass', SassProcessor, mime_type: 'text/css', silence_deprecation: true
-
1
register_engine '.scss', ScssProcessor, mime_type: 'text/css', silence_deprecation: true
-
end
-
1
register_bundle_metadata_reducer 'text/css', :sass_dependencies, Set.new, :+
-
-
# Other
-
1
require 'sprockets/erb_processor'
-
1
register_engine '.erb', ERBProcessor, mime_type: 'text/plain', silence_deprecation: true
-
-
1
register_dependency_resolver 'environment-version' do |env|
-
1
env.version
-
end
-
1
register_dependency_resolver 'environment-paths' do |env|
-
9
env.paths.map {|path| env.compress_from_root(path) }
-
end
-
1
register_dependency_resolver 'file-digest' do |env, str|
-
44
env.file_digest(env.parse_file_digest_uri(str))
-
end
-
1
register_dependency_resolver 'processors' do |env, str|
-
6
env.resolve_processors_cache_key_uri(str)
-
end
-
-
1
depend_on 'environment-version'
-
1
depend_on 'environment-paths'
-
end
-
-
1
require 'sprockets/legacy'
-
1
module Sprockets
-
1
module Autoload
-
1
autoload :Closure, 'sprockets/autoload/closure'
-
1
autoload :CoffeeScript, 'sprockets/autoload/coffee_script'
-
1
autoload :Eco, 'sprockets/autoload/eco'
-
1
autoload :EJS, 'sprockets/autoload/ejs'
-
1
autoload :Sass, 'sprockets/autoload/sass'
-
1
autoload :Uglifier, 'sprockets/autoload/uglifier'
-
1
autoload :YUI, 'sprockets/autoload/yui'
-
end
-
end
-
1
require 'coffee_script'
-
-
1
module Sprockets
-
1
module Autoload
-
1
CoffeeScript = ::CoffeeScript
-
end
-
end
-
1
require 'sass'
-
-
1
module Sprockets
-
1
module Autoload
-
1
Sass = ::Sass
-
end
-
end
-
1
require 'sprockets/asset'
-
1
require 'sprockets/bower'
-
1
require 'sprockets/cache'
-
1
require 'sprockets/configuration'
-
1
require 'sprockets/digest_utils'
-
1
require 'sprockets/errors'
-
1
require 'sprockets/loader'
-
1
require 'sprockets/path_digest_utils'
-
1
require 'sprockets/path_dependency_utils'
-
1
require 'sprockets/path_utils'
-
1
require 'sprockets/resolve'
-
1
require 'sprockets/server'
-
1
require 'sprockets/loader'
-
1
require 'sprockets/uri_tar'
-
-
1
module Sprockets
-
# `Base` class for `Environment` and `Cached`.
-
1
class Base
-
1
include PathUtils, PathDependencyUtils, PathDigestUtils, DigestUtils
-
1
include Configuration
-
1
include Server
-
1
include Resolve, Loader
-
1
include Bower
-
-
# Get persistent cache store
-
1
attr_reader :cache
-
-
# Set persistent cache store
-
#
-
# The cache store must implement a pair of getters and
-
# setters. Either `get(key)`/`set(key, value)`,
-
# `[key]`/`[key]=value`, `read(key)`/`write(key, value)`.
-
1
def cache=(cache)
-
2
@cache = Cache.new(cache, logger)
-
end
-
-
# Return an `Cached`. Must be implemented by the subclass.
-
1
def cached
-
raise NotImplementedError
-
end
-
1
alias_method :index, :cached
-
-
# Internal: Compute digest for path.
-
#
-
# path - String filename or directory path.
-
#
-
# Returns a String digest or nil.
-
1
def file_digest(path)
-
46
if stat = self.stat(path)
-
# Caveat: Digests are cached by the path's current mtime. Its possible
-
# for a files contents to have changed and its mtime to have been
-
# negligently reset thus appearing as if the file hasn't changed on
-
# disk. Also, the mtime is only read to the nearest second. It's
-
# also possible the file was updated more than once in a given second.
-
26
key = UnloadedAsset.new(path, self).file_digest_key(stat.mtime.to_i)
-
26
cache.fetch(key) do
-
self.stat_digest(path, stat)
-
end
-
end
-
end
-
-
# Find asset by logical path or expanded path.
-
1
def find_asset(path, options = {})
-
112
uri, _ = resolve(path, options.merge(compat: false))
-
112
if uri
-
112
load(uri)
-
end
-
end
-
-
1
def find_all_linked_assets(path, options = {})
-
2
return to_enum(__method__, path, options) unless block_given?
-
-
2
asset = find_asset(path, options)
-
2
return unless asset
-
-
2
yield asset
-
2
stack = asset.links.to_a
-
-
2
while uri = stack.shift
-
yield asset = load(uri)
-
stack = asset.links.to_a + stack
-
end
-
-
nil
-
end
-
-
# Preferred `find_asset` shorthand.
-
#
-
# environment['application.js']
-
#
-
1
def [](*args)
-
110
find_asset(*args)
-
end
-
-
# Pretty inspect
-
1
def inspect
-
"#<#{self.class}:0x#{object_id.to_s(16)} " +
-
"root=#{root.to_s.inspect}, " +
-
"paths=#{paths.inspect}>"
-
end
-
-
1
def compress_from_root(uri)
-
8
URITar.new(uri, self).compress
-
end
-
-
1
def expand_from_root(uri)
-
112
URITar.new(uri, self).expand
-
end
-
end
-
end
-
1
require 'json'
-
-
1
module Sprockets
-
1
module Bower
-
# Internal: All supported bower.json files.
-
#
-
# https://github.com/bower/json/blob/0.4.0/lib/json.js#L7
-
1
POSSIBLE_BOWER_JSONS = ['bower.json', 'component.json', '.bower.json']
-
-
# Internal: Override resolve_alternates to install bower.json behavior.
-
#
-
# load_path - String environment path
-
# logical_path - String path relative to base
-
#
-
# Returns candiate filenames.
-
1
def resolve_alternates(load_path, logical_path)
-
275
candidates, deps = super
-
-
# bower.json can only be nested one level deep
-
275
if !logical_path.index('/')
-
275
dirname = File.join(load_path, logical_path)
-
-
275
if directory?(dirname)
-
filenames = POSSIBLE_BOWER_JSONS.map { |basename| File.join(dirname, basename) }
-
filename = filenames.detect { |fn| self.file?(fn) }
-
-
if filename
-
deps << build_file_digest_uri(filename)
-
read_bower_main(dirname, filename) do |path|
-
candidates << path
-
end
-
end
-
end
-
end
-
-
275
return candidates, deps
-
end
-
-
# Internal: Read bower.json's main directive.
-
#
-
# dirname - String path to component directory.
-
# filename - String path to bower.json.
-
#
-
# Returns nothing.
-
1
def read_bower_main(dirname, filename)
-
bower = JSON.parse(File.read(filename), create_additions: false)
-
-
case bower['main']
-
when String
-
yield File.expand_path(bower['main'], dirname)
-
when Array
-
bower['main'].each do |name|
-
yield File.expand_path(name, dirname)
-
end
-
end
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'sprockets/utils'
-
-
1
module Sprockets
-
# Internal: Bundle processor takes a single file asset and prepends all the
-
# `:required` URIs to the contents.
-
#
-
# Uses pipeline metadata:
-
#
-
# :required - Ordered Set of asset URIs to prepend
-
# :stubbed - Set of asset URIs to substract from the required set.
-
#
-
# Also see DirectiveProcessor.
-
1
class Bundle
-
1
def self.call(input)
-
env = input[:environment]
-
type = input[:content_type]
-
dependencies = Set.new(input[:metadata][:dependencies])
-
-
processed_uri, deps = env.resolve(input[:filename], accept: type, pipeline: :self, compat: false)
-
dependencies.merge(deps)
-
-
find_required = proc { |uri| env.load(uri).metadata[:required] }
-
required = Utils.dfs(processed_uri, &find_required)
-
stubbed = Utils.dfs(env.load(processed_uri).metadata[:stubbed], &find_required)
-
required.subtract(stubbed)
-
assets = required.map { |uri| env.load(uri) }
-
-
(required + stubbed).each do |uri|
-
dependencies.merge(env.load(uri).metadata[:dependencies])
-
end
-
-
reducers = Hash[env.match_mime_type_keys(env.config[:bundle_reducers], type).flat_map(&:to_a)]
-
process_bundle_reducers(assets, reducers).merge(dependencies: dependencies, included: assets.map(&:uri))
-
end
-
-
# Internal: Run bundle reducers on set of Assets producing a reduced
-
# metadata Hash.
-
#
-
# assets - Array of Assets
-
# reducers - Array of [initial, reducer_proc] pairs
-
#
-
# Returns reduced asset metadata Hash.
-
1
def self.process_bundle_reducers(assets, reducers)
-
initial = {}
-
reducers.each do |k, (v, _)|
-
if v.respond_to?(:call)
-
initial[k] = v.call
-
elsif !v.nil?
-
initial[k] = v
-
end
-
end
-
-
assets.reduce(initial) do |h, asset|
-
reducers.each do |k, (_, block)|
-
value = k == :data ? asset.source : asset.metadata[k]
-
if h.key?(k)
-
if !value.nil?
-
h[k] = block.call(h[k], value)
-
end
-
else
-
h[k] = value
-
end
-
end
-
h
-
end
-
end
-
end
-
end
-
1
require 'logger'
-
1
require 'sprockets/digest_utils'
-
-
1
module Sprockets
-
# Public: Wrapper interface to backend cache stores. Ensures a consistent API
-
# even when the backend uses get/set or read/write.
-
#
-
# Public cache interface
-
#
-
# Always assign the backend store instance to Environment#cache=.
-
#
-
# environment.cache = Sprockets::Cache::MemoryStore.new(1000)
-
#
-
# Environment#cache will always return a wrapped Cache interface. See the
-
# methods marked public on this class.
-
#
-
#
-
# Backend cache interface
-
#
-
# The Backend cache store must implement two methods.
-
#
-
# get(key)
-
#
-
# key - An opaque String with a length less than 250 characters.
-
#
-
# Returns an JSON serializable object.
-
#
-
# set(key, value)
-
#
-
# Will only be called once per key. Setting a key "foo" with value "bar",
-
# then later key "foo" with value "baz" is an undefined behavior.
-
#
-
# key - An opaque String with a length less than 250 characters.
-
# value - A JSON serializable object.
-
#
-
# Returns argument value.
-
#
-
1
class Cache
-
# Builtin cache stores.
-
1
autoload :FileStore, 'sprockets/cache/file_store'
-
1
autoload :MemoryStore, 'sprockets/cache/memory_store'
-
1
autoload :NullStore, 'sprockets/cache/null_store'
-
-
# Internal: Cache key version for this class. Rarely should have to change
-
# unless the cache format radically changes. Will be bump on major version
-
# releases though.
-
1
VERSION = '3.0'
-
-
1
def self.default_logger
-
logger = Logger.new($stderr)
-
logger.level = Logger::FATAL
-
logger
-
end
-
-
# Internal: Wrap a backend cache store.
-
#
-
# Always assign a backend cache store instance to Environment#cache= and
-
# use Environment#cache to retreive a wrapped interface.
-
#
-
# cache - A compatible backend cache store instance.
-
1
def initialize(cache = nil, logger = self.class.default_logger)
-
2
@cache_wrapper = get_cache_wrapper(cache)
-
2
@fetch_cache = Cache::MemoryStore.new(1024)
-
2
@logger = logger
-
end
-
-
# Public: Prefer API to retrieve and set values in the cache store.
-
#
-
# key - JSON serializable key
-
# block -
-
# Must return a consistent JSON serializable object for the given key.
-
#
-
# Examples
-
#
-
# cache.fetch("foo") { "bar" }
-
#
-
# Returns a JSON serializable object.
-
1
def fetch(key)
-
26
start = Time.now.to_f
-
26
expanded_key = expand_key(key)
-
26
value = @fetch_cache.get(expanded_key)
-
26
if value.nil?
-
24
value = @cache_wrapper.get(expanded_key)
-
24
if value.nil?
-
value = yield
-
@cache_wrapper.set(expanded_key, value)
-
@logger.debug do
-
ms = "(#{((Time.now.to_f - start) * 1000).to_i}ms)"
-
"Sprockets Cache miss #{peek_key(key)} #{ms}"
-
end
-
end
-
24
@fetch_cache.set(expanded_key, value)
-
end
-
26
value
-
end
-
-
# Public: Low level API to retrieve item directly from the backend cache
-
# store.
-
#
-
# This API may be used publicly, but may have undefined behavior
-
# depending on the backend store being used. Prefer the
-
# Cache#fetch API over using this.
-
#
-
# key - JSON serializable key
-
# local - Check local cache first (default: false)
-
#
-
# Returns a JSON serializable object or nil if there was a cache miss.
-
1
def get(key, local = false)
-
6
expanded_key = expand_key(key)
-
-
6
if local && value = @fetch_cache.get(expanded_key)
-
return value
-
end
-
-
6
value = @cache_wrapper.get(expanded_key)
-
6
@fetch_cache.set(expanded_key, value) if local
-
-
6
value
-
end
-
-
# Public: Low level API to set item directly to the backend cache store.
-
#
-
# This API may be used publicly, but may have undefined behavior
-
# depending on the backend store being used. Prefer the
-
# Cache#fetch API over using this.
-
#
-
# key - JSON serializable key
-
# value - A consistent JSON serializable object for the given key. Setting
-
# a different value for the given key has undefined behavior.
-
# local - Set on local cache (default: false)
-
#
-
# Returns the value argument.
-
1
def set(key, value, local = false)
-
expanded_key = expand_key(key)
-
@fetch_cache.set(expanded_key, value) if local
-
@cache_wrapper.set(expanded_key, value)
-
end
-
-
# Public: Pretty inspect
-
#
-
# Returns String.
-
1
def inspect
-
"#<#{self.class} local=#{@fetch_cache.inspect} store=#{@cache_wrapper.cache.inspect}>"
-
end
-
-
1
private
-
# Internal: Expand object cache key into a short String key.
-
#
-
# The String should be under 250 characters so its compatible with
-
# Memcache.
-
#
-
# key - JSON serializable key
-
#
-
# Returns a String with a length less than 250 characters.
-
1
def expand_key(key)
-
32
digest_key = DigestUtils.pack_urlsafe_base64digest(DigestUtils.digest(key))
-
32
namespace = digest_key[0, 2]
-
32
"sprockets/v#{VERSION}/#{namespace}/#{digest_key}"
-
end
-
-
1
PEEK_SIZE = 100
-
-
# Internal: Show first 100 characters of cache key for logging purposes.
-
#
-
# Returns a String with a length less than 100 characters.
-
1
def peek_key(key)
-
case key
-
when Integer
-
key.to_s
-
when String
-
key[0, PEEK_SIZE].inspect
-
when Array
-
str = []
-
key.each { |k| str << peek_key(k) }
-
str.join(':')[0, PEEK_SIZE]
-
else
-
peek_key(DigestUtils.pack_urlsafe_base64digest(DigestUtils.digest(key)))
-
end
-
end
-
-
1
def get_cache_wrapper(cache)
-
2
if cache.is_a?(Cache)
-
cache
-
-
# `Cache#get(key)` for Memcache
-
2
elsif cache.respond_to?(:get)
-
2
GetWrapper.new(cache)
-
-
# `Cache#[key]` so `Hash` can be used
-
elsif cache.respond_to?(:[])
-
HashWrapper.new(cache)
-
-
# `Cache#read(key)` for `ActiveSupport::Cache` support
-
elsif cache.respond_to?(:read)
-
ReadWriteWrapper.new(cache)
-
-
else
-
cache = Sprockets::Cache::NullStore.new
-
GetWrapper.new(cache)
-
end
-
end
-
-
1
class Wrapper < Struct.new(:cache)
-
end
-
-
1
class GetWrapper < Wrapper
-
1
def get(key)
-
30
cache.get(key)
-
end
-
-
1
def set(key, value)
-
cache.set(key, value)
-
end
-
end
-
-
1
class HashWrapper < Wrapper
-
1
def get(key)
-
cache[key]
-
end
-
-
1
def set(key, value)
-
cache[key] = value
-
end
-
end
-
-
1
class ReadWriteWrapper < Wrapper
-
1
def get(key)
-
cache.read(key)
-
end
-
-
1
def set(key, value)
-
cache.write(key, value)
-
end
-
end
-
end
-
end
-
1
require 'fileutils'
-
1
require 'logger'
-
1
require 'sprockets/encoding_utils'
-
1
require 'sprockets/path_utils'
-
1
require 'zlib'
-
-
1
module Sprockets
-
1
class Cache
-
# Public: A file system cache store that automatically cleans up old keys.
-
#
-
# Assign the instance to the Environment#cache.
-
#
-
# environment.cache = Sprockets::Cache::FileStore.new("/tmp")
-
#
-
# See Also
-
#
-
# ActiveSupport::Cache::FileStore
-
#
-
1
class FileStore
-
# Internal: Default key limit for store.
-
1
DEFAULT_MAX_SIZE = 25 * 1024 * 1024
-
-
# Internal: Default standard error fatal logger.
-
#
-
# Returns a Logger.
-
1
def self.default_logger
-
logger = Logger.new($stderr)
-
logger.level = Logger::FATAL
-
logger
-
end
-
-
# Public: Initialize the cache store.
-
#
-
# root - A String path to a directory to persist cached values to.
-
# max_size - A Integer of the maximum number of keys the store will hold.
-
# (default: 1000).
-
1
def initialize(root, max_size = DEFAULT_MAX_SIZE, logger = self.class.default_logger)
-
1
@root = root
-
1
@max_size = max_size
-
1
@gc_size = max_size * 0.75
-
1
@logger = logger
-
end
-
-
# Public: Retrieve value from cache.
-
#
-
# This API should not be used directly, but via the Cache wrapper API.
-
#
-
# key - String cache key.
-
#
-
# Returns Object or nil or the value is not set.
-
1
def get(key)
-
30
path = File.join(@root, "#{key}.cache")
-
-
30
value = safe_open(path) do |f|
-
30
begin
-
30
EncodingUtils.unmarshaled_deflated(f.read, Zlib::MAX_WBITS)
-
rescue Exception => e
-
@logger.error do
-
"#{self.class}[#{path}] could not be unmarshaled: " +
-
"#{e.class}: #{e.message}"
-
end
-
nil
-
end
-
end
-
-
30
if value
-
30
FileUtils.touch(path)
-
30
value
-
end
-
end
-
-
# Public: Set a key and value in the cache.
-
#
-
# This API should not be used directly, but via the Cache wrapper API.
-
#
-
# key - String cache key.
-
# value - Object value.
-
#
-
# Returns Object value.
-
1
def set(key, value)
-
path = File.join(@root, "#{key}.cache")
-
-
# Ensure directory exists
-
FileUtils.mkdir_p File.dirname(path)
-
-
# Check if cache exists before writing
-
exists = File.exist?(path)
-
-
# Serialize value
-
marshaled = Marshal.dump(value)
-
-
# Compress if larger than 4KB
-
if marshaled.bytesize > 4 * 1024
-
deflater = Zlib::Deflate.new(
-
Zlib::BEST_COMPRESSION,
-
Zlib::MAX_WBITS,
-
Zlib::MAX_MEM_LEVEL,
-
Zlib::DEFAULT_STRATEGY
-
)
-
deflater << marshaled
-
raw = deflater.finish
-
else
-
raw = marshaled
-
end
-
-
# Write data
-
PathUtils.atomic_write(path) do |f|
-
f.write(raw)
-
@size = size + f.size unless exists
-
end
-
-
# GC if necessary
-
gc! if size > @max_size
-
-
value
-
end
-
-
# Public: Pretty inspect
-
#
-
# Returns String.
-
1
def inspect
-
"#<#{self.class} size=#{size}/#{@max_size}>"
-
end
-
-
1
private
-
# Internal: Get all cache files along with stats.
-
#
-
# Returns an Array of [String filename, File::Stat] pairs sorted by
-
# mtime.
-
1
def find_caches
-
Dir.glob(File.join(@root, '**/*.cache')).reduce([]) { |stats, filename|
-
stat = safe_stat(filename)
-
# stat maybe nil if file was removed between the time we called
-
# dir.glob and the next stat
-
stats << [filename, stat] if stat
-
stats
-
}.sort_by { |_, stat| stat.mtime.to_i }
-
end
-
-
1
def size
-
@size ||= compute_size(find_caches)
-
end
-
-
1
def compute_size(caches)
-
caches.inject(0) { |sum, (_, stat)| sum + stat.size }
-
end
-
-
1
def safe_stat(fn)
-
File.stat(fn)
-
rescue Errno::ENOENT
-
nil
-
end
-
-
1
def safe_open(path, &block)
-
30
if File.exist?(path)
-
30
File.open(path, 'rb', &block)
-
end
-
rescue Errno::ENOENT
-
end
-
-
1
def gc!
-
start_time = Time.now
-
-
caches = find_caches
-
size = compute_size(caches)
-
-
delete_caches, keep_caches = caches.partition { |filename, stat|
-
deleted = size > @gc_size
-
size -= stat.size
-
deleted
-
}
-
-
return if delete_caches.empty?
-
-
FileUtils.remove(delete_caches.map(&:first), force: true)
-
@size = compute_size(keep_caches)
-
-
@logger.warn do
-
secs = Time.now.to_f - start_time.to_f
-
"#{self.class}[#{@root}] garbage collected " +
-
"#{delete_caches.size} files (#{(secs * 1000).to_i}ms)"
-
end
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
1
class Cache
-
# Public: Basic in memory LRU cache.
-
#
-
# Assign the instance to the Environment#cache.
-
#
-
# environment.cache = Sprockets::Cache::MemoryStore.new(1000)
-
#
-
# See Also
-
#
-
# ActiveSupport::Cache::MemoryStore
-
#
-
1
class MemoryStore
-
# Internal: Default key limit for store.
-
1
DEFAULT_MAX_SIZE = 1000
-
-
# Public: Initialize the cache store.
-
#
-
# max_size - A Integer of the maximum number of keys the store will hold.
-
# (default: 1000).
-
1
def initialize(max_size = DEFAULT_MAX_SIZE)
-
3
@max_size = max_size
-
3
@cache = {}
-
end
-
-
# Public: Retrieve value from cache.
-
#
-
# This API should not be used directly, but via the Cache wrapper API.
-
#
-
# key - String cache key.
-
#
-
# Returns Object or nil or the value is not set.
-
1
def get(key)
-
30
exists = true
-
58
value = @cache.delete(key) { exists = false }
-
30
if exists
-
2
@cache[key] = value
-
else
-
nil
-
end
-
end
-
-
# Public: Set a key and value in the cache.
-
#
-
# This API should not be used directly, but via the Cache wrapper API.
-
#
-
# key - String cache key.
-
# value - Object value.
-
#
-
# Returns Object value.
-
1
def set(key, value)
-
28
@cache.delete(key)
-
28
@cache[key] = value
-
28
@cache.shift if @cache.size > @max_size
-
28
value
-
end
-
-
# Public: Pretty inspect
-
#
-
# Returns String.
-
1
def inspect
-
"#<#{self.class} size=#{@cache.size}/#{@max_size}>"
-
end
-
end
-
end
-
end
-
1
require 'sprockets/base'
-
-
1
module Sprockets
-
# `Cached` is a special cached version of `Environment`.
-
#
-
# The expection is that all of its file system methods are cached
-
# for the instances lifetime. This makes `Cached` much faster. This
-
# behavior is ideal in production environments where the file system
-
# is immutable.
-
#
-
# `Cached` should not be initialized directly. Instead use
-
# `Environment#cached`.
-
1
class CachedEnvironment < Base
-
1
def initialize(environment)
-
1
initialize_configuration(environment)
-
-
1
@cache = environment.cache
-
57
@stats = Hash.new { |h, k| h[k] = _stat(k) }
-
9
@entries = Hash.new { |h, k| h[k] = _entries(k) }
-
3
@uris = Hash.new { |h, k| h[k] = _load(k) }
-
-
8
@processor_cache_keys = Hash.new { |h, k| h[k] = _processor_cache_key(k) }
-
54
@resolved_dependencies = Hash.new { |h, k| h[k] = _resolve_dependency(k) }
-
end
-
-
# No-op return self as cached environment.
-
1
def cached
-
111
self
-
end
-
1
alias_method :index, :cached
-
-
# Internal: Cache Environment#entries
-
1
alias_method :_entries, :entries
-
1
def entries(path)
-
283
@entries[path]
-
end
-
-
# Internal: Cache Environment#stat
-
1
alias_method :_stat, :stat
-
1
def stat(path)
-
788
@stats[path]
-
end
-
-
# Internal: Cache Environment#load
-
1
alias_method :_load, :load
-
1
def load(uri)
-
112
@uris[uri]
-
end
-
-
# Internal: Cache Environment#processor_cache_key
-
1
alias_method :_processor_cache_key, :processor_cache_key
-
1
def processor_cache_key(str)
-
13
@processor_cache_keys[str]
-
end
-
-
# Internal: Cache Environment#resolve_dependency
-
1
alias_method :_resolve_dependency, :resolve_dependency
-
1
def resolve_dependency(str)
-
57
@resolved_dependencies[str]
-
end
-
-
1
private
-
# Cache is immutable, any methods that try to change the runtime config
-
# should bomb.
-
1
def config=(config)
-
raise RuntimeError, "can't modify immutable cached environment"
-
end
-
end
-
end
-
1
require 'sprockets/autoload'
-
1
require 'sprockets/digest_utils'
-
-
1
module Sprockets
-
# Public: Closure Compiler minifier.
-
#
-
# To accept the default options
-
#
-
# environment.register_bundle_processor 'application/javascript',
-
# Sprockets::ClosureCompressor
-
#
-
# Or to pass options to the Closure::Compiler class.
-
#
-
# environment.register_bundle_processor 'application/javascript',
-
# Sprockets::ClosureCompressor.new({ ... })
-
#
-
1
class ClosureCompressor
-
1
VERSION = '1'
-
-
# Public: Return singleton instance with default options.
-
#
-
# Returns ClosureCompressor object.
-
1
def self.instance
-
@instance ||= new
-
end
-
-
1
def self.call(input)
-
instance.call(input)
-
end
-
-
1
def self.cache_key
-
instance.cache_key
-
end
-
-
1
attr_reader :cache_key
-
-
1
def initialize(options = {})
-
@options = options
-
@cache_key = "#{self.class.name}:#{Autoload::Closure::VERSION}:#{Autoload::Closure::COMPILER_VERSION}:#{VERSION}:#{DigestUtils.digest(options)}".freeze
-
end
-
-
1
def call(input)
-
@compiler ||= Autoload::Closure::Compiler.new(@options)
-
@compiler.compile(input[:data])
-
end
-
end
-
end
-
1
require 'sprockets/autoload'
-
-
1
module Sprockets
-
# Processor engine class for the CoffeeScript compiler.
-
# Depends on the `coffee-script` and `coffee-script-source` gems.
-
#
-
# For more infomation see:
-
#
-
# https://github.com/josh/ruby-coffee-script
-
#
-
1
module CoffeeScriptProcessor
-
1
VERSION = '1'
-
-
1
def self.cache_key
-
1
@cache_key ||= "#{name}:#{Autoload::CoffeeScript::Source.version}:#{VERSION}".freeze
-
end
-
-
1
def self.call(input)
-
data = input[:data]
-
input[:cache].fetch([self.cache_key, data]) do
-
Autoload::CoffeeScript.compile(data)
-
end
-
end
-
end
-
end
-
1
require 'sprockets/utils'
-
-
1
module Sprockets
-
# `Compressing` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `CachedEnvironment` classes.
-
1
module Compressing
-
1
include Utils
-
-
1
def compressors
-
config[:compressors]
-
end
-
-
1
def register_compressor(mime_type, sym, klass)
-
7
self.config = hash_reassoc(config, :compressors, mime_type) do |compressors|
-
7
compressors[sym] = klass
-
7
compressors
-
end
-
end
-
-
# Return CSS compressor or nil if none is set
-
1
def css_compressor
-
if defined? @css_compressor
-
@css_compressor
-
end
-
end
-
-
# Assign a compressor to run on `text/css` assets.
-
#
-
# The compressor object must respond to `compress`.
-
1
def css_compressor=(compressor)
-
1
unregister_bundle_processor 'text/css', @css_compressor if defined? @css_compressor
-
1
@css_compressor = nil
-
1
return unless compressor
-
-
1
if compressor.is_a?(Symbol)
-
1
@css_compressor = klass = config[:compressors]['text/css'][compressor] || raise(Error, "unknown compressor: #{compressor}")
-
elsif compressor.respond_to?(:compress)
-
klass = LegacyProcProcessor.new(:css_compressor, proc { |context, data| compressor.compress(data) })
-
@css_compressor = :css_compressor
-
else
-
@css_compressor = klass = compressor
-
end
-
-
1
register_bundle_processor 'text/css', klass
-
end
-
-
# Return JS compressor or nil if none is set
-
1
def js_compressor
-
if defined? @js_compressor
-
@js_compressor
-
end
-
end
-
-
# Assign a compressor to run on `application/javascript` assets.
-
#
-
# The compressor object must respond to `compress`.
-
1
def js_compressor=(compressor)
-
1
unregister_bundle_processor 'application/javascript', @js_compressor if defined? @js_compressor
-
1
@js_compressor = nil
-
1
return unless compressor
-
-
if compressor.is_a?(Symbol)
-
@js_compressor = klass = config[:compressors]['application/javascript'][compressor] || raise(Error, "unknown compressor: #{compressor}")
-
elsif compressor.respond_to?(:compress)
-
klass = LegacyProcProcessor.new(:js_compressor, proc { |context, data| compressor.compress(data) })
-
@js_compressor = :js_compressor
-
else
-
@js_compressor = klass = compressor
-
end
-
-
register_bundle_processor 'application/javascript', klass
-
end
-
-
# Public: Checks if Gzip is enabled.
-
1
def gzip?
-
config[:gzip_enabled]
-
end
-
-
# Public: Checks if Gzip is disabled.
-
1
def skip_gzip?
-
!gzip?
-
end
-
-
# Public: Enable or disable the creation of Gzip files.
-
#
-
# Defaults to true.
-
#
-
# environment.gzip = false
-
#
-
1
def gzip=(gzip)
-
1
self.config = config.merge(gzip_enabled: gzip).freeze
-
end
-
end
-
end
-
1
require 'sprockets/compressing'
-
1
require 'sprockets/dependencies'
-
1
require 'sprockets/engines'
-
1
require 'sprockets/mime'
-
1
require 'sprockets/paths'
-
1
require 'sprockets/processing'
-
1
require 'sprockets/transformers'
-
1
require 'sprockets/utils'
-
-
1
module Sprockets
-
1
module Configuration
-
1
include Paths, Mime, Engines, Transformers, Processing, Compressing, Dependencies, Utils
-
-
1
def initialize_configuration(parent)
-
2
@config = parent.config
-
2
@computed_config = parent.computed_config
-
2
@logger = parent.logger
-
2
@context_class = Class.new(parent.context_class)
-
end
-
-
1
attr_reader :config
-
-
1
attr_accessor :computed_config
-
-
1
def config=(config)
-
131
raise TypeError, "can't assign mutable config" unless config.frozen?
-
131
@config = config
-
end
-
-
# Get and set `Logger` instance.
-
1
attr_accessor :logger
-
-
# The `Environment#version` is a custom value used for manually
-
# expiring all asset caches.
-
#
-
# Sprockets is able to track most file and directory changes and
-
# will take care of expiring the cache for you. However, its
-
# impossible to know when any custom helpers change that you mix
-
# into the `Context`.
-
#
-
# It would be wise to increment this value anytime you make a
-
# configuration change to the `Environment` object.
-
1
def version
-
1
config[:version]
-
end
-
-
# Assign an environment version.
-
#
-
# environment.version = '2.0'
-
#
-
1
def version=(version)
-
2
self.config = hash_reassoc(config, :version) { version.dup }
-
end
-
-
# Public: Returns a `Digest` implementation class.
-
#
-
# Defaults to `Digest::SHA256`.
-
1
def digest_class
-
config[:digest_class]
-
end
-
-
# Deprecated: Assign a `Digest` implementation class. This maybe any Ruby
-
# `Digest::` implementation such as `Digest::SHA256` or
-
# `Digest::MD5`.
-
#
-
# environment.digest_class = Digest::MD5
-
#
-
1
def digest_class=(klass)
-
self.config = config.merge(digest_class: klass).freeze
-
end
-
-
# Deprecated: Get `Context` class.
-
#
-
# This class maybe mutated and mixed in with custom helpers.
-
#
-
# environment.context_class.instance_eval do
-
# include MyHelpers
-
# def asset_url; end
-
# end
-
#
-
1
attr_reader :context_class
-
end
-
end
-
1
require 'pathname'
-
1
require 'rack/utils'
-
1
require 'set'
-
1
require 'sprockets/errors'
-
-
1
module Sprockets
-
# Deprecated: `Context` provides helper methods to all processors.
-
# They are typically accessed by ERB templates. You can mix in custom helpers
-
# by injecting them into `Environment#context_class`. Do not mix them into
-
# `Context` directly.
-
#
-
# environment.context_class.class_eval do
-
# include MyHelper
-
# def asset_url; end
-
# end
-
#
-
# <%= asset_url "foo.png" %>
-
#
-
# The `Context` also collects dependencies declared by
-
# assets. See `DirectiveProcessor` for an example of this.
-
1
class Context
-
1
attr_reader :environment, :filename, :pathname
-
-
# Deprecated
-
1
attr_accessor :__LINE__
-
-
1
def initialize(input)
-
@environment = input[:environment]
-
@metadata = input[:metadata]
-
@load_path = input[:load_path]
-
@logical_path = input[:name]
-
@filename = input[:filename]
-
@dirname = File.dirname(@filename)
-
@pathname = Pathname.new(@filename)
-
@content_type = input[:content_type]
-
-
@required = Set.new(@metadata[:required])
-
@stubbed = Set.new(@metadata[:stubbed])
-
@links = Set.new(@metadata[:links])
-
@dependencies = Set.new(input[:metadata][:dependencies])
-
end
-
-
1
def metadata
-
{ required: @required,
-
stubbed: @stubbed,
-
links: @links,
-
dependencies: @dependencies }
-
end
-
-
# Returns the environment path that contains the file.
-
#
-
# If `app/javascripts` and `app/stylesheets` are in your path, and
-
# current file is `app/javascripts/foo/bar.js`, `load_path` would
-
# return `app/javascripts`.
-
1
attr_reader :load_path
-
1
alias_method :root_path, :load_path
-
-
# Returns logical path without any file extensions.
-
#
-
# 'app/javascripts/application.js'
-
# # => 'application'
-
#
-
1
attr_reader :logical_path
-
-
# Returns content type of file
-
#
-
# 'application/javascript'
-
# 'text/css'
-
#
-
1
attr_reader :content_type
-
-
# Public: Given a logical path, `resolve` will find and return an Asset URI.
-
# Relative paths will also be resolved. An accept type maybe given to
-
# restrict the search.
-
#
-
# resolve("foo.js")
-
# # => "file:///path/to/app/javascripts/foo.js?type=application/javascript"
-
#
-
# resolve("./bar.js")
-
# # => "file:///path/to/app/javascripts/bar.js?type=application/javascript"
-
#
-
# path - String logical or absolute path
-
# options
-
# accept - String content accept type
-
#
-
# Returns an Asset URI String.
-
1
def resolve(path, options = {})
-
uri, deps = environment.resolve!(path, options.merge(base_path: @dirname))
-
@dependencies.merge(deps)
-
uri
-
end
-
-
# Public: Load Asset by AssetURI and track it as a dependency.
-
#
-
# uri - AssetURI
-
#
-
# Returns Asset.
-
1
def load(uri)
-
asset = environment.load(uri)
-
@dependencies.merge(asset.metadata[:dependencies])
-
asset
-
end
-
-
# `depend_on` allows you to state a dependency on a file without
-
# including it.
-
#
-
# This is used for caching purposes. Any changes made to
-
# the dependency file with invalidate the cache of the
-
# source file.
-
1
def depend_on(path)
-
path = path.to_s if path.is_a?(Pathname)
-
-
if environment.absolute_path?(path) && environment.stat(path)
-
@dependencies << environment.build_file_digest_uri(path)
-
else
-
resolve(path, compat: false)
-
end
-
nil
-
end
-
-
# `depend_on_asset` allows you to state an asset dependency
-
# without including it.
-
#
-
# This is used for caching purposes. Any changes that would
-
# invalidate the dependency asset will invalidate the source
-
# file. Unlike `depend_on`, this will include recursively include
-
# the target asset's dependencies.
-
1
def depend_on_asset(path)
-
load(resolve(path, compat: false))
-
end
-
-
# `require_asset` declares `path` as a dependency of the file. The
-
# dependency will be inserted before the file and will only be
-
# included once.
-
#
-
# If ERB processing is enabled, you can use it to dynamically
-
# require assets.
-
#
-
# <%= require_asset "#{framework}.js" %>
-
#
-
1
def require_asset(path)
-
@required << resolve(path, accept: @content_type, pipeline: :self, compat: false)
-
nil
-
end
-
-
# `stub_asset` blacklists `path` from being included in the bundle.
-
# `path` must be an asset which may or may not already be included
-
# in the bundle.
-
1
def stub_asset(path)
-
@stubbed << resolve(path, accept: @content_type, pipeline: :self, compat: false)
-
nil
-
end
-
-
# `link_asset` declares an external dependency on an asset without directly
-
# including it. The target asset is returned from this function making it
-
# easy to construct a link to it.
-
#
-
# Returns an Asset or nil.
-
1
def link_asset(path)
-
asset = depend_on_asset(path)
-
@links << asset.uri
-
asset
-
end
-
-
# Returns a Base64-encoded `data:` URI with the contents of the
-
# asset at the specified path, and marks that path as a dependency
-
# of the current file.
-
#
-
# Use `asset_data_uri` from ERB with CSS or JavaScript assets:
-
#
-
# #logo { background: url(<%= asset_data_uri 'logo.png' %>) }
-
#
-
# $('<img>').attr('src', '<%= asset_data_uri 'avatar.jpg' %>')
-
#
-
1
def asset_data_uri(path)
-
asset = depend_on_asset(path)
-
data = EncodingUtils.base64(asset.source)
-
"data:#{asset.content_type};base64,#{Rack::Utils.escape(data)}"
-
end
-
-
# Expands logical path to full url to asset.
-
#
-
# NOTE: This helper is currently not implemented and should be
-
# customized by the application. Though, in the future, some
-
# basics implemention may be provided with different methods that
-
# are required to be overridden.
-
1
def asset_path(path, options = {})
-
message = <<-EOS
-
Custom asset_path helper is not implemented
-
-
Extend your environment context with a custom method.
-
-
environment.context_class.class_eval do
-
def asset_path(path, options = {})
-
end
-
end
-
EOS
-
raise NotImplementedError, message
-
end
-
-
# Expand logical image asset path.
-
1
def image_path(path)
-
asset_path(path, type: :image)
-
end
-
-
# Expand logical video asset path.
-
1
def video_path(path)
-
asset_path(path, type: :video)
-
end
-
-
# Expand logical audio asset path.
-
1
def audio_path(path)
-
asset_path(path, type: :audio)
-
end
-
-
# Expand logical font asset path.
-
1
def font_path(path)
-
asset_path(path, type: :font)
-
end
-
-
# Expand logical javascript asset path.
-
1
def javascript_path(path)
-
asset_path(path, type: :javascript)
-
end
-
-
# Expand logical stylesheet asset path.
-
1
def stylesheet_path(path)
-
asset_path(path, type: :stylesheet)
-
end
-
end
-
end
-
1
require 'sprockets/digest_utils'
-
1
require 'sprockets/path_digest_utils'
-
1
require 'sprockets/uri_utils'
-
-
1
module Sprockets
-
# `Dependencies` is an internal mixin whose public methods are exposed on the
-
# `Environment` and `CachedEnvironment` classes.
-
1
module Dependencies
-
1
include DigestUtils, PathDigestUtils, URIUtils
-
-
# Public: Mapping dependency schemes to resolver functions.
-
#
-
# key - String scheme
-
# value - Proc.call(Environment, String)
-
#
-
# Returns Hash.
-
1
def dependency_resolvers
-
config[:dependency_resolvers]
-
end
-
-
# Public: Default set of dependency URIs for assets.
-
#
-
# Returns Set of String URIs.
-
1
def dependencies
-
config[:dependencies]
-
end
-
-
# Public: Register new dependency URI resolver.
-
#
-
# scheme - String scheme
-
# block -
-
# environment - Environment
-
# uri - String dependency URI
-
#
-
# Returns nothing.
-
1
def register_dependency_resolver(scheme, &block)
-
6
self.config = hash_reassoc(config, :dependency_resolvers) do |hash|
-
6
hash.merge(scheme => block)
-
end
-
end
-
-
# Public: Add environmental dependency inheirted by all assets.
-
#
-
# uri - String dependency URI
-
#
-
# Returns nothing.
-
1
def add_dependency(uri)
-
3
self.config = hash_reassoc(config, :dependencies) do |set|
-
3
set + Set.new([uri])
-
end
-
end
-
1
alias_method :depend_on, :add_dependency
-
-
# Internal: Resolve dependency URIs.
-
#
-
# Returns resolved Object.
-
1
def resolve_dependency(str)
-
# Optimize for the most common scheme to
-
# save 22k allocations on an average Spree app.
-
53
scheme = if str.start_with?('file-digest:'.freeze)
-
44
'file-digest'.freeze
-
else
-
9
str[/([^:]+)/, 1]
-
end
-
-
53
if resolver = config[:dependency_resolvers][scheme]
-
53
resolver.call(self, str)
-
else
-
nil
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
1
class Deprecation
-
1
THREAD_LOCAL__SILENCE_KEY = "_sprockets_deprecation_silence".freeze
-
1
DEFAULT_BEHAVIORS = {
-
raise: ->(message, callstack) {
-
e = DeprecationException.new(message)
-
e.set_backtrace(callstack.map(&:to_s))
-
raise e
-
},
-
-
stderr: ->(message, callstack) {
-
$stderr.puts(message)
-
},
-
}
-
-
1
attr_reader :callstack
-
-
1
def self.silence(&block)
-
3
Thread.current[THREAD_LOCAL__SILENCE_KEY] = true
-
3
block.call
-
ensure
-
3
Thread.current[THREAD_LOCAL__SILENCE_KEY] = false
-
end
-
-
1
def initialize(callstack = nil)
-
@callstack = callstack || caller(2)
-
end
-
-
1
def warn(message)
-
return if Thread.current[THREAD_LOCAL__SILENCE_KEY]
-
deprecation_message(message).tap do |m|
-
behavior.each { |b| b.call(m, callstack) }
-
end
-
end
-
-
1
private
-
1
def behavior
-
@behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
-
end
-
-
1
def behavior=(behavior)
-
@behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
-
end
-
-
1
def deprecation_message(message = nil)
-
message ||= "You are using deprecated behavior which will be removed from the next major or minor release."
-
"DEPRECATION WARNING: #{message} #{ deprecation_caller_message }"
-
end
-
-
1
def deprecation_caller_message
-
file, line, method = extract_callstack
-
if file
-
if line && method
-
"(called from #{method} at #{file}:#{line})"
-
else
-
"(called from #{file}:#{line})"
-
end
-
end
-
end
-
-
1
SPROCKETS_GEM_ROOT = File.expand_path("../../../../..", __FILE__) + "/"
-
-
1
def ignored_callstack(path)
-
path.start_with?(SPROCKETS_GEM_ROOT) || path.start_with?(RbConfig::CONFIG['rubylibdir'])
-
end
-
-
1
def extract_callstack
-
return _extract_callstack if callstack.first.is_a? String
-
-
offending_line = callstack.find { |frame|
-
frame.absolute_path && !ignored_callstack(frame.absolute_path)
-
} || callstack.first
-
-
[offending_line.path, offending_line.lineno, offending_line.label]
-
end
-
-
1
def _extract_callstack
-
offending_line = callstack.find { |line| !ignored_callstack(line) } || callstack.first
-
-
if offending_line
-
if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
-
md.captures
-
else
-
offending_line
-
end
-
end
-
end
-
end
-
1
private_constant :Deprecation
-
end
-
1
require 'digest/md5'
-
1
require 'digest/sha1'
-
1
require 'digest/sha2'
-
1
require 'set'
-
-
1
module Sprockets
-
# Internal: Hash functions and digest related utilities. Mixed into
-
# Environment.
-
1
module DigestUtils
-
1
extend self
-
-
# Internal: Default digest class.
-
#
-
# Returns a Digest::Base subclass.
-
1
def digest_class
-
35
Digest::SHA256
-
end
-
-
# Internal: Maps digest bytesize to the digest class.
-
1
DIGEST_SIZES = {
-
16 => Digest::MD5,
-
20 => Digest::SHA1,
-
32 => Digest::SHA256,
-
48 => Digest::SHA384,
-
64 => Digest::SHA512
-
}
-
-
# Internal: Detect digest class hash algorithm for digest bytes.
-
#
-
# While not elegant, all the supported digests have a unique bytesize.
-
#
-
# Returns Digest::Base or nil.
-
1
def detect_digest_class(bytes)
-
DIGEST_SIZES[bytes.bytesize]
-
end
-
-
1
ADD_VALUE_TO_DIGEST = {
-
79
String => ->(val, digest) { digest << val },
-
FalseClass => ->(val, digest) { digest << 'FalseClass'.freeze },
-
TrueClass => ->(val, digest) { digest << 'TrueClass'.freeze },
-
31
NilClass => ->(val, digest) { digest << 'NilClass'.freeze },
-
-
Symbol => ->(val, digest) {
-
digest << 'Symbol'.freeze
-
digest << val.to_s
-
},
-
Integer => ->(val, digest) {
-
digest << 'Integer'.freeze
-
digest << val.to_s
-
},
-
Array => ->(val, digest) {
-
10
digest << 'Array'.freeze
-
10
val.each do |element|
-
86
ADD_VALUE_TO_DIGEST[element.class].call(element, digest)
-
end
-
},
-
Hash => ->(val, digest) {
-
1
digest << 'Hash'.freeze
-
1
val.sort.each do |array|
-
ADD_VALUE_TO_DIGEST[Array].call(array, digest)
-
end
-
},
-
Set => ->(val, digest) {
-
digest << 'Set'.freeze
-
ADD_VALUE_TO_DIGEST[Array].call(val.to_a, digest)
-
},
-
Encoding => ->(val, digest) {
-
digest << 'Encoding'.freeze
-
digest << val.name
-
},
-
}
-
1
if 0.class != Integer # Ruby < 2.4
-
1
ADD_VALUE_TO_DIGEST[Fixnum] = ->(val, digest) {
-
digest << 'Integer'.freeze
-
digest << val.to_s
-
}
-
1
ADD_VALUE_TO_DIGEST[Bignum] = ->(val, digest) {
-
digest << 'Integer'.freeze
-
digest << val.to_s
-
}
-
end
-
1
ADD_VALUE_TO_DIGEST.default_proc = ->(_, val) {
-
raise TypeError, "couldn't digest #{ val }"
-
}
-
1
private_constant :ADD_VALUE_TO_DIGEST
-
-
# Internal: Generate a hexdigest for a nested JSON serializable object.
-
#
-
# This is used for generating cache keys, so its pretty important its
-
# wicked fast. Microbenchmarks away!
-
#
-
# obj - A JSON serializable object.
-
#
-
# Returns a String digest of the object.
-
1
def digest(obj)
-
35
digest = digest_class.new
-
-
35
ADD_VALUE_TO_DIGEST[obj.class].call(obj, digest)
-
35
digest.digest
-
end
-
-
# Internal: Pack a binary digest to a hex encoded string.
-
#
-
# bin - String bytes
-
#
-
# Returns hex String.
-
1
def pack_hexdigest(bin)
-
110
bin.unpack('H*').first
-
end
-
-
# Internal: Unpack a hex encoded digest string into binary bytes.
-
#
-
# hex - String hex
-
#
-
# Returns binary String.
-
1
def unpack_hexdigest(hex)
-
[hex].pack('H*')
-
end
-
-
# Internal: Pack a binary digest to a base64 encoded string.
-
#
-
# bin - String bytes
-
#
-
# Returns base64 String.
-
1
def pack_base64digest(bin)
-
32
[bin].pack('m0')
-
end
-
-
# Internal: Pack a binary digest to a urlsafe base64 encoded string.
-
#
-
# bin - String bytes
-
#
-
# Returns urlsafe base64 String.
-
1
def pack_urlsafe_base64digest(bin)
-
32
str = pack_base64digest(bin)
-
32
str.tr!('+/'.freeze, '-_'.freeze)
-
32
str.tr!('='.freeze, ''.freeze)
-
32
str
-
end
-
-
# Internal: Maps digest class to the CSP hash algorithm name.
-
1
HASH_ALGORITHMS = {
-
Digest::SHA256 => 'sha256'.freeze,
-
Digest::SHA384 => 'sha384'.freeze,
-
Digest::SHA512 => 'sha512'.freeze
-
}
-
-
# Public: Generate hash for use in the `integrity` attribute of an asset tag
-
# as per the subresource integrity specification.
-
#
-
# digest - The String byte digest of the asset content.
-
#
-
# Returns a String or nil if hash algorithm is incompatible.
-
1
def integrity_uri(digest)
-
case digest
-
when Digest::Base
-
digest_class = digest.class
-
digest = digest.digest
-
when String
-
digest_class = DIGEST_SIZES[digest.bytesize]
-
else
-
raise TypeError, "unknown digest: #{digest.inspect}"
-
end
-
-
if hash_name = HASH_ALGORITHMS[digest_class]
-
"#{hash_name}-#{pack_base64digest(digest)}"
-
end
-
end
-
-
# Public: Generate hash for use in the `integrity` attribute of an asset tag
-
# as per the subresource integrity specification.
-
#
-
# digest - The String hexbyte digest of the asset content.
-
#
-
# Returns a String or nil if hash algorithm is incompatible.
-
1
def hexdigest_integrity_uri(hexdigest)
-
integrity_uri(unpack_hexdigest(hexdigest))
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'shellwords'
-
-
1
module Sprockets
-
# The `DirectiveProcessor` is responsible for parsing and evaluating
-
# directive comments in a source file.
-
#
-
# A directive comment starts with a comment prefix, followed by an "=",
-
# then the directive name, then any arguments.
-
#
-
# // JavaScript
-
# //= require "foo"
-
#
-
# # CoffeeScript
-
# #= require "bar"
-
#
-
# /* CSS
-
# *= require "baz"
-
# */
-
#
-
# This makes it possible to disable or modify the processor to do whatever
-
# you'd like. You could add your own custom directives or invent your own
-
# directive syntax.
-
#
-
# `Environment#processors` includes `DirectiveProcessor` by default.
-
#
-
# To remove the processor entirely:
-
#
-
# env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
-
# env.unregister_processor('application/javascript', Sprockets::DirectiveProcessor)
-
#
-
# Then inject your own preprocessor:
-
#
-
# env.register_processor('text/css', MyProcessor)
-
#
-
1
class DirectiveProcessor
-
1
VERSION = '1'
-
-
# Directives are denoted by a `=` followed by the name, then
-
# argument list.
-
#
-
# A few different styles are allowed:
-
#
-
# // =require foo
-
# //= require foo
-
# //= require "foo"
-
#
-
1
DIRECTIVE_PATTERN = /
-
^ \W* = \s* (\w+.*?) (\*\/)? $
-
/x
-
-
1
def self.instance
-
@instance ||= new(
-
# Deprecated: Default to C and Ruby comment styles
-
comments: ["//", ["/*", "*/"]] + ["#", ["###", "###"]]
-
)
-
end
-
-
1
def self.call(input)
-
instance.call(input)
-
end
-
-
1
def initialize(options = {})
-
2
@header_pattern = compile_header_pattern(Array(options[:comments]))
-
end
-
-
1
def call(input)
-
dup._call(input)
-
end
-
-
1
def _call(input)
-
@environment = input[:environment]
-
@uri = input[:uri]
-
@filename = input[:filename]
-
@dirname = File.dirname(@filename)
-
@content_type = input[:content_type]
-
@required = Set.new(input[:metadata][:required])
-
@stubbed = Set.new(input[:metadata][:stubbed])
-
@links = Set.new(input[:metadata][:links])
-
@dependencies = Set.new(input[:metadata][:dependencies])
-
-
data, directives = process_source(input[:data])
-
process_directives(directives)
-
-
{ data: data,
-
required: @required,
-
stubbed: @stubbed,
-
links: @links,
-
dependencies: @dependencies }
-
end
-
-
1
protected
-
# Directives will only be picked up if they are in the header
-
# of the source file. C style (/* */), JavaScript (//), and
-
# Ruby (#) comments are supported.
-
#
-
# Directives in comments after the first non-whitespace line
-
# of code will not be processed.
-
1
def compile_header_pattern(comments)
-
2
re = comments.map { |c|
-
6
case c
-
when String
-
3
"(?:#{Regexp.escape(c)}.*\\n?)+"
-
when Array
-
3
"(?:#{Regexp.escape(c[0])}(?m:.*?)#{Regexp.escape(c[1])})"
-
else
-
raise TypeError, "unknown comment type: #{c.class}"
-
end
-
}.join("|")
-
2
Regexp.compile("\\A(?:(?m:\\s*)(?:#{re}))+")
-
end
-
-
1
def process_source(source)
-
header = source[@header_pattern, 0] || ""
-
body = $' || source
-
-
header, directives = extract_directives(header)
-
-
data = ""
-
data.force_encoding(body.encoding)
-
data << header << "\n" unless header.empty?
-
data << body
-
# Ensure body ends in a new line
-
data << "\n" if data.length > 0 && data[-1] != "\n"
-
-
return data, directives
-
end
-
-
# Returns an Array of directive structures. Each structure
-
# is an Array with the line number as the first element, the
-
# directive name as the second element, followed by any
-
# arguments.
-
#
-
# [[1, "require", "foo"], [2, "require", "bar"]]
-
#
-
1
def extract_directives(header)
-
processed_header = ""
-
directives = []
-
-
header.lines.each_with_index do |line, index|
-
if directive = line[DIRECTIVE_PATTERN, 1]
-
name, *args = Shellwords.shellwords(directive)
-
if respond_to?("process_#{name}_directive", true)
-
directives << [index + 1, name, *args]
-
# Replace directive line with a clean break
-
line = "\n"
-
end
-
end
-
processed_header << line
-
end
-
-
return processed_header.chomp, directives
-
end
-
-
# Gathers comment directives in the source and processes them.
-
# Any directive method matching `process_*_directive` will
-
# automatically be available. This makes it easy to extend the
-
# processor.
-
#
-
# To implement a custom directive called `require_glob`, subclass
-
# `Sprockets::DirectiveProcessor`, then add a method called
-
# `process_require_glob_directive`.
-
#
-
# class DirectiveProcessor < Sprockets::DirectiveProcessor
-
# def process_require_glob_directive
-
# Dir["#{dirname}/#{glob}"].sort.each do |filename|
-
# require(filename)
-
# end
-
# end
-
# end
-
#
-
# Replace the current processor on the environment with your own:
-
#
-
# env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
-
# env.register_processor('text/css', DirectiveProcessor)
-
#
-
1
def process_directives(directives)
-
directives.each do |line_number, name, *args|
-
begin
-
send("process_#{name}_directive", *args)
-
rescue Exception => e
-
e.set_backtrace(["#{@filename}:#{line_number}"] + e.backtrace)
-
raise e
-
end
-
end
-
end
-
-
# The `require` directive functions similar to Ruby's own `require`.
-
# It provides a way to declare a dependency on a file in your path
-
# and ensures its only loaded once before the source file.
-
#
-
# `require` works with files in the environment path:
-
#
-
# //= require "foo.js"
-
#
-
# Extensions are optional. If your source file is ".js", it
-
# assumes you are requiring another ".js".
-
#
-
# //= require "foo"
-
#
-
# Relative paths work too. Use a leading `./` to denote a relative
-
# path:
-
#
-
# //= require "./bar"
-
#
-
1
def process_require_directive(path)
-
@required << resolve(path, accept: @content_type, pipeline: :self)
-
end
-
-
# `require_self` causes the body of the current file to be inserted
-
# before any subsequent `require` directives. Useful in CSS files, where
-
# it's common for the index file to contain global styles that need to
-
# be defined before other dependencies are loaded.
-
#
-
# /*= require "reset"
-
# *= require_self
-
# *= require_tree .
-
# */
-
#
-
1
def process_require_self_directive
-
if @required.include?(@uri)
-
raise ArgumentError, "require_self can only be called once per source file"
-
end
-
@required << @uri
-
end
-
-
# `require_directory` requires all the files inside a single
-
# directory. It's similar to `path/*` since it does not follow
-
# nested directories.
-
#
-
# //= require_directory "./javascripts"
-
#
-
1
def process_require_directory_directive(path = ".")
-
path = expand_relative_dirname(:require_directory, path)
-
require_paths(*@environment.stat_directory_with_dependencies(path))
-
end
-
-
# `require_tree` requires all the nested files in a directory.
-
# Its glob equivalent is `path/**/*`.
-
#
-
# //= require_tree "./public"
-
#
-
1
def process_require_tree_directive(path = ".")
-
path = expand_relative_dirname(:require_tree, path)
-
require_paths(*@environment.stat_sorted_tree_with_dependencies(path))
-
end
-
-
# Allows you to state a dependency on a file without
-
# including it.
-
#
-
# This is used for caching purposes. Any changes made to
-
# the dependency file will invalidate the cache of the
-
# source file.
-
#
-
# This is useful if you are using ERB and File.read to pull
-
# in contents from another file.
-
#
-
# //= depend_on "foo.png"
-
#
-
1
def process_depend_on_directive(path)
-
resolve(path)
-
end
-
-
# Allows you to state a dependency on an asset without including
-
# it.
-
#
-
# This is used for caching purposes. Any changes that would
-
# invalid the asset dependency will invalidate the cache our the
-
# source file.
-
#
-
# Unlike `depend_on`, the path must be a requirable asset.
-
#
-
# //= depend_on_asset "bar.js"
-
#
-
1
def process_depend_on_asset_directive(path)
-
load(resolve(path))
-
end
-
-
# Allows dependency to be excluded from the asset bundle.
-
#
-
# The `path` must be a valid asset and may or may not already
-
# be part of the bundle. Once stubbed, it is blacklisted and
-
# can't be brought back by any other `require`.
-
#
-
# //= stub "jquery"
-
#
-
1
def process_stub_directive(path)
-
@stubbed << resolve(path, accept: @content_type, pipeline: :self)
-
end
-
-
# Declares a linked dependency on the target asset.
-
#
-
# The `path` must be a valid asset and should not already be part of the
-
# bundle. Any linked assets will automatically be compiled along with the
-
# current.
-
#
-
# /*= link "logo.png" */
-
#
-
1
def process_link_directive(path)
-
@links << load(resolve(path)).uri
-
end
-
-
# `link_directory` links all the files inside a single
-
# directory. It's similar to `path/*` since it does not follow
-
# nested directories.
-
#
-
# //= link_directory "./fonts"
-
#
-
# Use caution when linking against JS or CSS assets. Include an explicit
-
# extension or content type in these cases
-
#
-
# //= link_directory "./scripts" .js
-
#
-
1
def process_link_directory_directive(path = ".", accept = nil)
-
path = expand_relative_dirname(:link_directory, path)
-
accept = expand_accept_shorthand(accept)
-
link_paths(*@environment.stat_directory_with_dependencies(path), accept)
-
end
-
-
# `link_tree` links all the nested files in a directory.
-
# Its glob equivalent is `path/**/*`.
-
#
-
# //= link_tree "./images"
-
#
-
# Use caution when linking against JS or CSS assets. Include an explicit
-
# extension or content type in these cases
-
#
-
# //= link_tree "./styles" .css
-
#
-
1
def process_link_tree_directive(path = ".", accept = nil)
-
path = expand_relative_dirname(:link_tree, path)
-
accept = expand_accept_shorthand(accept)
-
link_paths(*@environment.stat_sorted_tree_with_dependencies(path), accept)
-
end
-
-
1
private
-
1
def expand_accept_shorthand(accept)
-
if accept.nil?
-
nil
-
elsif accept.include?("/")
-
accept
-
elsif accept.start_with?(".")
-
@environment.mime_exts[accept]
-
else
-
@environment.mime_exts[".#{accept}"]
-
end
-
end
-
-
1
def require_paths(paths, deps)
-
resolve_paths(paths, deps, accept: @content_type, pipeline: :self) do |uri|
-
@required << uri
-
end
-
end
-
-
1
def link_paths(paths, deps, accept)
-
resolve_paths(paths, deps, accept: accept) do |uri|
-
@links << load(uri).uri
-
end
-
end
-
-
1
def resolve_paths(paths, deps, options = {})
-
@dependencies.merge(deps)
-
paths.each do |subpath, stat|
-
next if subpath == @filename || stat.directory?
-
uri, deps = @environment.resolve(subpath, options.merge(compat: false))
-
@dependencies.merge(deps)
-
yield uri if uri
-
end
-
end
-
-
1
def expand_relative_dirname(directive, path)
-
if @environment.relative_path?(path)
-
path = File.expand_path(path, @dirname)
-
stat = @environment.stat(path)
-
-
if stat && stat.directory?
-
path
-
else
-
raise ArgumentError, "#{directive} argument must be a directory"
-
end
-
else
-
# The path must be relative and start with a `./`.
-
raise ArgumentError, "#{directive} argument must be a relative path"
-
end
-
end
-
-
1
def load(uri)
-
asset = @environment.load(uri)
-
@dependencies.merge(asset.metadata[:dependencies])
-
asset
-
end
-
-
1
def resolve(path, options = {})
-
# Prevent absolute paths in directives
-
if @environment.absolute_path?(path)
-
raise FileOutsidePaths, "can't require absolute file: #{path}"
-
end
-
-
uri, deps = @environment.resolve!(path, options.merge(base_path: @dirname))
-
@dependencies.merge(deps)
-
uri
-
end
-
end
-
end
-
1
require 'sprockets/autoload'
-
-
1
module Sprockets
-
# Processor engine class for the Eco compiler. Depends on the `eco` gem.
-
#
-
# For more infomation see:
-
#
-
# https://github.com/sstephenson/ruby-eco
-
# https://github.com/sstephenson/eco
-
#
-
1
module EcoProcessor
-
1
VERSION = '1'
-
-
1
def self.cache_key
-
@cache_key ||= "#{name}:#{Autoload::Eco::Source::VERSION}:#{VERSION}".freeze
-
end
-
-
# Compile template data with Eco compiler.
-
#
-
# Returns a JS function definition String. The result should be
-
# assigned to a JS variable.
-
#
-
# # => "function(...) {...}"
-
#
-
1
def self.call(input)
-
data = input[:data]
-
input[:cache].fetch([cache_key, data]) do
-
Autoload::Eco.compile(data)
-
end
-
end
-
end
-
end
-
1
require 'sprockets/autoload'
-
-
1
module Sprockets
-
# Processor engine class for the EJS compiler. Depends on the `ejs` gem.
-
#
-
# For more infomation see:
-
#
-
# https://github.com/sstephenson/ruby-ejs
-
#
-
1
module EjsProcessor
-
1
VERSION = '1'
-
-
1
def self.cache_key
-
@cache_key ||= "#{name}:#{VERSION}".freeze
-
end
-
-
# Compile template data with EJS compiler.
-
#
-
# Returns a JS function definition String. The result should be
-
# assigned to a JS variable.
-
#
-
# # => "function(obj){...}"
-
#
-
1
def self.call(input)
-
data = input[:data]
-
input[:cache].fetch([cache_key, data]) do
-
Autoload::EJS.compile(data)
-
end
-
end
-
end
-
end
-
1
require 'base64'
-
1
require 'stringio'
-
1
require 'zlib'
-
-
1
module Sprockets
-
# Internal: HTTP transport encoding and charset detecting related functions.
-
# Mixed into Environment.
-
1
module EncodingUtils
-
1
extend self
-
-
## Binary encodings ##
-
-
# Public: Use deflate to compress data.
-
#
-
# str - String data
-
#
-
# Returns a compressed String
-
1
def deflate(str)
-
deflater = Zlib::Deflate.new(
-
Zlib::BEST_COMPRESSION,
-
-Zlib::MAX_WBITS,
-
Zlib::MAX_MEM_LEVEL,
-
Zlib::DEFAULT_STRATEGY
-
)
-
deflater << str
-
deflater.finish
-
end
-
-
# Internal: Unmarshal optionally deflated data.
-
#
-
# Checks leading marshal header to see if the bytes are uncompressed
-
# otherwise inflate the data an unmarshal.
-
#
-
# str - Marshaled String
-
# window_bits - Integer deflate window size. See ZLib::Inflate.new()
-
#
-
# Returns unmarshaled Object or raises an Exception.
-
1
def unmarshaled_deflated(str, window_bits = -Zlib::MAX_WBITS)
-
30
major, minor = str[0], str[1]
-
30
if major && major.ord == Marshal::MAJOR_VERSION &&
-
minor && minor.ord <= Marshal::MINOR_VERSION
-
27
marshaled = str
-
else
-
3
begin
-
3
marshaled = Zlib::Inflate.new(window_bits).inflate(str)
-
rescue Zlib::DataError
-
marshaled = str
-
end
-
end
-
30
Marshal.load(marshaled)
-
end
-
-
# Public: Use gzip to compress data.
-
#
-
# str - String data
-
#
-
# Returns a compressed String
-
1
def gzip(str)
-
io = StringIO.new
-
gz = Zlib::GzipWriter.new(io, Zlib::BEST_COMPRESSION)
-
gz.mtime = 1
-
gz << str
-
gz.finish
-
io.string
-
end
-
-
# Public: Use base64 to encode data.
-
#
-
# str - String data
-
#
-
# Returns a encoded String
-
1
def base64(str)
-
Base64.strict_encode64(str)
-
end
-
-
-
## Charset encodings ##
-
-
# Internal: Shorthand aliases for detecter functions.
-
1
CHARSET_DETECT = {}
-
-
# Internal: Mapping unicode encodings to byte order markers.
-
1
BOM = {
-
Encoding::UTF_32LE => [0xFF, 0xFE, 0x00, 0x00],
-
Encoding::UTF_32BE => [0x00, 0x00, 0xFE, 0xFF],
-
Encoding::UTF_8 => [0xEF, 0xBB, 0xBF],
-
Encoding::UTF_16LE => [0xFF, 0xFE],
-
Encoding::UTF_16BE => [0xFE, 0xFF]
-
}
-
-
# Public: Basic string detecter.
-
#
-
# Attempts to parse any Unicode BOM otherwise falls back to the
-
# environment's external encoding.
-
#
-
# str - ASCII-8BIT encoded String
-
#
-
# Returns encoded String.
-
1
def detect(str)
-
str = detect_unicode_bom(str)
-
-
# Attempt Charlock detection
-
if str.encoding == Encoding::BINARY
-
charlock_detect(str)
-
end
-
-
# Fallback to environment's external encoding
-
if str.encoding == Encoding::BINARY
-
str.force_encoding(Encoding.default_external)
-
end
-
-
str
-
end
-
1
CHARSET_DETECT[:default] = method(:detect)
-
-
# Internal: Use Charlock Holmes to detect encoding.
-
#
-
# To enable this code path, require 'charlock_holmes'
-
#
-
# Returns encoded String.
-
1
def charlock_detect(str)
-
if defined? CharlockHolmes::EncodingDetector
-
if detected = CharlockHolmes::EncodingDetector.detect(str)
-
str.force_encoding(detected[:encoding]) if detected[:encoding]
-
end
-
end
-
-
str
-
end
-
-
# Public: Detect Unicode string.
-
#
-
# Attempts to parse Unicode BOM and falls back to UTF-8.
-
#
-
# str - ASCII-8BIT encoded String
-
#
-
# Returns encoded String.
-
1
def detect_unicode(str)
-
str = detect_unicode_bom(str)
-
-
# Fallback to UTF-8
-
if str.encoding == Encoding::BINARY
-
str.force_encoding(Encoding::UTF_8)
-
end
-
-
str
-
end
-
1
CHARSET_DETECT[:unicode] = method(:detect_unicode)
-
-
# Public: Detect and strip BOM from possible unicode string.
-
#
-
# str - ASCII-8BIT encoded String
-
#
-
# Returns UTF 8/16/32 encoded String without BOM or the original String if
-
# no BOM was present.
-
1
def detect_unicode_bom(str)
-
bom_bytes = str.byteslice(0, 4).bytes.to_a
-
-
BOM.each do |encoding, bytes|
-
if bom_bytes[0, bytes.size] == bytes
-
str = str.dup
-
str.force_encoding(Encoding::BINARY)
-
str.slice!(0, bytes.size)
-
str.force_encoding(encoding)
-
return str
-
end
-
end
-
-
return str
-
end
-
-
# Public: Detect and strip @charset from CSS style sheet.
-
#
-
# str - String.
-
#
-
# Returns a encoded String.
-
1
def detect_css(str)
-
str = detect_unicode_bom(str)
-
-
if name = scan_css_charset(str)
-
encoding = Encoding.find(name)
-
str = str.dup
-
str.force_encoding(encoding)
-
len = "@charset \"#{name}\";".encode(encoding).size
-
str.slice!(0, len)
-
str
-
end
-
-
# Fallback to UTF-8
-
if str.encoding == Encoding::BINARY
-
str.force_encoding(Encoding::UTF_8)
-
end
-
-
str
-
end
-
1
CHARSET_DETECT[:css] = method(:detect_css)
-
-
# Internal: @charset bytes
-
1
CHARSET_START = [0x40, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x20, 0x22]
-
1
CHARSET_SIZE = CHARSET_START.size
-
-
# Internal: Scan binary CSS string for @charset encoding name.
-
#
-
# str - ASCII-8BIT encoded String
-
#
-
# Returns encoding String name or nil.
-
1
def scan_css_charset(str)
-
buf = []
-
i = 0
-
-
str.each_byte.each do |byte|
-
# Halt on line breaks
-
break if byte == 0x0A || byte == 0x0D
-
-
# Only ascii bytes
-
next unless 0x0 < byte && byte <= 0xFF
-
-
if i < CHARSET_SIZE
-
elsif i == CHARSET_SIZE
-
if buf == CHARSET_START
-
buf = []
-
else
-
break
-
end
-
elsif byte == 0x22
-
return buf.pack('C*')
-
end
-
-
buf << byte
-
i += 1
-
end
-
-
nil
-
end
-
-
# Public: Detect charset from HTML document.
-
#
-
# Attempts to parse any Unicode BOM otherwise attempt Charlock detection
-
# and finally falls back to the environment's external encoding.
-
#
-
# str - String.
-
#
-
# Returns a encoded String.
-
1
def detect_html(str)
-
str = detect_unicode_bom(str)
-
-
# Attempt Charlock detection
-
if str.encoding == Encoding::BINARY
-
charlock_detect(str)
-
end
-
-
# Fallback to environment's external encoding
-
if str.encoding == Encoding::BINARY
-
str.force_encoding(Encoding.default_external)
-
end
-
-
str
-
end
-
1
CHARSET_DETECT[:html] = method(:detect_html)
-
end
-
end
-
1
require 'sprockets/legacy_tilt_processor'
-
1
require 'sprockets/utils'
-
-
1
module Sprockets
-
# `Engines` provides a global and `Environment` instance registry.
-
#
-
# An engine is a type of processor that is bound to a filename
-
# extension. `application.js.coffee` indicates that the
-
# `CoffeeScriptProcessor` engine will be ran on the file.
-
#
-
# Extensions can be stacked and will be evaulated from right to
-
# left. `application.js.coffee.erb` will first run `ERBProcessor`
-
# then `CoffeeScriptProcessor`.
-
#
-
# All `Engine`s must follow the `Template` interface. It is
-
# recommended to subclass `Template`.
-
#
-
# Its recommended that you register engine changes on your local
-
# `Environment` instance.
-
#
-
# environment.register_engine '.foo', FooProcessor
-
#
-
# The global registry is exposed for plugins to register themselves.
-
#
-
# Sprockets.register_engine '.sass', SassProcessor
-
#
-
1
module Engines
-
1
include Utils
-
-
# Returns a `Hash` of `Engine`s registered on the `Environment`.
-
# If an `ext` argument is supplied, the `Engine` associated with
-
# that extension will be returned.
-
#
-
# environment.engines
-
# # => {".coffee" => CoffeeScriptProcessor, ".sass" => SassProcessor, ...}
-
#
-
1
def engines
-
2
config[:engines]
-
end
-
-
# Internal: Returns a `Hash` of engine extensions to mime types.
-
#
-
# # => { '.coffee' => 'application/javascript' }
-
1
def engine_mime_types
-
config[:engine_mime_types]
-
end
-
-
# Registers a new Engine `klass` for `ext`. If the `ext` already
-
# has an engine registered, it will be overridden.
-
#
-
# environment.register_engine '.coffee', CoffeeScriptProcessor
-
#
-
1
def register_engine(ext, klass, options = {})
-
9
unless options[:silence_deprecation]
-
msg = <<-MSG
-
Sprockets method `register_engine` is deprecated.
-
Please register a mime type using `register_mime_type` then
-
use `register_compressor` or `register_transformer`.
-
https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md#supporting-all-versions-of-sprockets-in-processors
-
MSG
-
-
Deprecation.new([caller.first]).warn(msg)
-
end
-
-
9
ext = Sprockets::Utils.normalize_extension(ext)
-
-
9
self.computed_config = {}
-
-
9
if klass.respond_to?(:call)
-
7
processor = klass
-
7
self.config = hash_reassoc(config, :engines) do |engines|
-
7
engines.merge(ext => klass)
-
end
-
7
if options[:mime_type]
-
7
self.config = hash_reassoc(config, :engine_mime_types) do |mime_types|
-
7
mime_types.merge(ext.to_s => options[:mime_type])
-
end
-
end
-
else
-
2
processor = LegacyTiltProcessor.new(klass)
-
2
self.config = hash_reassoc(config, :engines) do |engines|
-
2
engines.merge(ext => processor)
-
end
-
2
if klass.respond_to?(:default_mime_type) && klass.default_mime_type
-
2
self.config = hash_reassoc(config, :engine_mime_types) do |mime_types|
-
2
mime_types.merge(ext.to_s => klass.default_mime_type)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'sprockets/base'
-
1
require 'sprockets/cache/memory_store'
-
1
require 'sprockets/cached_environment'
-
-
1
module Sprockets
-
1
class Environment < Base
-
# `Environment` should initialized with your application's root
-
# directory. This should be the same as your Rails or Rack root.
-
#
-
# env = Environment.new(Rails.root)
-
#
-
1
def initialize(root = ".")
-
1
initialize_configuration(Sprockets)
-
1
self.root = root
-
1
self.cache = Cache::MemoryStore.new
-
1
yield self if block_given?
-
end
-
-
# Returns a cached version of the environment.
-
#
-
# All its file system calls are cached which makes `cached` much
-
# faster. This behavior is ideal in production since the file
-
# system only changes between deploys.
-
1
def cached
-
1
CachedEnvironment.new(self)
-
end
-
1
alias_method :index, :cached
-
-
1
def find_asset(*args)
-
cached.find_asset(*args)
-
end
-
-
1
def find_all_linked_assets(*args, &block)
-
cached.find_all_linked_assets(*args, &block)
-
end
-
-
1
def load(*args)
-
cached.load(*args)
-
end
-
end
-
end
-
1
require 'erb'
-
-
1
module Sprockets
-
1
class ERBProcessor
-
# Public: Return singleton instance with default options.
-
#
-
# Returns ERBProcessor object.
-
1
def self.instance
-
@instance ||= new
-
end
-
-
1
def self.call(input)
-
instance.call(input)
-
end
-
-
1
def initialize(&block)
-
@block = block
-
end
-
-
1
def call(input)
-
engine = ::ERB.new(input[:data], nil, '<>')
-
context = input[:environment].context_class.new(input)
-
klass = (class << context; self; end)
-
klass.class_eval(&@block) if @block
-
engine.def_method(klass, :_evaluate_template, input[:filename])
-
data = context._evaluate_template
-
context.metadata.merge(data: data)
-
end
-
end
-
end
-
# Define some basic Sprockets error classes
-
1
module Sprockets
-
1
class Error < StandardError; end
-
1
class ArgumentError < Error; end
-
1
class ContentTypeMismatch < Error; end
-
1
class NotImplementedError < Error; end
-
1
class NotFound < Error; end
-
1
class ConversionError < NotFound; end
-
1
class FileNotFound < NotFound; end
-
1
class FileOutsidePaths < NotFound; end
-
end
-
1
require 'set'
-
-
1
module Sprockets
-
# Internal: The first processor in the pipeline that reads the file into
-
# memory and passes it along as `input[:data]`.
-
1
class FileReader
-
1
def self.call(input)
-
env = input[:environment]
-
data = env.read_file(input[:filename], input[:content_type])
-
dependencies = Set.new(input[:metadata][:dependencies])
-
dependencies += [env.build_file_digest_uri(input[:filename])]
-
{ data: data, dependencies: dependencies }
-
end
-
end
-
end
-
1
module Sprockets
-
# Internal: HTTP URI utilities. Many adapted from Rack::Utils. Mixed into
-
# Environment.
-
1
module HTTPUtils
-
1
extend self
-
-
# Public: Test mime type against mime range.
-
#
-
# match_mime_type?('text/html', 'text/*') => true
-
# match_mime_type?('text/plain', '*') => true
-
# match_mime_type?('text/html', 'application/json') => false
-
#
-
# Returns true if the given value is a mime match for the given mime match
-
# specification, false otherwise.
-
1
def match_mime_type?(value, matcher)
-
497
v1, v2 = value.split('/', 2)
-
497
m1, m2 = matcher.split('/', 2)
-
497
(m1 == '*' || v1 == m1) && (m2.nil? || m2 == '*' || m2 == v2)
-
end
-
-
# Public: Return values from Hash where the key matches the mime type.
-
#
-
# hash - Hash of String matcher keys to Object values
-
# mime_type - String mime type
-
#
-
# Returns Array of Object values.
-
1
def match_mime_type_keys(hash, mime_type)
-
type, subtype = mime_type.split('/', 2)
-
[
-
hash["*"],
-
hash["*/*"],
-
hash["#{type}/*"],
-
hash["#{type}/#{subtype}"]
-
].compact
-
end
-
-
# Internal: Parse Accept header quality values.
-
#
-
# Adapted from Rack::Utils#q_values.
-
#
-
# Returns an Array of [String, Float].
-
1
def parse_q_values(values)
-
2
values.to_s.split(/\s*,\s*/).map do |part|
-
2
value, parameters = part.split(/\s*;\s*/, 2)
-
2
quality = 1.0
-
2
if md = /\Aq=([\d.]+)/.match(parameters)
-
quality = md[1].to_f
-
end
-
2
[value, quality]
-
end
-
end
-
-
# Internal: Find all qvalue matches from an Array of available options.
-
#
-
# Adapted from Rack::Utils#q_values.
-
#
-
# Returns Array of matched Strings from available Array or [].
-
1
def find_q_matches(q_values, available, &matcher)
-
387
matcher ||= lambda { |a, b| a == b }
-
-
387
matches = []
-
-
387
case q_values
-
when Array
-
when String
-
2
q_values = parse_q_values(q_values)
-
when NilClass
-
q_values = []
-
else
-
raise TypeError, "unknown q_values type: #{q_values.class}"
-
end
-
-
387
q_values.each do |accepted, quality|
-
1214
if match = available.find { |option| matcher.call(option, accepted) }
-
222
matches << [match, quality]
-
end
-
end
-
-
609
matches.sort_by! { |match, quality| -quality }
-
609
matches.map! { |match, quality| match }
-
387
matches
-
end
-
-
# Internal: Find the best qvalue match from an Array of available options.
-
#
-
# Adapted from Rack::Utils#q_values.
-
#
-
# Returns the matched String from available Array or nil.
-
1
def find_best_q_match(q_values, available, &matcher)
-
387
find_q_matches(q_values, available, &matcher).first
-
end
-
-
# Internal: Find the all qvalue match from an Array of available mime type
-
# options.
-
#
-
# Adapted from Rack::Utils#q_values.
-
#
-
# Returns Array of matched mime type Strings from available Array or [].
-
1
def find_mime_type_matches(q_value_header, available)
-
find_q_matches(q_value_header, available) do |a, b|
-
match_mime_type?(a, b)
-
end
-
end
-
-
# Internal: Find the best qvalue match from an Array of available mime type
-
# options.
-
#
-
# Adapted from Rack::Utils#q_values.
-
#
-
# Returns the matched mime type String from available Array or nil.
-
1
def find_best_mime_type_match(q_value_header, available)
-
112
find_best_q_match(q_value_header, available) do |a, b|
-
112
match_mime_type?(a, b)
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
# Public: .jst engine.
-
#
-
# Exports server side compiled templates to an object.
-
#
-
# Name your template "users/show.jst.ejs", "users/new.jst.eco", etc.
-
#
-
# To accept the default options
-
#
-
# environment.register_engine '.jst',
-
# JstProcessor,
-
# mime_type: 'application/javascript'
-
#
-
# Change the default namespace.
-
#
-
# environment.register_engine '.jst',
-
# JstProcessor.new(namespace: 'App.templates'),
-
# mime_type: 'application/javascript'
-
#
-
1
class JstProcessor
-
1
def self.default_namespace
-
'this.JST'
-
end
-
-
# Public: Return singleton instance with default options.
-
#
-
# Returns JstProcessor object.
-
1
def self.instance
-
@instance ||= new
-
end
-
-
1
def self.call(input)
-
instance.call(input)
-
end
-
-
1
def initialize(options = {})
-
@namespace = options[:namespace] || self.class.default_namespace
-
end
-
-
1
def call(input)
-
data = input[:data].gsub(/$(.)/m, "\\1 ").strip
-
key = input[:name]
-
<<-JST
-
(function() { #{@namespace} || (#{@namespace} = {}); #{@namespace}[#{key.inspect}] = #{data};
-
}).call(this);
-
JST
-
end
-
end
-
end
-
1
require 'pathname'
-
1
require 'sprockets/asset'
-
1
require 'sprockets/base'
-
1
require 'sprockets/cached_environment'
-
1
require 'sprockets/context'
-
1
require 'sprockets/manifest'
-
1
require 'sprockets/resolve'
-
-
1
module Sprockets
-
1
autoload :CoffeeScriptTemplate, 'sprockets/coffee_script_template'
-
1
autoload :EcoTemplate, 'sprockets/eco_template'
-
1
autoload :EjsTemplate, 'sprockets/ejs_template'
-
1
autoload :ERBTemplate, 'sprockets/erb_template'
-
1
autoload :SassTemplate, 'sprockets/sass_template'
-
1
autoload :ScssTemplate, 'sprockets/sass_template'
-
-
# Deprecated
-
1
Index = CachedEnvironment
-
-
1
class Base
-
1
include Resolve
-
-
# Deprecated: Change default return type of resolve() to return 2.x
-
# compatible plain filename String. 4.x will always return an Asset URI
-
# and a set of file system dependencies that had to be read to compute the
-
# result.
-
#
-
# 2.x
-
#
-
# resolve("foo.js")
-
# # => "/path/to/app/javascripts/foo.js"
-
#
-
# 3.x
-
#
-
# resolve("foo.js")
-
# # => "/path/to/app/javascripts/foo.js"
-
#
-
# resolve("foo.js", compat: true)
-
# # => "/path/to/app/javascripts/foo.js"
-
#
-
# resolve("foo.js", compat: false)
-
# # => [
-
# # "file:///path/to/app/javascripts/foo.js?type=application/javascript"
-
# # #<Set: {"file-digest:/path/to/app/javascripts/foo.js"}>
-
# # ]
-
#
-
# 4.x
-
#
-
# resolve("foo.js")
-
# # => [
-
# # "file:///path/to/app/javascripts/foo.js?type=application/javascript"
-
# # #<Set: {"file-digest:/path/to/app/javascripts/foo.js"}>
-
# # ]
-
#
-
1
def resolve_with_compat(path, options = {})
-
112
options = options.dup
-
112
if options.delete(:compat) { true }
-
uri, _ = resolve_without_compat(path, options)
-
if uri
-
path, _ = parse_asset_uri(uri)
-
path
-
else
-
nil
-
end
-
else
-
112
resolve_without_compat(path, options)
-
end
-
end
-
1
alias_method :resolve_without_compat, :resolve
-
1
alias_method :resolve, :resolve_with_compat
-
-
# Deprecated: Iterate over all logical paths with a matcher.
-
#
-
# Remove from 4.x.
-
#
-
# args - List of matcher objects.
-
#
-
# Returns Enumerator if no block is given.
-
1
def each_logical_path(*args, &block)
-
return to_enum(__method__, *args) unless block_given?
-
-
filters = args.flatten.map { |arg| Manifest.compile_match_filter(arg) }
-
logical_paths.each do |a, b|
-
if filters.any? { |f| f.call(a, b) }
-
if block.arity == 2
-
yield a, b
-
else
-
yield a
-
end
-
end
-
end
-
-
nil
-
end
-
-
# Deprecated: Enumerate over all logical paths in the environment.
-
#
-
# Returns an Enumerator of [logical_path, filename].
-
1
def logical_paths
-
1
return to_enum(__method__) unless block_given?
-
-
1
seen = Set.new
-
-
1
paths.each do |load_path|
-
8
stat_tree(load_path).each do |filename, stat|
-
25
next unless stat.file?
-
-
25
path = split_subpath(load_path, filename)
-
25
path, mime_type, _, _ = parse_path_extnames(path)
-
25
path = normalize_logical_path(path)
-
25
path += mime_types[mime_type][:extensions].first if mime_type
-
-
25
if !seen.include?(path)
-
25
yield path, filename
-
25
seen << path
-
end
-
end
-
end
-
-
nil
-
end
-
-
1
def cache_get(key)
-
cache.get(key)
-
end
-
-
1
def cache_set(key, value)
-
cache.set(key, value)
-
end
-
-
1
def normalize_logical_path(path)
-
25
dirname, basename = File.split(path)
-
25
path = dirname if basename == 'index'
-
25
path
-
end
-
-
1
private
-
# Deprecated: Seriously.
-
1
def matches_filter(filters, logical_path, filename)
-
return true if filters.empty?
-
-
filters.any? do |filter|
-
if filter.is_a?(Regexp)
-
filter.match(logical_path)
-
elsif filter.respond_to?(:call)
-
if filter.arity == 1
-
filter.call(logical_path)
-
else
-
filter.call(logical_path, filename.to_s)
-
end
-
else
-
File.fnmatch(filter.to_s, logical_path)
-
end
-
end
-
end
-
-
# URI.unescape is deprecated on 1.9. We need to use URI::Parser
-
# if its available.
-
1
if defined? URI::DEFAULT_PARSER
-
1
def unescape(str)
-
str = URI::DEFAULT_PARSER.unescape(str)
-
str.force_encoding(Encoding.default_internal) if Encoding.default_internal
-
str
-
end
-
else
-
def unescape(str)
-
URI.unescape(str)
-
end
-
end
-
end
-
-
1
class Asset
-
# Deprecated: Use #filename instead.
-
#
-
# Returns Pathname.
-
1
def pathname
-
@pathname ||= Pathname.new(filename)
-
end
-
-
# Deprecated: Expand asset into an `Array` of parts.
-
#
-
# Appending all of an assets body parts together should give you
-
# the asset's contents as a whole.
-
#
-
# This allows you to link to individual files for debugging
-
# purposes.
-
#
-
# Use Asset#included instead. Keeping a full copy of the bundle's processed
-
# assets in memory (and in cache) is expensive and redundant. The common use
-
# case is to relink to the assets anyway.
-
#
-
# Returns Array of Assets.
-
1
def to_a
-
if metadata[:included]
-
metadata[:included].map { |uri| @environment.load(uri) }
-
else
-
[self]
-
end
-
end
-
-
# Deprecated: Get all required Assets.
-
#
-
# See Asset#to_a
-
#
-
# Returns Array of Assets.
-
1
def dependencies
-
to_a.reject { |a| a.filename.eql?(self.filename) }
-
end
-
-
# Deprecated: Returns Time of the last time the source was modified.
-
#
-
# Time resolution is normalized to the nearest second.
-
#
-
# Returns Time.
-
1
def mtime
-
Time.at(@mtime)
-
end
-
end
-
-
1
class Context
-
# Deprecated: Change default return type of resolve() to return 2.x
-
# compatible plain filename String. 4.x will always return an Asset URI.
-
#
-
# 2.x
-
#
-
# resolve("foo.js")
-
# # => "/path/to/app/javascripts/foo.js"
-
#
-
# 3.x
-
#
-
# resolve("foo.js")
-
# # => "/path/to/app/javascripts/foo.js"
-
#
-
# resolve("foo.js", compat: true)
-
# # => "/path/to/app/javascripts/foo.js"
-
#
-
# resolve("foo.js", compat: false)
-
# # => "file:///path/to/app/javascripts/foo.js?type=application/javascript"
-
#
-
# 4.x
-
#
-
# resolve("foo.js")
-
# # => "file:///path/to/app/javascripts/foo.js?type=application/javascript"
-
#
-
1
def resolve_with_compat(path, options = {})
-
options = options.dup
-
-
# Support old :content_type option, prefer :accept going forward
-
if type = options.delete(:content_type)
-
type = self.content_type if type == :self
-
options[:accept] ||= type
-
end
-
-
if options.delete(:compat) { true }
-
uri = resolve_without_compat(path, options)
-
path, _ = environment.parse_asset_uri(uri)
-
path
-
else
-
resolve_without_compat(path, options)
-
end
-
end
-
1
alias_method :resolve_without_compat, :resolve
-
1
alias_method :resolve, :resolve_with_compat
-
end
-
-
1
class Manifest
-
# Deprecated: Compile logical path matching filter into a proc that can be
-
# passed to logical_paths.select(&proc).
-
#
-
# compile_match_filter(proc { |logical_path|
-
# File.extname(logical_path) == '.js'
-
# })
-
#
-
# compile_match_filter(/application.js/)
-
#
-
# compile_match_filter("foo/*.js")
-
#
-
# Returns a Proc or raise a TypeError.
-
1
def self.compile_match_filter(filter)
-
# If the filter is already a proc, great nothing to do.
-
2
if filter.respond_to?(:call)
-
1
filter
-
# If the filter is a regexp, wrap it in a proc that tests it against the
-
# logical path.
-
1
elsif filter.is_a?(Regexp)
-
26
proc { |logical_path| filter.match(logical_path) }
-
elsif filter.is_a?(String)
-
# If its an absolute path, detect the matching full filename
-
if PathUtils.absolute_path?(filter)
-
proc { |logical_path, filename| filename == filter.to_s }
-
else
-
# Otherwise do an fnmatch against the logical path.
-
proc { |logical_path| File.fnmatch(filter.to_s, logical_path) }
-
end
-
else
-
raise TypeError, "unknown filter type: #{filter.inspect}"
-
end
-
end
-
-
1
def self.simple_logical_path?(str)
-
str.is_a?(String) &&
-
2
!PathUtils.absolute_path?(str) &&
-
str !~ /\*|\*\*|\?|\[|\]|\{|\}/
-
end
-
-
1
def self.compute_alias_logical_path(path)
-
dirname, basename = File.split(path)
-
extname = File.extname(basename)
-
if File.basename(basename, extname) == 'index'
-
"#{dirname}#{extname}"
-
else
-
nil
-
end
-
end
-
-
# Deprecated: Filter logical paths in environment. Useful for selecting what
-
# files you want to compile.
-
#
-
# Returns an Enumerator.
-
1
def filter_logical_paths(*args)
-
filters = args.flatten.map { |arg| self.class.compile_match_filter(arg) }
-
environment.cached.logical_paths.select do |a, b|
-
filters.any? { |f| f.call(a, b) }
-
end
-
end
-
-
# Deprecated alias.
-
1
alias_method :find_logical_paths, :filter_logical_paths
-
end
-
end
-
1
require 'delegate'
-
-
1
module Sprockets
-
# Deprecated: Wraps legacy process Procs with new processor call signature.
-
#
-
# Will be removed in Sprockets 4.x.
-
#
-
# LegacyProcProcessor.new(:compress,
-
# proc { |context, data| data.gsub(...) })
-
#
-
1
class LegacyProcProcessor < Delegator
-
1
def initialize(name, proc)
-
@name = name
-
@proc = proc
-
end
-
-
1
def __getobj__
-
@proc
-
end
-
-
1
def name
-
"Sprockets::LegacyProcProcessor (#{@name})"
-
end
-
-
1
def to_s
-
name
-
end
-
-
1
def call(input)
-
context = input[:environment].context_class.new(input)
-
data = @proc.call(context, input[:data])
-
context.metadata.merge(data: data.to_str)
-
end
-
end
-
end
-
1
require 'delegate'
-
-
1
module Sprockets
-
# Deprecated: Wraps legacy engine and process Tilt templates with new
-
# processor call signature.
-
#
-
# Will be removed in Sprockets 4.x.
-
#
-
# LegacyTiltProcessor.new(Tilt::CoffeeScriptProcessor)
-
#
-
1
class LegacyTiltProcessor < Delegator
-
1
def initialize(klass)
-
2
@klass = klass
-
end
-
-
1
def __getobj__
-
3
@klass
-
end
-
-
1
def call(input)
-
filename = input[:filename]
-
data = input[:data]
-
context = input[:environment].context_class.new(input)
-
-
data = @klass.new(filename) { data }.render(context, {})
-
context.metadata.merge(data: data.to_str)
-
end
-
end
-
end
-
1
require 'sprockets/asset'
-
1
require 'sprockets/digest_utils'
-
1
require 'sprockets/engines'
-
1
require 'sprockets/errors'
-
1
require 'sprockets/file_reader'
-
1
require 'sprockets/mime'
-
1
require 'sprockets/path_utils'
-
1
require 'sprockets/processing'
-
1
require 'sprockets/processor_utils'
-
1
require 'sprockets/resolve'
-
1
require 'sprockets/transformers'
-
1
require 'sprockets/uri_utils'
-
1
require 'sprockets/unloaded_asset'
-
-
1
module Sprockets
-
-
# The loader phase takes a asset URI location and returns a constructed Asset
-
# object.
-
1
module Loader
-
1
include DigestUtils, PathUtils, ProcessorUtils, URIUtils
-
1
include Engines, Mime, Processing, Resolve, Transformers
-
-
-
# Public: Load Asset by Asset URI.
-
#
-
# uri - A String containing complete URI to a file including schema
-
# and full path such as:
-
# "file:///Path/app/assets/js/app.js?type=application/javascript"
-
#
-
#
-
# Returns Asset.
-
1
def load(uri)
-
2
unloaded = UnloadedAsset.new(uri, self)
-
2
if unloaded.params.key?(:id)
-
unless asset = asset_from_cache(unloaded.asset_key)
-
id = unloaded.params.delete(:id)
-
uri_without_id = build_asset_uri(unloaded.filename, unloaded.params)
-
asset = load_from_unloaded(UnloadedAsset.new(uri_without_id, self))
-
if asset[:id] != id
-
@logger.warn "Sprockets load error: Tried to find #{uri}, but latest was id #{asset[:id]}"
-
end
-
end
-
else
-
2
asset = fetch_asset_from_dependency_cache(unloaded) do |paths|
-
# When asset is previously generated, its "dependencies" are stored in the cache.
-
# The presence of `paths` indicates dependencies were stored.
-
# We can check to see if the dependencies have not changed by "resolving" them and
-
# generating a digest key from the resolved entries. If this digest key has not
-
# changed the asset will be pulled from cache.
-
#
-
# If this `paths` is present but the cache returns nothing then `fetch_asset_from_dependency_cache`
-
# will confusingly be called again with `paths` set to nil where the asset will be
-
# loaded from disk.
-
2
if paths
-
2
digest = DigestUtils.digest(resolve_dependencies(paths))
-
2
if uri_from_cache = cache.get(unloaded.digest_key(digest), true)
-
2
asset_from_cache(UnloadedAsset.new(uri_from_cache, self).asset_key)
-
end
-
else
-
load_from_unloaded(unloaded)
-
end
-
end
-
end
-
2
Asset.new(self, asset)
-
end
-
-
1
private
-
-
# Internal: Load asset hash from cache
-
#
-
# key - A String containing lookup information for an asset
-
#
-
# This method converts all "compressed" paths to absolute paths.
-
# Returns a hash of values representing an asset
-
1
def asset_from_cache(key)
-
2
asset = cache.get(key, true)
-
2
if asset
-
2
asset[:uri] = expand_from_root(asset[:uri])
-
2
asset[:load_path] = expand_from_root(asset[:load_path])
-
2
asset[:filename] = expand_from_root(asset[:filename])
-
18
asset[:metadata][:included].map! { |uri| expand_from_root(uri) } if asset[:metadata][:included]
-
2
asset[:metadata][:links].map! { |uri| expand_from_root(uri) } if asset[:metadata][:links]
-
2
asset[:metadata][:stubbed].map! { |uri| expand_from_root(uri) } if asset[:metadata][:stubbed]
-
2
asset[:metadata][:required].map! { |uri| expand_from_root(uri) } if asset[:metadata][:required]
-
59
asset[:metadata][:dependencies].map! { |uri| uri.start_with?("file-digest://") ? expand_from_root(uri) : uri } if asset[:metadata][:dependencies]
-
-
2
asset[:metadata].each_key do |k|
-
13
next unless k =~ /_dependencies\z/
-
1
asset[:metadata][k].map! { |uri| expand_from_root(uri) }
-
end
-
end
-
2
asset
-
end
-
-
# Internal: Loads an asset and saves it to cache
-
#
-
# unloaded - An UnloadedAsset
-
#
-
# This method is only called when the given unloaded asset could not be
-
# successfully pulled from cache.
-
1
def load_from_unloaded(unloaded)
-
unless file?(unloaded.filename)
-
raise FileNotFound, "could not find file: #{unloaded.filename}"
-
end
-
-
load_path, logical_path = paths_split(config[:paths], unloaded.filename)
-
-
unless load_path
-
raise FileOutsidePaths, "#{unloaded.filename} is no longer under a load path: #{self.paths.join(', ')}"
-
end
-
-
logical_path, file_type, engine_extnames, _ = parse_path_extnames(logical_path)
-
name = logical_path
-
-
if pipeline = unloaded.params[:pipeline]
-
logical_path += ".#{pipeline}"
-
end
-
-
if type = unloaded.params[:type]
-
logical_path += config[:mime_types][type][:extensions].first
-
end
-
-
if type != file_type && !config[:transformers][file_type][type]
-
raise ConversionError, "could not convert #{file_type.inspect} to #{type.inspect}"
-
end
-
-
processors = processors_for(type, file_type, engine_extnames, pipeline)
-
-
processors_dep_uri = build_processors_uri(type, file_type, engine_extnames, pipeline)
-
dependencies = config[:dependencies] + [processors_dep_uri]
-
-
# Read into memory and process if theres a processor pipeline
-
if processors.any?
-
result = call_processors(processors, {
-
environment: self,
-
cache: self.cache,
-
uri: unloaded.uri,
-
filename: unloaded.filename,
-
load_path: load_path,
-
name: name,
-
content_type: type,
-
metadata: { dependencies: dependencies }
-
})
-
validate_processor_result!(result)
-
source = result.delete(:data)
-
metadata = result
-
metadata[:charset] = source.encoding.name.downcase unless metadata.key?(:charset)
-
metadata[:digest] = digest(source)
-
metadata[:length] = source.bytesize
-
else
-
dependencies << build_file_digest_uri(unloaded.filename)
-
metadata = {
-
digest: file_digest(unloaded.filename),
-
length: self.stat(unloaded.filename).size,
-
dependencies: dependencies
-
}
-
end
-
-
asset = {
-
uri: unloaded.uri,
-
load_path: load_path,
-
filename: unloaded.filename,
-
name: name,
-
logical_path: logical_path,
-
content_type: type,
-
source: source,
-
metadata: metadata,
-
dependencies_digest: DigestUtils.digest(resolve_dependencies(metadata[:dependencies]))
-
}
-
-
asset[:id] = pack_hexdigest(digest(asset))
-
asset[:uri] = build_asset_uri(unloaded.filename, unloaded.params.merge(id: asset[:id]))
-
-
# Deprecated: Avoid tracking Asset mtime
-
asset[:mtime] = metadata[:dependencies].map { |u|
-
if u.start_with?("file-digest:")
-
s = self.stat(parse_file_digest_uri(u))
-
s ? s.mtime.to_i : nil
-
else
-
nil
-
end
-
}.compact.max
-
asset[:mtime] ||= self.stat(unloaded.filename).mtime.to_i
-
-
store_asset(asset, unloaded)
-
asset
-
end
-
-
# Internal: Save a given asset to the cache
-
#
-
# asset - A hash containing values of loaded asset
-
# unloaded - The UnloadedAsset used to lookup the `asset`
-
#
-
# This method converts all absolute paths to "compressed" paths
-
# which are relative if they're in the root.
-
1
def store_asset(asset, unloaded)
-
# Save the asset in the cache under the new URI
-
cached_asset = asset.dup
-
cached_asset[:uri] = compress_from_root(asset[:uri])
-
cached_asset[:filename] = compress_from_root(asset[:filename])
-
cached_asset[:load_path] = compress_from_root(asset[:load_path])
-
-
if cached_asset[:metadata]
-
# Deep dup to avoid modifying `asset`
-
cached_asset[:metadata] = cached_asset[:metadata].dup
-
if cached_asset[:metadata][:included] && !cached_asset[:metadata][:included].empty?
-
cached_asset[:metadata][:included] = cached_asset[:metadata][:included].dup
-
cached_asset[:metadata][:included].map! { |uri| compress_from_root(uri) }
-
end
-
-
if cached_asset[:metadata][:links] && !cached_asset[:metadata][:links].empty?
-
cached_asset[:metadata][:links] = cached_asset[:metadata][:links].dup
-
cached_asset[:metadata][:links].map! { |uri| compress_from_root(uri) }
-
end
-
-
if cached_asset[:metadata][:stubbed] && !cached_asset[:metadata][:stubbed].empty?
-
cached_asset[:metadata][:stubbed] = cached_asset[:metadata][:stubbed].dup
-
cached_asset[:metadata][:stubbed].map! { |uri| compress_from_root(uri) }
-
end
-
-
if cached_asset[:metadata][:required] && !cached_asset[:metadata][:required].empty?
-
cached_asset[:metadata][:required] = cached_asset[:metadata][:required].dup
-
cached_asset[:metadata][:required].map! { |uri| compress_from_root(uri) }
-
end
-
-
if cached_asset[:metadata][:dependencies] && !cached_asset[:metadata][:dependencies].empty?
-
cached_asset[:metadata][:dependencies] = cached_asset[:metadata][:dependencies].dup
-
cached_asset[:metadata][:dependencies].map! do |uri|
-
uri.start_with?("file-digest://".freeze) ? compress_from_root(uri) : uri
-
end
-
end
-
-
# compress all _dependencies in metadata like `sass_dependencies`
-
cached_asset[:metadata].each do |key, value|
-
next unless key =~ /_dependencies\z/
-
cached_asset[:metadata][key] = value.dup
-
cached_asset[:metadata][key].map! {|uri| compress_from_root(uri) }
-
end
-
end
-
-
# Unloaded asset and stored_asset now have a different URI
-
stored_asset = UnloadedAsset.new(asset[:uri], self)
-
cache.set(stored_asset.asset_key, cached_asset, true)
-
-
# Save the new relative path for the digest key of the unloaded asset
-
cache.set(unloaded.digest_key(asset[:dependencies_digest]), stored_asset.compressed_path, true)
-
end
-
-
-
# Internal: Resolve set of dependency URIs.
-
#
-
# uris - An Array of "dependencies" for example:
-
# ["environment-version", "environment-paths", "processors:type=text/css&file_type=text/css",
-
# "file-digest:///Full/path/app/assets/stylesheets/application.css",
-
# "processors:type=text/css&file_type=text/css&pipeline=self",
-
# "file-digest:///Full/path/app/assets/stylesheets"]
-
#
-
# Returns back array of things that the given uri dpends on
-
# For example the environment version, if you're using a different version of sprockets
-
# then the dependencies should be different, this is used only for generating cache key
-
# for example the "environment-version" may be resolved to "environment-1.0-3.2.0" for
-
# version "3.2.0" of sprockets.
-
#
-
# Any paths that are returned are converted to relative paths
-
#
-
# Returns array of resolved dependencies
-
1
def resolve_dependencies(uris)
-
59
uris.map { |uri| resolve_dependency(uri) }
-
end
-
-
# Internal: Retrieves an asset based on its digest
-
#
-
# unloaded - An UnloadedAsset
-
# limit - A Fixnum which sets the maximum number of versions of "histories"
-
# stored in the cache
-
#
-
# This method attempts to retrieve the last `limit` number of histories of an asset
-
# from the cache a "history" which is an array of unresolved "dependencies" that the asset needs
-
# to compile. In this case A dependency can refer to either an asset i.e. index.js
-
# may rely on jquery.js (so jquery.js is a depndency), or other factors that may affect
-
# compilation, such as the VERSION of sprockets (i.e. the environment) and what "processors"
-
# are used.
-
#
-
# For example a history array may look something like this
-
#
-
# [["environment-version", "environment-paths", "processors:type=text/css&file_type=text/css",
-
# "file-digest:///Full/path/app/assets/stylesheets/application.css",
-
# "processors:type=text/css&file_digesttype=text/css&pipeline=self",
-
# "file-digest:///Full/path/app/assets/stylesheets"]]
-
#
-
# Where the first entry is a Set of dependencies for last generated version of that asset.
-
# Multiple versions are stored since sprockets keeps the last `limit` number of assets
-
# generated present in the system.
-
#
-
# If a "history" of dependencies is present in the cache, each version of "history" will be
-
# yielded to the passed block which is responsible for loading the asset. If found, the existing
-
# history will be saved with the dependency that found a valid asset moved to the front.
-
#
-
# If no history is present, or if none of the histories could be resolved to a valid asset then,
-
# the block is yielded to and expected to return a valid asset.
-
# When this happens the dependencies for the returned asset are added to the "history", and older
-
# entries are removed if the "history" is above `limit`.
-
1
def fetch_asset_from_dependency_cache(unloaded, limit = 3)
-
2
key = unloaded.dependency_history_key
-
-
2
history = cache.get(key) || []
-
2
history.each_with_index do |deps, index|
-
2
expanded_deps = deps.map do |path|
-
57
path.start_with?("file-digest://") ? expand_from_root(path) : path
-
end
-
2
if asset = yield(expanded_deps)
-
2
cache.set(key, history.rotate!(index)) if index > 0
-
2
return asset
-
end
-
end
-
-
asset = yield
-
deps = asset[:metadata][:dependencies].dup.map! do |uri|
-
uri.start_with?("file-digest://") ? compress_from_root(uri) : uri
-
end
-
cache.set(key, history.unshift(deps).take(limit))
-
asset
-
end
-
end
-
end
-
1
require 'json'
-
1
require 'time'
-
-
1
require 'concurrent'
-
-
1
require 'sprockets/manifest_utils'
-
1
require 'sprockets/utils/gzip'
-
-
1
module Sprockets
-
# The Manifest logs the contents of assets compiled to a single directory. It
-
# records basic attributes about the asset for fast lookup without having to
-
# compile. A pointer from each logical path indicates which fingerprinted
-
# asset is the current one.
-
#
-
# The JSON is part of the public API and should be considered stable. This
-
# should make it easy to read from other programming languages and processes
-
# that don't have sprockets loaded. See `#assets` and `#files` for more
-
# infomation about the structure.
-
1
class Manifest
-
1
include ManifestUtils
-
-
1
attr_reader :environment
-
-
# Create new Manifest associated with an `environment`. `filename` is a full
-
# path to the manifest json file. The file may or may not already exist. The
-
# dirname of the `filename` will be used to write compiled assets to.
-
# Otherwise, if the path is a directory, the filename will default a random
-
# ".sprockets-manifest-*.json" file in that directory.
-
#
-
# Manifest.new(environment, "./public/assets/manifest.json")
-
#
-
1
def initialize(*args)
-
1
if args.first.is_a?(Base) || args.first.nil?
-
1
@environment = args.shift
-
end
-
-
1
@directory, @filename = args[0], args[1]
-
-
# Whether the manifest file is using the old manifest-*.json naming convention
-
1
@legacy_manifest = false
-
-
# Expand paths
-
1
@directory = File.expand_path(@directory) if @directory
-
1
@filename = File.expand_path(@filename) if @filename
-
-
# If filename is given as the second arg
-
1
if @directory && File.extname(@directory) != ""
-
@directory, @filename = nil, @directory
-
end
-
-
# Default dir to the directory of the filename
-
1
@directory ||= File.dirname(@filename) if @filename
-
-
# If directory is given w/o filename, pick a random manifest location
-
1
@rename_filename = nil
-
1
if @directory && @filename.nil?
-
1
@filename = find_directory_manifest(@directory)
-
-
# If legacy manifest name autodetected, mark to rename on save
-
1
if File.basename(@filename).start_with?("manifest")
-
@rename_filename = File.join(@directory, generate_manifest_path)
-
end
-
end
-
-
1
unless @directory && @filename
-
raise ArgumentError, "manifest requires output filename"
-
end
-
-
1
data = {}
-
-
1
begin
-
1
if File.exist?(@filename)
-
data = json_decode(File.read(@filename))
-
end
-
rescue JSON::ParserError => e
-
logger.error "#{@filename} is invalid: #{e.class} #{e.message}"
-
end
-
-
1
@data = data
-
end
-
-
# Returns String path to manifest.json file.
-
1
attr_reader :filename
-
1
alias_method :path, :filename
-
-
1
attr_reader :directory
-
1
alias_method :dir, :directory
-
-
# Returns internal assets mapping. Keys are logical paths which
-
# map to the latest fingerprinted filename.
-
#
-
# Logical path (String): Fingerprint path (String)
-
#
-
# { "application.js" => "application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js",
-
# "jquery.js" => "jquery-ae0908555a245f8266f77df5a8edca2e.js" }
-
#
-
1
def assets
-
110
@data['assets'] ||= {}
-
end
-
-
# Returns internal file directory listing. Keys are filenames
-
# which map to an attributes array.
-
#
-
# Fingerprint path (String):
-
# logical_path: Logical path (String)
-
# mtime: ISO8601 mtime (String)
-
# digest: Base64 hex digest (String)
-
#
-
# { "application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js" =>
-
# { 'logical_path' => "application.js",
-
# 'mtime' => "2011-12-13T21:47:08-06:00",
-
# 'digest' => "2e8e9a7c6b0aafa0c9bdeec90ea30213" } }
-
#
-
1
def files
-
@data['files'] ||= {}
-
end
-
-
# Public: Find all assets matching pattern set in environment.
-
#
-
# Returns Enumerator of Assets.
-
1
def find(*args)
-
2
unless environment
-
raise Error, "manifest requires environment for compilation"
-
end
-
-
2
return to_enum(__method__, *args) unless block_given?
-
-
3
paths, filters = args.flatten.partition { |arg| self.class.simple_logical_path?(arg) }
-
3
filters = filters.map { |arg| self.class.compile_match_filter(arg) }
-
-
1
environment = self.environment.cached
-
-
1
paths.each do |path|
-
environment.find_all_linked_assets(path) do |asset|
-
yield asset
-
end
-
end
-
-
1
if filters.any?
-
1
environment.logical_paths do |logical_path, filename|
-
75
if filters.any? { |f| f.call(logical_path, filename) }
-
2
environment.find_all_linked_assets(filename) do |asset|
-
2
yield asset
-
end
-
end
-
end
-
end
-
-
nil
-
end
-
-
# Public: Find the source of assets by paths.
-
#
-
# Returns Enumerator of assets file content.
-
1
def find_sources(*args)
-
return to_enum(__method__, *args) unless block_given?
-
-
if environment
-
find(*args).each do |asset|
-
yield asset.source
-
end
-
else
-
args.each do |path|
-
yield File.binread(File.join(dir, assets[path]))
-
end
-
end
-
end
-
-
# Compile and write asset to directory. The asset is written to a
-
# fingerprinted filename like
-
# `application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js`. An entry is
-
# also inserted into the manifest file.
-
#
-
# compile("application.js")
-
#
-
1
def compile(*args)
-
unless environment
-
raise Error, "manifest requires environment for compilation"
-
end
-
-
filenames = []
-
concurrent_compressors = []
-
concurrent_writers = []
-
-
find(*args) do |asset|
-
files[asset.digest_path] = {
-
'logical_path' => asset.logical_path,
-
'mtime' => asset.mtime.iso8601,
-
'size' => asset.bytesize,
-
'digest' => asset.hexdigest,
-
-
# Deprecated: Remove beta integrity attribute in next release.
-
# Callers should DigestUtils.hexdigest_integrity_uri to compute the
-
# digest themselves.
-
'integrity' => DigestUtils.hexdigest_integrity_uri(asset.hexdigest)
-
}
-
assets[asset.logical_path] = asset.digest_path
-
-
if alias_logical_path = self.class.compute_alias_logical_path(asset.logical_path)
-
assets[alias_logical_path] = asset.digest_path
-
end
-
-
target = File.join(dir, asset.digest_path)
-
-
if File.exist?(target)
-
logger.debug "Skipping #{target}, already exists"
-
else
-
logger.info "Writing #{target}"
-
write_file = Concurrent::Future.execute { asset.write_to target }
-
concurrent_writers << write_file
-
end
-
filenames << asset.filename
-
-
next if environment.skip_gzip?
-
gzip = Utils::Gzip.new(asset)
-
next if gzip.cannot_compress?(environment.mime_types)
-
-
if File.exist?("#{target}.gz")
-
logger.debug "Skipping #{target}.gz, already exists"
-
else
-
logger.info "Writing #{target}.gz"
-
concurrent_compressors << Concurrent::Future.execute do
-
write_file.wait! if write_file
-
gzip.compress(target)
-
end
-
end
-
-
end
-
concurrent_writers.each(&:wait!)
-
concurrent_compressors.each(&:wait!)
-
save
-
-
filenames
-
end
-
-
# Removes file from directory and from manifest. `filename` must
-
# be the name with any directory path.
-
#
-
# manifest.remove("application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js")
-
#
-
1
def remove(filename)
-
path = File.join(dir, filename)
-
gzip = "#{path}.gz"
-
logical_path = files[filename]['logical_path']
-
-
if assets[logical_path] == filename
-
assets.delete(logical_path)
-
end
-
-
files.delete(filename)
-
FileUtils.rm(path) if File.exist?(path)
-
FileUtils.rm(gzip) if File.exist?(gzip)
-
-
save
-
-
logger.info "Removed #{filename}"
-
-
nil
-
end
-
-
# Cleanup old assets in the compile directory. By default it will
-
# keep the latest version, 2 backups and any created within the past hour.
-
#
-
# Examples
-
#
-
# To force only 1 backup to be kept, set count=1 and age=0.
-
#
-
# To only keep files created within the last 10 minutes, set count=0 and
-
# age=600.
-
#
-
1
def clean(count = 2, age = 3600)
-
asset_versions = files.group_by { |_, attrs| attrs['logical_path'] }
-
-
asset_versions.each do |logical_path, versions|
-
current = assets[logical_path]
-
-
versions.reject { |path, _|
-
path == current
-
}.sort_by { |_, attrs|
-
# Sort by timestamp
-
Time.parse(attrs['mtime'])
-
}.reverse.each_with_index.drop_while { |(_, attrs), index|
-
_age = [0, Time.now - Time.parse(attrs['mtime'])].max
-
# Keep if under age or within the count limit
-
_age < age || index < count
-
}.each { |(path, _), _|
-
# Remove old assets
-
remove(path)
-
}
-
end
-
end
-
-
# Wipe directive
-
1
def clobber
-
FileUtils.rm_r(directory) if File.exist?(directory)
-
logger.info "Removed #{directory}"
-
nil
-
end
-
-
# Persist manfiest back to FS
-
1
def save
-
if @rename_filename
-
logger.info "Renaming #{@filename} to #{@rename_filename}"
-
FileUtils.mv(@filename, @rename_filename)
-
@filename = @rename_filename
-
@rename_filename = nil
-
end
-
-
data = json_encode(@data)
-
FileUtils.mkdir_p File.dirname(@filename)
-
PathUtils.atomic_write(@filename) do |f|
-
f.write(data)
-
end
-
end
-
-
1
private
-
1
def json_decode(obj)
-
JSON.parse(obj, create_additions: false)
-
end
-
-
1
def json_encode(obj)
-
JSON.generate(obj)
-
end
-
-
1
def logger
-
if environment
-
environment.logger
-
else
-
logger = Logger.new($stderr)
-
logger.level = Logger::FATAL
-
logger
-
end
-
end
-
end
-
end
-
1
require 'securerandom'
-
-
1
module Sprockets
-
# Public: Manifest utilities.
-
1
module ManifestUtils
-
1
extend self
-
-
1
MANIFEST_RE = /^\.sprockets-manifest-[0-9a-f]{32}.json$/
-
1
LEGACY_MANIFEST_RE = /^manifest(-[0-9a-f]{32})?.json$/
-
-
# Public: Generate a new random manifest path.
-
#
-
# Manifests are not intended to be accessed publicly, but typically live
-
# alongside public assets for convenience. To avoid being served, the
-
# filename is prefixed with a "." which is usually hidden by web servers
-
# like Apache. To help in other environments that may not control this,
-
# a random hex string is appended to the filename to prevent people from
-
# guessing the location. If directory indexes are enabled on the server,
-
# all bets are off.
-
#
-
# Return String path.
-
1
def generate_manifest_path
-
1
".sprockets-manifest-#{SecureRandom.hex(16)}.json"
-
end
-
-
# Public: Find or pick a new manifest filename for target build directory.
-
#
-
# dirname - String dirname
-
#
-
# Examples
-
#
-
# find_directory_manifest("/app/public/assets")
-
# # => "/app/public/assets/.sprockets-manifest-abc123.json"
-
#
-
# Returns String filename.
-
1
def find_directory_manifest(dirname)
-
1
entries = File.directory?(dirname) ? Dir.entries(dirname) : []
-
1
entry = entries.find { |e| e =~ MANIFEST_RE } ||
-
# Deprecated: Will be removed in 4.x
-
entries.find { |e| e =~ LEGACY_MANIFEST_RE } ||
-
generate_manifest_path
-
1
File.join(dirname, entry)
-
end
-
end
-
end
-
1
require 'sprockets/encoding_utils'
-
1
require 'sprockets/http_utils'
-
1
require 'sprockets/utils'
-
-
1
module Sprockets
-
1
module Mime
-
1
include HTTPUtils, Utils
-
-
# Public: Mapping of MIME type Strings to properties Hash.
-
#
-
# key - MIME Type String
-
# value - Hash
-
# extensions - Array of extnames
-
# charset - Default Encoding or function to detect encoding
-
#
-
# Returns Hash.
-
1
def mime_types
-
22
config[:mime_types]
-
end
-
-
# Internal: Mapping of MIME extension Strings to MIME type Strings.
-
#
-
# Used for internal fast lookup purposes.
-
#
-
# Examples:
-
#
-
# mime_exts['.js'] #=> 'application/javascript'
-
#
-
# key - MIME extension String
-
# value - MIME Type String
-
#
-
# Returns Hash.
-
1
def mime_exts
-
config[:mime_exts]
-
end
-
-
# Public: Register a new mime type.
-
#
-
# mime_type - String MIME Type
-
# options - Hash
-
# extensions: Array of String extnames
-
# charset: Proc/Method that detects the charset of a file.
-
# See EncodingUtils.
-
#
-
# Returns nothing.
-
1
def register_mime_type(mime_type, options = {})
-
# Legacy extension argument, will be removed from 4.x
-
28
if options.is_a?(String)
-
options = { extensions: [options] }
-
end
-
-
28
extnames = Array(options[:extensions]).map { |extname|
-
40
Sprockets::Utils.normalize_extension(extname)
-
}
-
-
28
charset = options[:charset]
-
28
charset ||= :default if mime_type.start_with?('text/')
-
28
charset = EncodingUtils::CHARSET_DETECT[charset] if charset.is_a?(Symbol)
-
-
28
self.computed_config = {}
-
-
28
self.config = hash_reassoc(config, :mime_exts) do |mime_exts|
-
28
extnames.each do |extname|
-
40
mime_exts[extname] = mime_type
-
end
-
28
mime_exts
-
end
-
-
28
self.config = hash_reassoc(config, :mime_types) do |mime_types|
-
28
type = { extensions: extnames }
-
28
type[:charset] = charset if charset
-
28
mime_types.merge(mime_type => type)
-
end
-
end
-
-
# Internal: Get detecter function for MIME type.
-
#
-
# mime_type - String MIME type
-
#
-
# Returns Proc detector or nil if none is available.
-
1
def mime_type_charset_detecter(mime_type)
-
if type = config[:mime_types][mime_type]
-
if detect = type[:charset]
-
return detect
-
end
-
end
-
end
-
-
# Public: Read file on disk with MIME type specific encoding.
-
#
-
# filename - String path
-
# content_type - String MIME type
-
#
-
# Returns String file contents transcoded to UTF-8 or in its external
-
# encoding.
-
1
def read_file(filename, content_type = nil)
-
data = File.binread(filename)
-
-
if detect = mime_type_charset_detecter(content_type)
-
detect.call(data).encode(Encoding::UTF_8, :universal_newline => true)
-
else
-
data
-
end
-
end
-
-
1
private
-
1
def extname_map
-
302
self.computed_config[:_extnames] ||= compute_extname_map
-
end
-
-
1
def compute_extname_map
-
1
graph = {}
-
-
1
([nil] + pipelines.keys.map(&:to_s)).each do |pipeline|
-
5
pipeline_extname = ".#{pipeline}" if pipeline
-
5
([[nil, nil]] + config[:mime_exts].to_a).each do |format_extname, format_type|
-
205
4.times do |n|
-
820
config[:engines].keys.permutation(n).each do |engine_extnames|
-
53300
key = "#{pipeline_extname}#{format_extname}#{engine_extnames.join}"
-
53300
type = format_type || config[:engine_mime_types][engine_extnames.first]
-
53300
graph[key] = {type: type, engines: engine_extnames, pipeline: pipeline}
-
end
-
end
-
end
-
end
-
-
1
graph
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'sprockets/path_utils'
-
1
require 'sprockets/uri_utils'
-
-
1
module Sprockets
-
# Internal: Related PathUtils helpers that also track all the file system
-
# calls they make for caching purposes. All functions return a standard
-
# return value and a Set of cache dependency URIs that can be used in the
-
# future to see if the returned value should be invalidated from cache.
-
#
-
# entries_with_dependencies("app/assets/javascripts")
-
# # => [
-
# # ["application.js", "projects.js", "users.js", ...]
-
# # #<Set: {"file-digest:/path/to/app/assets/javascripts"}>
-
# # ]
-
#
-
# The returned dependency set can be passed to resolve_dependencies(deps)
-
# to check if the returned result is still fresh. In this case, entry always
-
# returns a single path, but multiple calls should accumulate dependencies
-
# into a single set thats saved off and checked later.
-
#
-
# resolve_dependencies(deps)
-
# # => "\x01\x02\x03"
-
#
-
# Later, resolving the same set again will produce a different hash if
-
# something on the file system has changed.
-
#
-
# resolve_dependencies(deps)
-
# # => "\x03\x04\x05"
-
#
-
1
module PathDependencyUtils
-
1
include PathUtils
-
1
include URIUtils
-
-
# Internal: List directory entries and return a set of dependencies that
-
# would invalid the cached return result.
-
#
-
# See PathUtils#entries
-
#
-
# path - String directory path
-
#
-
# Returns an Array of entry names and a Set of dependency URIs.
-
1
def entries_with_dependencies(path)
-
return entries(path), file_digest_dependency_set(path)
-
end
-
-
# Internal: List directory filenames and associated Stats under a
-
# directory.
-
#
-
# See PathUtils#stat_directory
-
#
-
# dir - A String directory
-
#
-
# Returns an Array of filenames and a Set of dependency URIs.
-
1
def stat_directory_with_dependencies(dir)
-
return stat_directory(dir).to_a, file_digest_dependency_set(dir)
-
end
-
-
# Internal: Returns a set of dependencies for a particular path.
-
#
-
# path - String directory path
-
#
-
# Returns a Set of dependency URIs.
-
1
def file_digest_dependency_set(path)
-
550
Set.new([build_file_digest_uri(path)])
-
end
-
-
# Internal: List directory filenames and associated Stats under an entire
-
# directory tree.
-
#
-
# See PathUtils#stat_sorted_tree
-
#
-
# dir - A String directory
-
#
-
# Returns an Array of filenames and a Set of dependency URIs.
-
1
def stat_sorted_tree_with_dependencies(dir)
-
deps = Set.new([build_file_digest_uri(dir)])
-
results = stat_sorted_tree(dir).map do |path, stat|
-
deps << build_file_digest_uri(path) if stat.directory?
-
[path, stat]
-
end
-
return results, deps
-
end
-
end
-
end
-
1
require 'sprockets/digest_utils'
-
1
require 'sprockets/path_utils'
-
-
1
module Sprockets
-
# Internal: Crossover of path and digest utilities functions.
-
1
module PathDigestUtils
-
1
include DigestUtils, PathUtils
-
-
# Internal: Compute digest for file stat.
-
#
-
# path - String filename
-
# stat - File::Stat
-
#
-
# Returns String digest bytes.
-
1
def stat_digest(path, stat)
-
if stat.directory?
-
# If its a directive, digest the list of filenames
-
digest_class.digest(self.entries(path).join(','))
-
elsif stat.file?
-
# If its a file, digest the contents
-
digest_class.file(path.to_s).digest
-
else
-
raise TypeError, "stat was not a directory or file: #{stat.ftype}"
-
end
-
end
-
-
# Internal: Compute digest for path.
-
#
-
# path - String filename or directory path.
-
#
-
# Returns String digest bytes or nil.
-
1
def file_digest(path)
-
if stat = self.stat(path)
-
self.stat_digest(path, stat)
-
end
-
end
-
-
# Internal: Compute digest for a set of paths.
-
#
-
# paths - Array of filename or directory paths.
-
#
-
# Returns String digest bytes.
-
1
def files_digest(paths)
-
self.digest(paths.map { |path| self.file_digest(path) })
-
end
-
end
-
end
-
1
module Sprockets
-
# Internal: File and path related utilities. Mixed into Environment.
-
#
-
# Probably would be called FileUtils, but that causes namespace annoyances
-
# when code actually wants to reference ::FileUtils.
-
1
module PathUtils
-
1
extend self
-
-
# Public: Like `File.stat`.
-
#
-
# path - String file or directory path
-
#
-
# Returns nil if the file does not exist.
-
1
def stat(path)
-
56
if File.exist?(path)
-
33
File.stat(path.to_s)
-
else
-
nil
-
end
-
end
-
-
# Public: Like `File.file?`.
-
#
-
# path - String file path.
-
#
-
# Returns true path exists and is a file.
-
1
def file?(path)
-
167
if stat = self.stat(path)
-
167
stat.file?
-
else
-
false
-
end
-
end
-
-
# Public: Like `File.directory?`.
-
#
-
# path - String file path.
-
#
-
# Returns true path exists and is a directory.
-
1
def directory?(path)
-
550
if stat = self.stat(path)
-
stat.directory?
-
else
-
550
false
-
end
-
end
-
-
# Public: A version of `Dir.entries` that filters out `.` files and `~`
-
# swap files.
-
#
-
# path - String directory path
-
#
-
# Returns an empty `Array` if the directory does not exist.
-
1
def entries(path)
-
8
if File.directory?(path)
-
8
entries = Dir.entries(path, :encoding => Encoding.default_internal)
-
8
entries.reject! { |entry|
-
entry.start_with?(".".freeze) ||
-
44
(entry.start_with?("#".freeze) && entry.end_with?("#".freeze)) ||
-
entry.end_with?("~".freeze)
-
}
-
8
entries.sort!
-
else
-
[]
-
end
-
end
-
-
# Public: Check if path is absolute or relative.
-
#
-
# path - String path.
-
#
-
# Returns true if path is absolute, otherwise false.
-
1
if File::ALT_SEPARATOR
-
require 'pathname'
-
-
# On Windows, ALT_SEPARATOR is \
-
# Delegate to Pathname since the logic gets complex.
-
def absolute_path?(path)
-
Pathname.new(path).absolute?
-
end
-
else
-
1
def absolute_path?(path)
-
224
path[0] == File::SEPARATOR
-
end
-
end
-
-
1
if File::ALT_SEPARATOR
-
SEPARATOR_PATTERN = "#{Regexp.quote(File::SEPARATOR)}|#{Regexp.quote(File::ALT_SEPARATOR)}"
-
else
-
1
SEPARATOR_PATTERN = "#{Regexp.quote(File::SEPARATOR)}"
-
end
-
-
# Public: Check if path is explicitly relative.
-
# Starts with "./" or "../".
-
#
-
# path - String path.
-
#
-
# Returns true if path is relative, otherwise false.
-
1
def relative_path?(path)
-
110
path =~ /^\.\.?($|#{SEPARATOR_PATTERN})/ ? true : false
-
end
-
-
# Internal: Get relative path for root path and subpath.
-
#
-
# path - String path
-
# subpath - String subpath of path
-
#
-
# Returns relative String path if subpath is a subpath of path, or nil if
-
# subpath is outside of path.
-
1
def split_subpath(path, subpath)
-
68
return "" if path == subpath
-
68
path = File.join(path, '')
-
68
if subpath.start_with?(path)
-
63
subpath[path.length..-1]
-
else
-
nil
-
end
-
end
-
-
# Internal: Detect root path and base for file in a set of paths.
-
#
-
# paths - Array of String paths
-
# filename - String path of file expected to be in one of the paths.
-
#
-
# Returns [String root, String path]
-
1
def paths_split(paths, filename)
-
2
paths.each do |path|
-
5
if subpath = split_subpath(path, filename)
-
2
return path, subpath
-
end
-
end
-
nil
-
end
-
-
# Internal: Get path's extensions.
-
#
-
# path - String
-
#
-
# Returns an Array of String extnames.
-
1
def path_extnames(path)
-
File.basename(path).scan(/\.[^.]+/)
-
end
-
-
# Internal: Match path extnames against available extensions.
-
#
-
# path - String
-
# extensions - Hash of String extnames to values
-
#
-
# Returns [String extname, Object value] or nil nothing matched.
-
1
def match_path_extname(path, extensions)
-
302
basename = File.basename(path)
-
-
302
i = basename.index('.'.freeze)
-
302
while i && i < basename.length - 1
-
308
extname = basename[i..-1]
-
308
if value = extensions[extname]
-
299
return extname, value
-
end
-
-
9
i = basename.index('.'.freeze, i+1)
-
end
-
-
nil
-
end
-
-
# Internal: Returns all parents for path
-
#
-
# path - String absolute filename or directory
-
# root - String path to stop at (default: system root)
-
#
-
# Returns an Array of String paths.
-
1
def path_parents(path, root = nil)
-
root = "#{root}#{File::SEPARATOR}" if root
-
parents = []
-
-
loop do
-
parent = File.dirname(path)
-
break if parent == path
-
break if root && !path.start_with?(root)
-
parents << path = parent
-
end
-
-
parents
-
end
-
-
# Internal: Find target basename checking upwards from path.
-
#
-
# basename - String filename: ".sprocketsrc"
-
# path - String path to start search: "app/assets/javascripts/app.js"
-
# root - String path to stop at (default: system root)
-
#
-
# Returns String filename or nil.
-
1
def find_upwards(basename, path, root = nil)
-
path_parents(path, root).each do |dir|
-
filename = File.join(dir, basename)
-
return filename if file?(filename)
-
end
-
nil
-
end
-
-
# Public: Stat all the files under a directory.
-
#
-
# dir - A String directory
-
#
-
# Returns an Enumerator of [path, stat].
-
1
def stat_directory(dir)
-
8
return to_enum(__method__, dir) unless block_given?
-
-
8
self.entries(dir).each do |entry|
-
25
path = File.join(dir, entry)
-
25
if stat = self.stat(path)
-
25
yield path, stat
-
end
-
end
-
-
nil
-
end
-
-
# Public: Recursive stat all the files under a directory.
-
#
-
# dir - A String directory
-
#
-
# Returns an Enumerator of [path, stat].
-
1
def stat_tree(dir, &block)
-
16
return to_enum(__method__, dir) unless block_given?
-
-
8
self.stat_directory(dir) do |path, stat|
-
25
yield path, stat
-
-
25
if stat.directory?
-
stat_tree(path, &block)
-
end
-
end
-
-
nil
-
end
-
-
# Public: Recursive stat all the files under a directory in alphabetical
-
# order.
-
#
-
# dir - A String directory
-
#
-
# Returns an Enumerator of [path, stat].
-
1
def stat_sorted_tree(dir, &block)
-
return to_enum(__method__, dir) unless block_given?
-
-
self.stat_directory(dir).sort_by { |path, stat|
-
stat.directory? ? "#{path}/" : path
-
}.each do |path, stat|
-
yield path, stat
-
-
if stat.directory?
-
stat_sorted_tree(path, &block)
-
end
-
end
-
-
nil
-
end
-
-
# Public: Write to a file atomically. Useful for situations where you
-
# don't want other processes or threads to see half-written files.
-
#
-
# Utils.atomic_write('important.file') do |file|
-
# file.write('hello')
-
# end
-
#
-
# Returns nothing.
-
1
def atomic_write(filename)
-
dirname, basename = File.split(filename)
-
basename = [
-
basename,
-
Thread.current.object_id,
-
Process.pid,
-
rand(1000000)
-
].join('.')
-
tmpname = File.join(dirname, basename)
-
-
File.open(tmpname, 'wb+') do |f|
-
yield f
-
end
-
-
File.rename(tmpname, filename)
-
ensure
-
File.delete(tmpname) if File.exist?(tmpname)
-
end
-
end
-
end
-
1
require 'sprockets/path_utils'
-
1
require 'sprockets/utils'
-
-
1
module Sprockets
-
1
module Paths
-
1
include PathUtils, Utils
-
-
# Returns `Environment` root.
-
#
-
# All relative paths are expanded with root as its base. To be
-
# useful set this to your applications root directory. (`Rails.root`)
-
1
def root
-
151
config[:root]
-
end
-
-
# Internal: Change Environment root.
-
#
-
# Only the initializer should change the root.
-
1
def root=(path)
-
1
self.config = hash_reassoc(config, :root) do
-
1
File.expand_path(path)
-
end
-
end
-
1
private :root=
-
-
# Returns an `Array` of path `String`s.
-
#
-
# These paths will be used for asset logical path lookups.
-
1
def paths
-
2
config[:paths]
-
end
-
-
# Prepend a `path` to the `paths` list.
-
#
-
# Paths at the end of the `Array` have the least priority.
-
1
def prepend_path(path)
-
self.config = hash_reassoc(config, :paths) do |paths|
-
path = File.expand_path(path, config[:root]).freeze
-
paths.unshift(path)
-
end
-
end
-
-
# Append a `path` to the `paths` list.
-
#
-
# Paths at the beginning of the `Array` have a higher priority.
-
1
def append_path(path)
-
8
self.config = hash_reassoc(config, :paths) do |paths|
-
8
path = File.expand_path(path, config[:root]).freeze
-
8
paths.push(path)
-
end
-
end
-
-
# Clear all paths and start fresh.
-
#
-
# There is no mechanism for reordering paths, so its best to
-
# completely wipe the paths list and reappend them in the order
-
# you want.
-
1
def clear_paths
-
self.config = hash_reassoc(config, :paths) do |paths|
-
paths.clear
-
end
-
end
-
-
# Public: Iterate over every file under all load paths.
-
#
-
# Returns Enumerator if no block is given.
-
1
def each_file
-
return to_enum(__method__) unless block_given?
-
-
paths.each do |root|
-
stat_tree(root).each do |filename, stat|
-
if stat.file?
-
yield filename
-
end
-
end
-
end
-
-
nil
-
end
-
end
-
end
-
1
require 'sprockets/engines'
-
1
require 'sprockets/file_reader'
-
1
require 'sprockets/legacy_proc_processor'
-
1
require 'sprockets/legacy_tilt_processor'
-
1
require 'sprockets/mime'
-
1
require 'sprockets/processor_utils'
-
1
require 'sprockets/uri_utils'
-
1
require 'sprockets/utils'
-
-
1
module Sprockets
-
# `Processing` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `CachedEnvironment` classes.
-
1
module Processing
-
1
include ProcessorUtils, URIUtils, Utils
-
-
1
def pipelines
-
1
config[:pipelines]
-
end
-
-
1
def register_pipeline(name, proc = nil, &block)
-
4
proc ||= block
-
-
4
self.config = hash_reassoc(config, :pipelines) do |pipelines|
-
4
pipelines.merge(name.to_sym => proc)
-
end
-
end
-
-
# Preprocessors are ran before Postprocessors and Engine
-
# processors.
-
1
def preprocessors
-
config[:preprocessors]
-
end
-
1
alias_method :processors, :preprocessors
-
-
# Postprocessors are ran after Preprocessors and Engine processors.
-
1
def postprocessors
-
config[:postprocessors]
-
end
-
-
# Registers a new Preprocessor `klass` for `mime_type`.
-
#
-
# register_preprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_preprocessor 'text/css', :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
1
def register_preprocessor(*args, &block)
-
2
register_config_processor(:preprocessors, *args, &block)
-
end
-
1
alias_method :register_processor, :register_preprocessor
-
-
# Registers a new Postprocessor `klass` for `mime_type`.
-
#
-
# register_postprocessor 'application/javascript', Sprockets::DirectiveProcessor
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_postprocessor 'application/javascript', :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
1
def register_postprocessor(*args, &block)
-
register_config_processor(:postprocessors, *args, &block)
-
end
-
-
# Remove Preprocessor `klass` for `mime_type`.
-
#
-
# unregister_preprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
1
def unregister_preprocessor(*args)
-
unregister_config_processor(:preprocessors, *args)
-
end
-
1
alias_method :unregister_processor, :unregister_preprocessor
-
-
# Remove Postprocessor `klass` for `mime_type`.
-
#
-
# unregister_postprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
1
def unregister_postprocessor(*args)
-
unregister_config_processor(:postprocessors, *args)
-
end
-
-
# Bundle Processors are ran on concatenated assets rather than
-
# individual files.
-
1
def bundle_processors
-
config[:bundle_processors]
-
end
-
-
# Registers a new Bundle Processor `klass` for `mime_type`.
-
#
-
# register_bundle_processor 'application/javascript', Sprockets::DirectiveProcessor
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_bundle_processor 'application/javascript', :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
1
def register_bundle_processor(*args, &block)
-
3
register_config_processor(:bundle_processors, *args, &block)
-
end
-
-
# Remove Bundle Processor `klass` for `mime_type`.
-
#
-
# unregister_bundle_processor 'application/javascript', Sprockets::DirectiveProcessor
-
#
-
1
def unregister_bundle_processor(*args)
-
unregister_config_processor(:bundle_processors, *args)
-
end
-
-
# Public: Register bundle metadata reducer function.
-
#
-
# Examples
-
#
-
# Sprockets.register_bundle_metadata_reducer 'application/javascript', :jshint_errors, [], :+
-
#
-
# Sprockets.register_bundle_metadata_reducer 'text/css', :selector_count, 0 { |total, count|
-
# total + count
-
# }
-
#
-
# mime_type - String MIME Type. Use '*/*' applies to all types.
-
# key - Symbol metadata key
-
# initial - Initial memo to pass to the reduce funciton (default: nil)
-
# block - Proc accepting the memo accumulator and current value
-
#
-
# Returns nothing.
-
1
def register_bundle_metadata_reducer(mime_type, key, *args, &block)
-
4
case args.size
-
when 0
-
reducer = block
-
when 1
-
1
if block_given?
-
initial = args[0]
-
reducer = block
-
else
-
1
initial = nil
-
1
reducer = args[0].to_proc
-
end
-
when 2
-
3
initial = args[0]
-
3
reducer = args[1].to_proc
-
else
-
raise ArgumentError, "wrong number of arguments (#{args.size} for 0..2)"
-
end
-
-
4
self.config = hash_reassoc(config, :bundle_reducers, mime_type) do |reducers|
-
4
reducers.merge(key => [initial, reducer])
-
end
-
end
-
-
1
protected
-
1
def resolve_processors_cache_key_uri(uri)
-
6
params = parse_uri_query_params(uri[11..-1])
-
6
params[:engine_extnames] = params[:engines] ? params[:engines].split(',') : []
-
6
processors = processors_for(params[:type], params[:file_type], params[:engine_extnames], params[:pipeline])
-
6
processors_cache_keys(processors)
-
end
-
-
1
def build_processors_uri(type, file_type, engine_extnames, pipeline)
-
engines = engine_extnames.join(',') if engine_extnames.any?
-
query = encode_uri_query_params(
-
type: type,
-
file_type: file_type,
-
engines: engines,
-
pipeline: pipeline
-
)
-
"processors:#{query}"
-
end
-
-
1
def processors_for(type, file_type, engine_extnames, pipeline)
-
6
pipeline ||= :default
-
6
config[:pipelines][pipeline.to_sym].call(self, type, file_type, engine_extnames)
-
end
-
-
1
def default_processors_for(type, file_type, engine_extnames)
-
2
bundled_processors = config[:bundle_processors][type]
-
2
if bundled_processors.any?
-
2
bundled_processors
-
else
-
self_processors_for(type, file_type, engine_extnames)
-
end
-
end
-
-
1
def self_processors_for(type, file_type, engine_extnames)
-
4
processors = []
-
-
4
processors.concat config[:postprocessors][type]
-
-
4
if type != file_type && processor = config[:transformers][file_type][type]
-
processors << processor
-
end
-
-
6
processors.concat engine_extnames.map { |ext| engines[ext] }
-
4
processors.concat config[:preprocessors][file_type]
-
-
4
if processors.any? || mime_type_charset_detecter(type)
-
4
processors << FileReader
-
end
-
-
4
processors
-
end
-
-
1
private
-
1
def register_config_processor(type, mime_type, klass, proc = nil, &block)
-
5
proc ||= block
-
5
processor = wrap_processor(klass, proc)
-
-
5
self.config = hash_reassoc(config, type, mime_type) do |processors|
-
5
processors.unshift(processor)
-
5
processors
-
end
-
-
5
compute_transformers!
-
end
-
-
1
def unregister_config_processor(type, mime_type, klass)
-
if klass.is_a?(String) || klass.is_a?(Symbol)
-
klass = config[type][mime_type].detect do |cls|
-
cls.respond_to?(:name) && cls.name == "Sprockets::LegacyProcProcessor (#{klass})"
-
end
-
end
-
-
self.config = hash_reassoc(config, type, mime_type) do |processors|
-
processors.delete(klass)
-
processors
-
end
-
-
compute_transformers!
-
end
-
-
1
def deprecate_legacy_processor_interface(interface)
-
msg = "You are using the a deprecated processor interface #{ interface.inspect }.\n" +
-
"Please update your processor interface:\n" +
-
"https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md#supporting-all-versions-of-sprockets-in-processors\n"
-
-
Deprecation.new([caller[3]]).warn msg
-
end
-
-
1
def wrap_processor(klass, proc)
-
5
if !proc
-
5
if klass.respond_to?(:call)
-
5
klass
-
else
-
deprecate_legacy_processor_interface(klass)
-
LegacyTiltProcessor.new(klass)
-
end
-
elsif proc.respond_to?(:arity) && proc.arity == 2
-
deprecate_legacy_processor_interface(proc)
-
LegacyProcProcessor.new(klass.to_s, proc)
-
else
-
proc
-
end
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Sprockets
-
# Functional utilities for dealing with Processor functions.
-
#
-
# A Processor is a general function that my modify or transform an asset as
-
# part of the pipeline. CoffeeScript to JavaScript conversion, Minification
-
# or Concatenation are all implemented as seperate Processor steps.
-
#
-
# Processors maybe any object that responds to call. So procs or a class that
-
# defines a self.call method.
-
#
-
# For ergonomics, processors may return a number of shorthand values.
-
# Unfortunately, this means that processors can not compose via ordinary
-
# function composition. The composition helpers here can help.
-
1
module ProcessorUtils
-
1
extend self
-
-
# Public: Compose processors in right to left order.
-
#
-
# processors - Array of processors callables
-
#
-
# Returns a composed Proc.
-
1
def compose_processors(*processors)
-
5
context = self
-
-
5
if processors.length == 1
-
obj = method(:call_processor).to_proc.curry[processors.first]
-
else
-
5
obj = method(:call_processors).to_proc.curry[processors]
-
end
-
-
10
metaclass = (class << obj; self; end)
-
5
metaclass.send(:define_method, :cache_key) do
-
context.processors_cache_keys(processors)
-
end
-
-
5
obj
-
end
-
-
# Public: Invoke list of processors in right to left order.
-
#
-
# The right to left order processing mirrors standard function composition.
-
# Think about:
-
#
-
# bundle.call(uglify.call(coffee.call(input)))
-
#
-
# processors - Array of processor callables
-
# input - Hash of input data to pass to each processor
-
#
-
# Returns a Hash with :data and other processor metadata key/values.
-
1
def call_processors(processors, input)
-
data = input[:data] || ""
-
metadata = (input[:metadata] || {}).dup
-
-
processors.reverse_each do |processor|
-
result = call_processor(processor, input.merge(data: data, metadata: metadata))
-
data = result.delete(:data)
-
metadata.merge!(result)
-
end
-
-
metadata.merge(data: data)
-
end
-
-
# Public: Invoke processor.
-
#
-
# processor - Processor callables
-
# input - Hash of input data to pass to processor
-
#
-
# Returns a Hash with :data and other processor metadata key/values.
-
1
def call_processor(processor, input)
-
metadata = (input[:metadata] || {}).dup
-
metadata[:data] = input[:data]
-
-
case result = processor.call({data: "", metadata: {}}.merge(input))
-
when NilClass
-
metadata
-
when Hash
-
metadata.merge(result)
-
when String
-
metadata.merge(data: result)
-
else
-
raise TypeError, "invalid processor return type: #{result.class}"
-
end
-
end
-
-
# Internal: Get processor defined cached key.
-
#
-
# processor - Processor function
-
#
-
# Returns JSON serializable key or nil.
-
1
def processor_cache_key(processor)
-
7
processor.cache_key if processor.respond_to?(:cache_key)
-
end
-
-
# Internal: Get combined cache keys for set of processors.
-
#
-
# processors - Array of processor functions
-
#
-
# Returns Array of JSON serializable keys.
-
1
def processors_cache_keys(processors)
-
19
processors.map { |processor| processor_cache_key(processor) }
-
end
-
-
# Internal: Set of all "simple" value types allowed to be returned in
-
# processor metadata.
-
1
VALID_METADATA_VALUE_TYPES = Set.new([
-
String,
-
Symbol,
-
TrueClass,
-
FalseClass,
-
NilClass
-
1
] + (0.class == Integer ? [Integer] : [Bignum, Fixnum])).freeze
-
-
# Internal: Set of all nested compound metadata types that can nest values.
-
1
VALID_METADATA_COMPOUND_TYPES = Set.new([
-
Array,
-
Hash,
-
Set
-
]).freeze
-
-
# Internal: Hash of all "simple" value types allowed to be returned in
-
# processor metadata.
-
1
VALID_METADATA_VALUE_TYPES_HASH = VALID_METADATA_VALUE_TYPES.each_with_object({}) do |type, hash|
-
7
hash[type] = true
-
end.freeze
-
-
# Internal: Hash of all nested compound metadata types that can nest values.
-
1
VALID_METADATA_COMPOUND_TYPES_HASH = VALID_METADATA_COMPOUND_TYPES.each_with_object({}) do |type, hash|
-
3
hash[type] = true
-
end.freeze
-
-
# Internal: Set of all allowed metadata types.
-
1
VALID_METADATA_TYPES = (VALID_METADATA_VALUE_TYPES + VALID_METADATA_COMPOUND_TYPES).freeze
-
-
# Internal: Validate returned result of calling a processor pipeline and
-
# raise a friendly user error message.
-
#
-
# result - Metadata Hash returned from call_processors
-
#
-
# Returns result or raises a TypeError.
-
1
def validate_processor_result!(result)
-
if !result.instance_of?(Hash)
-
raise TypeError, "processor metadata result was expected to be a Hash, but was #{result.class}"
-
end
-
-
if !result[:data].instance_of?(String)
-
raise TypeError, "processor :data was expected to be a String, but as #{result[:data].class}"
-
end
-
-
result.each do |key, value|
-
if !key.instance_of?(Symbol)
-
raise TypeError, "processor metadata[#{key.inspect}] expected to be a Symbol"
-
end
-
-
if !valid_processor_metadata_value?(value)
-
raise TypeError, "processor metadata[:#{key}] returned a complex type: #{value.inspect}\n" +
-
"Only #{VALID_METADATA_TYPES.to_a.join(", ")} maybe used."
-
end
-
end
-
-
result
-
end
-
-
# Internal: Validate object is in validate metadata whitelist.
-
#
-
# value - Any Object
-
#
-
# Returns true if class is in whitelist otherwise false.
-
1
def valid_processor_metadata_value?(value)
-
if VALID_METADATA_VALUE_TYPES_HASH[value.class]
-
true
-
elsif VALID_METADATA_COMPOUND_TYPES_HASH[value.class]
-
value.all? { |v| valid_processor_metadata_value?(v) }
-
else
-
false
-
end
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'sprockets/http_utils'
-
1
require 'sprockets/path_dependency_utils'
-
1
require 'sprockets/uri_utils'
-
-
1
module Sprockets
-
1
module Resolve
-
1
include HTTPUtils, PathDependencyUtils, URIUtils
-
-
# Public: Find Asset URI for given a logical path by searching the
-
# environment's load paths.
-
#
-
# resolve("application.js")
-
# # => "file:///path/to/app/javascripts/application.js?type=application/javascript"
-
#
-
# An accept content type can be given if the logical path doesn't have a
-
# format extension.
-
#
-
# resolve("application", accept: "application/javascript")
-
# # => "file:///path/to/app/javascripts/application.coffee?type=application/javascript"
-
#
-
# The String Asset URI is returned or nil if no results are found.
-
1
def resolve(path, options = {})
-
112
path = path.to_s
-
112
paths = options[:load_paths] || config[:paths]
-
112
accept = options[:accept]
-
-
112
if valid_asset_uri?(path)
-
uri, deps = resolve_asset_uri(path)
-
elsif absolute_path?(path)
-
2
filename, type, deps = resolve_absolute_path(paths, path, accept)
-
elsif relative_path?(path)
-
filename, type, pipeline, deps = resolve_relative_path(paths, path, options[:base_path], accept)
-
else
-
110
filename, type, pipeline, deps = resolve_logical_path(paths, path, accept)
-
end
-
-
112
if filename
-
112
params = {}
-
112
params[:type] = type if type
-
112
params[:pipeline] = pipeline if pipeline
-
112
params[:pipeline] = options[:pipeline] if options[:pipeline]
-
112
uri = build_asset_uri(filename, params)
-
end
-
-
112
return uri, deps
-
end
-
-
# Public: Same as resolve() but raises a FileNotFound exception instead of
-
# nil if no assets are found.
-
1
def resolve!(path, options = {})
-
uri, deps = resolve(path, options.merge(compat: false))
-
-
unless uri
-
message = "couldn't find file '#{path}'"
-
-
if relative_path?(path) && options[:base_path]
-
load_path, _ = paths_split(config[:paths], options[:base_path])
-
message << " under '#{load_path}'"
-
end
-
-
message << " with type '#{options[:accept]}'" if options[:accept]
-
message << "\nChecked in these paths: \n #{ config[:paths].join("\n ") }"
-
-
raise FileNotFound, message
-
end
-
-
return uri, deps
-
end
-
-
1
protected
-
1
def resolve_asset_uri(uri)
-
filename, _ = parse_asset_uri(uri)
-
return uri, Set.new([build_file_digest_uri(filename)])
-
end
-
-
1
def resolve_absolute_path(paths, filename, accept)
-
2
deps = Set.new
-
2
filename = File.expand_path(filename)
-
-
# Ensure path is under load paths
-
2
return nil, nil, deps unless paths_split(paths, filename)
-
-
2
_, mime_type, _, _ = parse_path_extnames(filename)
-
2
type = resolve_transform_type(mime_type, accept)
-
2
return nil, nil, deps if accept && !type
-
-
2
return nil, nil, deps unless file?(filename)
-
-
2
deps << build_file_digest_uri(filename)
-
2
return filename, type, deps
-
end
-
-
1
def resolve_relative_path(paths, path, dirname, accept)
-
filename = File.expand_path(path, dirname)
-
load_path, _ = paths_split(paths, dirname)
-
if load_path && logical_path = split_subpath(load_path, filename)
-
resolve_logical_path([load_path], logical_path, accept)
-
else
-
return nil, nil, Set.new
-
end
-
end
-
-
1
def resolve_logical_path(paths, logical_path, accept)
-
110
logical_name, mime_type, _, pipeline = parse_path_extnames(logical_path)
-
110
parsed_accept = parse_accept_options(mime_type, accept)
-
110
transformed_accepts = expand_transform_accepts(parsed_accept)
-
110
filename, mime_type, deps = resolve_under_paths(paths, logical_name, transformed_accepts)
-
-
110
if filename
-
110
deps << build_file_digest_uri(filename)
-
110
type = resolve_transform_type(mime_type, parsed_accept)
-
110
return filename, type, pipeline, deps
-
else
-
return nil, nil, nil, deps
-
end
-
end
-
-
1
def resolve_under_paths(paths, logical_name, accepts)
-
110
all_deps = Set.new
-
110
return nil, nil, all_deps if accepts.empty?
-
-
110
logical_basename = File.basename(logical_name)
-
110
paths.each do |load_path|
-
275
candidates, deps = path_matches(load_path, logical_name, logical_basename)
-
275
all_deps.merge(deps)
-
275
candidate = find_best_q_match(accepts, candidates) do |c, matcher|
-
385
match_mime_type?(c[1] || "application/octet-stream", matcher)
-
end
-
275
return candidate + [all_deps] if candidate
-
end
-
-
return nil, nil, all_deps
-
end
-
-
1
def parse_accept_options(mime_type, types)
-
110
accepts = []
-
110
accepts += parse_q_values(types) if types
-
-
110
if mime_type
-
110
if accepts.empty? || accepts.any? { |accept, _| match_mime_type?(mime_type, accept) }
-
110
accepts = [[mime_type, 1.0]]
-
else
-
return []
-
end
-
end
-
-
110
if accepts.empty?
-
accepts << ['*/*', 1.0]
-
end
-
-
110
accepts
-
end
-
-
1
def path_matches(load_path, logical_name, logical_basename)
-
275
dirname = File.dirname(File.join(load_path, logical_name))
-
275
candidates = dirname_matches(dirname, logical_basename)
-
275
deps = file_digest_dependency_set(dirname)
-
-
275
result = resolve_alternates(load_path, logical_name)
-
275
result[0].each do |fn|
-
candidates << [fn, parse_path_extnames(fn)[1]]
-
end
-
275
deps.merge(result[1])
-
-
275
dirname = File.join(load_path, logical_name)
-
275
if directory? dirname
-
result = dirname_matches(dirname, "index")
-
candidates.concat(result)
-
end
-
-
275
deps.merge(file_digest_dependency_set(dirname))
-
-
440
return candidates.select { |fn, _| file?(fn) }, deps
-
end
-
-
1
def dirname_matches(dirname, basename)
-
275
candidates = []
-
275
entries = self.entries(dirname)
-
275
entries.each do |entry|
-
1045
next unless File.basename(entry).start_with?(basename)
-
165
name, type, _, _ = parse_path_extnames(entry)
-
165
if basename == name
-
165
candidates << [File.join(dirname, entry), type]
-
end
-
end
-
275
candidates
-
end
-
-
1
def resolve_alternates(load_path, logical_name)
-
275
return [], Set.new
-
end
-
-
# Internal: Returns the name, mime type and `Array` of engine extensions.
-
#
-
# "foo.js.coffee.erb"
-
# # => ["foo", "application/javascript", [".coffee", ".erb"]]
-
#
-
1
def parse_path_extnames(path)
-
302
engines = []
-
302
extname, value = match_path_extname(path, extname_map)
-
-
302
if extname
-
299
path = path.chomp(extname)
-
299
type, engines, pipeline = value.values_at(:type, :engines, :pipeline)
-
end
-
-
302
return path, type, engines, pipeline
-
end
-
end
-
end
-
1
require 'sprockets/autoload'
-
1
require 'sprockets/digest_utils'
-
-
1
module Sprockets
-
# Public: Sass CSS minifier.
-
#
-
# To accept the default options
-
#
-
# environment.register_bundle_processor 'text/css',
-
# Sprockets::SassCompressor
-
#
-
# Or to pass options to the Sass::Engine class.
-
#
-
# environment.register_bundle_processor 'text/css',
-
# Sprockets::SassCompressor.new({ ... })
-
#
-
1
class SassCompressor
-
1
VERSION = '1'
-
-
# Public: Return singleton instance with default options.
-
#
-
# Returns SassCompressor object.
-
1
def self.instance
-
1
@instance ||= new
-
end
-
-
1
def self.call(input)
-
instance.call(input)
-
end
-
-
1
def self.cache_key
-
1
instance.cache_key
-
end
-
-
1
attr_reader :cache_key
-
-
1
def initialize(options = {})
-
1
@options = {
-
syntax: :scss,
-
cache: false,
-
read_cache: false,
-
style: :compressed
-
}.merge(options).freeze
-
1
@cache_key = "#{self.class.name}:#{Autoload::Sass::VERSION}:#{VERSION}:#{DigestUtils.digest(options)}".freeze
-
end
-
-
1
def call(input)
-
Autoload::Sass::Engine.new(input[:data], @options).render
-
end
-
end
-
end
-
# Deprecated: Require sprockets/sass_processor instead
-
1
require 'sprockets/sass_processor'
-
# Deprecated: Require sprockets/sass_processor instead
-
1
require 'sprockets/sass_processor'
-
1
require 'rack/utils'
-
1
require 'sprockets/autoload'
-
1
require 'uri'
-
-
1
module Sprockets
-
# Processor engine class for the SASS/SCSS compiler. Depends on the `sass` gem.
-
#
-
# For more infomation see:
-
#
-
# https://github.com/sass/sass
-
# https://github.com/rails/sass-rails
-
#
-
1
class SassProcessor
-
1
autoload :CacheStore, 'sprockets/sass_cache_store'
-
-
# Internal: Defines default sass syntax to use. Exposed so the ScssProcessor
-
# may override it.
-
1
def self.syntax
-
:sass
-
end
-
-
# Public: Return singleton instance with default options.
-
#
-
# Returns SassProcessor object.
-
1
def self.instance
-
@instance ||= new
-
end
-
-
1
def self.call(input)
-
instance.call(input)
-
end
-
-
1
def self.cache_key
-
instance.cache_key
-
end
-
-
1
attr_reader :cache_key
-
-
# Public: Initialize template with custom options.
-
#
-
# options - Hash
-
# cache_version - String custom cache version. Used to force a cache
-
# change after code changes are made to Sass Functions.
-
#
-
1
def initialize(options = {}, &block)
-
2
@cache_version = options[:cache_version]
-
2
@cache_key = "#{self.class.name}:#{VERSION}:#{Autoload::Sass::VERSION}:#{@cache_version}".freeze
-
-
2
@functions = Module.new do
-
2
include Functions
-
2
include options[:functions] if options[:functions]
-
2
class_eval(&block) if block_given?
-
end
-
end
-
-
1
def call(input)
-
context = input[:environment].context_class.new(input)
-
-
options = {
-
filename: input[:filename],
-
syntax: self.class.syntax,
-
cache_store: build_cache_store(input, @cache_version),
-
load_paths: input[:environment].paths,
-
sprockets: {
-
context: context,
-
environment: input[:environment],
-
dependencies: context.metadata[:dependencies]
-
}
-
}
-
-
engine = Autoload::Sass::Engine.new(input[:data], options)
-
-
css = Utils.module_include(Autoload::Sass::Script::Functions, @functions) do
-
engine.render
-
end
-
-
# Track all imported files
-
sass_dependencies = Set.new([input[:filename]])
-
engine.dependencies.map do |dependency|
-
sass_dependencies << dependency.options[:filename]
-
context.metadata[:dependencies] << URIUtils.build_file_digest_uri(dependency.options[:filename])
-
end
-
-
context.metadata.merge(data: css, sass_dependencies: sass_dependencies)
-
end
-
-
# Public: Build the cache store to be used by the Sass engine.
-
#
-
# input - the input hash.
-
# version - the cache version.
-
#
-
# Override this method if you need to use a different cache than the
-
# Sprockets cache.
-
1
def build_cache_store(input, version)
-
CacheStore.new(input[:cache], version)
-
end
-
1
private :build_cache_store
-
-
# Public: Functions injected into Sass context during Sprockets evaluation.
-
#
-
# This module may be extended to add global functionality to all Sprockets
-
# Sass environments. Though, scoping your functions to just your environment
-
# is preferred.
-
#
-
# module Sprockets::SassProcessor::Functions
-
# def asset_path(path, options = {})
-
# end
-
# end
-
#
-
1
module Functions
-
# Public: Generate a url for asset path.
-
#
-
# Default implementation is deprecated. Currently defaults to
-
# Context#asset_path.
-
#
-
# Will raise NotImplementedError in the future. Users should provide their
-
# own base implementation.
-
#
-
# Returns a Sass::Script::String.
-
1
def asset_path(path, options = {})
-
path = path.value
-
-
path, _, query, fragment = URI.split(path)[5..8]
-
path = sprockets_context.asset_path(path, options)
-
query = "?#{query}" if query
-
fragment = "##{fragment}" if fragment
-
-
Autoload::Sass::Script::String.new("#{path}#{query}#{fragment}", :string)
-
end
-
-
# Public: Generate a asset url() link.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def asset_url(path, options = {})
-
Autoload::Sass::Script::String.new("url(#{asset_path(path, options).value})")
-
end
-
-
# Public: Generate url for image path.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def image_path(path)
-
asset_path(path, type: :image)
-
end
-
-
# Public: Generate a image url() link.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def image_url(path)
-
asset_url(path, type: :image)
-
end
-
-
# Public: Generate url for video path.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def video_path(path)
-
asset_path(path, type: :video)
-
end
-
-
# Public: Generate a video url() link.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def video_url(path)
-
asset_url(path, type: :video)
-
end
-
-
# Public: Generate url for audio path.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def audio_path(path)
-
asset_path(path, type: :audio)
-
end
-
-
# Public: Generate a audio url() link.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def audio_url(path)
-
asset_url(path, type: :audio)
-
end
-
-
# Public: Generate url for font path.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def font_path(path)
-
asset_path(path, type: :font)
-
end
-
-
# Public: Generate a font url() link.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def font_url(path)
-
asset_url(path, type: :font)
-
end
-
-
# Public: Generate url for javascript path.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def javascript_path(path)
-
asset_path(path, type: :javascript)
-
end
-
-
# Public: Generate a javascript url() link.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def javascript_url(path)
-
asset_url(path, type: :javascript)
-
end
-
-
# Public: Generate url for stylesheet path.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def stylesheet_path(path)
-
asset_path(path, type: :stylesheet)
-
end
-
-
# Public: Generate a stylesheet url() link.
-
#
-
# path - Sass::Script::String URL path
-
#
-
# Returns a Sass::Script::String.
-
1
def stylesheet_url(path)
-
asset_url(path, type: :stylesheet)
-
end
-
-
# Public: Generate a data URI for asset path.
-
#
-
# path - Sass::Script::String logical asset path
-
#
-
# Returns a Sass::Script::String.
-
1
def asset_data_url(path)
-
url = sprockets_context.asset_data_uri(path.value)
-
Autoload::Sass::Script::String.new("url(" + url + ")")
-
end
-
-
1
protected
-
# Public: The Environment.
-
#
-
# Returns Sprockets::Environment.
-
1
def sprockets_environment
-
options[:sprockets][:environment]
-
end
-
-
# Public: Mutatable set of dependencies.
-
#
-
# Returns a Set.
-
1
def sprockets_dependencies
-
options[:sprockets][:dependencies]
-
end
-
-
# Deprecated: Get the Context instance. Use APIs on
-
# sprockets_environment or sprockets_dependencies directly.
-
#
-
# Returns a Context instance.
-
1
def sprockets_context
-
options[:sprockets][:context]
-
end
-
-
end
-
end
-
-
1
class ScssProcessor < SassProcessor
-
1
def self.syntax
-
:scss
-
end
-
end
-
-
# Deprecated: Use Sprockets::SassProcessor::Functions instead.
-
1
SassFunctions = SassProcessor::Functions
-
end
-
1
require 'time'
-
1
require 'rack/utils'
-
-
1
module Sprockets
-
# `Server` is a concern mixed into `Environment` and
-
# `CachedEnvironment` that provides a Rack compatible `call`
-
# interface and url generation helpers.
-
1
module Server
-
# `call` implements the Rack 1.x specification which accepts an
-
# `env` Hash and returns a three item tuple with the status code,
-
# headers, and body.
-
#
-
# Mapping your environment at a url prefix will serve all assets
-
# in the path.
-
#
-
# map "/assets" do
-
# run Sprockets::Environment.new
-
# end
-
#
-
# A request for `"/assets/foo/bar.js"` will search your
-
# environment for `"foo/bar.js"`.
-
1
def call(env)
-
start_time = Time.now.to_f
-
time_elapsed = lambda { ((Time.now.to_f - start_time) * 1000).to_i }
-
-
if !['GET', 'HEAD'].include?(env['REQUEST_METHOD'])
-
return method_not_allowed_response
-
end
-
-
msg = "Served asset #{env['PATH_INFO']} -"
-
-
# Extract the path from everything after the leading slash
-
path = Rack::Utils.unescape(env['PATH_INFO'].to_s.sub(/^\//, ''))
-
-
# Strip fingerprint
-
if fingerprint = path_fingerprint(path)
-
path = path.sub("-#{fingerprint}", '')
-
end
-
-
# URLs containing a `".."` are rejected for security reasons.
-
if forbidden_request?(path)
-
return forbidden_response(env)
-
end
-
-
# Look up the asset.
-
options = {}
-
options[:pipeline] = :self if body_only?(env)
-
-
asset = find_asset(path, options)
-
-
# 2.x/3.x compatibility hack. Just ignore fingerprints on ?body=1 requests.
-
# 3.x/4.x prefers strong validation of fingerprint to body contents, but
-
# 2.x just ignored it.
-
if asset && parse_asset_uri(asset.uri)[1][:pipeline] == "self"
-
fingerprint = nil
-
end
-
-
if fingerprint
-
if_match = fingerprint
-
elsif env['HTTP_IF_MATCH']
-
if_match = env['HTTP_IF_MATCH'][/^"(\w+)"$/, 1]
-
end
-
-
if env['HTTP_IF_NONE_MATCH']
-
if_none_match = env['HTTP_IF_NONE_MATCH'][/^"(\w+)"$/, 1]
-
end
-
-
if asset.nil?
-
status = :not_found
-
elsif fingerprint && asset.etag != fingerprint
-
status = :not_found
-
elsif if_match && asset.etag != if_match
-
status = :precondition_failed
-
elsif if_none_match && asset.etag == if_none_match
-
status = :not_modified
-
else
-
status = :ok
-
end
-
-
case status
-
when :ok
-
logger.info "#{msg} 200 OK (#{time_elapsed.call}ms)"
-
ok_response(asset, env)
-
when :not_modified
-
logger.info "#{msg} 304 Not Modified (#{time_elapsed.call}ms)"
-
not_modified_response(env, if_none_match)
-
when :not_found
-
logger.info "#{msg} 404 Not Found (#{time_elapsed.call}ms)"
-
not_found_response(env)
-
when :precondition_failed
-
logger.info "#{msg} 412 Precondition Failed (#{time_elapsed.call}ms)"
-
precondition_failed_response(env)
-
end
-
rescue Exception => e
-
logger.error "Error compiling asset #{path}:"
-
logger.error "#{e.class.name}: #{e.message}"
-
-
case File.extname(path)
-
when ".js"
-
# Re-throw JavaScript asset exceptions to the browser
-
logger.info "#{msg} 500 Internal Server Error\n\n"
-
return javascript_exception_response(e)
-
when ".css"
-
# Display CSS asset exceptions in the browser
-
logger.info "#{msg} 500 Internal Server Error\n\n"
-
return css_exception_response(e)
-
else
-
raise
-
end
-
end
-
-
1
private
-
1
def forbidden_request?(path)
-
# Prevent access to files elsewhere on the file system
-
#
-
# http://example.org/assets/../../../etc/passwd
-
#
-
path.include?("..") || absolute_path?(path)
-
end
-
-
1
def head_request?(env)
-
env['REQUEST_METHOD'] == 'HEAD'
-
end
-
-
# Returns a 200 OK response tuple
-
1
def ok_response(asset, env)
-
if head_request?(env)
-
[ 200, headers(env, asset, 0), [] ]
-
else
-
[ 200, headers(env, asset, asset.length), asset ]
-
end
-
end
-
-
# Returns a 304 Not Modified response tuple
-
1
def not_modified_response(env, etag)
-
[ 304, cache_headers(env, etag), [] ]
-
end
-
-
# Returns a 403 Forbidden response tuple
-
1
def forbidden_response(env)
-
if head_request?(env)
-
[ 403, { "Content-Type" => "text/plain", "Content-Length" => "0" }, [] ]
-
else
-
[ 403, { "Content-Type" => "text/plain", "Content-Length" => "9" }, [ "Forbidden" ] ]
-
end
-
end
-
-
# Returns a 404 Not Found response tuple
-
1
def not_found_response(env)
-
if head_request?(env)
-
[ 404, { "Content-Type" => "text/plain", "Content-Length" => "0", "X-Cascade" => "pass" }, [] ]
-
else
-
[ 404, { "Content-Type" => "text/plain", "Content-Length" => "9", "X-Cascade" => "pass" }, [ "Not found" ] ]
-
end
-
end
-
-
1
def method_not_allowed_response
-
[ 405, { "Content-Type" => "text/plain", "Content-Length" => "18" }, [ "Method Not Allowed" ] ]
-
end
-
-
1
def precondition_failed_response(env)
-
if head_request?(env)
-
[ 412, { "Content-Type" => "text/plain", "Content-Length" => "0", "X-Cascade" => "pass" }, [] ]
-
else
-
[ 412, { "Content-Type" => "text/plain", "Content-Length" => "19", "X-Cascade" => "pass" }, [ "Precondition Failed" ] ]
-
end
-
end
-
-
# Returns a JavaScript response that re-throws a Ruby exception
-
# in the browser
-
1
def javascript_exception_response(exception)
-
err = "#{exception.class.name}: #{exception.message}\n (in #{exception.backtrace[0]})"
-
body = "throw Error(#{err.inspect})"
-
[ 200, { "Content-Type" => "application/javascript", "Content-Length" => body.bytesize.to_s }, [ body ] ]
-
end
-
-
# Returns a CSS response that hides all elements on the page and
-
# displays the exception
-
1
def css_exception_response(exception)
-
message = "\n#{exception.class.name}: #{exception.message}"
-
backtrace = "\n #{exception.backtrace.first}"
-
-
body = <<-CSS
-
html {
-
padding: 18px 36px;
-
}
-
-
head {
-
display: block;
-
}
-
-
body {
-
margin: 0;
-
padding: 0;
-
}
-
-
body > * {
-
display: none !important;
-
}
-
-
head:after, body:before, body:after {
-
display: block !important;
-
}
-
-
head:after {
-
font-family: sans-serif;
-
font-size: large;
-
font-weight: bold;
-
content: "Error compiling CSS asset";
-
}
-
-
body:before, body:after {
-
font-family: monospace;
-
white-space: pre-wrap;
-
}
-
-
body:before {
-
font-weight: bold;
-
content: "#{escape_css_content(message)}";
-
}
-
-
body:after {
-
content: "#{escape_css_content(backtrace)}";
-
}
-
CSS
-
-
[ 200, { "Content-Type" => "text/css; charset=utf-8", "Content-Length" => body.bytesize.to_s }, [ body ] ]
-
end
-
-
# Escape special characters for use inside a CSS content("...") string
-
1
def escape_css_content(content)
-
content.
-
gsub('\\', '\\\\005c ').
-
gsub("\n", '\\\\000a ').
-
gsub('"', '\\\\0022 ').
-
gsub('/', '\\\\002f ')
-
end
-
-
# Test if `?body=1` or `body=true` query param is set
-
1
def body_only?(env)
-
env["QUERY_STRING"].to_s =~ /body=(1|t)/
-
end
-
-
1
def cache_headers(env, etag)
-
headers = {}
-
-
# Set caching headers
-
headers["Cache-Control"] = "public"
-
headers["ETag"] = %("#{etag}")
-
-
# If the request url contains a fingerprint, set a long
-
# expires on the response
-
if path_fingerprint(env["PATH_INFO"])
-
headers["Cache-Control"] << ", max-age=31536000"
-
-
# Otherwise set `must-revalidate` since the asset could be modified.
-
else
-
headers["Cache-Control"] << ", must-revalidate"
-
headers["Vary"] = "Accept-Encoding"
-
end
-
-
headers
-
end
-
-
1
def headers(env, asset, length)
-
headers = {}
-
-
# Set content length header
-
headers["Content-Length"] = length.to_s
-
-
# Set content type header
-
if type = asset.content_type
-
# Set charset param for text/* mime types
-
if type.start_with?("text/") && asset.charset
-
type += "; charset=#{asset.charset}"
-
end
-
headers["Content-Type"] = type
-
end
-
-
headers.merge(cache_headers(env, asset.etag))
-
end
-
-
# Gets ETag fingerprint.
-
#
-
# "foo-0aa2105d29558f3eb790d411d7d8fb66.js"
-
# # => "0aa2105d29558f3eb790d411d7d8fb66"
-
#
-
1
def path_fingerprint(path)
-
path[/-([0-9a-f]{7,128})\.[^.]+\z/, 1]
-
end
-
end
-
end
-
1
require 'sprockets/http_utils'
-
1
require 'sprockets/processor_utils'
-
1
require 'sprockets/utils'
-
-
1
module Sprockets
-
1
module Transformers
-
1
include HTTPUtils, ProcessorUtils, Utils
-
-
# Public: Two level mapping of a source mime type to a target mime type.
-
#
-
# environment.transformers
-
# # => { 'text/coffeescript' => {
-
# 'application/javascript' => ConvertCoffeeScriptToJavaScript
-
# }
-
# }
-
#
-
1
def transformers
-
config[:transformers]
-
end
-
-
# Public: Register a transformer from and to a mime type.
-
#
-
# from - String mime type
-
# to - String mime type
-
# proc - Callable block that accepts an input Hash.
-
#
-
# Examples
-
#
-
# register_transformer 'text/coffeescript', 'application/javascript',
-
# ConvertCoffeeScriptToJavaScript
-
#
-
# register_transformer 'image/svg+xml', 'image/png', ConvertSvgToPng
-
#
-
# Returns nothing.
-
1
def register_transformer(from, to, proc)
-
2
self.config = hash_reassoc(config, :registered_transformers, from) do |transformers|
-
2
transformers.merge(to => proc)
-
end
-
2
compute_transformers!
-
end
-
-
# Internal: Resolve target mime type that the source type should be
-
# transformed to.
-
#
-
# type - String from mime type
-
# accept - String accept type list (default: '*/*')
-
#
-
# Examples
-
#
-
# resolve_transform_type('text/plain', 'text/plain')
-
# # => 'text/plain'
-
#
-
# resolve_transform_type('image/svg+xml', 'image/png, image/*')
-
# # => 'image/png'
-
#
-
# resolve_transform_type('text/css', 'image/png')
-
# # => nil
-
#
-
# Returns String mime type or nil is no type satisfied the accept value.
-
1
def resolve_transform_type(type, accept)
-
112
find_best_mime_type_match(accept || '*/*', [type].compact + config[:transformers][type].keys)
-
end
-
-
# Internal: Expand accept type list to include possible transformed types.
-
#
-
# parsed_accepts - Array of accept q values
-
#
-
# Examples
-
#
-
# expand_transform_accepts([['application/javascript', 1.0]])
-
# # => [['application/javascript', 1.0], ['text/coffeescript', 0.8]]
-
#
-
# Returns an expanded Array of q values.
-
1
def expand_transform_accepts(parsed_accepts)
-
110
accepts = []
-
110
parsed_accepts.each do |(type, q)|
-
110
accepts.push([type, q])
-
110
config[:inverted_transformers][type].each do |subtype|
-
110
accepts.push([subtype, q * 0.8])
-
end
-
end
-
110
accepts
-
end
-
-
# Internal: Compose multiple transformer steps into a single processor
-
# function.
-
#
-
# transformers - Two level Hash of a source mime type to a target mime type
-
# types - Array of mime type steps
-
#
-
# Returns Processor.
-
1
def compose_transformers(transformers, types)
-
5
if types.length < 2
-
raise ArgumentError, "too few transform types: #{types.inspect}"
-
end
-
-
5
i = 0
-
5
processors = []
-
-
5
loop do
-
10
src = types[i]
-
10
dst = types[i+1]
-
10
break unless src && dst
-
-
5
unless processor = transformers[src][dst]
-
raise ArgumentError, "missing transformer for type: #{src} to #{dst}"
-
end
-
5
processors.concat config[:postprocessors][src]
-
5
processors << processor
-
5
processors.concat config[:preprocessors][dst]
-
-
5
i += 1
-
end
-
-
5
if processors.size > 1
-
5
compose_processors(*processors.reverse)
-
elsif processors.size == 1
-
processors.first
-
end
-
end
-
-
1
private
-
1
def compute_transformers!
-
7
registered_transformers = self.config[:registered_transformers]
-
119
transformers = Hash.new { {} }
-
62
inverted_transformers = Hash.new { Set.new }
-
-
registered_transformers.keys.flat_map do |key|
-
15
dfs_paths([key]) { |k| registered_transformers[k].keys }
-
7
end.each do |types|
-
5
src, dst = types.first, types.last
-
5
processor = compose_transformers(registered_transformers, types)
-
-
5
transformers[src] = {} unless transformers.key?(src)
-
5
transformers[src][dst] = processor
-
-
5
inverted_transformers[dst] = Set.new unless inverted_transformers.key?(dst)
-
5
inverted_transformers[dst] << src
-
end
-
-
14
self.config = hash_reassoc(config, :transformers) { transformers }
-
14
self.config = hash_reassoc(config, :inverted_transformers) { inverted_transformers }
-
end
-
end
-
end
-
1
require 'sprockets/autoload'
-
1
require 'sprockets/digest_utils'
-
-
1
module Sprockets
-
# Public: Uglifier/Uglify compressor.
-
#
-
# To accept the default options
-
#
-
# environment.register_bundle_processor 'application/javascript',
-
# Sprockets::UglifierCompressor
-
#
-
# Or to pass options to the Uglifier class.
-
#
-
# environment.register_bundle_processor 'application/javascript',
-
# Sprockets::UglifierCompressor.new(comments: :copyright)
-
#
-
1
class UglifierCompressor
-
1
VERSION = '1'
-
-
# Public: Return singleton instance with default options.
-
#
-
# Returns UglifierCompressor object.
-
1
def self.instance
-
@instance ||= new
-
end
-
-
1
def self.call(input)
-
instance.call(input)
-
end
-
-
1
def self.cache_key
-
instance.cache_key
-
end
-
-
1
attr_reader :cache_key
-
-
1
def initialize(options = {})
-
# Feature detect Uglifier 2.0 option support
-
if Autoload::Uglifier::DEFAULTS[:copyright]
-
# Uglifier < 2.x
-
options[:copyright] ||= false
-
else
-
# Uglifier >= 2.x
-
options[:comments] ||= :none
-
end
-
-
@options = options
-
@cache_key = "#{self.class.name}:#{Autoload::Uglifier::VERSION}:#{VERSION}:#{DigestUtils.digest(options)}".freeze
-
end
-
-
1
def call(input)
-
@uglifier ||= Autoload::Uglifier.new(@options)
-
@uglifier.compile(input[:data])
-
end
-
end
-
end
-
1
require 'sprockets/uri_utils'
-
1
require 'sprockets/uri_tar'
-
-
1
module Sprockets
-
# Internal: Used to parse and store the URI to an unloaded asset
-
# Generates keys used to store and retrieve items from cache
-
1
class UnloadedAsset
-
-
# Internal: Initialize object for generating cache keys
-
#
-
# uri - A String containing complete URI to a file including scheme
-
# and full path such as
-
# "file:///Path/app/assets/js/app.js?type=application/javascript"
-
# env - The current "environment" that assets are being loaded into.
-
# We need it so we know where the +root+ (directory where sprockets
-
# is being invoked). We also need for the `file_digest` method,
-
# since, for some strange reason, memoization is provided by
-
# overriding methods such as `stat` in the `PathUtils` module.
-
#
-
# Returns UnloadedAsset.
-
1
def initialize(uri, env)
-
30
@uri = uri.to_s
-
30
@env = env
-
30
@compressed_path = URITar.new(uri, env).compressed_path
-
30
@params = nil # lazy loaded
-
30
@filename = nil # lazy loaded
-
end
-
1
attr_reader :compressed_path, :uri
-
-
# Internal: Full file path without schema
-
#
-
# This returns a string containing the full path to the asset without the schema.
-
# Information is loaded lazilly since we want `UnloadedAsset.new(dep, self).relative_path`
-
# to be fast. Calling this method the first time allocates an array and a hash.
-
#
-
# Example
-
#
-
# If the URI is `file:///Full/path/app/assets/javascripts/application.js"` then the
-
# filename would be `"/Full/path/app/assets/javascripts/application.js"`
-
#
-
# Returns a String.
-
1
def filename
-
2
unless @filename
-
load_file_params
-
end
-
2
@filename
-
end
-
-
# Internal: Hash of param values
-
#
-
# This information is generated and used internally by sprockets.
-
# Known keys include `:type` which store the asset's mime-type, `:id` which is a fully resolved
-
# digest for the asset (includes dependency digest as opposed to a digest of only file contents)
-
# and `:pipeline`. Hash may be empty.
-
#
-
# Example
-
#
-
# If the URI is `file:///Full/path/app/assets/javascripts/application.js"type=application/javascript`
-
# Then the params would be `{type: "application/javascript"}`
-
#
-
# Returns a Hash.
-
1
def params
-
2
unless @params
-
2
load_file_params
-
end
-
2
@params
-
end
-
-
# Internal: Key of asset
-
#
-
# Used to retrieve an asset from the cache based on "compressed" path to asset.
-
# A "compressed" path can either be relative to the root of the project or an
-
# absolute path.
-
#
-
# Returns a String.
-
1
def asset_key
-
2
"asset-uri:#{compressed_path}"
-
end
-
-
# Public: Dependency History key
-
#
-
# Used to retrieve an array of "histories" each of which contain a set of stored dependencies
-
# for a given asset path and filename digest.
-
#
-
# A dependency can refer to either an asset i.e. index.js
-
# may rely on jquery.js (so jquery.js is a dependency), or other factors that may affect
-
# compilation, such as the VERSION of sprockets (i.e. the environment) and what "processors"
-
# are used.
-
#
-
# For example a history array with one Set of dependencies may look like:
-
#
-
# [["environment-version", "environment-paths", "processors:type=text/css&file_type=text/css",
-
# "file-digest:///Full/path/app/assets/stylesheets/application.css",
-
# "processors:type=text/css&file_type=text/css&pipeline=self",
-
# "file-digest:///Full/path/app/assets/stylesheets"]]
-
#
-
# This method of asset lookup is used to ensure that none of the dependencies have been modified
-
# since last lookup. If one of them has, the key will be different and a new entry must be stored.
-
#
-
# URI depndencies are later converted to "compressed" paths
-
#
-
# Returns a String.
-
1
def dependency_history_key
-
2
"asset-uri-cache-dependencies:#{compressed_path}:#{ @env.file_digest(filename) }"
-
end
-
-
# Internal: Digest key
-
#
-
# Used to retrieve a string containing the "compressed" path to an asset based on
-
# a digest. The digest is generated from dependencies stored via information stored in
-
# the `dependency_history_key` after each of the "dependencies" is "resolved" for example
-
# "environment-version" may be resolved to "environment-1.0-3.2.0" for version "3.2.0" of sprockets
-
#
-
# Returns a String.
-
1
def digest_key(digest)
-
2
"asset-uri-digest:#{compressed_path}:#{digest}"
-
end
-
-
# Internal: File digest key
-
#
-
# The digest for a given file won't change if the path and the stat time hasn't changed
-
# We can save time by not re-computing this information and storing it in the cache
-
#
-
# Returns a String.
-
1
def file_digest_key(stat)
-
26
"file_digest:#{compressed_path}:#{stat}"
-
end
-
-
1
private
-
# Internal: Parses uri into filename and params hash
-
#
-
# Returns Array with filename and params hash
-
1
def load_file_params
-
2
@filename, @params = URIUtils.parse_asset_uri(uri)
-
end
-
end
-
end
-
1
require 'sprockets/path_utils'
-
-
1
module Sprockets
-
# Internal: used to "expand" and "compress" values for storage
-
1
class URITar
-
1
attr_reader :scheme, :root, :path
-
-
# Internal: Initialize object for compression or expansion
-
#
-
# uri - A String containing URI that may or may not contain the scheme
-
# env - The current "environment" that assets are being loaded into.
-
1
def initialize(uri, env)
-
150
@root = env.root
-
150
@env = env
-
150
uri = uri.to_s
-
150
if uri.include?("://".freeze)
-
110
@scheme, _, @path = uri.partition("://".freeze)
-
110
@scheme << "://".freeze
-
else
-
40
@scheme = "".freeze
-
40
@path = uri
-
end
-
end
-
-
# Internal: Converts full uri to a "compressed" uri
-
#
-
# If a uri is inside of an environment's root it will
-
# be shortened to be a relative path.
-
#
-
# If a uri is outside of the environment's root the original
-
# uri will be returned.
-
#
-
# Returns String
-
1
def compress
-
8
scheme + compressed_path
-
end
-
-
# Internal: Tells us if we are using an absolute path
-
#
-
# Nix* systems start with a `/` like /Users/schneems.
-
# Windows systems start with a drive letter than colon and slash
-
# like C:/Schneems.
-
1
def absolute_path?
-
112
PathUtils.absolute_path?(path)
-
end
-
-
# Internal: Convert a "compressed" uri to an absolute path
-
#
-
# If a uri is inside of the environment's root it will not
-
# start with a slash for example:
-
#
-
# file://this/is/a/relative/path
-
#
-
# If a uri is outside the root, it will start with a slash:
-
#
-
# file:///This/is/an/absolute/path
-
#
-
# Returns String
-
1
def expand
-
112
if absolute_path?
-
# Stored path was absolute, don't add root
-
scheme + path
-
else
-
112
if scheme.empty?
-
4
File.join(root, path)
-
else
-
# We always want to return an absolute uri,
-
# make sure the path starts with a slash.
-
108
scheme + File.join("/".freeze, root, path)
-
end
-
end
-
end
-
-
# Internal: Returns "compressed" path
-
#
-
# If the input uri is relative to the environment root
-
# it will return a path relative to the environment root.
-
# Otherwise an absolute path will be returned.
-
#
-
# Only path information is returned, and not scheme.
-
#
-
# Returns String
-
1
def compressed_path
-
# windows
-
38
if !@root.start_with?("/".freeze) && path.start_with?("/".freeze)
-
consistent_root = "/".freeze + @root
-
else
-
38
consistent_root = @root
-
end
-
-
38
if compressed_path = PathUtils.split_subpath(consistent_root, path)
-
36
compressed_path
-
else
-
2
path
-
end
-
end
-
end
-
end
-
1
require 'uri'
-
-
1
module Sprockets
-
# Internal: Asset URI related parsing utilities. Mixed into Environment.
-
#
-
# An Asset URI identifies the compiled Asset result. It shares the file:
-
# scheme and requires an absolute path.
-
#
-
# Other query parameters
-
#
-
# type - String output content type. Otherwise assumed from file extension.
-
# This maybe different than the extension if the asset is transformed
-
# from one content type to another. For an example .coffee -> .js.
-
#
-
# id - Unique fingerprint of the entire asset and all its metadata. Assets
-
# will only have the same id if they serialize to an identical value.
-
#
-
# pipeline - String name of pipeline.
-
#
-
1
module URIUtils
-
1
extend self
-
-
# Internal: Parse URI into component parts.
-
#
-
# uri - String uri
-
#
-
# Returns Array of components.
-
1
def split_uri(uri)
-
URI.split(uri)
-
end
-
-
# Internal: Join URI component parts into String.
-
#
-
# Returns String.
-
1
def join_uri(scheme, userinfo, host, port, registry, path, opaque, query, fragment)
-
URI::Generic.new(scheme, userinfo, host, port, registry, path, opaque, query, fragment).to_s
-
end
-
-
# Internal: Parse file: URI into component parts.
-
#
-
# uri - String uri
-
#
-
# Returns [scheme, host, path, query].
-
1
def split_file_uri(uri)
-
46
scheme, _, host, _, _, path, _, query, _ = URI.split(uri)
-
-
46
path = URI::Generic::DEFAULT_PARSER.unescape(path)
-
46
path.force_encoding(Encoding::UTF_8)
-
-
# Hack for parsing Windows "file:///C:/Users/IEUser" paths
-
46
path.gsub!(/^\/([a-zA-Z]:)/, '\1'.freeze)
-
-
46
[scheme, host, path, query]
-
end
-
-
# Internal: Join file: URI component parts into String.
-
#
-
# Returns String.
-
1
def join_file_uri(scheme, host, path, query)
-
774
str = "#{scheme}://"
-
774
str << host if host
-
774
path = "/#{path}" unless path.start_with?("/")
-
774
str << URI::Generic::DEFAULT_PARSER.escape(path)
-
774
str << "?#{query}" if query
-
774
str
-
end
-
-
# Internal: Check if String is a valid Asset URI.
-
#
-
# str - Possible String asset URI.
-
#
-
# Returns true or false.
-
1
def valid_asset_uri?(str)
-
# Quick prefix check before attempting a full parse
-
112
str.start_with?("file://") && parse_asset_uri(str) ? true : false
-
rescue URI::InvalidURIError
-
false
-
end
-
-
# Internal: Parse Asset URI.
-
#
-
# Examples
-
#
-
# parse("file:///tmp/js/application.coffee?type=application/javascript")
-
# # => "/tmp/js/application.coffee", {type: "application/javascript"}
-
#
-
# uri - String asset URI
-
#
-
# Returns String path and Hash of symbolized parameters.
-
1
def parse_asset_uri(uri)
-
2
scheme, _, path, query = split_file_uri(uri)
-
-
2
unless scheme == 'file'
-
raise URI::InvalidURIError, "expected file:// scheme: #{uri}"
-
end
-
-
2
return path, parse_uri_query_params(query)
-
end
-
-
# Internal: Build Asset URI.
-
#
-
# Examples
-
#
-
# build("/tmp/js/application.coffee", type: "application/javascript")
-
# # => "file:///tmp/js/application.coffee?type=application/javascript"
-
#
-
# path - String file path
-
# params - Hash of optional parameters
-
#
-
# Returns String URI.
-
1
def build_asset_uri(path, params = {})
-
112
join_file_uri("file", nil, path, encode_uri_query_params(params))
-
end
-
-
# Internal: Parse file-digest dependency URI.
-
#
-
# Examples
-
#
-
# parse("file-digest:/tmp/js/application.js")
-
# # => "/tmp/js/application.js"
-
#
-
# uri - String file-digest URI
-
#
-
# Returns String path.
-
1
def parse_file_digest_uri(uri)
-
44
scheme, _, path, _ = split_file_uri(uri)
-
-
44
unless scheme == 'file-digest'.freeze
-
raise URI::InvalidURIError, "expected file-digest scheme: #{uri}"
-
end
-
-
44
path
-
end
-
-
# Internal: Build file-digest dependency URI.
-
#
-
# Examples
-
#
-
# build("/tmp/js/application.js")
-
# # => "file-digest:/tmp/js/application.js"
-
#
-
# path - String file path
-
#
-
# Returns String URI.
-
1
def build_file_digest_uri(path)
-
662
join_file_uri('file-digest'.freeze, nil, path, nil)
-
end
-
-
# Internal: Serialize hash of params into query string.
-
#
-
# params - Hash of params to serialize
-
#
-
# Returns String query or nil if empty.
-
1
def encode_uri_query_params(params)
-
112
query = []
-
-
112
params.each do |key, value|
-
112
case value
-
when Integer
-
query << "#{key}=#{value}"
-
when String, Symbol
-
112
query << "#{key}=#{URI::Generic::DEFAULT_PARSER.escape(value.to_s)}"
-
when TrueClass
-
query << "#{key}"
-
when FalseClass, NilClass
-
else
-
raise TypeError, "unexpected type: #{value.class}"
-
end
-
end
-
-
112
"#{query.join('&')}" if query.any?
-
end
-
-
# Internal: Parse query string into hash of params
-
#
-
# query - String query string
-
#
-
# Return Hash of params.
-
1
def parse_uri_query_params(query)
-
8
query.to_s.split('&').reduce({}) do |h, p|
-
20
k, v = p.split('=', 2)
-
20
v = URI::Generic::DEFAULT_PARSER.unescape(v) if v
-
20
h[k.to_sym] = v || true
-
20
h
-
end
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Sprockets
-
# Internal: Utils, we didn't know where else to put it! Functions may
-
# eventually be shuffled into more specific drawers.
-
1
module Utils
-
1
extend self
-
-
# Internal: Check if object can safely be .dup'd.
-
#
-
# Similar to ActiveSupport #duplicable? check.
-
#
-
# obj - Any Object
-
#
-
# Returns false if .dup would raise a TypeError, otherwise true.
-
1
def duplicable?(obj)
-
294
if RUBY_VERSION >= "2.4.0"
-
true
-
else
-
294
case obj
-
when NilClass, FalseClass, TrueClass, Symbol, Numeric
-
1
false
-
else
-
293
true
-
end
-
end
-
end
-
-
# Internal: Duplicate and store key/value on new frozen hash.
-
#
-
# Seperated for recursive calls, always use hash_reassoc(hash, *keys).
-
#
-
# hash - Hash
-
# key - Object key
-
#
-
# Returns Hash.
-
1
def hash_reassoc1(hash, key)
-
147
hash = hash.dup if hash.frozen?
-
147
old_value = hash[key]
-
147
old_value = old_value.dup if duplicable?(old_value)
-
147
new_value = yield old_value
-
147
new_value.freeze if duplicable?(new_value)
-
147
hash.store(key, new_value)
-
147
hash.freeze
-
end
-
-
# Internal: Duplicate and store key/value on new frozen hash.
-
#
-
# Similar to Hash#store for nested frozen hashes.
-
#
-
# hash - Hash
-
# key - Object keys. Use multiple keys for nested hashes.
-
# block - Receives current value at key.
-
#
-
# Examples
-
#
-
# config = {paths: ["/bin", "/sbin"]}.freeze
-
# new_config = hash_reassoc(config, :paths) do |paths|
-
# paths << "/usr/local/bin"
-
# end
-
#
-
# Returns duplicated frozen Hash.
-
1
def hash_reassoc(hash, *keys, &block)
-
147
if keys.size == 1
-
129
hash_reassoc1(hash, keys[0], &block)
-
else
-
18
hash_reassoc1(hash, keys[0]) do |value|
-
18
hash_reassoc(value, *keys[1..-1], &block)
-
end
-
end
-
end
-
-
# Internal: Check if string has a trailing semicolon.
-
#
-
# str - String
-
#
-
# Returns true or false.
-
1
def string_end_with_semicolon?(str)
-
i = str.size - 1
-
while i >= 0
-
c = str[i].ord
-
i -= 1
-
-
# Need to compare against the ordinals because the string can be UTF_8 or UTF_32LE encoded
-
# 0x0A == "\n"
-
# 0x20 == " "
-
# 0x09 == "\t"
-
# 0x3B == ";"
-
unless c == 0x0A || c == 0x20 || c == 0x09
-
return c === 0x3B
-
end
-
end
-
-
true
-
end
-
-
# Internal: Accumulate asset source to buffer and append a trailing
-
# semicolon if necessary.
-
#
-
# buf - String buffer to append to
-
# source - String source to append
-
#
-
# Returns buf String.
-
1
def concat_javascript_sources(buf, source)
-
if source.bytesize > 0
-
buf << source
-
-
# If the source contains non-ASCII characters, indexing on it becomes O(N).
-
# This will lead to O(N^2) performance in string_end_with_semicolon?, so we should use 32 bit encoding to make sure indexing stays O(1)
-
source = source.encode(Encoding::UTF_32LE) unless source.ascii_only?
-
-
if !string_end_with_semicolon?(source)
-
buf << ";\n"
-
elsif source[source.size - 1].ord != 0x0A
-
buf << "\n"
-
end
-
end
-
-
buf
-
end
-
-
# Internal: Prepends a leading "." to an extension if its missing.
-
#
-
# normalize_extension("js")
-
# # => ".js"
-
#
-
# normalize_extension(".css")
-
# # => ".css"
-
#
-
1
def normalize_extension(extension)
-
49
extension = extension.to_s
-
49
if extension[/^\./]
-
49
extension
-
else
-
".#{extension}"
-
end
-
end
-
-
# Internal: Feature detect if UnboundMethods can #bind to any Object or
-
# just Objects that share the same super class.
-
# Basically if RUBY_VERSION >= 2.
-
1
UNBOUND_METHODS_BIND_TO_ANY_OBJECT = begin
-
2
foo = Module.new { def bar; end }
-
1
foo.instance_method(:bar).bind(Object.new)
-
1
true
-
rescue TypeError
-
false
-
end
-
-
# Internal: Inject into target module for the duration of the block.
-
#
-
# mod - Module
-
#
-
# Returns result of block.
-
1
def module_include(base, mod)
-
old_methods = {}
-
-
mod.instance_methods.each do |sym|
-
old_methods[sym] = base.instance_method(sym) if base.method_defined?(sym)
-
end
-
-
unless UNBOUND_METHODS_BIND_TO_ANY_OBJECT
-
base.send(:include, mod) unless base < mod
-
end
-
-
mod.instance_methods.each do |sym|
-
method = mod.instance_method(sym)
-
base.send(:define_method, sym, method)
-
end
-
-
yield
-
ensure
-
mod.instance_methods.each do |sym|
-
base.send(:undef_method, sym) if base.method_defined?(sym)
-
end
-
old_methods.each do |sym, method|
-
base.send(:define_method, sym, method)
-
end
-
end
-
-
# Internal: Post-order Depth-First search algorithm.
-
#
-
# Used for resolving asset dependencies.
-
#
-
# initial - Initial Array of nodes to traverse.
-
# block -
-
# node - Current node to get children of
-
#
-
# Returns a Set of nodes.
-
1
def dfs(initial)
-
nodes, seen = Set.new, Set.new
-
stack = Array(initial).reverse
-
-
while node = stack.pop
-
if seen.include?(node)
-
nodes.add(node)
-
else
-
seen.add(node)
-
stack.push(node)
-
stack.concat(Array(yield node).reverse)
-
end
-
end
-
-
nodes
-
end
-
-
# Internal: Post-order Depth-First search algorithm that gathers all paths
-
# along the way.
-
#
-
# TODO: Rename function.
-
#
-
# path - Initial Array node path
-
# block -
-
# node - Current node to get children of
-
#
-
# Returns an Array of node Arrays.
-
1
def dfs_paths(path)
-
5
paths = []
-
5
stack, seen = [path], Set.new
-
-
5
while path = stack.pop
-
10
if !seen.include?(path.last)
-
10
seen.add(path.last)
-
10
paths << path if path.size > 1
-
-
10
Array(yield path.last).reverse_each do |node|
-
5
stack.push(path + [node])
-
end
-
end
-
end
-
-
5
paths
-
end
-
end
-
end
-
1
module Sprockets
-
1
module Utils
-
1
class Gzip
-
# Private: Generates a gzipped file based off of reference file.
-
1
def initialize(asset)
-
@content_type = asset.content_type
-
@source = asset.source
-
@charset = asset.charset
-
end
-
-
# What non-text mime types should we compress? This list comes from:
-
# https://www.fastly.com/blog/new-gzip-settings-and-deciding-what-compress
-
1
COMPRESSABLE_MIME_TYPES = {
-
"application/vnd.ms-fontobject" => true,
-
"application/x-font-opentype" => true,
-
"application/x-font-ttf" => true,
-
"image/x-icon" => true,
-
"image/svg+xml" => true
-
}
-
-
# Private: Returns whether or not an asset can be compressed.
-
#
-
# We want to compress any file that is text based.
-
# You do not want to compress binary
-
# files as they may already be compressed and running them
-
# through a compression algorithm would make them larger.
-
#
-
# Return Boolean.
-
1
def can_compress?(mime_types)
-
# The "charset" of a mime type is present if the value is
-
# encoded text. We can check this value to see if the asset
-
# can be compressed.
-
#
-
# We also check against our list of non-text compressible mime types
-
@charset || COMPRESSABLE_MIME_TYPES.include?(@content_type)
-
end
-
-
# Private: Opposite of `can_compress?`.
-
#
-
# Returns Boolean.
-
1
def cannot_compress?(mime_types)
-
!can_compress?(mime_types)
-
end
-
-
# Private: Generates a gzipped file based off of reference asset.
-
#
-
# Compresses the target asset's contents and puts it into a file with
-
# the same name plus a `.gz` extension in the same folder as the original.
-
# Does not modify the target asset.
-
#
-
# Returns nothing.
-
1
def compress(target)
-
mtime = PathUtils.stat(target).mtime
-
PathUtils.atomic_write("#{target}.gz") do |f|
-
gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)
-
gz.mtime = mtime
-
gz.write(@source)
-
gz.close
-
-
File.utime(mtime, mtime, f.path)
-
end
-
-
nil
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
1
VERSION = "3.7.1"
-
end
-
1
require 'sprockets/autoload'
-
1
require 'sprockets/digest_utils'
-
-
1
module Sprockets
-
# Public: YUI compressor.
-
#
-
# To accept the default options
-
#
-
# environment.register_bundle_processor 'application/javascript',
-
# Sprockets::YUICompressor
-
#
-
# Or to pass options to the YUI::JavaScriptCompressor class.
-
#
-
# environment.register_bundle_processor 'application/javascript',
-
# Sprockets::YUICompressor.new(munge: true)
-
#
-
1
class YUICompressor
-
1
VERSION = '1'
-
-
# Public: Return singleton instance with default options.
-
#
-
# Returns YUICompressor object.
-
1
def self.instance
-
@instance ||= new
-
end
-
-
1
def self.call(input)
-
instance.call(input)
-
end
-
-
1
def self.cache_key
-
instance.cache_key
-
end
-
-
1
attr_reader :cache_key
-
-
1
def initialize(options = {})
-
@options = options
-
@cache_key = "#{self.class.name}:#{Autoload::YUI::Compressor::VERSION}:#{VERSION}:#{DigestUtils.digest(options)}".freeze
-
end
-
-
1
def call(input)
-
data = input[:data]
-
-
case input[:content_type]
-
when 'application/javascript'
-
Autoload::YUI::JavaScriptCompressor.new(@options).compress(data)
-
when 'text/css'
-
Autoload::YUI::CssCompressor.new(@options).compress(data)
-
else
-
data
-
end
-
end
-
end
-
end
-
1
require 'action_view'
-
1
require 'sprockets'
-
-
1
module Sprockets
-
1
module Rails
-
1
module Context
-
1
include ActionView::Helpers::AssetUrlHelper
-
1
include ActionView::Helpers::AssetTagHelper
-
-
1
def self.included(klass)
-
1
klass.class_eval do
-
1
class_attribute :config, :assets_prefix, :digest_assets
-
end
-
end
-
-
1
def compute_asset_path(path, options = {})
-
@dependencies << 'actioncontroller-asset-url-config'
-
-
begin
-
asset_uri = resolve(path)
-
rescue FileNotFound
-
# TODO: eh, we should be able to use a form of locate that returns
-
# nil instead of raising an exception.
-
end
-
-
if asset_uri
-
asset = link_asset(path)
-
digest_path = asset.digest_path
-
path = digest_path if digest_assets
-
File.join(assets_prefix || "/", path)
-
else
-
super
-
end
-
end
-
end
-
end
-
-
1
register_dependency_resolver 'actioncontroller-asset-url-config' do |env|
-
config = env.context_class.config
-
[config.relative_url_root,
-
(config.asset_host unless config.asset_host.respond_to?(:call))]
-
end
-
-
# fallback to the default pipeline when using Sprockets 3.x
-
1
unless config[:pipelines].include? :debug
-
1
register_pipeline :debug, config[:pipelines][:default]
-
end
-
end
-
1
require 'action_view'
-
1
require 'sprockets'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'sprockets/rails/utils'
-
-
1
module Sprockets
-
1
module Rails
-
1
module Helper
-
1
class AssetNotFound < StandardError; end
-
-
1
class AssetNotPrecompiled < StandardError
-
1
include Sprockets::Rails::Utils
-
1
def initialize(source)
-
msg =
-
if using_sprockets4?
-
"Asset `#{ source }` was not declared to be precompiled in production.\n" +
-
"Declare links to your assets in `app/assets/config/manifest.js`.\n\n" +
-
" //= link #{ source }\n" +
-
"and restart your server"
-
else
-
"Asset was not declared to be precompiled in production.\n" +
-
"Add `Rails.application.config.assets.precompile += " +
-
"%w( #{source} )` to `config/initializers/assets.rb` and " +
-
"restart your server"
-
end
-
super(msg)
-
end
-
end
-
-
1
include ActionView::Helpers::AssetUrlHelper
-
1
include ActionView::Helpers::AssetTagHelper
-
1
include Sprockets::Rails::Utils
-
-
1
VIEW_ACCESSORS = [
-
:assets_environment, :assets_manifest,
-
:assets_precompile, :precompiled_asset_checker,
-
:assets_prefix, :digest_assets, :debug_assets,
-
:resolve_assets_with, :check_precompiled_asset,
-
:unknown_asset_fallback
-
]
-
-
1
def self.included(klass)
-
1
klass.class_attribute(*VIEW_ACCESSORS)
-
-
1
klass.class_eval do
-
1
remove_method :assets_environment
-
1
def assets_environment
-
110
if instance_variable_defined?(:@assets_environment)
-
55
@assets_environment = @assets_environment.cached
-
55
elsif env = self.class.assets_environment
-
55
@assets_environment = env.cached
-
else
-
nil
-
end
-
end
-
end
-
end
-
-
1
def self.extended(obj)
-
obj.class_eval do
-
attr_accessor(*VIEW_ACCESSORS)
-
-
remove_method :assets_environment
-
def assets_environment
-
if env = @assets_environment
-
@assets_environment = env.cached
-
else
-
nil
-
end
-
end
-
end
-
end
-
-
# Writes over the built in ActionView::Helpers::AssetUrlHelper#compute_asset_path
-
# to use the asset pipeline.
-
1
def compute_asset_path(path, options = {})
-
110
debug = options[:debug]
-
-
110
if asset_path = resolve_asset_path(path, debug)
-
110
File.join(assets_prefix || "/", legacy_debug_path(asset_path, debug))
-
else
-
message = "The asset #{ path.inspect } is not present in the asset pipeline."
-
raise AssetNotFound, message unless unknown_asset_fallback
-
-
if respond_to?(:public_compute_asset_path)
-
message << "Falling back to an asset that may be in the public folder.\n"
-
message << "This behavior is deprecated and will be removed.\n"
-
message << "To bypass the asset pipeline and preserve this behavior,\n"
-
message << "use the `skip_pipeline: true` option.\n"
-
-
call_stack = respond_to?(:caller_locations) ? caller_locations : caller
-
ActiveSupport::Deprecation.warn(message, call_stack)
-
end
-
super
-
end
-
end
-
-
# Resolve the asset path against the Sprockets manifest or environment.
-
# Returns nil if it's an asset we don't know about.
-
1
def resolve_asset_path(path, allow_non_precompiled = false) #:nodoc:
-
110
resolve_asset do |resolver|
-
220
resolver.asset_path path, digest_assets, allow_non_precompiled
-
end
-
end
-
-
# Expand asset path to digested form.
-
#
-
# path - String path
-
# options - Hash options
-
#
-
# Returns String path or nil if no asset was found.
-
1
def asset_digest_path(path, options = {})
-
resolve_asset do |resolver|
-
resolver.digest_path path, options[:debug]
-
end
-
end
-
-
# Experimental: Get integrity for asset path.
-
#
-
# path - String path
-
# options - Hash options
-
#
-
# Returns String integrity attribute or nil if no asset was found.
-
1
def asset_integrity(path, options = {})
-
path = path_with_extname(path, options)
-
-
resolve_asset do |resolver|
-
resolver.integrity path
-
end
-
end
-
-
# Override javascript tag helper to provide debugging support.
-
#
-
# Eventually will be deprecated and replaced by source maps.
-
1
def javascript_include_tag(*sources)
-
55
options = sources.extract_options!.stringify_keys
-
55
integrity = compute_integrity?(options)
-
-
55
if options["debug"] != false && request_debug_assets?
-
sources.map { |source|
-
if asset = lookup_debug_asset(source, type: :javascript)
-
if asset.respond_to?(:to_a)
-
asset.to_a.map do |a|
-
super(path_to_javascript(a.logical_path, debug: true), options)
-
end
-
else
-
super(path_to_javascript(asset.logical_path, debug: true), options)
-
end
-
else
-
super(source, options)
-
end
-
}.flatten.uniq.join("\n").html_safe
-
else
-
sources.map { |source|
-
55
options = options.merge('integrity' => asset_integrity(source, type: :javascript)) if integrity
-
55
super source, options
-
55
}.join("\n").html_safe
-
end
-
end
-
-
# Override stylesheet tag helper to provide debugging support.
-
#
-
# Eventually will be deprecated and replaced by source maps.
-
1
def stylesheet_link_tag(*sources)
-
55
options = sources.extract_options!.stringify_keys
-
55
integrity = compute_integrity?(options)
-
-
55
if options["debug"] != false && request_debug_assets?
-
sources.map { |source|
-
if asset = lookup_debug_asset(source, type: :stylesheet)
-
if asset.respond_to?(:to_a)
-
asset.to_a.map do |a|
-
super(path_to_stylesheet(a.logical_path, debug: true), options)
-
end
-
else
-
super(path_to_stylesheet(asset.logical_path, debug: true), options)
-
end
-
else
-
super(source, options)
-
end
-
}.flatten.uniq.join("\n").html_safe
-
else
-
sources.map { |source|
-
55
options = options.merge('integrity' => asset_integrity(source, type: :stylesheet)) if integrity
-
55
super source, options
-
55
}.join("\n").html_safe
-
end
-
end
-
-
1
protected
-
# This is awkward: `integrity` is a boolean option indicating whether
-
# we want to include or omit the subresource integrity hash, but the
-
# options hash is also passed through as literal tag attributes.
-
# That means we have to delete the shortcut boolean option so it
-
# doesn't bleed into the tag attributes, but also check its value if
-
# it's boolean-ish.
-
1
def compute_integrity?(options)
-
110
if secure_subresource_integrity_context?
-
110
case options['integrity']
-
when nil, false, true
-
110
options.delete('integrity') == true
-
end
-
else
-
options.delete 'integrity'
-
false
-
end
-
end
-
-
# Only serve integrity metadata for HTTPS requests:
-
# http://www.w3.org/TR/SRI/#non-secure-contexts-remain-non-secure
-
1
def secure_subresource_integrity_context?
-
110
respond_to?(:request) && self.request && (self.request.local? || self.request.ssl?)
-
end
-
-
# Enable split asset debugging. Eventually will be deprecated
-
# and replaced by source maps in Sprockets 3.x.
-
1
def request_debug_assets?
-
110
debug_assets || (defined?(controller) && controller && params[:debug_assets])
-
rescue # FIXME: what exactly are we rescuing?
-
false
-
end
-
-
# Internal method to support multifile debugging. Will
-
# eventually be removed w/ Sprockets 3.x.
-
1
def lookup_debug_asset(path, options = {})
-
path = path_with_extname(path, options)
-
-
resolve_asset do |resolver|
-
resolver.find_debug_asset path
-
end
-
end
-
-
# compute_asset_extname is in AV::Helpers::AssetUrlHelper
-
1
def path_with_extname(path, options)
-
path = path.to_s
-
"#{path}#{compute_asset_extname(path, options)}"
-
end
-
-
# Try each asset resolver and return the first non-nil result.
-
1
def resolve_asset
-
110
asset_resolver_strategies.detect do |resolver|
-
220
if result = yield(resolver)
-
110
break result
-
end
-
end
-
end
-
-
# List of resolvers in `config.assets.resolve_with` order.
-
1
def asset_resolver_strategies
-
@asset_resolver_strategies ||=
-
Array(resolve_assets_with).map do |name|
-
110
HelperAssetResolvers[name].new(self)
-
110
end
-
end
-
-
# Append ?body=1 if debug is on and we're on old Sprockets.
-
1
def legacy_debug_path(path, debug)
-
110
if debug && !using_sprockets4?
-
"#{path}?body=1"
-
else
-
110
path
-
end
-
end
-
end
-
-
# Use a separate module since Helper is mixed in and we needn't pollute
-
# the class namespace with our internals.
-
1
module HelperAssetResolvers #:nodoc:
-
1
def self.[](name)
-
110
case name
-
when :manifest
-
55
Manifest
-
when :environment
-
55
Environment
-
else
-
raise ArgumentError, "Unrecognized asset resolver: #{name.inspect}. Expected :manifest or :environment"
-
end
-
end
-
-
1
class Manifest #:nodoc:
-
1
def initialize(view)
-
55
@manifest = view.assets_manifest
-
55
raise ArgumentError, 'config.assets.resolve_with includes :manifest, but app.assets_manifest is nil' unless @manifest
-
end
-
-
1
def asset_path(path, digest, allow_non_precompiled = false)
-
110
if digest
-
110
digest_path path, allow_non_precompiled
-
end
-
end
-
-
1
def digest_path(path, allow_non_precompiled = false)
-
110
@manifest.assets[path]
-
end
-
-
1
def integrity(path)
-
if meta = metadata(path)
-
meta["integrity"]
-
end
-
end
-
-
1
def find_debug_asset(path)
-
nil
-
end
-
-
1
private
-
1
def metadata(path)
-
if digest_path = digest_path(path)
-
@manifest.files[digest_path]
-
end
-
end
-
end
-
-
1
class Environment #:nodoc:
-
1
def initialize(view)
-
55
raise ArgumentError, 'config.assets.resolve_with includes :environment, but app.assets is nil' unless view.assets_environment
-
55
@env = view.assets_environment
-
55
@precompiled_asset_checker = view.precompiled_asset_checker
-
55
@check_precompiled_asset = view.check_precompiled_asset
-
end
-
-
1
def asset_path(path, digest, allow_non_precompiled = false)
-
# Digests enabled? Do the work to calculate the full asset path.
-
110
if digest
-
110
digest_path path, allow_non_precompiled
-
-
# Otherwise, ask the Sprockets environment whether the asset exists
-
# and check whether it's also precompiled for production deploys.
-
elsif asset = find_asset(path)
-
raise_unless_precompiled_asset asset.logical_path unless allow_non_precompiled
-
path
-
end
-
end
-
-
1
def digest_path(path, allow_non_precompiled = false)
-
110
if asset = find_asset(path)
-
110
raise_unless_precompiled_asset asset.logical_path unless allow_non_precompiled
-
110
asset.digest_path
-
end
-
end
-
-
1
def integrity(path)
-
find_asset(path).try :integrity
-
end
-
-
1
def find_debug_asset(path)
-
if asset = find_asset(path, pipeline: :debug)
-
raise_unless_precompiled_asset asset.logical_path.sub('.debug', '')
-
asset
-
end
-
end
-
-
1
private
-
1
def find_asset(path, options = {})
-
110
@env[path, options]
-
end
-
-
1
def precompiled?(path)
-
110
@precompiled_asset_checker.call path
-
end
-
-
1
def raise_unless_precompiled_asset(path)
-
110
raise Helper::AssetNotPrecompiled.new(path) if @check_precompiled_asset && !precompiled?(path)
-
end
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
1
module Rails
-
1
class QuietAssets
-
1
def initialize(app)
-
@app = app
-
@assets_regex = %r(\A/{0,2}#{::Rails.application.config.assets.prefix})
-
end
-
-
1
def call(env)
-
if env['PATH_INFO'] =~ @assets_regex
-
::Rails.logger.silence { @app.call(env) }
-
else
-
@app.call(env)
-
end
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
1
module Rails
-
1
module RouteWrapper
-
-
1
def internal_assets_path?
-
path =~ %r{\A#{self.class.assets_prefix}\z}
-
end
-
-
1
def internal?
-
super || internal_assets_path?
-
end
-
-
1
def self.included(klass)
-
klass.class_eval do
-
def internal_with_sprockets?
-
internal_without_sprockets? || internal_assets_path?
-
end
-
alias_method_chain :internal?, :sprockets
-
end
-
end
-
end
-
end
-
end
-
1
require 'sprockets'
-
-
1
module Sprockets
-
1
module Rails
-
1
module Utils
-
1
def using_sprockets4?
-
1
Gem::Version.new(Sprockets::VERSION) >= Gem::Version.new('4.x')
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
1
module Rails
-
1
VERSION = "3.2.0"
-
end
-
end
-
1
require 'rails'
-
1
require 'rails/railtie'
-
1
require 'action_controller/railtie'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/numeric/bytes'
-
1
require 'sprockets'
-
1
require 'sprockets/rails/context'
-
1
require 'sprockets/rails/helper'
-
1
require 'sprockets/rails/quiet_assets'
-
1
require 'sprockets/rails/route_wrapper'
-
1
require 'sprockets/rails/version'
-
1
require 'set'
-
-
1
module Rails
-
1
class Application
-
# Hack: We need to remove Rails' built in config.assets so we can
-
# do our own thing.
-
1
class Configuration
-
1
remove_possible_method :assets
-
end
-
-
# Undefine Rails' assets method before redefining it, to avoid warnings.
-
1
remove_possible_method :assets
-
1
remove_possible_method :assets=
-
-
# Returns Sprockets::Environment for app config.
-
1
attr_accessor :assets
-
-
# Returns Sprockets::Manifest for app config.
-
1
attr_accessor :assets_manifest
-
-
# Called from asset helpers to alert you if you reference an asset URL that
-
# isn't precompiled and hence won't be available in production.
-
1
def asset_precompiled?(logical_path)
-
110
if precompiled_assets.include?(logical_path)
-
110
true
-
elsif !config.cache_classes
-
# Check to see if precompile list has been updated
-
precompiled_assets(true).include?(logical_path)
-
else
-
false
-
end
-
end
-
-
# Lazy-load the precompile list so we don't cause asset compilation at app
-
# boot time, but ensure we cache the list so we don't recompute it for each
-
# request or test case.
-
1
def precompiled_assets(clear_cache = false)
-
110
@precompiled_assets = nil if clear_cache
-
110
@precompiled_assets ||= assets_manifest.find(config.assets.precompile).map(&:logical_path).to_set
-
end
-
end
-
-
1
class Engine < Railtie
-
# Skip defining append_assets_path on Rails <= 4.2
-
8
unless initializers.find { |init| init.name == :append_assets_path }
-
initializer :append_assets_path, :group => :all do |app|
-
app.config.assets.paths.unshift(*paths["vendor/assets"].existent_directories)
-
app.config.assets.paths.unshift(*paths["lib/assets"].existent_directories)
-
app.config.assets.paths.unshift(*paths["app/assets"].existent_directories)
-
end
-
end
-
end
-
end
-
-
1
module Sprockets
-
1
class Railtie < ::Rails::Railtie
-
1
include Sprockets::Rails::Utils
-
-
1
class ManifestNeededError < StandardError
-
1
def initialize
-
msg = "Expected to find a manifest file in `app/assets/config/manifest.js`\n" +
-
"But did not, please create this file and use it to link any assets that need\n" +
-
"to be rendered by your app:\n\n" +
-
"Example:\n" +
-
" //= link_tree ../images\n" +
-
" //= link_directory ../javascripts .js\n" +
-
" //= link_directory ../stylesheets .css\n" +
-
"and restart your server"
-
super msg
-
end
-
end
-
-
1
LOOSE_APP_ASSETS = lambda do |logical_path, filename|
-
filename.start_with?(::Rails.root.join("app/assets").to_s) &&
-
25
!['.js', '.css', ''].include?(File.extname(logical_path))
-
end
-
-
1
class OrderedOptions < ActiveSupport::OrderedOptions
-
1
def configure(&block)
-
7
self._blocks << block
-
end
-
end
-
-
1
config.assets = OrderedOptions.new
-
1
config.assets._blocks = []
-
1
config.assets.paths = []
-
1
config.assets.precompile = []
-
1
config.assets.prefix = "/assets"
-
1
config.assets.manifest = nil
-
1
config.assets.quiet = false
-
-
1
initializer :set_default_precompile do |app|
-
1
if using_sprockets4?
-
raise ManifestNeededError unless ::Rails.root.join("app/assets/config/manifest.js").exist?
-
app.config.assets.precompile += %w( manifest.js )
-
else
-
1
app.config.assets.precompile += [LOOSE_APP_ASSETS, /(?:\/|\\|\A)application\.(css|js)$/]
-
end
-
end
-
-
1
initializer :quiet_assets do |app|
-
1
if app.config.assets.quiet
-
app.middleware.insert_before ::Rails::Rack::Logger, ::Sprockets::Rails::QuietAssets
-
end
-
end
-
-
1
config.assets.version = ""
-
1
config.assets.debug = false
-
1
config.assets.compile = true
-
1
config.assets.digest = true
-
1
config.assets.cache_limit = 50.megabytes
-
1
config.assets.gzip = true
-
1
config.assets.check_precompiled_asset = true
-
1
config.assets.unknown_asset_fallback = true
-
-
1
config.assets.configure do |env|
-
9
config.assets.paths.each { |path| env.append_path(path) }
-
end
-
-
1
config.assets.configure do |env|
-
1
env.context_class.send :include, ::Sprockets::Rails::Context
-
1
env.context_class.assets_prefix = config.assets.prefix
-
1
env.context_class.digest_assets = config.assets.digest
-
1
env.context_class.config = config.action_controller
-
end
-
-
1
config.assets.configure do |env|
-
1
env.cache = Sprockets::Cache::FileStore.new(
-
"#{env.root}/tmp/cache/assets",
-
config.assets.cache_limit,
-
env.logger
-
)
-
end
-
-
1
Sprockets.register_dependency_resolver 'rails-env' do
-
1
::Rails.env.to_s
-
end
-
-
1
config.assets.configure do |env|
-
1
env.depend_on 'rails-env'
-
end
-
-
1
config.assets.configure do |env|
-
1
env.version = config.assets.version
-
end
-
-
1
config.assets.configure do |env|
-
1
env.gzip = config.assets.gzip if env.respond_to?(:gzip=)
-
end
-
-
1
rake_tasks do |app|
-
require 'sprockets/rails/task'
-
Sprockets::Rails::Task.new(app)
-
end
-
-
1
def build_environment(app, initialized = nil)
-
1
initialized = app.initialized? if initialized.nil?
-
1
unless initialized
-
::Rails.logger.warn "Application uninitialized: Try calling YourApp::Application.initialize!"
-
end
-
-
1
env = Sprockets::Environment.new(app.root.to_s)
-
-
1
config = app.config
-
-
# Run app.assets.configure blocks
-
1
config.assets._blocks.each do |block|
-
7
block.call(env)
-
end
-
-
# Set compressors after the configure blocks since they can
-
# define new compressors and we only accept existent compressors.
-
1
env.js_compressor = config.assets.js_compressor
-
1
env.css_compressor = config.assets.css_compressor
-
-
# No more configuration changes at this point.
-
# With cache classes on, Sprockets won't check the FS when files
-
# change. Preferable in production when the FS only changes on
-
# deploys when the app restarts.
-
1
if config.cache_classes
-
1
env = env.cached
-
end
-
-
1
env
-
end
-
-
1
def self.build_manifest(app)
-
1
config = app.config
-
1
path = File.join(config.paths['public'].first, config.assets.prefix)
-
1
Sprockets::Manifest.new(app.assets, path, config.assets.manifest)
-
end
-
-
1
config.after_initialize do |app|
-
1
config = app.config
-
-
1
if config.assets.compile
-
1
app.assets = self.build_environment(app, true)
-
1
app.routes.prepend do
-
1
mount app.assets => config.assets.prefix
-
end
-
end
-
-
1
app.assets_manifest = build_manifest(app)
-
-
1
if config.assets.resolve_with.nil?
-
1
config.assets.resolve_with = []
-
1
config.assets.resolve_with << :manifest if config.assets.digest && !config.assets.debug
-
1
config.assets.resolve_with << :environment if config.assets.compile
-
end
-
-
1
ActionDispatch::Routing::RouteWrapper.class_eval do
-
1
class_attribute :assets_prefix
-
-
1
if defined?(prepend) && ::Rails.version >= '4'
-
1
prepend Sprockets::Rails::RouteWrapper
-
else
-
include Sprockets::Rails::RouteWrapper
-
end
-
-
1
self.assets_prefix = config.assets.prefix
-
end
-
-
1
ActiveSupport.on_load(:action_view) do
-
1
include Sprockets::Rails::Helper
-
-
# Copy relevant config to AV context
-
1
self.debug_assets = config.assets.debug
-
1
self.digest_assets = config.assets.digest
-
1
self.assets_prefix = config.assets.prefix
-
1
self.assets_precompile = config.assets.precompile
-
-
1
self.assets_environment = app.assets
-
1
self.assets_manifest = app.assets_manifest
-
-
1
self.resolve_assets_with = config.assets.resolve_with
-
-
1
self.check_precompiled_asset = config.assets.check_precompiled_asset
-
1
self.unknown_asset_fallback = config.assets.unknown_asset_fallback
-
# Expose the app precompiled asset check to the view
-
111
self.precompiled_asset_checker = -> logical_path { app.asset_precompiled? logical_path }
-
end
-
end
-
end
-
end
-
# support multiple ruby version (fat binaries under windows)
-
1
begin
-
1
RUBY_VERSION =~ /(\d+\.\d+)/
-
1
require "sqlite3/#{$1}/sqlite3_native"
-
rescue LoadError
-
1
require 'sqlite3/sqlite3_native'
-
end
-
-
1
require 'sqlite3/database'
-
1
require 'sqlite3/version'
-
-
1
module SQLite3
-
# Was sqlite3 compiled with thread safety on?
-
1
def self.threadsafe?; threadsafe > 0; end
-
end
-
2
module SQLite3 ; module Constants
-
-
1
module TextRep
-
1
UTF8 = 1
-
1
UTF16LE = 2
-
1
UTF16BE = 3
-
1
UTF16 = 4
-
1
ANY = 5
-
end
-
-
1
module ColumnType
-
1
INTEGER = 1
-
1
FLOAT = 2
-
1
TEXT = 3
-
1
BLOB = 4
-
1
NULL = 5
-
end
-
-
1
module ErrorCode
-
1
OK = 0 # Successful result
-
1
ERROR = 1 # SQL error or missing database
-
1
INTERNAL = 2 # An internal logic error in SQLite
-
1
PERM = 3 # Access permission denied
-
1
ABORT = 4 # Callback routine requested an abort
-
1
BUSY = 5 # The database file is locked
-
1
LOCKED = 6 # A table in the database is locked
-
1
NOMEM = 7 # A malloc() failed
-
1
READONLY = 8 # Attempt to write a readonly database
-
1
INTERRUPT = 9 # Operation terminated by sqlite_interrupt()
-
1
IOERR = 10 # Some kind of disk I/O error occurred
-
1
CORRUPT = 11 # The database disk image is malformed
-
1
NOTFOUND = 12 # (Internal Only) Table or record not found
-
1
FULL = 13 # Insertion failed because database is full
-
1
CANTOPEN = 14 # Unable to open the database file
-
1
PROTOCOL = 15 # Database lock protocol error
-
1
EMPTY = 16 # (Internal Only) Database table is empty
-
1
SCHEMA = 17 # The database schema changed
-
1
TOOBIG = 18 # Too much data for one row of a table
-
1
CONSTRAINT = 19 # Abort due to contraint violation
-
1
MISMATCH = 20 # Data type mismatch
-
1
MISUSE = 21 # Library used incorrectly
-
1
NOLFS = 22 # Uses OS features not supported on host
-
1
AUTH = 23 # Authorization denied
-
-
1
ROW = 100 # sqlite_step() has another row ready
-
1
DONE = 101 # sqlite_step() has finished executing
-
end
-
-
end ; end
-
1
require 'sqlite3/constants'
-
1
require 'sqlite3/errors'
-
1
require 'sqlite3/pragmas'
-
1
require 'sqlite3/statement'
-
1
require 'sqlite3/translator'
-
1
require 'sqlite3/value'
-
-
1
module SQLite3
-
-
# The Database class encapsulates a single connection to a SQLite3 database.
-
# Its usage is very straightforward:
-
#
-
# require 'sqlite3'
-
#
-
# SQLite3::Database.new( "data.db" ) do |db|
-
# db.execute( "select * from table" ) do |row|
-
# p row
-
# end
-
# end
-
#
-
# It wraps the lower-level methods provides by the selected driver, and
-
# includes the Pragmas module for access to various pragma convenience
-
# methods.
-
#
-
# The Database class provides type translation services as well, by which
-
# the SQLite3 data types (which are all represented as strings) may be
-
# converted into their corresponding types (as defined in the schemas
-
# for their tables). This translation only occurs when querying data from
-
# the database--insertions and updates are all still typeless.
-
#
-
# Furthermore, the Database class has been designed to work well with the
-
# ArrayFields module from Ara Howard. If you require the ArrayFields
-
# module before performing a query, and if you have not enabled results as
-
# hashes, then the results will all be indexible by field name.
-
1
class Database
-
1
attr_reader :collations
-
-
1
include Pragmas
-
-
1
class << self
-
-
1
alias :open :new
-
-
# Quotes the given string, making it safe to use in an SQL statement.
-
# It replaces all instances of the single-quote character with two
-
# single-quote characters. The modified string is returned.
-
1
def quote( string )
-
string.gsub( /'/, "''" )
-
end
-
-
end
-
-
# A boolean that indicates whether rows in result sets should be returned
-
# as hashes or not. By default, rows are returned as arrays.
-
1
attr_accessor :results_as_hash
-
-
1
def type_translation= value # :nodoc:
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#type_translation=
-
SQLite3::Database#type_translation= is deprecated and will be removed
-
in version 2.0.0.
-
eowarn
-
@type_translation = value
-
end
-
1
attr_reader :type_translation # :nodoc:
-
-
# Return the type translator employed by this database instance. Each
-
# database instance has its own type translator; this allows for different
-
# type handlers to be installed in each instance without affecting other
-
# instances. Furthermore, the translators are instantiated lazily, so that
-
# if a database does not use type translation, it will not be burdened by
-
# the overhead of a useless type translator. (See the Translator class.)
-
1
def translator
-
@translator ||= Translator.new
-
end
-
-
# Installs (or removes) a block that will be invoked for every access
-
# to the database. If the block returns 0 (or +nil+), the statement
-
# is allowed to proceed. Returning 1 causes an authorization error to
-
# occur, and returning 2 causes the access to be silently denied.
-
1
def authorizer( &block )
-
self.authorizer = block
-
end
-
-
# Returns a Statement object representing the given SQL. This does not
-
# execute the statement; it merely prepares the statement for execution.
-
#
-
# The Statement can then be executed using Statement#execute.
-
#
-
1
def prepare sql
-
187
stmt = SQLite3::Statement.new( self, sql )
-
187
return stmt unless block_given?
-
-
136
begin
-
136
yield stmt
-
ensure
-
136
stmt.close unless stmt.closed?
-
end
-
end
-
-
# Returns the filename for the database named +db_name+. +db_name+ defaults
-
# to "main". Main return `nil` or an empty string if the database is
-
# temporary or in-memory.
-
1
def filename db_name = 'main'
-
db_filename db_name
-
end
-
-
# Executes the given SQL statement. If additional parameters are given,
-
# they are treated as bind variables, and are bound to the placeholders in
-
# the query.
-
#
-
# Note that if any of the values passed to this are hashes, then the
-
# key/value pairs are each bound separately, with the key being used as
-
# the name of the placeholder to bind the value to.
-
#
-
# The block is optional. If given, it will be invoked for each row returned
-
# by the query. Otherwise, any results are accumulated into an array and
-
# returned wholesale.
-
#
-
# See also #execute2, #query, and #execute_batch for additional ways of
-
# executing statements.
-
1
def execute sql, bind_vars = [], *args, &block
-
136
if bind_vars.nil? || !args.empty?
-
if args.empty?
-
bind_vars = []
-
else
-
bind_vars = [bind_vars] + args
-
end
-
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#execute with nil or multiple bind params
-
without using an array. Please switch to passing bind parameters as an array.
-
Support for bind parameters as *args will be removed in 2.0.0.
-
eowarn
-
end
-
-
136
prepare( sql ) do |stmt|
-
136
stmt.bind_params(bind_vars)
-
136
columns = stmt.columns
-
136
stmt = ResultSet.new(self, stmt).to_a if type_translation
-
-
136
if block_given?
-
stmt.each do |row|
-
if @results_as_hash
-
yield type_translation ? row : ordered_map_for(columns, row)
-
else
-
yield row
-
end
-
end
-
else
-
136
if @results_as_hash
-
136
stmt.map { |row|
-
type_translation ? row : ordered_map_for(columns, row)
-
}
-
else
-
stmt.to_a
-
end
-
end
-
end
-
end
-
-
# Executes the given SQL statement, exactly as with #execute. However, the
-
# first row returned (either via the block, or in the returned array) is
-
# always the names of the columns. Subsequent rows correspond to the data
-
# from the result set.
-
#
-
# Thus, even if the query itself returns no rows, this method will always
-
# return at least one row--the names of the columns.
-
#
-
# See also #execute, #query, and #execute_batch for additional ways of
-
# executing statements.
-
1
def execute2( sql, *bind_vars )
-
prepare( sql ) do |stmt|
-
result = stmt.execute( *bind_vars )
-
if block_given?
-
yield stmt.columns
-
result.each { |row| yield row }
-
else
-
return result.inject( [ stmt.columns ] ) { |arr,row|
-
arr << row; arr }
-
end
-
end
-
end
-
-
# Executes all SQL statements in the given string. By contrast, the other
-
# means of executing queries will only execute the first statement in the
-
# string, ignoring all subsequent statements. This will execute each one
-
# in turn. The same bind parameters, if given, will be applied to each
-
# statement.
-
#
-
# This always returns +nil+, making it unsuitable for queries that return
-
# rows.
-
1
def execute_batch( sql, bind_vars = [], *args )
-
# FIXME: remove this stuff later
-
unless [Array, Hash].include?(bind_vars.class)
-
bind_vars = [bind_vars]
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#execute_batch with bind parameters
-
that are not a list of a hash. Please switch to passing bind parameters as an
-
array or hash. Support for this behavior will be removed in version 2.0.0.
-
eowarn
-
end
-
-
# FIXME: remove this stuff later
-
if bind_vars.nil? || !args.empty?
-
if args.empty?
-
bind_vars = []
-
else
-
bind_vars = [nil] + args
-
end
-
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#execute_batch with nil or multiple bind params
-
without using an array. Please switch to passing bind parameters as an array.
-
Support for this behavior will be removed in version 2.0.0.
-
eowarn
-
end
-
-
sql = sql.strip
-
until sql.empty? do
-
prepare( sql ) do |stmt|
-
unless stmt.closed?
-
# FIXME: this should probably use sqlite3's api for batch execution
-
# This implementation requires stepping over the results.
-
if bind_vars.length == stmt.bind_parameter_count
-
stmt.bind_params(bind_vars)
-
end
-
stmt.step
-
end
-
sql = stmt.remainder.strip
-
end
-
end
-
# FIXME: we should not return `nil` as a success return value
-
nil
-
end
-
-
# This is a convenience method for creating a statement, binding
-
# paramters to it, and calling execute:
-
#
-
# result = db.query( "select * from foo where a=?", [5])
-
# # is the same as
-
# result = db.prepare( "select * from foo where a=?" ).execute( 5 )
-
#
-
# You must be sure to call +close+ on the ResultSet instance that is
-
# returned, or you could have problems with locks on the table. If called
-
# with a block, +close+ will be invoked implicitly when the block
-
# terminates.
-
1
def query( sql, bind_vars = [], *args )
-
-
if bind_vars.nil? || !args.empty?
-
if args.empty?
-
bind_vars = []
-
else
-
bind_vars = [bind_vars] + args
-
end
-
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#query with nil or multiple bind params
-
without using an array. Please switch to passing bind parameters as an array.
-
Support for this will be removed in version 2.0.0.
-
eowarn
-
end
-
-
result = prepare( sql ).execute( bind_vars )
-
if block_given?
-
begin
-
yield result
-
ensure
-
result.close
-
end
-
else
-
return result
-
end
-
end
-
-
# A convenience method for obtaining the first row of a result set, and
-
# discarding all others. It is otherwise identical to #execute.
-
#
-
# See also #get_first_value.
-
1
def get_first_row( sql, *bind_vars )
-
execute( sql, *bind_vars ).first
-
end
-
-
# A convenience method for obtaining the first value of the first row of a
-
# result set, and discarding all other values and rows. It is otherwise
-
# identical to #execute.
-
#
-
# See also #get_first_row.
-
1
def get_first_value( sql, *bind_vars )
-
execute( sql, *bind_vars ) { |row| return row[0] }
-
nil
-
end
-
-
1
alias :busy_timeout :busy_timeout=
-
-
# Creates a new function for use in SQL statements. It will be added as
-
# +name+, with the given +arity+. (For variable arity functions, use
-
# -1 for the arity.)
-
#
-
# The block should accept at least one parameter--the FunctionProxy
-
# instance that wraps this function invocation--and any other
-
# arguments it needs (up to its arity).
-
#
-
# The block does not return a value directly. Instead, it will invoke
-
# the FunctionProxy#result= method on the +func+ parameter and
-
# indicate the return value that way.
-
#
-
# Example:
-
#
-
# db.create_function( "maim", 1 ) do |func, value|
-
# if value.nil?
-
# func.result = nil
-
# else
-
# func.result = value.split(//).sort.join
-
# end
-
# end
-
#
-
# puts db.get_first_value( "select maim(name) from table" )
-
1
def create_function name, arity, text_rep=Constants::TextRep::ANY, &block
-
define_function(name) do |*args|
-
fp = FunctionProxy.new
-
block.call(fp, *args)
-
fp.result
-
end
-
self
-
end
-
-
# Creates a new aggregate function for use in SQL statements. Aggregate
-
# functions are functions that apply over every row in the result set,
-
# instead of over just a single row. (A very common aggregate function
-
# is the "count" function, for determining the number of rows that match
-
# a query.)
-
#
-
# The new function will be added as +name+, with the given +arity+. (For
-
# variable arity functions, use -1 for the arity.)
-
#
-
# The +step+ parameter must be a proc object that accepts as its first
-
# parameter a FunctionProxy instance (representing the function
-
# invocation), with any subsequent parameters (up to the function's arity).
-
# The +step+ callback will be invoked once for each row of the result set.
-
#
-
# The +finalize+ parameter must be a +proc+ object that accepts only a
-
# single parameter, the FunctionProxy instance representing the current
-
# function invocation. It should invoke FunctionProxy#result= to
-
# store the result of the function.
-
#
-
# Example:
-
#
-
# db.create_aggregate( "lengths", 1 ) do
-
# step do |func, value|
-
# func[ :total ] ||= 0
-
# func[ :total ] += ( value ? value.length : 0 )
-
# end
-
#
-
# finalize do |func|
-
# func.result = func[ :total ] || 0
-
# end
-
# end
-
#
-
# puts db.get_first_value( "select lengths(name) from table" )
-
#
-
# See also #create_aggregate_handler for a more object-oriented approach to
-
# aggregate functions.
-
1
def create_aggregate( name, arity, step=nil, finalize=nil,
-
text_rep=Constants::TextRep::ANY, &block )
-
-
factory = Class.new do
-
def self.step( &block )
-
define_method(:step, &block)
-
end
-
-
def self.finalize( &block )
-
define_method(:finalize, &block)
-
end
-
end
-
-
if block_given?
-
factory.instance_eval(&block)
-
else
-
factory.class_eval do
-
define_method(:step, step)
-
define_method(:finalize, finalize)
-
end
-
end
-
-
proxy = factory.new
-
proxy.extend(Module.new {
-
attr_accessor :ctx
-
-
def step( *args )
-
super(@ctx, *args)
-
end
-
-
def finalize
-
super(@ctx)
-
result = @ctx.result
-
@ctx = FunctionProxy.new
-
result
-
end
-
})
-
proxy.ctx = FunctionProxy.new
-
define_aggregator(name, proxy)
-
end
-
-
# This is another approach to creating an aggregate function (see
-
# #create_aggregate). Instead of explicitly specifying the name,
-
# callbacks, arity, and type, you specify a factory object
-
# (the "handler") that knows how to obtain all of that information. The
-
# handler should respond to the following messages:
-
#
-
# +arity+:: corresponds to the +arity+ parameter of #create_aggregate. This
-
# message is optional, and if the handler does not respond to it,
-
# the function will have an arity of -1.
-
# +name+:: this is the name of the function. The handler _must_ implement
-
# this message.
-
# +new+:: this must be implemented by the handler. It should return a new
-
# instance of the object that will handle a specific invocation of
-
# the function.
-
#
-
# The handler instance (the object returned by the +new+ message, described
-
# above), must respond to the following messages:
-
#
-
# +step+:: this is the method that will be called for each step of the
-
# aggregate function's evaluation. It should implement the same
-
# signature as the +step+ callback for #create_aggregate.
-
# +finalize+:: this is the method that will be called to finalize the
-
# aggregate function's evaluation. It should implement the
-
# same signature as the +finalize+ callback for
-
# #create_aggregate.
-
#
-
# Example:
-
#
-
# class LengthsAggregateHandler
-
# def self.arity; 1; end
-
# def self.name; 'lengths'; end
-
#
-
# def initialize
-
# @total = 0
-
# end
-
#
-
# def step( ctx, name )
-
# @total += ( name ? name.length : 0 )
-
# end
-
#
-
# def finalize( ctx )
-
# ctx.result = @total
-
# end
-
# end
-
#
-
# db.create_aggregate_handler( LengthsAggregateHandler )
-
# puts db.get_first_value( "select lengths(name) from A" )
-
1
def create_aggregate_handler( handler )
-
proxy = Class.new do
-
def initialize klass
-
@klass = klass
-
@fp = FunctionProxy.new
-
end
-
-
def step( *args )
-
instance.step(@fp, *args)
-
end
-
-
def finalize
-
instance.finalize @fp
-
@instance = nil
-
@fp.result
-
end
-
-
private
-
-
def instance
-
@instance ||= @klass.new
-
end
-
end
-
define_aggregator(handler.name, proxy.new(handler))
-
self
-
end
-
-
# Begins a new transaction. Note that nested transactions are not allowed
-
# by SQLite, so attempting to nest a transaction will result in a runtime
-
# exception.
-
#
-
# The +mode+ parameter may be either <tt>:deferred</tt> (the default),
-
# <tt>:immediate</tt>, or <tt>:exclusive</tt>.
-
#
-
# If a block is given, the database instance is yielded to it, and the
-
# transaction is committed when the block terminates. If the block
-
# raises an exception, a rollback will be performed instead. Note that if
-
# a block is given, #commit and #rollback should never be called
-
# explicitly or you'll get an error when the block terminates.
-
#
-
# If a block is not given, it is the caller's responsibility to end the
-
# transaction explicitly, either by calling #commit, or by calling
-
# #rollback.
-
1
def transaction( mode = :deferred )
-
36
execute "begin #{mode.to_s} transaction"
-
-
36
if block_given?
-
abort = false
-
begin
-
yield self
-
rescue ::Object
-
abort = true
-
raise
-
ensure
-
abort and rollback or commit
-
end
-
end
-
-
36
true
-
end
-
-
# Commits the current transaction. If there is no current transaction,
-
# this will cause an error to be raised. This returns +true+, in order
-
# to allow it to be used in idioms like
-
# <tt>abort? and rollback or commit</tt>.
-
1
def commit
-
18
execute "commit transaction"
-
18
true
-
end
-
-
# Rolls the current transaction back. If there is no current transaction,
-
# this will cause an error to be raised. This returns +true+, in order
-
# to allow it to be used in idioms like
-
# <tt>abort? and rollback or commit</tt>.
-
1
def rollback
-
18
execute "rollback transaction"
-
18
true
-
end
-
-
# Returns +true+ if the database has been open in readonly mode
-
# A helper to check before performing any operation
-
1
def readonly?
-
@readonly
-
end
-
-
# A helper class for dealing with custom functions (see #create_function,
-
# #create_aggregate, and #create_aggregate_handler). It encapsulates the
-
# opaque function object that represents the current invocation. It also
-
# provides more convenient access to the API functions that operate on
-
# the function object.
-
#
-
# This class will almost _always_ be instantiated indirectly, by working
-
# with the create methods mentioned above.
-
1
class FunctionProxy
-
1
attr_accessor :result
-
-
# Create a new FunctionProxy that encapsulates the given +func+ object.
-
# If context is non-nil, the functions context will be set to that. If
-
# it is non-nil, it must quack like a Hash. If it is nil, then none of
-
# the context functions will be available.
-
1
def initialize
-
@result = nil
-
@context = {}
-
end
-
-
# Set the result of the function to the given error message.
-
# The function will then return that error.
-
1
def set_error( error )
-
@driver.result_error( @func, error.to_s, -1 )
-
end
-
-
# (Only available to aggregate functions.) Returns the number of rows
-
# that the aggregate has processed so far. This will include the current
-
# row, and so will always return at least 1.
-
1
def count
-
@driver.aggregate_count( @func )
-
end
-
-
# Returns the value with the given key from the context. This is only
-
# available to aggregate functions.
-
1
def []( key )
-
@context[ key ]
-
end
-
-
# Sets the value with the given key in the context. This is only
-
# available to aggregate functions.
-
1
def []=( key, value )
-
@context[ key ] = value
-
end
-
end
-
-
1
private
-
-
1
def ordered_map_for columns, row
-
h = Hash[*columns.zip(row).flatten]
-
row.each_with_index { |r, i| h[i] = r }
-
h
-
end
-
end
-
end
-
1
require 'sqlite3/constants'
-
-
1
module SQLite3
-
1
class Exception < ::StandardError
-
1
@code = 0
-
-
# The numeric error code that this exception represents.
-
1
def self.code
-
@code
-
end
-
-
# A convenience for accessing the error code for this exception.
-
1
def code
-
self.class.code
-
end
-
end
-
-
1
class SQLException < Exception; end
-
1
class InternalException < Exception; end
-
1
class PermissionException < Exception; end
-
1
class AbortException < Exception; end
-
1
class BusyException < Exception; end
-
1
class LockedException < Exception; end
-
1
class MemoryException < Exception; end
-
1
class ReadOnlyException < Exception; end
-
1
class InterruptException < Exception; end
-
1
class IOException < Exception; end
-
1
class CorruptException < Exception; end
-
1
class NotFoundException < Exception; end
-
1
class FullException < Exception; end
-
1
class CantOpenException < Exception; end
-
1
class ProtocolException < Exception; end
-
1
class EmptyException < Exception; end
-
1
class SchemaChangedException < Exception; end
-
1
class TooBigException < Exception; end
-
1
class ConstraintException < Exception; end
-
1
class MismatchException < Exception; end
-
1
class MisuseException < Exception; end
-
1
class UnsupportedException < Exception; end
-
1
class AuthorizationException < Exception; end
-
1
class FormatException < Exception; end
-
1
class RangeException < Exception; end
-
1
class NotADatabaseException < Exception; end
-
end
-
1
require 'sqlite3/errors'
-
-
1
module SQLite3
-
-
# This module is intended for inclusion solely by the Database class. It
-
# defines convenience methods for the various pragmas supported by SQLite3.
-
#
-
# For a detailed description of these pragmas, see the SQLite3 documentation
-
# at http://sqlite.org/pragma.html.
-
1
module Pragmas
-
-
# Returns +true+ or +false+ depending on the value of the named pragma.
-
1
def get_boolean_pragma( name )
-
get_first_value( "PRAGMA #{name}" ) != "0"
-
end
-
-
# Sets the given pragma to the given boolean value. The value itself
-
# may be +true+ or +false+, or any other commonly used string or
-
# integer that represents truth.
-
1
def set_boolean_pragma( name, mode )
-
case mode
-
when String
-
case mode.downcase
-
when "on", "yes", "true", "y", "t"; mode = "'ON'"
-
when "off", "no", "false", "n", "f"; mode = "'OFF'"
-
else
-
raise Exception,
-
"unrecognized pragma parameter #{mode.inspect}"
-
end
-
when true, 1
-
mode = "ON"
-
when false, 0, nil
-
mode = "OFF"
-
else
-
raise Exception,
-
"unrecognized pragma parameter #{mode.inspect}"
-
end
-
-
execute( "PRAGMA #{name}=#{mode}" )
-
end
-
-
# Requests the given pragma (and parameters), and if the block is given,
-
# each row of the result set will be yielded to it. Otherwise, the results
-
# are returned as an array.
-
1
def get_query_pragma( name, *parms, &block ) # :yields: row
-
if parms.empty?
-
execute( "PRAGMA #{name}", &block )
-
else
-
args = "'" + parms.join("','") + "'"
-
execute( "PRAGMA #{name}( #{args} )", &block )
-
end
-
end
-
-
# Return the value of the given pragma.
-
1
def get_enum_pragma( name )
-
get_first_value( "PRAGMA #{name}" )
-
end
-
-
# Set the value of the given pragma to +mode+. The +mode+ parameter must
-
# conform to one of the values in the given +enum+ array. Each entry in
-
# the array is another array comprised of elements in the enumeration that
-
# have duplicate values. See #synchronous, #default_synchronous,
-
# #temp_store, and #default_temp_store for usage examples.
-
1
def set_enum_pragma( name, mode, enums )
-
match = enums.find { |p| p.find { |i| i.to_s.downcase == mode.to_s.downcase } }
-
raise Exception,
-
"unrecognized #{name} #{mode.inspect}" unless match
-
execute( "PRAGMA #{name}='#{match.first.upcase}'" )
-
end
-
-
# Returns the value of the given pragma as an integer.
-
1
def get_int_pragma( name )
-
get_first_value( "PRAGMA #{name}" ).to_i
-
end
-
-
# Set the value of the given pragma to the integer value of the +value+
-
# parameter.
-
1
def set_int_pragma( name, value )
-
execute( "PRAGMA #{name}=#{value.to_i}" )
-
end
-
-
# The enumeration of valid synchronous modes.
-
1
SYNCHRONOUS_MODES = [ [ 'full', 2 ], [ 'normal', 1 ], [ 'off', 0 ] ]
-
-
# The enumeration of valid temp store modes.
-
1
TEMP_STORE_MODES = [ [ 'default', 0 ], [ 'file', 1 ], [ 'memory', 2 ] ]
-
-
# The enumeration of valid auto vacuum modes.
-
1
AUTO_VACUUM_MODES = [ [ 'none', 0 ], [ 'full', 1 ], [ 'incremental', 2 ] ]
-
-
# The list of valid journaling modes.
-
1
JOURNAL_MODES = [ [ 'delete' ], [ 'truncate' ], [ 'persist' ], [ 'memory' ],
-
[ 'wal' ], [ 'off' ] ]
-
-
# The list of valid locking modes.
-
1
LOCKING_MODES = [ [ 'normal' ], [ 'exclusive' ] ]
-
-
# The list of valid encodings.
-
1
ENCODINGS = [ [ 'utf-8' ], [ 'utf-16' ], [ 'utf-16le' ], [ 'utf-16be ' ] ]
-
-
# The list of valid WAL checkpoints.
-
1
WAL_CHECKPOINTS = [ [ 'passive' ], [ 'full' ], [ 'restart' ], [ 'truncate' ] ]
-
-
1
def application_id
-
get_int_pragma "application_id"
-
end
-
-
1
def application_id=( integer )
-
set_int_pragma "application_id", integer
-
end
-
-
1
def auto_vacuum
-
get_enum_pragma "auto_vacuum"
-
end
-
-
1
def auto_vacuum=( mode )
-
set_enum_pragma "auto_vacuum", mode, AUTO_VACUUM_MODES
-
end
-
-
1
def automatic_index
-
get_boolean_pragma "automatic_index"
-
end
-
-
1
def automatic_index=( mode )
-
set_boolean_pragma "automatic_index", mode
-
end
-
-
1
def busy_timeout
-
get_int_pragma "busy_timeout"
-
end
-
-
1
def busy_timeout=( milliseconds )
-
set_int_pragma "busy_timeout", milliseconds
-
end
-
-
1
def cache_size
-
get_int_pragma "cache_size"
-
end
-
-
1
def cache_size=( size )
-
set_int_pragma "cache_size", size
-
end
-
-
1
def cache_spill
-
get_boolean_pragma "cache_spill"
-
end
-
-
1
def cache_spill=( mode )
-
set_boolean_pragma "cache_spill", mode
-
end
-
-
1
def case_sensitive_like=( mode )
-
set_boolean_pragma "case_sensitive_like", mode
-
end
-
-
1
def cell_size_check
-
get_boolean_pragma "cell_size_check"
-
end
-
-
1
def cell_size_check=( mode )
-
set_boolean_pragma "cell_size_check", mode
-
end
-
-
1
def checkpoint_fullfsync
-
get_boolean_pragma "checkpoint_fullfsync"
-
end
-
-
1
def checkpoint_fullfsync=( mode )
-
set_boolean_pragma "checkpoint_fullfsync", mode
-
end
-
-
1
def collation_list( &block ) # :yields: row
-
get_query_pragma "collation_list", &block
-
end
-
-
1
def compile_options( &block ) # :yields: row
-
get_query_pragma "compile_options", &block
-
end
-
-
1
def count_changes
-
get_boolean_pragma "count_changes"
-
end
-
-
1
def count_changes=( mode )
-
set_boolean_pragma "count_changes", mode
-
end
-
-
1
def data_version
-
get_int_pragma "data_version"
-
end
-
-
1
def database_list( &block ) # :yields: row
-
get_query_pragma "database_list", &block
-
end
-
-
1
def default_cache_size
-
get_int_pragma "default_cache_size"
-
end
-
-
1
def default_cache_size=( size )
-
set_int_pragma "default_cache_size", size
-
end
-
-
1
def default_synchronous
-
get_enum_pragma "default_synchronous"
-
end
-
-
1
def default_synchronous=( mode )
-
set_enum_pragma "default_synchronous", mode, SYNCHRONOUS_MODES
-
end
-
-
1
def default_temp_store
-
get_enum_pragma "default_temp_store"
-
end
-
-
1
def default_temp_store=( mode )
-
set_enum_pragma "default_temp_store", mode, TEMP_STORE_MODES
-
end
-
-
1
def defer_foreign_keys
-
get_boolean_pragma "defer_foreign_keys"
-
end
-
-
1
def defer_foreign_keys=( mode )
-
set_boolean_pragma "defer_foreign_keys", mode
-
end
-
-
1
def encoding
-
get_enum_pragma "encoding"
-
end
-
-
1
def encoding=( mode )
-
set_enum_pragma "encoding", mode, ENCODINGS
-
end
-
-
1
def foreign_key_check( *table, &block ) # :yields: row
-
get_query_pragma "foreign_key_check", *table, &block
-
end
-
-
1
def foreign_key_list( table, &block ) # :yields: row
-
get_query_pragma "foreign_key_list", table, &block
-
end
-
-
1
def foreign_keys
-
get_boolean_pragma "foreign_keys"
-
end
-
-
1
def foreign_keys=( mode )
-
set_boolean_pragma "foreign_keys", mode
-
end
-
-
1
def freelist_count
-
get_int_pragma "freelist_count"
-
end
-
-
1
def full_column_names
-
get_boolean_pragma "full_column_names"
-
end
-
-
1
def full_column_names=( mode )
-
set_boolean_pragma "full_column_names", mode
-
end
-
-
1
def fullfsync
-
get_boolean_pragma "fullfsync"
-
end
-
-
1
def fullfsync=( mode )
-
set_boolean_pragma "fullfsync", mode
-
end
-
-
1
def ignore_check_constraints=( mode )
-
set_boolean_pragma "ignore_check_constraints", mode
-
end
-
-
1
def incremental_vacuum( pages, &block ) # :yields: row
-
get_query_pragma "incremental_vacuum", pages, &block
-
end
-
-
1
def index_info( index, &block ) # :yields: row
-
get_query_pragma "index_info", index, &block
-
end
-
-
1
def index_list( table, &block ) # :yields: row
-
get_query_pragma "index_list", table, &block
-
end
-
-
1
def index_xinfo( index, &block ) # :yields: row
-
get_query_pragma "index_xinfo", index, &block
-
end
-
-
1
def integrity_check( *num_errors, &block ) # :yields: row
-
get_query_pragma "integrity_check", *num_errors, &block
-
end
-
-
1
def journal_mode
-
get_enum_pragma "journal_mode"
-
end
-
-
1
def journal_mode=( mode )
-
set_enum_pragma "journal_mode", mode, JOURNAL_MODES
-
end
-
-
1
def journal_size_limit
-
get_int_pragma "journal_size_limit"
-
end
-
-
1
def journal_size_limit=( size )
-
set_int_pragma "journal_size_limit", size
-
end
-
-
1
def legacy_file_format
-
get_boolean_pragma "legacy_file_format"
-
end
-
-
1
def legacy_file_format=( mode )
-
set_boolean_pragma "legacy_file_format", mode
-
end
-
-
1
def locking_mode
-
get_enum_pragma "locking_mode"
-
end
-
-
1
def locking_mode=( mode )
-
set_enum_pragma "locking_mode", mode, LOCKING_MODES
-
end
-
-
1
def max_page_count
-
get_int_pragma "max_page_count"
-
end
-
-
1
def max_page_count=( size )
-
set_int_pragma "max_page_count", size
-
end
-
-
1
def mmap_size
-
get_int_pragma "mmap_size"
-
end
-
-
1
def mmap_size=( size )
-
set_int_pragma "mmap_size", size
-
end
-
-
1
def page_count
-
get_int_pragma "page_count"
-
end
-
-
1
def page_size
-
get_int_pragma "page_size"
-
end
-
-
1
def page_size=( size )
-
set_int_pragma "page_size", size
-
end
-
-
1
def parser_trace=( mode )
-
set_boolean_pragma "parser_trace", mode
-
end
-
-
1
def query_only
-
get_boolean_pragma "query_only"
-
end
-
-
1
def query_only=( mode )
-
set_boolean_pragma "query_only", mode
-
end
-
-
1
def quick_check( *num_errors, &block ) # :yields: row
-
get_query_pragma "quick_check", *num_errors, &block
-
end
-
-
1
def read_uncommitted
-
get_boolean_pragma "read_uncommitted"
-
end
-
-
1
def read_uncommitted=( mode )
-
set_boolean_pragma "read_uncommitted", mode
-
end
-
-
1
def recursive_triggers
-
get_boolean_pragma "recursive_triggers"
-
end
-
-
1
def recursive_triggers=( mode )
-
set_boolean_pragma "recursive_triggers", mode
-
end
-
-
1
def reverse_unordered_selects
-
get_boolean_pragma "reverse_unordered_selects"
-
end
-
-
1
def reverse_unordered_selects=( mode )
-
set_boolean_pragma "reverse_unordered_selects", mode
-
end
-
-
1
def schema_cookie
-
get_int_pragma "schema_cookie"
-
end
-
-
1
def schema_cookie=( cookie )
-
set_int_pragma "schema_cookie", cookie
-
end
-
-
1
def schema_version
-
get_int_pragma "schema_version"
-
end
-
-
1
def schema_version=( version )
-
set_int_pragma "schema_version", version
-
end
-
-
1
def secure_delete
-
get_boolean_pragma "secure_delete"
-
end
-
-
1
def secure_delete=( mode )
-
set_boolean_pragma "secure_delete", mode
-
end
-
-
1
def short_column_names
-
get_boolean_pragma "short_column_names"
-
end
-
-
1
def short_column_names=( mode )
-
set_boolean_pragma "short_column_names", mode
-
end
-
-
1
def shrink_memory
-
execute( "PRAGMA shrink_memory" )
-
end
-
-
1
def soft_heap_limit
-
get_int_pragma "soft_heap_limit"
-
end
-
-
1
def soft_heap_limit=( mode )
-
set_int_pragma "soft_heap_limit", mode
-
end
-
-
1
def stats( &block ) # :yields: row
-
get_query_pragma "stats", &block
-
end
-
-
1
def synchronous
-
get_enum_pragma "synchronous"
-
end
-
-
1
def synchronous=( mode )
-
set_enum_pragma "synchronous", mode, SYNCHRONOUS_MODES
-
end
-
-
1
def temp_store
-
get_enum_pragma "temp_store"
-
end
-
-
1
def temp_store=( mode )
-
set_enum_pragma "temp_store", mode, TEMP_STORE_MODES
-
end
-
-
1
def threads
-
get_int_pragma "threads"
-
end
-
-
1
def threads=( count )
-
set_int_pragma "threads", count
-
end
-
-
1
def user_cookie
-
get_int_pragma "user_cookie"
-
end
-
-
1
def user_cookie=( cookie )
-
set_int_pragma "user_cookie", cookie
-
end
-
-
1
def user_version
-
get_int_pragma "user_version"
-
end
-
-
1
def user_version=( version )
-
set_int_pragma "user_version", version
-
end
-
-
1
def vdbe_addoptrace=( mode )
-
set_boolean_pragma "vdbe_addoptrace", mode
-
end
-
-
1
def vdbe_debug=( mode )
-
set_boolean_pragma "vdbe_debug", mode
-
end
-
-
1
def vdbe_listing=( mode )
-
set_boolean_pragma "vdbe_listing", mode
-
end
-
-
1
def vdbe_trace
-
get_boolean_pragma "vdbe_trace"
-
end
-
-
1
def vdbe_trace=( mode )
-
set_boolean_pragma "vdbe_trace", mode
-
end
-
-
1
def wal_autocheckpoint
-
get_int_pragma "wal_autocheckpoint"
-
end
-
-
1
def wal_autocheckpoint=( mode )
-
set_int_pragma "wal_autocheckpoint", mode
-
end
-
-
1
def wal_checkpoint
-
get_enum_pragma "wal_checkpoint"
-
end
-
-
1
def wal_checkpoint=( mode )
-
set_enum_pragma "wal_checkpoint", mode, WAL_CHECKPOINTS
-
end
-
-
1
def writable_schema=( mode )
-
set_boolean_pragma "writable_schema", mode
-
end
-
-
###
-
# Returns information about +table+. Yields each row of table information
-
# if a block is provided.
-
1
def table_info table
-
stmt = prepare "PRAGMA table_info(#{table})"
-
columns = stmt.columns
-
-
needs_tweak_default =
-
version_compare(SQLite3.libversion.to_s, "3.3.7") > 0
-
-
result = [] unless block_given?
-
stmt.each do |row|
-
new_row = Hash[columns.zip(row)]
-
-
# FIXME: This should be removed but is required for older versions
-
# of rails
-
if(Object.const_defined?(:ActiveRecord))
-
new_row['notnull'] = new_row['notnull'].to_s
-
end
-
-
tweak_default(new_row) if needs_tweak_default
-
-
if block_given?
-
yield new_row
-
else
-
result << new_row
-
end
-
end
-
stmt.close
-
-
result
-
end
-
-
1
private
-
-
# Compares two version strings
-
1
def version_compare(v1, v2)
-
v1 = v1.split(".").map { |i| i.to_i }
-
v2 = v2.split(".").map { |i| i.to_i }
-
parts = [v1.length, v2.length].max
-
v1.push 0 while v1.length < parts
-
v2.push 0 while v2.length < parts
-
v1.zip(v2).each do |a,b|
-
return -1 if a < b
-
return 1 if a > b
-
end
-
return 0
-
end
-
-
# Since SQLite 3.3.8, the table_info pragma has returned the default
-
# value of the row as a quoted SQL value. This method essentially
-
# unquotes those values.
-
1
def tweak_default(hash)
-
case hash["dflt_value"]
-
when /^null$/i
-
hash["dflt_value"] = nil
-
when /^'(.*)'$/m
-
hash["dflt_value"] = $1.gsub(/''/, "'")
-
when /^"(.*)"$/m
-
hash["dflt_value"] = $1.gsub(/""/, '"')
-
end
-
end
-
end
-
-
end
-
1
require 'sqlite3/constants'
-
1
require 'sqlite3/errors'
-
-
1
module SQLite3
-
-
# The ResultSet object encapsulates the enumerability of a query's output.
-
# It is a simple cursor over the data that the query returns. It will
-
# very rarely (if ever) be instantiated directly. Instead, clients should
-
# obtain a ResultSet instance via Statement#execute.
-
1
class ResultSet
-
1
include Enumerable
-
-
1
class ArrayWithTypes < Array # :nodoc:
-
1
attr_accessor :types
-
end
-
-
1
class ArrayWithTypesAndFields < Array # :nodoc:
-
1
attr_writer :types
-
1
attr_writer :fields
-
-
1
def types
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#types. This method will be removed in
-
sqlite3 version 2.0.0, please call the `types` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@types
-
end
-
-
1
def fields
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#fields. This method will be removed in
-
sqlite3 version 2.0.0, please call the `columns` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@fields
-
end
-
end
-
-
# The class of which we return an object in case we want a Hash as
-
# result.
-
1
class HashWithTypesAndFields < Hash # :nodoc:
-
1
attr_writer :types
-
1
attr_writer :fields
-
-
1
def types
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#types. This method will be removed in
-
sqlite3 version 2.0.0, please call the `types` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@types
-
end
-
-
1
def fields
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#fields. This method will be removed in
-
sqlite3 version 2.0.0, please call the `columns` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@fields
-
end
-
-
1
def [] key
-
key = fields[key] if key.is_a? Numeric
-
super key
-
end
-
end
-
-
# Create a new ResultSet attached to the given database, using the
-
# given sql text.
-
1
def initialize db, stmt
-
@db = db
-
@stmt = stmt
-
end
-
-
# Reset the cursor, so that a result set which has reached end-of-file
-
# can be rewound and reiterated.
-
1
def reset( *bind_params )
-
@stmt.reset!
-
@stmt.bind_params( *bind_params )
-
@eof = false
-
end
-
-
# Query whether the cursor has reached the end of the result set or not.
-
1
def eof?
-
@stmt.done?
-
end
-
-
# Obtain the next row from the cursor. If there are no more rows to be
-
# had, this will return +nil+. If type translation is active on the
-
# corresponding database, the values in the row will be translated
-
# according to their types.
-
#
-
# The returned value will be an array, unless Database#results_as_hash has
-
# been set to +true+, in which case the returned value will be a hash.
-
#
-
# For arrays, the column names are accessible via the +fields+ property,
-
# and the column types are accessible via the +types+ property.
-
#
-
# For hashes, the column names are the keys of the hash, and the column
-
# types are accessible via the +types+ property.
-
1
def next
-
if @db.results_as_hash
-
return next_hash
-
end
-
-
row = @stmt.step
-
return nil if @stmt.done?
-
-
if @db.type_translation
-
row = @stmt.types.zip(row).map do |type, value|
-
@db.translator.translate( type, value )
-
end
-
end
-
-
if row.respond_to?(:fields)
-
# FIXME: this can only happen if the translator returns something
-
# that responds to `fields`. Since we're removing the translator
-
# in 2.0, we can remove this branch in 2.0.
-
row = ArrayWithTypes.new(row)
-
else
-
# FIXME: the `fields` and `types` methods are deprecated on this
-
# object for version 2.0, so we can safely remove this branch
-
# as well.
-
row = ArrayWithTypesAndFields.new(row)
-
end
-
-
row.fields = @stmt.columns
-
row.types = @stmt.types
-
row
-
end
-
-
# Required by the Enumerable mixin. Provides an internal iterator over the
-
# rows of the result set.
-
1
def each
-
while node = self.next
-
yield node
-
end
-
end
-
-
# Provides an internal iterator over the rows of the result set where
-
# each row is yielded as a hash.
-
1
def each_hash
-
while node = next_hash
-
yield node
-
end
-
end
-
-
# Closes the statement that spawned this result set.
-
# <em>Use with caution!</em> Closing a result set will automatically
-
# close any other result sets that were spawned from the same statement.
-
1
def close
-
@stmt.close
-
end
-
-
# Queries whether the underlying statement has been closed or not.
-
1
def closed?
-
@stmt.closed?
-
end
-
-
# Returns the types of the columns returned by this result set.
-
1
def types
-
@stmt.types
-
end
-
-
# Returns the names of the columns returned by this result set.
-
1
def columns
-
@stmt.columns
-
end
-
-
# Return the next row as a hash
-
1
def next_hash
-
row = @stmt.step
-
return nil if @stmt.done?
-
-
# FIXME: type translation is deprecated, so this can be removed
-
# in 2.0
-
if @db.type_translation
-
row = @stmt.types.zip(row).map do |type, value|
-
@db.translator.translate( type, value )
-
end
-
end
-
-
# FIXME: this can be switched to a regular hash in 2.0
-
row = HashWithTypesAndFields[*@stmt.columns.zip(row).flatten]
-
-
# FIXME: these methods are deprecated for version 2.0, so we can remove
-
# this code in 2.0
-
row.fields = @stmt.columns
-
row.types = @stmt.types
-
row
-
end
-
end
-
end
-
1
require 'sqlite3/errors'
-
1
require 'sqlite3/resultset'
-
-
1
class String
-
1
def to_blob
-
SQLite3::Blob.new( self )
-
end
-
end
-
-
1
module SQLite3
-
# A statement represents a prepared-but-unexecuted SQL query. It will rarely
-
# (if ever) be instantiated directly by a client, and is most often obtained
-
# via the Database#prepare method.
-
1
class Statement
-
1
include Enumerable
-
-
# This is any text that followed the first valid SQL statement in the text
-
# with which the statement was initialized. If there was no trailing text,
-
# this will be the empty string.
-
1
attr_reader :remainder
-
-
# Binds the given variables to the corresponding placeholders in the SQL
-
# text.
-
#
-
# See Database#execute for a description of the valid placeholder
-
# syntaxes.
-
#
-
# Example:
-
#
-
# stmt = db.prepare( "select * from table where a=? and b=?" )
-
# stmt.bind_params( 15, "hello" )
-
#
-
# See also #execute, #bind_param, Statement#bind_param, and
-
# Statement#bind_params.
-
1
def bind_params( *bind_vars )
-
190
index = 1
-
190
bind_vars.flatten.each do |var|
-
168
if Hash === var
-
var.each { |key, val| bind_param key, val }
-
else
-
168
bind_param index, var
-
168
index += 1
-
end
-
end
-
end
-
-
# Execute the statement. This creates a new ResultSet object for the
-
# statement's virtual machine. If a block was given, the new ResultSet will
-
# be yielded to it; otherwise, the ResultSet will be returned.
-
#
-
# Any parameters will be bound to the statement using #bind_params.
-
#
-
# Example:
-
#
-
# stmt = db.prepare( "select * from table" )
-
# stmt.execute do |result|
-
# ...
-
# end
-
#
-
# See also #bind_params, #execute!.
-
1
def execute( *bind_vars )
-
reset! if active? || done?
-
-
bind_params(*bind_vars) unless bind_vars.empty?
-
@results = ResultSet.new(@connection, self)
-
-
step if 0 == column_count
-
-
yield @results if block_given?
-
@results
-
end
-
-
# Execute the statement. If no block was given, this returns an array of
-
# rows returned by executing the statement. Otherwise, each row will be
-
# yielded to the block.
-
#
-
# Any parameters will be bound to the statement using #bind_params.
-
#
-
# Example:
-
#
-
# stmt = db.prepare( "select * from table" )
-
# stmt.execute! do |row|
-
# ...
-
# end
-
#
-
# See also #bind_params, #execute.
-
1
def execute!( *bind_vars, &block )
-
execute(*bind_vars)
-
block_given? ? each(&block) : to_a
-
end
-
-
# Returns true if the statement is currently active, meaning it has an
-
# open result set.
-
1
def active?
-
!done?
-
end
-
-
# Return an array of the column names for this statement. Note that this
-
# may execute the statement in order to obtain the metadata; this makes it
-
# a (potentially) expensive operation.
-
1
def columns
-
187
get_metadata unless @columns
-
187
return @columns
-
end
-
-
1
def each
-
225
loop do
-
340
val = step
-
340
break self if done?
-
115
yield val
-
end
-
end
-
-
# Return an array of the data types for each column in this statement. Note
-
# that this may execute the statement in order to obtain the metadata; this
-
# makes it a (potentially) expensive operation.
-
1
def types
-
must_be_open!
-
get_metadata unless @types
-
@types
-
end
-
-
# Performs a sanity check to ensure that the statement is not
-
# closed. If it is, an exception is raised.
-
1
def must_be_open! # :nodoc:
-
if closed?
-
raise SQLite3::Exception, "cannot use a closed statement"
-
end
-
end
-
-
1
private
-
# A convenience method for obtaining the metadata about the query. Note
-
# that this will actually execute the SQL, which means it can be a
-
# (potentially) expensive operation.
-
1
def get_metadata
-
187
@columns = Array.new(column_count) do |column|
-
241
column_name column
-
end
-
187
@types = Array.new(column_count) do |column|
-
241
column_decltype column
-
end
-
end
-
end
-
end
-
1
require 'time'
-
1
require 'date'
-
-
1
module SQLite3
-
-
# The Translator class encapsulates the logic and callbacks necessary for
-
# converting string data to a value of some specified type. Every Database
-
# instance may have a Translator instance, in order to assist in type
-
# translation (Database#type_translation).
-
#
-
# Further, applications may define their own custom type translation logic
-
# by registering translator blocks with the corresponding database's
-
# translator instance (Database#translator).
-
1
class Translator
-
-
# Create a new Translator instance. It will be preinitialized with default
-
# translators for most SQL data types.
-
1
def initialize
-
@translators = Hash.new( proc { |type,value| value } )
-
@type_name_cache = {}
-
register_default_translators
-
end
-
-
# Add a new translator block, which will be invoked to process type
-
# translations to the given type. The type should be an SQL datatype, and
-
# may include parentheses (i.e., "VARCHAR(30)"). However, any parenthetical
-
# information is stripped off and discarded, so type translation decisions
-
# are made solely on the "base" type name.
-
#
-
# The translator block itself should accept two parameters, "type" and
-
# "value". In this case, the "type" is the full type name (including
-
# parentheses), so the block itself may include logic for changing how a
-
# type is translated based on the additional data. The "value" parameter
-
# is the (string) data to convert.
-
#
-
# The block should return the translated value.
-
1
def add_translator( type, &block ) # :yields: type, value
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling `add_translator`.
-
Built in translators are deprecated and will be removed in version 2.0.0
-
eowarn
-
@translators[ type_name( type ) ] = block
-
end
-
-
# Translate the given string value to a value of the given type. In the
-
# absense of an installed translator block for the given type, the value
-
# itself is always returned. Further, +nil+ values are never translated,
-
# and are always passed straight through regardless of the type parameter.
-
1
def translate( type, value )
-
unless value.nil?
-
# FIXME: this is a hack to support Sequel
-
if type && %w{ datetime timestamp }.include?(type.downcase)
-
@translators[ type_name( type ) ].call( type, value.to_s )
-
else
-
@translators[ type_name( type ) ].call( type, value )
-
end
-
end
-
end
-
-
# A convenience method for working with type names. This returns the "base"
-
# type name, without any parenthetical data.
-
1
def type_name( type )
-
@type_name_cache[type] ||= begin
-
type = "" if type.nil?
-
type = $1 if type =~ /^(.*?)\(/
-
type.upcase
-
end
-
end
-
1
private :type_name
-
-
# Register the default translators for the current Translator instance.
-
# This includes translators for most major SQL data types.
-
1
def register_default_translators
-
[ "time",
-
"timestamp" ].each { |type| add_translator( type ) { |t, v| Time.parse( v ) } }
-
-
add_translator( "date" ) { |t,v| Date.parse(v) }
-
add_translator( "datetime" ) { |t,v| DateTime.parse(v) }
-
-
[ "decimal",
-
"float",
-
"numeric",
-
"double",
-
"real",
-
"dec",
-
"fixed" ].each { |type| add_translator( type ) { |t,v| v.to_f } }
-
-
[ "integer",
-
"smallint",
-
"mediumint",
-
"int",
-
"bigint" ].each { |type| add_translator( type ) { |t,v| v.to_i } }
-
-
[ "bit",
-
"bool",
-
"boolean" ].each do |type|
-
add_translator( type ) do |t,v|
-
!( v.strip.gsub(/00+/,"0") == "0" ||
-
v.downcase == "false" ||
-
v.downcase == "f" ||
-
v.downcase == "no" ||
-
v.downcase == "n" )
-
end
-
end
-
-
add_translator( "tinyint" ) do |type, value|
-
if type =~ /\(\s*1\s*\)/
-
value.to_i == 1
-
else
-
value.to_i
-
end
-
end
-
end
-
1
private :register_default_translators
-
-
end
-
-
end
-
1
require 'sqlite3/constants'
-
-
1
module SQLite3
-
-
1
class Value
-
1
attr_reader :handle
-
-
1
def initialize( db, handle )
-
@driver = db.driver
-
@handle = handle
-
end
-
-
1
def null?
-
type == :null
-
end
-
-
1
def to_blob
-
@driver.value_blob( @handle )
-
end
-
-
1
def length( utf16=false )
-
if utf16
-
@driver.value_bytes16( @handle )
-
else
-
@driver.value_bytes( @handle )
-
end
-
end
-
-
1
def to_f
-
@driver.value_double( @handle )
-
end
-
-
1
def to_i
-
@driver.value_int( @handle )
-
end
-
-
1
def to_int64
-
@driver.value_int64( @handle )
-
end
-
-
1
def to_s( utf16=false )
-
@driver.value_text( @handle, utf16 )
-
end
-
-
1
def type
-
case @driver.value_type( @handle )
-
when Constants::ColumnType::INTEGER then :int
-
when Constants::ColumnType::FLOAT then :float
-
when Constants::ColumnType::TEXT then :text
-
when Constants::ColumnType::BLOB then :blob
-
when Constants::ColumnType::NULL then :null
-
end
-
end
-
-
end
-
-
end
-
1
module SQLite3
-
-
1
VERSION = '1.3.13'
-
-
1
module VersionProxy
-
-
1
MAJOR = 1
-
1
MINOR = 3
-
1
TINY = 13
-
1
BUILD = nil
-
-
1
STRING = [ MAJOR, MINOR, TINY, BUILD ].compact.join( "." )
-
#:beta-tag:
-
-
1
VERSION = ::SQLite3::VERSION
-
end
-
-
1
def self.const_missing(name)
-
return super unless name == :Version
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]}: SQLite::Version will be removed in sqlite3-ruby version 2.0.0
-
eowarn
-
VersionProxy
-
end
-
end
-
1
require 'temple/version'
-
-
1
module Temple
-
1
autoload :InvalidExpression, 'temple/exceptions'
-
1
autoload :FilterError, 'temple/exceptions'
-
1
autoload :Generator, 'temple/generator'
-
1
autoload :Parser, 'temple/parser'
-
1
autoload :Engine, 'temple/engine'
-
1
autoload :Utils, 'temple/utils'
-
1
autoload :Filter, 'temple/filter'
-
1
autoload :Templates, 'temple/templates'
-
1
autoload :Grammar, 'temple/grammar'
-
1
autoload :ImmutableMap, 'temple/map'
-
1
autoload :MutableMap, 'temple/map'
-
1
autoload :OptionMap, 'temple/map'
-
1
autoload :StaticAnalyzer, 'temple/static_analyzer'
-
-
1
module Mixins
-
1
autoload :Dispatcher, 'temple/mixins/dispatcher'
-
1
autoload :CompiledDispatcher, 'temple/mixins/dispatcher'
-
1
autoload :EngineDSL, 'temple/mixins/engine_dsl'
-
1
autoload :GrammarDSL, 'temple/mixins/grammar_dsl'
-
1
autoload :Options, 'temple/mixins/options'
-
1
autoload :ClassOptions, 'temple/mixins/options'
-
1
autoload :Template, 'temple/mixins/template'
-
end
-
-
1
module ERB
-
1
autoload :Engine, 'temple/erb/engine'
-
1
autoload :Parser, 'temple/erb/parser'
-
1
autoload :Trimming, 'temple/erb/trimming'
-
1
autoload :Template, 'temple/erb/template'
-
end
-
-
1
module Generators
-
1
autoload :ERB, 'temple/generators/erb'
-
1
autoload :Array, 'temple/generators/array'
-
1
autoload :ArrayBuffer, 'temple/generators/array_buffer'
-
1
autoload :StringBuffer, 'temple/generators/string_buffer'
-
1
autoload :RailsOutputBuffer, 'temple/generators/rails_output_buffer'
-
end
-
-
1
module Filters
-
1
autoload :CodeMerger, 'temple/filters/code_merger'
-
1
autoload :ControlFlow, 'temple/filters/control_flow'
-
1
autoload :MultiFlattener, 'temple/filters/multi_flattener'
-
1
autoload :StaticAnalyzer, 'temple/filters/static_analyzer'
-
1
autoload :StaticMerger, 'temple/filters/static_merger'
-
1
autoload :StringSplitter, 'temple/filters/string_splitter'
-
1
autoload :DynamicInliner, 'temple/filters/dynamic_inliner'
-
1
autoload :Escapable, 'temple/filters/escapable'
-
1
autoload :Eraser, 'temple/filters/eraser'
-
1
autoload :Validator, 'temple/filters/validator'
-
1
autoload :Encoding, 'temple/filters/encoding'
-
1
autoload :RemoveBOM, 'temple/filters/remove_bom'
-
end
-
-
1
module HTML
-
1
autoload :Dispatcher, 'temple/html/dispatcher'
-
1
autoload :Filter, 'temple/html/filter'
-
1
autoload :Fast, 'temple/html/fast'
-
1
autoload :Pretty, 'temple/html/pretty'
-
1
autoload :AttributeMerger, 'temple/html/attribute_merger'
-
1
autoload :AttributeRemover, 'temple/html/attribute_remover'
-
1
autoload :AttributeSorter, 'temple/html/attribute_sorter'
-
end
-
end
-
1
module Temple
-
# An engine is simply a chain of compilers (that often includes a parser,
-
# some filters and a generator).
-
#
-
# class MyEngine < Temple::Engine
-
# # First run MyParser, passing the :strict option
-
# use MyParser, :strict
-
#
-
# # Then a custom filter
-
# use MyFilter
-
#
-
# # Then some general optimizations filters
-
# filter :MultiFlattener
-
# filter :StaticMerger
-
# filter :DynamicInliner
-
#
-
# # Finally the generator
-
# generator :ArrayBuffer, :buffer
-
# end
-
#
-
# class SpecialEngine < MyEngine
-
# append MyCodeOptimizer
-
# before :ArrayBuffer, Temple::Filters::Validator
-
# replace :ArrayBuffer, Temple::Generators::RailsOutputBuffer
-
# end
-
#
-
# engine = MyEngine.new(strict: "For MyParser")
-
# engine.call(something)
-
#
-
# @api public
-
1
class Engine
-
1
include Mixins::Options
-
1
include Mixins::EngineDSL
-
1
extend Mixins::EngineDSL
-
-
1
define_options :file, :streaming, :buffer, :save_buffer
-
-
1
attr_reader :chain
-
-
1
def self.chain
-
30
@chain ||= superclass.respond_to?(:chain) ? superclass.chain.dup : []
-
end
-
-
1
def initialize(opts = {})
-
22
super
-
22
@chain = self.class.chain.dup
-
end
-
-
1
def call(input)
-
176
call_chain.inject(input) {|m, e| e.call(m) }
-
end
-
-
1
protected
-
-
1
def chain_modified!
-
@call_chain = nil
-
end
-
-
1
def call_chain
-
@call_chain ||= @chain.map do |name, constructor|
-
154
f = constructor.call(self)
-
154
raise "Constructor #{name} must return callable object" if f && !f.respond_to?(:call)
-
154
f
-
22
end.compact
-
end
-
end
-
end
-
1
module Temple
-
# Temple base filter
-
# @api public
-
1
class Filter
-
1
include Utils
-
1
include Mixins::Dispatcher
-
1
include Mixins::Options
-
end
-
end
-
1
module Temple
-
1
module Filters
-
# Control flow filter which processes [:if, condition, yes-exp, no-exp]
-
# and [:block, code, content] expressions.
-
# This is useful for ruby code generation with lots of conditionals.
-
#
-
# @api public
-
1
class ControlFlow < Filter
-
1
def on_if(condition, yes, no = nil)
-
result = [:multi, [:code, "if #{condition}"], compile(yes)]
-
while no && no.first == :if
-
result << [:code, "elsif #{no[1]}"] << compile(no[2])
-
no = no[3]
-
end
-
result << [:code, 'else'] << compile(no) if no
-
result << [:code, 'end']
-
result
-
end
-
-
1
def on_case(arg, *cases)
-
result = [:multi, [:code, arg ? "case (#{arg})" : 'case']]
-
cases.map do |c|
-
condition, exp = c
-
result << [:code, condition == :else ? 'else' : "when #{condition}"] << compile(exp)
-
end
-
result << [:code, 'end']
-
result
-
end
-
-
1
def on_cond(*cases)
-
on_case(nil, *cases)
-
end
-
-
1
def on_block(code, exp)
-
[:multi,
-
[:code, code],
-
compile(exp),
-
[:code, 'end']]
-
end
-
end
-
end
-
end
-
1
module Temple
-
1
module Filters
-
# Flattens nested multi expressions
-
#
-
# @api public
-
1
class MultiFlattener < Filter
-
1
def on_multi(*exps)
-
# If the multi contains a single element, just return the element
-
181
return compile(exps.first) if exps.size == 1
-
160
result = [:multi]
-
-
160
exps.each do |exp|
-
975
exp = compile(exp)
-
975
if exp.first == :multi
-
138
result.concat(exp[1..-1])
-
else
-
837
result << exp
-
end
-
end
-
-
160
result
-
end
-
end
-
end
-
end
-
1
module Temple
-
1
module Filters
-
# Merges several statics into a single static. Example:
-
#
-
# [:multi,
-
# [:static, "Hello "],
-
# [:static, "World!"]]
-
#
-
# Compiles to:
-
#
-
# [:static, "Hello World!"]
-
#
-
# @api public
-
1
class StaticMerger < Filter
-
1
def on_multi(*exps)
-
22
result = [:multi]
-
22
text = nil
-
-
22
exps.each do |exp|
-
837
if exp.first == :static
-
607
if text
-
442
text << exp.last
-
else
-
165
text = exp.last.dup
-
165
result << [:static, text]
-
end
-
else
-
230
result << compile(exp)
-
230
text = nil unless exp.first == :newline
-
end
-
end
-
-
22
result.size == 2 ? result[1] : result
-
end
-
end
-
end
-
end
-
1
module Temple
-
# Immutable map class which supports map merging
-
# @api public
-
1
class ImmutableMap
-
1
include Enumerable
-
-
1
def initialize(*map)
-
140
@map = map.compact
-
end
-
-
1
def include?(key)
-
12148
@map.any? {|h| h.include?(key) }
-
end
-
-
1
def [](key)
-
7714
@map.each {|h| return h[key] if h.include?(key) }
-
nil
-
end
-
-
1
def each
-
3913
keys.each {|k| yield(k, self[k]) }
-
end
-
-
1
def keys
-
981
@map.inject([]) {|keys, h| keys.concat(h.keys) }.uniq
-
end
-
-
1
def values
-
keys.map {|k| self[k] }
-
end
-
-
1
def to_hash
-
243
result = {}
-
2659
each {|k, v| result[k] = v }
-
243
result
-
end
-
end
-
-
# Mutable map class which supports map merging
-
# @api public
-
1
class MutableMap < ImmutableMap
-
1
def initialize(*map)
-
8
super({}, *map)
-
end
-
-
1
def []=(key, value)
-
@map.first[key] = value
-
end
-
-
1
def update(map)
-
2
@map.first.update(map)
-
end
-
end
-
-
1
class OptionMap < MutableMap
-
1
def initialize(*map, &block)
-
8
super(*map)
-
8
@handler = block
-
8
@valid = {}
-
8
@deprecated = {}
-
end
-
-
1
def []=(key, value)
-
validate_key!(key)
-
super
-
end
-
-
1
def update(map)
-
2
validate_map!(map)
-
2
super
-
end
-
-
1
def valid_keys
-
(keys + @valid.keys +
-
22
@map.map {|h| h.valid_keys if h.respond_to?(:valid_keys) }.compact.flatten).uniq
-
end
-
-
1
def add_valid_keys(*keys)
-
34
keys.flatten.each { |key| @valid[key] = true }
-
end
-
-
1
def add_deprecated_keys(*keys)
-
keys.flatten.each { |key| @valid[key] = @deprecated[key] = true }
-
end
-
-
1
def validate_map!(map)
-
241
map.to_hash.keys.each {|key| validate_key!(key) }
-
end
-
-
1
def validate_key!(key)
-
107
@handler.call(self, key, :deprecated) if deprecated_key?(key)
-
107
@handler.call(self, key, :invalid) unless valid_key?(key)
-
end
-
-
1
def deprecated_key?(key)
-
@deprecated.include?(key) ||
-
532
@map.any? {|h| h.deprecated_key?(key) if h.respond_to?(:deprecated_key?) }
-
end
-
-
1
def valid_key?(key)
-
3671
include?(key) || @valid.include?(key) ||
-
5148
@map.any? {|h| h.valid_key?(key) if h.respond_to?(:valid_key?) }
-
end
-
end
-
end
-
1
module Temple
-
1
module Mixins
-
# @api private
-
1
module CoreDispatcher
-
1
def on_multi(*exps)
-
362
multi = [:multi]
-
2354
exps.each {|exp| multi << compile(exp) }
-
362
multi
-
end
-
-
1
def on_capture(name, exp)
-
[:capture, name, compile(exp)]
-
end
-
end
-
-
# @api private
-
1
module EscapeDispatcher
-
1
def on_escape(flag, exp)
-
[:escape, flag, compile(exp)]
-
end
-
end
-
-
# @api private
-
1
module ControlFlowDispatcher
-
1
def on_if(condition, *cases)
-
[:if, condition, *cases.compact.map {|e| compile(e) }]
-
end
-
-
1
def on_case(arg, *cases)
-
[:case, arg, *cases.map {|condition, exp| [condition, compile(exp)] }]
-
end
-
-
1
def on_block(code, content)
-
[:block, code, compile(content)]
-
end
-
-
1
def on_cond(*cases)
-
[:cond, *cases.map {|condition, exp| [condition, compile(exp)] }]
-
end
-
end
-
-
# @api private
-
1
module CompiledDispatcher
-
1
def call(exp)
-
88
compile(exp)
-
end
-
-
1
def compile(exp)
-
3723
dispatcher(exp)
-
end
-
-
1
private
-
-
1
def dispatcher(exp)
-
5
replace_dispatcher(exp)
-
end
-
-
1
def replace_dispatcher(exp)
-
5
tree = DispatchNode.new
-
5
dispatched_methods.each do |method|
-
70
method.split('_'.freeze)[1..-1].inject(tree) {|node, type| node[type.to_sym] }.method = method
-
end
-
5
self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def dispatcher(exp)
-
return replace_dispatcher(exp) if self.class != #{self.class}
-
#{tree.compile.gsub("\n", "\n ")}
-
end
-
RUBY
-
5
dispatcher(exp)
-
end
-
-
1
def dispatched_methods
-
5
re = /^on(_[a-zA-Z0-9]+)*$/
-
5
self.methods.map(&:to_s).select(&re.method(:=~))
-
end
-
-
# @api private
-
1
class DispatchNode < Hash
-
1
attr_accessor :method
-
-
1
def initialize
-
75
super { |hsh,key| hsh[key] = DispatchNode.new }
-
40
@method = nil
-
end
-
-
1
def compile(level = 0, call_parent = nil)
-
40
call_method = method ? (level == 0 ? "#{method}(*exp)" :
-
"#{method}(*exp[#{level}..-1])") : call_parent
-
40
if empty?
-
35
raise 'Invalid dispatcher node' unless method
-
35
call_method
-
else
-
5
code = "case(exp[#{level}])\n"
-
5
each do |key, child|
-
code << "when #{key.inspect}\n " <<
-
35
child.compile(level + 1, call_method).gsub("\n".freeze, "\n ".freeze) << "\n".freeze
-
end
-
5
code << "else\n " << (call_method || 'exp') << "\nend"
-
end
-
end
-
end
-
end
-
-
# @api public
-
#
-
# Implements a compatible call-method
-
# based on the including classe's methods.
-
#
-
# It uses every method starting with
-
# "on" and uses the rest of the method
-
# name as prefix of the expression it
-
# will receive. So, if a dispatcher
-
# has a method named "on_x", this method
-
# will be called with arg0,..,argN
-
# whenever an expression like [:x, arg0,..,argN ]
-
# is encountered.
-
#
-
# This works with longer prefixes, too.
-
# For example a method named "on_y_z"
-
# will be called whenever an expression
-
# like [:y, :z, .. ] is found. Furthermore,
-
# if additionally a method named "on_y"
-
# is present, it will be called when an
-
# expression starts with :y but then does
-
# not contain with :z. This way a
-
# dispatcher can implement namespaces.
-
#
-
# @note
-
# Processing does not reach into unknown
-
# expression types by default.
-
#
-
# @example
-
# class MyAwesomeDispatch
-
# include Temple::Mixins::Dispatcher
-
# def on_awesome(thing) # keep awesome things
-
# return [:awesome, thing]
-
# end
-
# def on_boring(thing) # make boring things awesome
-
# return [:awesome, thing+" with bacon"]
-
# end
-
# def on(type,*args) # unknown stuff is boring too
-
# return [:awesome, 'just bacon']
-
# end
-
# end
-
# filter = MyAwesomeDispatch.new
-
# # Boring things are converted:
-
# filter.call([:boring, 'egg']) #=> [:awesome, 'egg with bacon']
-
# # Unknown things too:
-
# filter.call([:foo]) #=> [:awesome, 'just bacon']
-
# # Known but not boring things won't be touched:
-
# filter.call([:awesome, 'chuck norris']) #=>[:awesome, 'chuck norris']
-
#
-
1
module Dispatcher
-
1
include CompiledDispatcher
-
1
include CoreDispatcher
-
1
include EscapeDispatcher
-
1
include ControlFlowDispatcher
-
end
-
end
-
end
-
1
module Temple
-
1
module Mixins
-
# @api private
-
1
module EngineDSL
-
1
def chain_modified!
-
end
-
-
1
def append(*args, &block)
-
7
chain << chain_element(args, block)
-
7
chain_modified!
-
end
-
-
1
def prepend(*args, &block)
-
chain.unshift(chain_element(args, block))
-
chain_modified!
-
end
-
-
1
def remove(name)
-
name = chain_name(name)
-
raise "#{name} not found" unless chain.reject! {|i| name === i.first }
-
chain_modified!
-
end
-
-
1
alias use append
-
-
1
def before(name, *args, &block)
-
name = chain_name(name)
-
e = chain_element(args, block)
-
chain.map! {|f| name === f.first ? [e, f] : [f] }.flatten!(1)
-
raise "#{name} not found" unless chain.include?(e)
-
chain_modified!
-
end
-
-
1
def after(name, *args, &block)
-
name = chain_name(name)
-
e = chain_element(args, block)
-
chain.map! {|f| name === f.first ? [f, e] : [f] }.flatten!(1)
-
raise "#{name} not found" unless chain.include?(e)
-
chain_modified!
-
end
-
-
1
def replace(name, *args, &block)
-
name = chain_name(name)
-
e = chain_element(args, block)
-
chain.map! {|f| name === f.first ? e : f }
-
raise "#{name} not found" unless chain.include?(e)
-
chain_modified!
-
end
-
-
# Shortcuts to access namespaces
-
{ filter: Temple::Filters,
-
generator: Temple::Generators,
-
1
html: Temple::HTML }.each do |method, mod|
-
3
define_method(method) do |name, *options|
-
3
use(name, mod.const_get(name), *options)
-
end
-
end
-
-
1
private
-
-
1
def chain_name(name)
-
case name
-
when Class
-
name.name.to_sym
-
when Symbol, String
-
name.to_sym
-
when Regexp
-
name
-
else
-
raise(ArgumentError, 'Name argument must be Class, Symbol, String or Regexp')
-
end
-
end
-
-
1
def chain_class_constructor(filter, local_options)
-
5
define_options(filter.options.valid_keys) if respond_to?(:define_options) && filter.respond_to?(:options)
-
5
proc do |engine|
-
110
opts = {}.update(engine.options)
-
2090
opts.delete_if {|k,v| !filter.options.valid_key?(k) } if filter.respond_to?(:options)
-
110
opts.update(local_options) if local_options
-
110
filter.new(opts)
-
end
-
end
-
-
1
def chain_proc_constructor(name, filter)
-
2
raise(ArgumentError, 'Proc or blocks must have arity 0 or 1') if filter.arity > 1
-
2
method_name = "FILTER #{name}"
-
2
c = Class === self ? self : singleton_class
-
4
filter = c.class_eval { define_method(method_name, &filter); instance_method(method_name) }
-
2
proc do |engine|
-
44
if filter.arity == 1
-
# the proc takes one argument, e.g. use(:Filter) {|exp| exp }
-
filter.bind(engine)
-
else
-
44
f = filter.bind(engine).call
-
44
if f.respond_to? :call
-
# the proc returns a callable object, e.g. use(:Filter) { Filter.new }
-
f
-
else
-
44
raise(ArgumentError, 'Proc or blocks must return a Callable or a Class') unless f.respond_to? :new
-
# the proc returns a class, e.g. use(:Filter) { Filter }
-
44
f.new(f.respond_to?(:options) ? engine.options.to_hash.select {|k,v| f.options.valid_key?(k) } : engine.options)
-
end
-
end
-
end
-
end
-
-
1
def chain_element(args, block)
-
7
name = args.shift
-
7
if Class === name
-
2
filter = name
-
2
name = filter.name.to_sym
-
else
-
5
raise(ArgumentError, 'Name argument must be Class or Symbol') unless Symbol === name
-
end
-
-
7
if block
-
raise(ArgumentError, 'Class and block argument are not allowed at the same time') if filter
-
filter = block
-
end
-
-
7
filter ||= args.shift
-
-
7
case filter
-
when Proc
-
# Proc or block argument
-
# The proc is converted to a method of the engine class.
-
# The proc can then access the option hash of the engine.
-
2
raise(ArgumentError, 'Too many arguments') unless args.empty?
-
2
[name, chain_proc_constructor(name, filter)]
-
when Class
-
# Class argument (e.g Filter class)
-
# The options are passed to the classes constructor.
-
5
raise(ArgumentError, 'Too many arguments') if args.size > 1
-
5
[name, chain_class_constructor(filter, args.first)]
-
else
-
# Other callable argument (e.g. Object of class which implements #call or Method)
-
# The callable has no access to the option hash of the engine.
-
raise(ArgumentError, 'Too many arguments') unless args.empty?
-
raise(ArgumentError, 'Class or callable argument is required') unless filter.respond_to?(:call)
-
[name, proc { filter }]
-
end
-
end
-
end
-
end
-
end
-
1
module Temple
-
1
module Mixins
-
# @api public
-
1
module ClassOptions
-
1
def set_default_options(opts)
-
warn 'set_default_options has been deprecated, use set_options'
-
set_options(opts)
-
end
-
-
1
def default_options
-
warn 'default_options has been deprecated, use options'
-
options
-
end
-
-
1
def set_options(opts)
-
options.update(opts)
-
end
-
-
1
def options
-
@options ||= OptionMap.new(superclass.respond_to?(:options) ?
-
superclass.options : nil) do |hash, key, what|
-
warn "#{self}: Option #{key.inspect} is #{what}" unless @option_validator_disabled
-
2267
end
-
end
-
-
1
def define_options(*opts)
-
8
if opts.last.respond_to?(:to_hash)
-
2
hash = opts.pop.to_hash
-
2
options.add_valid_keys(hash.keys)
-
2
options.update(hash)
-
end
-
8
options.add_valid_keys(opts)
-
end
-
-
1
def define_deprecated_options(*opts)
-
if opts.last.respond_to?(:to_hash)
-
hash = opts.pop.to_hash
-
options.add_deprecated_keys(hash.keys)
-
options.update(hash)
-
end
-
options.add_deprecated_keys(opts)
-
end
-
-
1
def disable_option_validator!
-
@option_validator_disabled = true
-
end
-
end
-
-
1
module ThreadOptions
-
1
def with_options(options)
-
old_options = thread_options
-
Thread.current[thread_options_key] = ImmutableMap.new(options, thread_options)
-
yield
-
ensure
-
Thread.current[thread_options_key] = old_options
-
end
-
-
1
def thread_options
-
264
Thread.current[thread_options_key]
-
end
-
-
1
protected
-
-
1
def thread_options_key
-
264
@thread_options_key ||= "#{self.name}-thread-options".to_sym
-
end
-
end
-
-
# @api public
-
1
module Options
-
1
def self.included(base)
-
3
base.class_eval do
-
3
extend ClassOptions
-
3
extend ThreadOptions
-
end
-
end
-
-
1
attr_reader :options
-
-
1
def initialize(opts = {})
-
132
self.class.options.validate_map!(opts)
-
132
self.class.options.validate_map!(self.class.thread_options) if self.class.thread_options
-
132
@options = ImmutableMap.new({}.update(self.class.options).update(self.class.thread_options || {}).update(opts))
-
end
-
end
-
end
-
end
-
1
begin
-
1
require 'ripper'
-
rescue LoadError
-
end
-
-
1
module Temple
-
1
module StaticAnalyzer
-
1
STATIC_TOKENS = [
-
:on_tstring_beg, :on_tstring_end, :on_tstring_content,
-
:on_embexpr_beg, :on_embexpr_end,
-
:on_lbracket, :on_rbracket,
-
:on_qwords_beg, :on_words_sep, :on_qwords_sep,
-
:on_lparen, :on_rparen,
-
:on_lbrace, :on_rbrace, :on_label,
-
:on_int, :on_float, :on_imaginary,
-
:on_comma, :on_sp, :on_ignored_nl,
-
].freeze
-
-
1
DYNAMIC_TOKENS = [
-
:on_ident, :on_period,
-
].freeze
-
-
1
STATIC_KEYWORDS = [
-
'true', 'false', 'nil',
-
].freeze
-
-
1
STATIC_OPERATORS = [
-
'=>',
-
].freeze
-
-
1
class << self
-
1
def available?
-
159
defined?(Ripper)
-
end
-
-
1
def static?(code)
-
31
return false if code.nil? || code.strip.empty?
-
31
return false if syntax_error?(code)
-
-
31
Ripper.lex(code).each do |_, token, str|
-
93
case token
-
when *STATIC_TOKENS
-
# noop
-
when :on_kw
-
return false unless STATIC_KEYWORDS.include?(str)
-
when :on_op
-
return false unless STATIC_OPERATORS.include?(str)
-
when *DYNAMIC_TOKENS
-
return false
-
else
-
return false
-
end
-
end
-
31
true
-
end
-
-
1
def syntax_error?(code)
-
31
SyntaxChecker.new(code).parse
-
31
false
-
rescue SyntaxChecker::ParseError
-
true
-
end
-
end
-
-
1
if defined?(Ripper)
-
1
class SyntaxChecker < Ripper
-
1
class ParseError < StandardError; end
-
-
1
private
-
-
1
def on_parse_error(*)
-
raise ParseError
-
end
-
end
-
end
-
end
-
end
-
1
begin
-
1
require 'escape_utils'
-
rescue LoadError
-
1
begin
-
1
require 'cgi/escape'
-
rescue LoadError
-
end
-
end
-
-
1
module Temple
-
# @api public
-
1
module Utils
-
1
extend self
-
-
# Returns an escaped copy of `html`.
-
# Strings which are declared as html_safe are not escaped.
-
#
-
# @param html [String] The string to escape
-
# @return [String] The escaped string
-
1
def escape_html_safe(html)
-
html.html_safe? ? html : escape_html(html)
-
end
-
-
1
if defined?(EscapeUtils)
-
# Returns an escaped copy of `html`.
-
#
-
# @param html [String] The string to escape
-
# @return [String] The escaped string
-
def escape_html(html)
-
EscapeUtils.escape_html(html.to_s, false)
-
end
-
elsif defined?(CGI.escapeHTML)
-
# Returns an escaped copy of `html`.
-
#
-
# @param html [String] The string to escape
-
# @return [String] The escaped string
-
1
def escape_html(html)
-
CGI.escapeHTML(html.to_s)
-
end
-
else
-
# Used by escape_html
-
# @api private
-
ESCAPE_HTML = {
-
'&' => '&',
-
'"' => '"',
-
'\'' => ''',
-
'<' => '<',
-
'>' => '>'
-
}.freeze
-
-
ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys)
-
-
# Returns an escaped copy of `html`.
-
#
-
# @param html [String] The string to escape
-
# @return [String] The escaped string
-
def escape_html(html)
-
html.to_s.gsub(ESCAPE_HTML_PATTERN, ESCAPE_HTML)
-
end
-
end
-
-
# Generate unique variable name
-
#
-
# @param prefix [String] Variable name prefix
-
# @return [String] Variable name
-
1
def unique_name(prefix = nil)
-
@unique_name ||= 0
-
prefix ||= (@unique_prefix ||= self.class.name.gsub('::'.freeze, '_'.freeze).downcase)
-
"_#{prefix}#{@unique_name += 1}"
-
end
-
-
# Check if expression is empty
-
#
-
# @param exp [Array] Temple expression
-
# @return true if expression is empty
-
1
def empty_exp?(exp)
-
case exp[0]
-
when :multi
-
exp[1..-1].all? {|e| empty_exp?(e) }
-
when :newline
-
true
-
else
-
false
-
end
-
end
-
-
1
def indent_dynamic(text, indent_next, indent, pre_tags = nil)
-
text = text.to_s
-
safe = text.respond_to?(:html_safe?) && text.html_safe?
-
return text if pre_tags && text =~ pre_tags
-
-
level = text.scan(/^\s*/).map(&:size).min
-
text = text.gsub(/(?!\A)^\s{#{level}}/, '') if level > 0
-
-
text = text.sub(/\A\s*\n?/, "\n".freeze) if indent_next
-
text = text.gsub("\n".freeze, indent)
-
-
safe ? text.html_safe : text
-
end
-
end
-
end
-
1
module Temple
-
1
VERSION = '0.8.0'
-
end
-
1
require "thor/command"
-
1
require "thor/core_ext/hash_with_indifferent_access"
-
1
require "thor/core_ext/ordered_hash"
-
1
require "thor/error"
-
1
require "thor/invocation"
-
1
require "thor/parser"
-
1
require "thor/shell"
-
1
require "thor/line_editor"
-
1
require "thor/util"
-
-
1
class Thor
-
1
autoload :Actions, "thor/actions"
-
1
autoload :RakeCompat, "thor/rake_compat"
-
1
autoload :Group, "thor/group"
-
-
# Shortcuts for help.
-
1
HELP_MAPPINGS = %w(-h -? --help -D)
-
-
# Thor methods that should not be overwritten by the user.
-
1
THOR_RESERVED_WORDS = %w(invoke shell options behavior root destination_root relative_root
-
action add_file create_file in_root inside run run_ruby_script)
-
-
1
TEMPLATE_EXTNAME = ".tt"
-
-
1
module Base
-
1
attr_accessor :options, :parent_options, :args
-
-
# It receives arguments in an Array and two hashes, one for options and
-
# other for configuration.
-
#
-
# Notice that it does not check if all required arguments were supplied.
-
# It should be done by the parser.
-
#
-
# ==== Parameters
-
# args<Array[Object]>:: An array of objects. The objects are applied to their
-
# respective accessors declared with <tt>argument</tt>.
-
#
-
# options<Hash>:: An options hash that will be available as self.options.
-
# The hash given is converted to a hash with indifferent
-
# access, magic predicates (options.skip?) and then frozen.
-
#
-
# config<Hash>:: Configuration for this Thor class.
-
#
-
1
def initialize(args = [], local_options = {}, config = {})
-
parse_options = config[:current_command] && config[:current_command].disable_class_options ? {} : self.class.class_options
-
-
# The start method splits inbound arguments at the first argument
-
# that looks like an option (starts with - or --). It then calls
-
# new, passing in the two halves of the arguments Array as the
-
# first two parameters.
-
-
command_options = config.delete(:command_options) # hook for start
-
parse_options = parse_options.merge(command_options) if command_options
-
if local_options.is_a?(Array)
-
array_options = local_options
-
hash_options = {}
-
else
-
# Handle the case where the class was explicitly instantiated
-
# with pre-parsed options.
-
array_options = []
-
hash_options = local_options
-
end
-
-
# Let Thor::Options parse the options first, so it can remove
-
# declared options from the array. This will leave us with
-
# a list of arguments that weren't declared.
-
stop_on_unknown = self.class.stop_on_unknown_option? config[:current_command]
-
opts = Thor::Options.new(parse_options, hash_options, stop_on_unknown)
-
self.options = opts.parse(array_options)
-
self.options = config[:class_options].merge(options) if config[:class_options]
-
-
# If unknown options are disallowed, make sure that none of the
-
# remaining arguments looks like an option.
-
opts.check_unknown! if self.class.check_unknown_options?(config)
-
-
# Add the remaining arguments from the options parser to the
-
# arguments passed in to initialize. Then remove any positional
-
# arguments declared using #argument (this is primarily used
-
# by Thor::Group). Tis will leave us with the remaining
-
# positional arguments.
-
to_parse = args
-
to_parse += opts.remaining unless self.class.strict_args_position?(config)
-
-
thor_args = Thor::Arguments.new(self.class.arguments)
-
thor_args.parse(to_parse).each { |k, v| __send__("#{k}=", v) }
-
@args = thor_args.remaining
-
end
-
-
1
class << self
-
1
def included(base) #:nodoc:
-
1
base.extend ClassMethods
-
1
base.send :include, Invocation
-
1
base.send :include, Shell
-
end
-
-
# Returns the classes that inherits from Thor or Thor::Group.
-
#
-
# ==== Returns
-
# Array[Class]
-
#
-
1
def subclasses
-
@subclasses ||= []
-
end
-
-
# Returns the files where the subclasses are kept.
-
#
-
# ==== Returns
-
# Hash[path<String> => Class]
-
#
-
1
def subclass_files
-
@subclass_files ||= Hash.new { |h, k| h[k] = [] }
-
end
-
-
# Whenever a class inherits from Thor or Thor::Group, we should track the
-
# class and the file on Thor::Base. This is the method responsable for it.
-
#
-
1
def register_klass_file(klass) #:nodoc:
-
file = caller[1].match(/(.*):\d+/)[1]
-
Thor::Base.subclasses << klass unless Thor::Base.subclasses.include?(klass)
-
-
file_subclasses = Thor::Base.subclass_files[File.expand_path(file)]
-
file_subclasses << klass unless file_subclasses.include?(klass)
-
end
-
end
-
-
1
module ClassMethods
-
1
def attr_reader(*) #:nodoc:
-
no_commands { super }
-
end
-
-
1
def attr_writer(*) #:nodoc:
-
no_commands { super }
-
end
-
-
1
def attr_accessor(*) #:nodoc:
-
no_commands { super }
-
end
-
-
# If you want to raise an error for unknown options, call check_unknown_options!
-
# This is disabled by default to allow dynamic invocations.
-
1
def check_unknown_options!
-
@check_unknown_options = true
-
end
-
-
1
def check_unknown_options #:nodoc:
-
@check_unknown_options ||= from_superclass(:check_unknown_options, false)
-
end
-
-
1
def check_unknown_options?(config) #:nodoc:
-
!!check_unknown_options
-
end
-
-
# If true, option parsing is suspended as soon as an unknown option or a
-
# regular argument is encountered. All remaining arguments are passed to
-
# the command as regular arguments.
-
1
def stop_on_unknown_option?(command_name) #:nodoc:
-
false
-
end
-
-
# If you want only strict string args (useful when cascading thor classes),
-
# call strict_args_position! This is disabled by default to allow dynamic
-
# invocations.
-
1
def strict_args_position!
-
@strict_args_position = true
-
end
-
-
1
def strict_args_position #:nodoc:
-
@strict_args_position ||= from_superclass(:strict_args_position, false)
-
end
-
-
1
def strict_args_position?(config) #:nodoc:
-
!!strict_args_position
-
end
-
-
# Adds an argument to the class and creates an attr_accessor for it.
-
#
-
# Arguments are different from options in several aspects. The first one
-
# is how they are parsed from the command line, arguments are retrieved
-
# from position:
-
#
-
# thor command NAME
-
#
-
# Instead of:
-
#
-
# thor command --name=NAME
-
#
-
# Besides, arguments are used inside your code as an accessor (self.argument),
-
# while options are all kept in a hash (self.options).
-
#
-
# Finally, arguments cannot have type :default or :boolean but can be
-
# optional (supplying :optional => :true or :required => false), although
-
# you cannot have a required argument after a non-required argument. If you
-
# try it, an error is raised.
-
#
-
# ==== Parameters
-
# name<Symbol>:: The name of the argument.
-
# options<Hash>:: Described below.
-
#
-
# ==== Options
-
# :desc - Description for the argument.
-
# :required - If the argument is required or not.
-
# :optional - If the argument is optional or not.
-
# :type - The type of the argument, can be :string, :hash, :array, :numeric.
-
# :default - Default value for this argument. It cannot be required and have default values.
-
# :banner - String to show on usage notes.
-
#
-
# ==== Errors
-
# ArgumentError:: Raised if you supply a required argument after a non required one.
-
#
-
1
def argument(name, options = {})
-
is_thor_reserved_word?(name, :argument)
-
no_commands { attr_accessor name }
-
-
required = if options.key?(:optional)
-
!options[:optional]
-
elsif options.key?(:required)
-
options[:required]
-
else
-
options[:default].nil?
-
end
-
-
remove_argument name
-
-
if required
-
arguments.each do |argument|
-
next if argument.required?
-
raise ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " \
-
"the non-required argument #{argument.human_name.inspect}."
-
end
-
end
-
-
options[:required] = required
-
-
arguments << Thor::Argument.new(name, options)
-
end
-
-
# Returns this class arguments, looking up in the ancestors chain.
-
#
-
# ==== Returns
-
# Array[Thor::Argument]
-
#
-
1
def arguments
-
@arguments ||= from_superclass(:arguments, [])
-
end
-
-
# Adds a bunch of options to the set of class options.
-
#
-
# class_options :foo => false, :bar => :required, :baz => :string
-
#
-
# If you prefer more detailed declaration, check class_option.
-
#
-
# ==== Parameters
-
# Hash[Symbol => Object]
-
#
-
1
def class_options(options = nil)
-
@class_options ||= from_superclass(:class_options, {})
-
build_options(options, @class_options) if options
-
@class_options
-
end
-
-
# Adds an option to the set of class options
-
#
-
# ==== Parameters
-
# name<Symbol>:: The name of the argument.
-
# options<Hash>:: Described below.
-
#
-
# ==== Options
-
# :desc:: -- Description for the argument.
-
# :required:: -- If the argument is required or not.
-
# :default:: -- Default value for this argument.
-
# :group:: -- The group for this options. Use by class options to output options in different levels.
-
# :aliases:: -- Aliases for this option. <b>Note:</b> Thor follows a convention of one-dash-one-letter options. Thus aliases like "-something" wouldn't be parsed; use either "\--something" or "-s" instead.
-
# :type:: -- The type of the argument, can be :string, :hash, :array, :numeric or :boolean.
-
# :banner:: -- String to show on usage notes.
-
# :hide:: -- If you want to hide this option from the help.
-
#
-
1
def class_option(name, options = {})
-
build_option(name, options, class_options)
-
end
-
-
# Removes a previous defined argument. If :undefine is given, undefine
-
# accessors as well.
-
#
-
# ==== Parameters
-
# names<Array>:: Arguments to be removed
-
#
-
# ==== Examples
-
#
-
# remove_argument :foo
-
# remove_argument :foo, :bar, :baz, :undefine => true
-
#
-
1
def remove_argument(*names)
-
options = names.last.is_a?(Hash) ? names.pop : {}
-
-
names.each do |name|
-
arguments.delete_if { |a| a.name == name.to_s }
-
undef_method name, "#{name}=" if options[:undefine]
-
end
-
end
-
-
# Removes a previous defined class option.
-
#
-
# ==== Parameters
-
# names<Array>:: Class options to be removed
-
#
-
# ==== Examples
-
#
-
# remove_class_option :foo
-
# remove_class_option :foo, :bar, :baz
-
#
-
1
def remove_class_option(*names)
-
names.each do |name|
-
class_options.delete(name)
-
end
-
end
-
-
# Defines the group. This is used when thor list is invoked so you can specify
-
# that only commands from a pre-defined group will be shown. Defaults to standard.
-
#
-
# ==== Parameters
-
# name<String|Symbol>
-
#
-
1
def group(name = nil)
-
if name
-
@group = name.to_s
-
else
-
@group ||= from_superclass(:group, "standard")
-
end
-
end
-
-
# Returns the commands for this Thor class.
-
#
-
# ==== Returns
-
# OrderedHash:: An ordered hash with commands names as keys and Thor::Command
-
# objects as values.
-
#
-
1
def commands
-
@commands ||= Thor::CoreExt::OrderedHash.new
-
end
-
1
alias_method :tasks, :commands
-
-
# Returns the commands for this Thor class and all subclasses.
-
#
-
# ==== Returns
-
# OrderedHash:: An ordered hash with commands names as keys and Thor::Command
-
# objects as values.
-
#
-
1
def all_commands
-
@all_commands ||= from_superclass(:all_commands, Thor::CoreExt::OrderedHash.new)
-
@all_commands.merge!(commands)
-
end
-
1
alias_method :all_tasks, :all_commands
-
-
# Removes a given command from this Thor class. This is usually done if you
-
# are inheriting from another class and don't want it to be available
-
# anymore.
-
#
-
# By default it only remove the mapping to the command. But you can supply
-
# :undefine => true to undefine the method from the class as well.
-
#
-
# ==== Parameters
-
# name<Symbol|String>:: The name of the command to be removed
-
# options<Hash>:: You can give :undefine => true if you want commands the method
-
# to be undefined from the class as well.
-
#
-
1
def remove_command(*names)
-
options = names.last.is_a?(Hash) ? names.pop : {}
-
-
names.each do |name|
-
commands.delete(name.to_s)
-
all_commands.delete(name.to_s)
-
undef_method name if options[:undefine]
-
end
-
end
-
1
alias_method :remove_task, :remove_command
-
-
# All methods defined inside the given block are not added as commands.
-
#
-
# So you can do:
-
#
-
# class MyScript < Thor
-
# no_commands do
-
# def this_is_not_a_command
-
# end
-
# end
-
# end
-
#
-
# You can also add the method and remove it from the command list:
-
#
-
# class MyScript < Thor
-
# def this_is_not_a_command
-
# end
-
# remove_command :this_is_not_a_command
-
# end
-
#
-
1
def no_commands
-
@no_commands = true
-
yield
-
ensure
-
@no_commands = false
-
end
-
1
alias_method :no_tasks, :no_commands
-
-
# Sets the namespace for the Thor or Thor::Group class. By default the
-
# namespace is retrieved from the class name. If your Thor class is named
-
# Scripts::MyScript, the help method, for example, will be called as:
-
#
-
# thor scripts:my_script -h
-
#
-
# If you change the namespace:
-
#
-
# namespace :my_scripts
-
#
-
# You change how your commands are invoked:
-
#
-
# thor my_scripts -h
-
#
-
# Finally, if you change your namespace to default:
-
#
-
# namespace :default
-
#
-
# Your commands can be invoked with a shortcut. Instead of:
-
#
-
# thor :my_command
-
#
-
1
def namespace(name = nil)
-
if name
-
@namespace = name.to_s
-
else
-
@namespace ||= Thor::Util.namespace_from_thor_class(self)
-
end
-
end
-
-
# Parses the command and options from the given args, instantiate the class
-
# and invoke the command. This method is used when the arguments must be parsed
-
# from an array. If you are inside Ruby and want to use a Thor class, you
-
# can simply initialize it:
-
#
-
# script = MyScript.new(args, options, config)
-
# script.invoke(:command, first_arg, second_arg, third_arg)
-
#
-
1
def start(given_args = ARGV, config = {})
-
config[:shell] ||= Thor::Base.shell.new
-
dispatch(nil, given_args.dup, nil, config)
-
rescue Thor::Error => e
-
config[:debug] || ENV["THOR_DEBUG"] == "1" ? (raise e) : config[:shell].error(e.message)
-
exit(1) if exit_on_failure?
-
rescue Errno::EPIPE
-
# This happens if a thor command is piped to something like `head`,
-
# which closes the pipe when it's done reading. This will also
-
# mean that if the pipe is closed, further unnecessary
-
# computation will not occur.
-
exit(0)
-
end
-
-
# Allows to use private methods from parent in child classes as commands.
-
#
-
# ==== Parameters
-
# names<Array>:: Method names to be used as commands
-
#
-
# ==== Examples
-
#
-
# public_command :foo
-
# public_command :foo, :bar, :baz
-
#
-
1
def public_command(*names)
-
names.each do |name|
-
class_eval "def #{name}(*); super end"
-
end
-
end
-
1
alias_method :public_task, :public_command
-
-
1
def handle_no_command_error(command, has_namespace = $thor_runner) #:nodoc:
-
raise UndefinedCommandError, "Could not find command #{command.inspect} in #{namespace.inspect} namespace." if has_namespace
-
raise UndefinedCommandError, "Could not find command #{command.inspect}."
-
end
-
1
alias_method :handle_no_task_error, :handle_no_command_error
-
-
1
def handle_argument_error(command, error, args, arity) #:nodoc:
-
msg = "ERROR: \"#{basename} #{command.name}\" was called with "
-
msg << "no arguments" if args.empty?
-
msg << "arguments " << args.inspect unless args.empty?
-
msg << "\nUsage: #{banner(command).inspect}"
-
raise InvocationError, msg
-
end
-
-
1
protected
-
-
# Prints the class options per group. If an option does not belong to
-
# any group, it's printed as Class option.
-
#
-
1
def class_options_help(shell, groups = {}) #:nodoc:
-
# Group options by group
-
class_options.each do |_, value|
-
groups[value.group] ||= []
-
groups[value.group] << value
-
end
-
-
# Deal with default group
-
global_options = groups.delete(nil) || []
-
print_options(shell, global_options)
-
-
# Print all others
-
groups.each do |group_name, options|
-
print_options(shell, options, group_name)
-
end
-
end
-
-
# Receives a set of options and print them.
-
1
def print_options(shell, options, group_name = nil)
-
return if options.empty?
-
-
list = []
-
padding = options.map { |o| o.aliases.size }.max.to_i * 4
-
-
options.each do |option|
-
next if option.hide
-
item = [option.usage(padding)]
-
item.push(option.description ? "# #{option.description}" : "")
-
-
list << item
-
list << ["", "# Default: #{option.default}"] if option.show_default?
-
list << ["", "# Possible values: #{option.enum.join(', ')}"] if option.enum
-
end
-
-
shell.say(group_name ? "#{group_name} options:" : "Options:")
-
shell.print_table(list, :indent => 2)
-
shell.say ""
-
end
-
-
# Raises an error if the word given is a Thor reserved word.
-
1
def is_thor_reserved_word?(word, type) #:nodoc:
-
return false unless THOR_RESERVED_WORDS.include?(word.to_s)
-
raise "#{word.inspect} is a Thor reserved word and cannot be defined as #{type}"
-
end
-
-
# Build an option and adds it to the given scope.
-
#
-
# ==== Parameters
-
# name<Symbol>:: The name of the argument.
-
# options<Hash>:: Described in both class_option and method_option.
-
# scope<Hash>:: Options hash that is being built up
-
1
def build_option(name, options, scope) #:nodoc:
-
scope[name] = Thor::Option.new(name, options)
-
end
-
-
# Receives a hash of options, parse them and add to the scope. This is a
-
# fast way to set a bunch of options:
-
#
-
# build_options :foo => true, :bar => :required, :baz => :string
-
#
-
# ==== Parameters
-
# Hash[Symbol => Object]
-
1
def build_options(options, scope) #:nodoc:
-
options.each do |key, value|
-
scope[key] = Thor::Option.parse(key, value)
-
end
-
end
-
-
# Finds a command with the given name. If the command belongs to the current
-
# class, just return it, otherwise dup it and add the fresh copy to the
-
# current command hash.
-
1
def find_and_refresh_command(name) #:nodoc:
-
if commands[name.to_s]
-
commands[name.to_s]
-
elsif command = all_commands[name.to_s] # rubocop:disable AssignmentInCondition
-
commands[name.to_s] = command.clone
-
else
-
raise ArgumentError, "You supplied :for => #{name.inspect}, but the command #{name.inspect} could not be found."
-
end
-
end
-
1
alias_method :find_and_refresh_task, :find_and_refresh_command
-
-
# Everytime someone inherits from a Thor class, register the klass
-
# and file into baseclass.
-
1
def inherited(klass)
-
Thor::Base.register_klass_file(klass)
-
klass.instance_variable_set(:@no_commands, false)
-
end
-
-
# Fire this callback whenever a method is added. Added methods are
-
# tracked as commands by invoking the create_command method.
-
1
def method_added(meth)
-
1
meth = meth.to_s
-
-
1
if meth == "initialize"
-
initialize_added
-
return
-
end
-
-
# Return if it's not a public instance method
-
1
return unless public_method_defined?(meth.to_sym)
-
-
@no_commands ||= false
-
return if @no_commands || !create_command(meth)
-
-
is_thor_reserved_word?(meth, :command)
-
Thor::Base.register_klass_file(self)
-
end
-
-
# Retrieves a value from superclass. If it reaches the baseclass,
-
# returns default.
-
1
def from_superclass(method, default = nil)
-
if self == baseclass || !superclass.respond_to?(method, true)
-
default
-
else
-
value = superclass.send(method)
-
-
# Ruby implements `dup` on Object, but raises a `TypeError`
-
# if the method is called on immediates. As a result, we
-
# don't have a good way to check whether dup will succeed
-
# without calling it and rescuing the TypeError.
-
begin
-
value.dup
-
rescue TypeError
-
value
-
end
-
-
end
-
end
-
-
# A flag that makes the process exit with status 1 if any error happens.
-
1
def exit_on_failure?
-
false
-
end
-
-
#
-
# The basename of the program invoking the thor class.
-
#
-
1
def basename
-
File.basename($PROGRAM_NAME).split(" ").first
-
end
-
-
# SIGNATURE: Sets the baseclass. This is where the superclass lookup
-
# finishes.
-
1
def baseclass #:nodoc:
-
end
-
-
# SIGNATURE: Creates a new command if valid_command? is true. This method is
-
# called when a new method is added to the class.
-
1
def create_command(meth) #:nodoc:
-
end
-
1
alias_method :create_task, :create_command
-
-
# SIGNATURE: Defines behavior when the initialize method is added to the
-
# class.
-
1
def initialize_added #:nodoc:
-
end
-
-
# SIGNATURE: The hook invoked by start.
-
1
def dispatch(command, given_args, given_opts, config) #:nodoc:
-
raise NotImplementedError
-
end
-
end
-
end
-
end
-
1
class Thor
-
1
class Command < Struct.new(:name, :description, :long_description, :usage, :options, :disable_class_options)
-
1
FILE_REGEXP = /^#{Regexp.escape(File.dirname(__FILE__))}/
-
-
1
def initialize(name, description, long_description, usage, options = nil, disable_class_options = false)
-
super(name.to_s, description, long_description, usage, options || {}, disable_class_options)
-
end
-
-
1
def initialize_copy(other) #:nodoc:
-
super(other)
-
self.options = other.options.dup if other.options
-
end
-
-
1
def hidden?
-
false
-
end
-
-
# By default, a command invokes a method in the thor class. You can change this
-
# implementation to create custom commands.
-
1
def run(instance, args = [])
-
arity = nil
-
-
if private_method?(instance)
-
instance.class.handle_no_command_error(name)
-
elsif public_method?(instance)
-
arity = instance.method(name).arity
-
instance.__send__(name, *args)
-
elsif local_method?(instance, :method_missing)
-
instance.__send__(:method_missing, name.to_sym, *args)
-
else
-
instance.class.handle_no_command_error(name)
-
end
-
rescue ArgumentError => e
-
handle_argument_error?(instance, e, caller) ? instance.class.handle_argument_error(self, e, args, arity) : (raise e)
-
rescue NoMethodError => e
-
handle_no_method_error?(instance, e, caller) ? instance.class.handle_no_command_error(name) : (raise e)
-
end
-
-
# Returns the formatted usage by injecting given required arguments
-
# and required options into the given usage.
-
1
def formatted_usage(klass, namespace = true, subcommand = false)
-
if namespace
-
namespace = klass.namespace
-
formatted = "#{namespace.gsub(/^(default)/, '')}:"
-
end
-
formatted = "#{klass.namespace.split(':').last} " if subcommand
-
-
formatted ||= ""
-
-
# Add usage with required arguments
-
formatted << if klass && !klass.arguments.empty?
-
usage.to_s.gsub(/^#{name}/) do |match|
-
match << " " << klass.arguments.map(&:usage).compact.join(" ")
-
end
-
else
-
usage.to_s
-
end
-
-
# Add required options
-
formatted << " #{required_options}"
-
-
# Strip and go!
-
formatted.strip
-
end
-
-
1
protected
-
-
1
def not_debugging?(instance)
-
!(instance.class.respond_to?(:debugging) && instance.class.debugging)
-
end
-
-
1
def required_options
-
@required_options ||= options.map { |_, o| o.usage if o.required? }.compact.sort.join(" ")
-
end
-
-
# Given a target, checks if this class name is a public method.
-
1
def public_method?(instance) #:nodoc:
-
!(instance.public_methods & [name.to_s, name.to_sym]).empty?
-
end
-
-
1
def private_method?(instance)
-
!(instance.private_methods & [name.to_s, name.to_sym]).empty?
-
end
-
-
1
def local_method?(instance, name)
-
methods = instance.public_methods(false) + instance.private_methods(false) + instance.protected_methods(false)
-
!(methods & [name.to_s, name.to_sym]).empty?
-
end
-
-
1
def sans_backtrace(backtrace, caller) #:nodoc:
-
saned = backtrace.reject { |frame| frame =~ FILE_REGEXP || (frame =~ /\.java:/ && RUBY_PLATFORM =~ /java/) || (frame =~ %r{^kernel/} && RUBY_ENGINE =~ /rbx/) }
-
saned - caller
-
end
-
-
1
def handle_argument_error?(instance, error, caller)
-
not_debugging?(instance) && (error.message =~ /wrong number of arguments/ || error.message =~ /given \d*, expected \d*/) && begin
-
saned = sans_backtrace(error.backtrace, caller)
-
# Ruby 1.9 always include the called method in the backtrace
-
saned.empty? || (saned.size == 1 && RUBY_VERSION >= "1.9")
-
end
-
end
-
-
1
def handle_no_method_error?(instance, error, caller)
-
not_debugging?(instance) &&
-
error.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/
-
end
-
end
-
1
Task = Command
-
-
# A command that is hidden in help messages but still invocable.
-
1
class HiddenCommand < Command
-
1
def hidden?
-
true
-
end
-
end
-
1
HiddenTask = HiddenCommand
-
-
# A dynamic command that handles method missing scenarios.
-
1
class DynamicCommand < Command
-
1
def initialize(name, options = nil)
-
super(name.to_s, "A dynamically-generated command", name.to_s, name.to_s, options)
-
end
-
-
1
def run(instance, args = [])
-
if (instance.methods & [name.to_s, name.to_sym]).empty?
-
super
-
else
-
instance.class.handle_no_command_error(name)
-
end
-
end
-
end
-
1
DynamicTask = DynamicCommand
-
end
-
1
class Thor
-
1
module CoreExt #:nodoc:
-
# A hash with indifferent access and magic predicates.
-
#
-
# hash = Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true
-
#
-
# hash[:foo] #=> 'bar'
-
# hash['foo'] #=> 'bar'
-
# hash.foo? #=> true
-
#
-
1
class HashWithIndifferentAccess < ::Hash #:nodoc:
-
1
def initialize(hash = {})
-
super()
-
hash.each do |key, value|
-
self[convert_key(key)] = value
-
end
-
end
-
-
1
def [](key)
-
super(convert_key(key))
-
end
-
-
1
def []=(key, value)
-
super(convert_key(key), value)
-
end
-
-
1
def delete(key)
-
super(convert_key(key))
-
end
-
-
1
def fetch(key, *args)
-
super(convert_key(key), *args)
-
end
-
-
1
def key?(key)
-
super(convert_key(key))
-
end
-
-
1
def values_at(*indices)
-
indices.map { |key| self[convert_key(key)] }
-
end
-
-
1
def merge(other)
-
dup.merge!(other)
-
end
-
-
1
def merge!(other)
-
other.each do |key, value|
-
self[convert_key(key)] = value
-
end
-
self
-
end
-
-
# Convert to a Hash with String keys.
-
1
def to_hash
-
Hash.new(default).merge!(self)
-
end
-
-
1
protected
-
-
1
def convert_key(key)
-
key.is_a?(Symbol) ? key.to_s : key
-
end
-
-
# Magic predicates. For instance:
-
#
-
# options.force? # => !!options['force']
-
# options.shebang # => "/usr/lib/local/ruby"
-
# options.test_framework?(:rspec) # => options[:test_framework] == :rspec
-
#
-
1
def method_missing(method, *args)
-
method = method.to_s
-
if method =~ /^(\w+)\?$/
-
if args.empty?
-
!!self[$1]
-
else
-
self[$1] == args.first
-
end
-
else
-
self[method]
-
end
-
end
-
end
-
end
-
end
-
1
class Thor
-
1
module CoreExt
-
1
class OrderedHash < ::Hash
-
1
if RUBY_VERSION < "1.9"
-
def initialize(*args, &block)
-
super
-
@keys = []
-
end
-
-
def initialize_copy(other)
-
super
-
# make a deep copy of keys
-
@keys = other.keys
-
end
-
-
def []=(key, value)
-
@keys << key unless key?(key)
-
super
-
end
-
-
def delete(key)
-
if key? key
-
index = @keys.index(key)
-
@keys.delete_at index
-
end
-
super
-
end
-
-
def delete_if
-
super
-
sync_keys!
-
self
-
end
-
-
alias_method :reject!, :delete_if
-
-
def reject(&block)
-
dup.reject!(&block)
-
end
-
-
def keys
-
@keys.dup
-
end
-
-
def values
-
@keys.map { |key| self[key] }
-
end
-
-
def to_hash
-
self
-
end
-
-
def to_a
-
@keys.map { |key| [key, self[key]] }
-
end
-
-
def each_key
-
return to_enum(:each_key) unless block_given?
-
@keys.each { |key| yield(key) }
-
self
-
end
-
-
def each_value
-
return to_enum(:each_value) unless block_given?
-
@keys.each { |key| yield(self[key]) }
-
self
-
end
-
-
def each
-
return to_enum(:each) unless block_given?
-
@keys.each { |key| yield([key, self[key]]) }
-
self
-
end
-
-
def each_pair
-
return to_enum(:each_pair) unless block_given?
-
@keys.each { |key| yield(key, self[key]) }
-
self
-
end
-
-
alias_method :select, :find_all
-
-
def clear
-
super
-
@keys.clear
-
self
-
end
-
-
def shift
-
k = @keys.first
-
v = delete(k)
-
[k, v]
-
end
-
-
def merge!(other_hash)
-
if block_given?
-
other_hash.each { |k, v| self[k] = key?(k) ? yield(k, self[k], v) : v }
-
else
-
other_hash.each { |k, v| self[k] = v }
-
end
-
self
-
end
-
-
alias_method :update, :merge!
-
-
def merge(other_hash, &block)
-
dup.merge!(other_hash, &block)
-
end
-
-
# When replacing with another hash, the initial order of our keys must come from the other hash -ordered or not.
-
def replace(other)
-
super
-
@keys = other.keys
-
self
-
end
-
-
def inspect
-
"#<#{self.class} #{super}>"
-
end
-
-
private
-
-
def sync_keys!
-
@keys.delete_if { |k| !key?(k) }
-
end
-
end
-
end
-
end
-
end
-
1
class Thor
-
# Thor::Error is raised when it's caused by wrong usage of thor classes. Those
-
# errors have their backtrace suppressed and are nicely shown to the user.
-
#
-
# Errors that are caused by the developer, like declaring a method which
-
# overwrites a thor keyword, SHOULD NOT raise a Thor::Error. This way, we
-
# ensure that developer errors are shown with full backtrace.
-
1
class Error < StandardError
-
end
-
-
# Raised when a command was not found.
-
1
class UndefinedCommandError < Error
-
end
-
1
UndefinedTaskError = UndefinedCommandError
-
-
1
class AmbiguousCommandError < Error
-
end
-
1
AmbiguousTaskError = AmbiguousCommandError
-
-
# Raised when a command was found, but not invoked properly.
-
1
class InvocationError < Error
-
end
-
-
1
class UnknownArgumentError < Error
-
end
-
-
1
class RequiredArgumentMissingError < InvocationError
-
end
-
-
1
class MalformattedArgumentError < InvocationError
-
end
-
end
-
1
require "thor/base"
-
-
# Thor has a special class called Thor::Group. The main difference to Thor class
-
# is that it invokes all commands at once. It also include some methods that allows
-
# invocations to be done at the class method, which are not available to Thor
-
# commands.
-
1
class Thor::Group
-
1
class << self
-
# The description for this Thor::Group. If none is provided, but a source root
-
# exists, tries to find the USAGE one folder above it, otherwise searches
-
# in the superclass.
-
#
-
# ==== Parameters
-
# description<String>:: The description for this Thor::Group.
-
#
-
1
def desc(description = nil)
-
if description
-
@desc = description
-
else
-
@desc ||= from_superclass(:desc, nil)
-
end
-
end
-
-
# Prints help information.
-
#
-
# ==== Options
-
# short:: When true, shows only usage.
-
#
-
1
def help(shell)
-
shell.say "Usage:"
-
shell.say " #{banner}\n"
-
shell.say
-
class_options_help(shell)
-
shell.say desc if desc
-
end
-
-
# Stores invocations for this class merging with superclass values.
-
#
-
1
def invocations #:nodoc:
-
@invocations ||= from_superclass(:invocations, {})
-
end
-
-
# Stores invocation blocks used on invoke_from_option.
-
#
-
1
def invocation_blocks #:nodoc:
-
@invocation_blocks ||= from_superclass(:invocation_blocks, {})
-
end
-
-
# Invoke the given namespace or class given. It adds an instance
-
# method that will invoke the klass and command. You can give a block to
-
# configure how it will be invoked.
-
#
-
# The namespace/class given will have its options showed on the help
-
# usage. Check invoke_from_option for more information.
-
#
-
1
def invoke(*names, &block)
-
options = names.last.is_a?(Hash) ? names.pop : {}
-
verbose = options.fetch(:verbose, true)
-
-
names.each do |name|
-
invocations[name] = false
-
invocation_blocks[name] = block if block_given?
-
-
class_eval <<-METHOD, __FILE__, __LINE__
-
def _invoke_#{name.to_s.gsub(/\W/, '_')}
-
klass, command = self.class.prepare_for_invocation(nil, #{name.inspect})
-
-
if klass
-
say_status :invoke, #{name.inspect}, #{verbose.inspect}
-
block = self.class.invocation_blocks[#{name.inspect}]
-
_invoke_for_class_method klass, command, &block
-
else
-
say_status :error, %(#{name.inspect} [not found]), :red
-
end
-
end
-
METHOD
-
end
-
end
-
-
# Invoke a thor class based on the value supplied by the user to the
-
# given option named "name". A class option must be created before this
-
# method is invoked for each name given.
-
#
-
# ==== Examples
-
#
-
# class GemGenerator < Thor::Group
-
# class_option :test_framework, :type => :string
-
# invoke_from_option :test_framework
-
# end
-
#
-
# ==== Boolean options
-
#
-
# In some cases, you want to invoke a thor class if some option is true or
-
# false. This is automatically handled by invoke_from_option. Then the
-
# option name is used to invoke the generator.
-
#
-
# ==== Preparing for invocation
-
#
-
# In some cases you want to customize how a specified hook is going to be
-
# invoked. You can do that by overwriting the class method
-
# prepare_for_invocation. The class method must necessarily return a klass
-
# and an optional command.
-
#
-
# ==== Custom invocations
-
#
-
# You can also supply a block to customize how the option is going to be
-
# invoked. The block receives two parameters, an instance of the current
-
# class and the klass to be invoked.
-
#
-
1
def invoke_from_option(*names, &block)
-
options = names.last.is_a?(Hash) ? names.pop : {}
-
verbose = options.fetch(:verbose, :white)
-
-
names.each do |name|
-
unless class_options.key?(name)
-
raise ArgumentError, "You have to define the option #{name.inspect} " \
-
"before setting invoke_from_option."
-
end
-
-
invocations[name] = true
-
invocation_blocks[name] = block if block_given?
-
-
class_eval <<-METHOD, __FILE__, __LINE__
-
def _invoke_from_option_#{name.to_s.gsub(/\W/, '_')}
-
return unless options[#{name.inspect}]
-
-
value = options[#{name.inspect}]
-
value = #{name.inspect} if TrueClass === value
-
klass, command = self.class.prepare_for_invocation(#{name.inspect}, value)
-
-
if klass
-
say_status :invoke, value, #{verbose.inspect}
-
block = self.class.invocation_blocks[#{name.inspect}]
-
_invoke_for_class_method klass, command, &block
-
else
-
say_status :error, %(\#{value} [not found]), :red
-
end
-
end
-
METHOD
-
end
-
end
-
-
# Remove a previously added invocation.
-
#
-
# ==== Examples
-
#
-
# remove_invocation :test_framework
-
#
-
1
def remove_invocation(*names)
-
names.each do |name|
-
remove_command(name)
-
remove_class_option(name)
-
invocations.delete(name)
-
invocation_blocks.delete(name)
-
end
-
end
-
-
# Overwrite class options help to allow invoked generators options to be
-
# shown recursively when invoking a generator.
-
#
-
1
def class_options_help(shell, groups = {}) #:nodoc:
-
get_options_from_invocations(groups, class_options) do |klass|
-
klass.send(:get_options_from_invocations, groups, class_options)
-
end
-
super(shell, groups)
-
end
-
-
# Get invocations array and merge options from invocations. Those
-
# options are added to group_options hash. Options that already exists
-
# in base_options are not added twice.
-
#
-
1
def get_options_from_invocations(group_options, base_options) #:nodoc: # rubocop:disable MethodLength
-
invocations.each do |name, from_option|
-
value = if from_option
-
option = class_options[name]
-
option.type == :boolean ? name : option.default
-
else
-
name
-
end
-
next unless value
-
-
klass, _ = prepare_for_invocation(name, value)
-
next unless klass && klass.respond_to?(:class_options)
-
-
value = value.to_s
-
human_name = value.respond_to?(:classify) ? value.classify : value
-
-
group_options[human_name] ||= []
-
group_options[human_name] += klass.class_options.values.select do |class_option|
-
base_options[class_option.name.to_sym].nil? && class_option.group.nil? &&
-
!group_options.values.flatten.any? { |i| i.name == class_option.name }
-
end
-
-
yield klass if block_given?
-
end
-
end
-
-
# Returns commands ready to be printed.
-
1
def printable_commands(*)
-
item = []
-
item << banner
-
item << (desc ? "# #{desc.gsub(/\s+/m, ' ')}" : "")
-
[item]
-
end
-
1
alias_method :printable_tasks, :printable_commands
-
-
1
def handle_argument_error(command, error, _args, arity) #:nodoc:
-
msg = "#{basename} #{command.name} takes #{arity} argument"
-
msg << "s" if arity > 1
-
msg << ", but it should not."
-
raise error, msg
-
end
-
-
1
protected
-
-
# The method responsible for dispatching given the args.
-
1
def dispatch(command, given_args, given_opts, config) #:nodoc:
-
if Thor::HELP_MAPPINGS.include?(given_args.first)
-
help(config[:shell])
-
return
-
end
-
-
args, opts = Thor::Options.split(given_args)
-
opts = given_opts || opts
-
-
instance = new(args, opts, config)
-
yield instance if block_given?
-
-
if command
-
instance.invoke_command(all_commands[command])
-
else
-
instance.invoke_all
-
end
-
end
-
-
# The banner for this class. You can customize it if you are invoking the
-
# thor class by another ways which is not the Thor::Runner.
-
1
def banner
-
"#{basename} #{self_command.formatted_usage(self, false)}"
-
end
-
-
# Represents the whole class as a command.
-
1
def self_command #:nodoc:
-
Thor::DynamicCommand.new(namespace, class_options)
-
end
-
1
alias_method :self_task, :self_command
-
-
1
def baseclass #:nodoc:
-
Thor::Group
-
end
-
-
1
def create_command(meth) #:nodoc:
-
commands[meth.to_s] = Thor::Command.new(meth, nil, nil, nil, nil)
-
true
-
end
-
1
alias_method :create_task, :create_command
-
end
-
-
1
include Thor::Base
-
-
1
protected
-
-
# Shortcut to invoke with padding and block handling. Use internally by
-
# invoke and invoke_from_option class methods.
-
1
def _invoke_for_class_method(klass, command = nil, *args, &block) #:nodoc:
-
with_padding do
-
if block
-
case block.arity
-
when 3
-
yield(self, klass, command)
-
when 2
-
yield(self, klass)
-
when 1
-
instance_exec(klass, &block)
-
end
-
else
-
invoke klass, command, *args
-
end
-
end
-
end
-
end
-
1
class Thor
-
1
module Invocation
-
1
def self.included(base) #:nodoc:
-
1
base.extend ClassMethods
-
end
-
-
1
module ClassMethods
-
# This method is responsible for receiving a name and find the proper
-
# class and command for it. The key is an optional parameter which is
-
# available only in class methods invocations (i.e. in Thor::Group).
-
1
def prepare_for_invocation(key, name) #:nodoc:
-
case name
-
when Symbol, String
-
Thor::Util.find_class_and_command_by_namespace(name.to_s, !key)
-
else
-
name
-
end
-
end
-
end
-
-
# Make initializer aware of invocations and the initialization args.
-
1
def initialize(args = [], options = {}, config = {}, &block) #:nodoc:
-
@_invocations = config[:invocations] || Hash.new { |h, k| h[k] = [] }
-
@_initializer = [args, options, config]
-
super
-
end
-
-
# Make the current command chain accessible with in a Thor-(sub)command
-
1
def current_command_chain
-
@_invocations.values.flatten.map(&:to_sym)
-
end
-
-
# Receives a name and invokes it. The name can be a string (either "command" or
-
# "namespace:command"), a Thor::Command, a Class or a Thor instance. If the
-
# command cannot be guessed by name, it can also be supplied as second argument.
-
#
-
# You can also supply the arguments, options and configuration values for
-
# the command to be invoked, if none is given, the same values used to
-
# initialize the invoker are used to initialize the invoked.
-
#
-
# When no name is given, it will invoke the default command of the current class.
-
#
-
# ==== Examples
-
#
-
# class A < Thor
-
# def foo
-
# invoke :bar
-
# invoke "b:hello", ["Erik"]
-
# end
-
#
-
# def bar
-
# invoke "b:hello", ["Erik"]
-
# end
-
# end
-
#
-
# class B < Thor
-
# def hello(name)
-
# puts "hello #{name}"
-
# end
-
# end
-
#
-
# You can notice that the method "foo" above invokes two commands: "bar",
-
# which belongs to the same class and "hello" which belongs to the class B.
-
#
-
# By using an invocation system you ensure that a command is invoked only once.
-
# In the example above, invoking "foo" will invoke "b:hello" just once, even
-
# if it's invoked later by "bar" method.
-
#
-
# When class A invokes class B, all arguments used on A initialization are
-
# supplied to B. This allows lazy parse of options. Let's suppose you have
-
# some rspec commands:
-
#
-
# class Rspec < Thor::Group
-
# class_option :mock_framework, :type => :string, :default => :rr
-
#
-
# def invoke_mock_framework
-
# invoke "rspec:#{options[:mock_framework]}"
-
# end
-
# end
-
#
-
# As you noticed, it invokes the given mock framework, which might have its
-
# own options:
-
#
-
# class Rspec::RR < Thor::Group
-
# class_option :style, :type => :string, :default => :mock
-
# end
-
#
-
# Since it's not rspec concern to parse mock framework options, when RR
-
# is invoked all options are parsed again, so RR can extract only the options
-
# that it's going to use.
-
#
-
# If you want Rspec::RR to be initialized with its own set of options, you
-
# have to do that explicitly:
-
#
-
# invoke "rspec:rr", [], :style => :foo
-
#
-
# Besides giving an instance, you can also give a class to invoke:
-
#
-
# invoke Rspec::RR, [], :style => :foo
-
#
-
1
def invoke(name = nil, *args)
-
if name.nil?
-
warn "[Thor] Calling invoke() without argument is deprecated. Please use invoke_all instead.\n#{caller.join("\n")}"
-
return invoke_all
-
end
-
-
args.unshift(nil) if args.first.is_a?(Array) || args.first.nil?
-
command, args, opts, config = args
-
-
klass, command = _retrieve_class_and_command(name, command)
-
raise "Missing Thor class for invoke #{name}" unless klass
-
raise "Expected Thor class, got #{klass}" unless klass <= Thor::Base
-
-
args, opts, config = _parse_initialization_options(args, opts, config)
-
klass.send(:dispatch, command, args, opts, config) do |instance|
-
instance.parent_options = options
-
end
-
end
-
-
# Invoke the given command if the given args.
-
1
def invoke_command(command, *args) #:nodoc:
-
current = @_invocations[self.class]
-
-
unless current.include?(command.name)
-
current << command.name
-
command.run(self, *args)
-
end
-
end
-
1
alias_method :invoke_task, :invoke_command
-
-
# Invoke all commands for the current instance.
-
1
def invoke_all #:nodoc:
-
self.class.all_commands.map { |_, command| invoke_command(command) }
-
end
-
-
# Invokes using shell padding.
-
1
def invoke_with_padding(*args)
-
with_padding { invoke(*args) }
-
end
-
-
1
protected
-
-
# Configuration values that are shared between invocations.
-
1
def _shared_configuration #:nodoc:
-
{:invocations => @_invocations}
-
end
-
-
# This method simply retrieves the class and command to be invoked.
-
# If the name is nil or the given name is a command in the current class,
-
# use the given name and return self as class. Otherwise, call
-
# prepare_for_invocation in the current class.
-
1
def _retrieve_class_and_command(name, sent_command = nil) #:nodoc:
-
if name.nil?
-
[self.class, nil]
-
elsif self.class.all_commands[name.to_s]
-
[self.class, name.to_s]
-
else
-
klass, command = self.class.prepare_for_invocation(nil, name)
-
[klass, command || sent_command]
-
end
-
end
-
1
alias_method :_retrieve_class_and_task, :_retrieve_class_and_command
-
-
# Initialize klass using values stored in the @_initializer.
-
1
def _parse_initialization_options(args, opts, config) #:nodoc:
-
stored_args, stored_opts, stored_config = @_initializer
-
-
args ||= stored_args.dup
-
opts ||= stored_opts.dup
-
-
config ||= {}
-
config = stored_config.merge(_shared_configuration).merge!(config)
-
-
[args, opts, config]
-
end
-
end
-
end
-
1
require "thor/line_editor/basic"
-
1
require "thor/line_editor/readline"
-
-
1
class Thor
-
1
module LineEditor
-
1
def self.readline(prompt, options = {})
-
best_available.new(prompt, options).readline
-
end
-
-
1
def self.best_available
-
[
-
Thor::LineEditor::Readline,
-
Thor::LineEditor::Basic
-
].detect(&:available?)
-
end
-
end
-
end
-
1
class Thor
-
1
module LineEditor
-
1
class Basic
-
1
attr_reader :prompt, :options
-
-
1
def self.available?
-
true
-
end
-
-
1
def initialize(prompt, options)
-
@prompt = prompt
-
@options = options
-
end
-
-
1
def readline
-
$stdout.print(prompt)
-
get_input
-
end
-
-
1
private
-
-
1
def get_input
-
if echo?
-
$stdin.gets
-
else
-
$stdin.noecho(&:gets)
-
end
-
end
-
-
1
def echo?
-
options.fetch(:echo, true)
-
end
-
end
-
end
-
end
-
1
begin
-
1
require "readline"
-
rescue LoadError
-
end
-
-
1
class Thor
-
1
module LineEditor
-
1
class Readline < Basic
-
1
def self.available?
-
Object.const_defined?(:Readline)
-
end
-
-
1
def readline
-
if echo?
-
::Readline.completion_append_character = nil
-
# Ruby 1.8.7 does not allow Readline.completion_proc= to receive nil.
-
if complete = completion_proc
-
::Readline.completion_proc = complete
-
end
-
::Readline.readline(prompt, add_to_history?)
-
else
-
super
-
end
-
end
-
-
1
private
-
-
1
def add_to_history?
-
options.fetch(:add_to_history, true)
-
end
-
-
1
def completion_proc
-
if use_path_completion?
-
proc { |text| PathCompletion.new(text).matches }
-
elsif completion_options.any?
-
proc do |text|
-
completion_options.select { |option| option.start_with?(text) }
-
end
-
end
-
end
-
-
1
def completion_options
-
options.fetch(:limited_to, [])
-
end
-
-
1
def use_path_completion?
-
options.fetch(:path, false)
-
end
-
-
1
class PathCompletion
-
1
attr_reader :text
-
1
private :text
-
-
1
def initialize(text)
-
@text = text
-
end
-
-
1
def matches
-
relative_matches
-
end
-
-
1
private
-
-
1
def relative_matches
-
absolute_matches.map { |path| path.sub(base_path, "") }
-
end
-
-
1
def absolute_matches
-
Dir[glob_pattern].map do |path|
-
if File.directory?(path)
-
"#{path}/"
-
else
-
path
-
end
-
end
-
end
-
-
1
def glob_pattern
-
"#{base_path}#{text}*"
-
end
-
-
1
def base_path
-
"#{Dir.pwd}/"
-
end
-
end
-
end
-
end
-
end
-
1
require "thor/parser/argument"
-
1
require "thor/parser/arguments"
-
1
require "thor/parser/option"
-
1
require "thor/parser/options"
-
1
class Thor
-
1
class Argument #:nodoc:
-
1
VALID_TYPES = [:numeric, :hash, :array, :string]
-
-
1
attr_reader :name, :description, :enum, :required, :type, :default, :banner
-
1
alias_method :human_name, :name
-
-
1
def initialize(name, options = {})
-
class_name = self.class.name.split("::").last
-
-
type = options[:type]
-
-
raise ArgumentError, "#{class_name} name can't be nil." if name.nil?
-
raise ArgumentError, "Type :#{type} is not valid for #{class_name.downcase}s." if type && !valid_type?(type)
-
-
@name = name.to_s
-
@description = options[:desc]
-
@required = options.key?(:required) ? options[:required] : true
-
@type = (type || :string).to_sym
-
@default = options[:default]
-
@banner = options[:banner] || default_banner
-
@enum = options[:enum]
-
-
validate! # Trigger specific validations
-
end
-
-
1
def usage
-
required? ? banner : "[#{banner}]"
-
end
-
-
1
def required?
-
required
-
end
-
-
1
def show_default?
-
case default
-
when Array, String, Hash
-
!default.empty?
-
else
-
default
-
end
-
end
-
-
1
protected
-
-
1
def validate!
-
raise ArgumentError, "An argument cannot be required and have default value." if required? && !default.nil?
-
raise ArgumentError, "An argument cannot have an enum other than an array." if @enum && !@enum.is_a?(Array)
-
end
-
-
1
def valid_type?(type)
-
self.class::VALID_TYPES.include?(type.to_sym)
-
end
-
-
1
def default_banner
-
case type
-
when :boolean
-
nil
-
when :string, :default
-
human_name.upcase
-
when :numeric
-
"N"
-
when :hash
-
"key:value"
-
when :array
-
"one two three"
-
end
-
end
-
end
-
end
-
1
class Thor
-
1
class Arguments #:nodoc: # rubocop:disable ClassLength
-
1
NUMERIC = /[-+]?(\d*\.\d+|\d+)/
-
-
# Receives an array of args and returns two arrays, one with arguments
-
# and one with switches.
-
#
-
1
def self.split(args)
-
arguments = []
-
-
args.each do |item|
-
break if item =~ /^-/
-
arguments << item
-
end
-
-
[arguments, args[Range.new(arguments.size, -1)]]
-
end
-
-
1
def self.parse(*args)
-
to_parse = args.pop
-
new(*args).parse(to_parse)
-
end
-
-
# Takes an array of Thor::Argument objects.
-
#
-
1
def initialize(arguments = [])
-
@assigns = {}
-
@non_assigned_required = []
-
@switches = arguments
-
-
arguments.each do |argument|
-
if !argument.default.nil?
-
@assigns[argument.human_name] = argument.default
-
elsif argument.required?
-
@non_assigned_required << argument
-
end
-
end
-
end
-
-
1
def parse(args)
-
@pile = args.dup
-
-
@switches.each do |argument|
-
break unless peek
-
@non_assigned_required.delete(argument)
-
@assigns[argument.human_name] = send(:"parse_#{argument.type}", argument.human_name)
-
end
-
-
check_requirement!
-
@assigns
-
end
-
-
1
def remaining
-
@pile
-
end
-
-
1
private
-
-
1
def no_or_skip?(arg)
-
arg =~ /^--(no|skip)-([-\w]+)$/
-
$2
-
end
-
-
1
def last?
-
@pile.empty?
-
end
-
-
1
def peek
-
@pile.first
-
end
-
-
1
def shift
-
@pile.shift
-
end
-
-
1
def unshift(arg)
-
if arg.is_a?(Array)
-
@pile = arg + @pile
-
else
-
@pile.unshift(arg)
-
end
-
end
-
-
1
def current_is_value?
-
peek && peek.to_s !~ /^-/
-
end
-
-
# Runs through the argument array getting strings that contains ":" and
-
# mark it as a hash:
-
#
-
# [ "name:string", "age:integer" ]
-
#
-
# Becomes:
-
#
-
# { "name" => "string", "age" => "integer" }
-
#
-
1
def parse_hash(name)
-
return shift if peek.is_a?(Hash)
-
hash = {}
-
-
while current_is_value? && peek.include?(":")
-
key, value = shift.split(":", 2)
-
raise MalformattedArgumentError, "You can't specify '#{key}' more than once in option '#{name}'; got #{key}:#{hash[key]} and #{key}:#{value}" if hash.include? key
-
hash[key] = value
-
end
-
hash
-
end
-
-
# Runs through the argument array getting all strings until no string is
-
# found or a switch is found.
-
#
-
# ["a", "b", "c"]
-
#
-
# And returns it as an array:
-
#
-
# ["a", "b", "c"]
-
#
-
1
def parse_array(name)
-
return shift if peek.is_a?(Array)
-
array = []
-
array << shift while current_is_value?
-
array
-
end
-
-
# Check if the peek is numeric format and return a Float or Integer.
-
# Check if the peek is included in enum if enum is provided.
-
# Otherwise raises an error.
-
#
-
1
def parse_numeric(name)
-
return shift if peek.is_a?(Numeric)
-
-
unless peek =~ NUMERIC && $& == peek
-
raise MalformattedArgumentError, "Expected numeric value for '#{name}'; got #{peek.inspect}"
-
end
-
-
value = $&.index(".") ? shift.to_f : shift.to_i
-
if @switches.is_a?(Hash) && switch = @switches[name]
-
if switch.enum && !switch.enum.include?(value)
-
raise MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
-
end
-
end
-
value
-
end
-
-
# Parse string:
-
# for --string-arg, just return the current value in the pile
-
# for --no-string-arg, nil
-
# Check if the peek is included in enum if enum is provided. Otherwise raises an error.
-
#
-
1
def parse_string(name)
-
if no_or_skip?(name)
-
nil
-
else
-
value = shift
-
if @switches.is_a?(Hash) && switch = @switches[name]
-
if switch.enum && !switch.enum.include?(value)
-
raise MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
-
end
-
end
-
value
-
end
-
end
-
-
# Raises an error if @non_assigned_required array is not empty.
-
#
-
1
def check_requirement!
-
return if @non_assigned_required.empty?
-
names = @non_assigned_required.map do |o|
-
o.respond_to?(:switch_name) ? o.switch_name : o.human_name
-
end.join("', '")
-
class_name = self.class.name.split("::").last.downcase
-
raise RequiredArgumentMissingError, "No value provided for required #{class_name} '#{names}'"
-
end
-
end
-
end
-
1
class Thor
-
1
class Option < Argument #:nodoc:
-
1
attr_reader :aliases, :group, :lazy_default, :hide
-
-
1
VALID_TYPES = [:boolean, :numeric, :hash, :array, :string]
-
-
1
def initialize(name, options = {})
-
options[:required] = false unless options.key?(:required)
-
super
-
@lazy_default = options[:lazy_default]
-
@group = options[:group].to_s.capitalize if options[:group]
-
@aliases = Array(options[:aliases])
-
@hide = options[:hide]
-
end
-
-
# This parse quick options given as method_options. It makes several
-
# assumptions, but you can be more specific using the option method.
-
#
-
# parse :foo => "bar"
-
# #=> Option foo with default value bar
-
#
-
# parse [:foo, :baz] => "bar"
-
# #=> Option foo with default value bar and alias :baz
-
#
-
# parse :foo => :required
-
# #=> Required option foo without default value
-
#
-
# parse :foo => 2
-
# #=> Option foo with default value 2 and type numeric
-
#
-
# parse :foo => :numeric
-
# #=> Option foo without default value and type numeric
-
#
-
# parse :foo => true
-
# #=> Option foo with default value true and type boolean
-
#
-
# The valid types are :boolean, :numeric, :hash, :array and :string. If none
-
# is given a default type is assumed. This default type accepts arguments as
-
# string (--foo=value) or booleans (just --foo).
-
#
-
# By default all options are optional, unless :required is given.
-
#
-
1
def self.parse(key, value)
-
if key.is_a?(Array)
-
name, *aliases = key
-
else
-
name = key
-
aliases = []
-
end
-
-
name = name.to_s
-
default = value
-
-
type = case value
-
when Symbol
-
default = nil
-
if VALID_TYPES.include?(value)
-
value
-
elsif required = (value == :required) # rubocop:disable AssignmentInCondition
-
:string
-
end
-
when TrueClass, FalseClass
-
:boolean
-
when Numeric
-
:numeric
-
when Hash, Array, String
-
value.class.name.downcase.to_sym
-
end
-
-
new(name.to_s, :required => required, :type => type, :default => default, :aliases => aliases)
-
end
-
-
1
def switch_name
-
@switch_name ||= dasherized? ? name : dasherize(name)
-
end
-
-
1
def human_name
-
@human_name ||= dasherized? ? undasherize(name) : name
-
end
-
-
1
def usage(padding = 0)
-
sample = if banner && !banner.to_s.empty?
-
"#{switch_name}=#{banner}"
-
else
-
switch_name
-
end
-
-
sample = "[#{sample}]" unless required?
-
-
if boolean?
-
sample << ", [#{dasherize('no-' + human_name)}]" unless (name == "force") || name.start_with?("no-")
-
end
-
-
if aliases.empty?
-
(" " * padding) << sample
-
else
-
"#{aliases.join(', ')}, #{sample}"
-
end
-
end
-
-
1
VALID_TYPES.each do |type|
-
5
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{type}?
-
self.type == #{type.inspect}
-
end
-
RUBY
-
end
-
-
1
protected
-
-
1
def validate!
-
raise ArgumentError, "An option cannot be boolean and required." if boolean? && required?
-
validate_default_type!
-
end
-
-
1
def validate_default_type!
-
default_type = case @default
-
when nil
-
return
-
when TrueClass, FalseClass
-
required? ? :string : :boolean
-
when Numeric
-
:numeric
-
when Symbol
-
:string
-
when Hash, Array, String
-
@default.class.name.downcase.to_sym
-
end
-
-
# TODO: This should raise an ArgumentError in a future version of Thor
-
warn "Expected #{@type} default value for '#{switch_name}'; got #{@default.inspect} (#{default_type})" unless default_type == @type
-
end
-
-
1
def dasherized?
-
name.index("-") == 0
-
end
-
-
1
def undasherize(str)
-
str.sub(/^-{1,2}/, "")
-
end
-
-
1
def dasherize(str)
-
(str.length > 1 ? "--" : "-") + str.tr("_", "-")
-
end
-
end
-
end
-
1
class Thor
-
1
class Options < Arguments #:nodoc: # rubocop:disable ClassLength
-
1
LONG_RE = /^(--\w+(?:-\w+)*)$/
-
1
SHORT_RE = /^(-[a-z])$/i
-
1
EQ_RE = /^(--\w+(?:-\w+)*|-[a-z])=(.*)$/i
-
1
SHORT_SQ_RE = /^-([a-z]{2,})$/i # Allow either -x -v or -xv style for single char args
-
1
SHORT_NUM = /^(-[a-z])#{NUMERIC}$/i
-
1
OPTS_END = "--".freeze
-
-
# Receives a hash and makes it switches.
-
1
def self.to_switches(options)
-
options.map do |key, value|
-
case value
-
when true
-
"--#{key}"
-
when Array
-
"--#{key} #{value.map(&:inspect).join(' ')}"
-
when Hash
-
"--#{key} #{value.map { |k, v| "#{k}:#{v}" }.join(' ')}"
-
when nil, false
-
""
-
else
-
"--#{key} #{value.inspect}"
-
end
-
end.join(" ")
-
end
-
-
# Takes a hash of Thor::Option and a hash with defaults.
-
#
-
# If +stop_on_unknown+ is true, #parse will stop as soon as it encounters
-
# an unknown option or a regular argument.
-
1
def initialize(hash_options = {}, defaults = {}, stop_on_unknown = false)
-
@stop_on_unknown = stop_on_unknown
-
options = hash_options.values
-
super(options)
-
-
# Add defaults
-
defaults.each do |key, value|
-
@assigns[key.to_s] = value
-
@non_assigned_required.delete(hash_options[key])
-
end
-
-
@shorts = {}
-
@switches = {}
-
@extra = []
-
-
options.each do |option|
-
@switches[option.switch_name] = option
-
-
option.aliases.each do |short|
-
name = short.to_s.sub(/^(?!\-)/, "-")
-
@shorts[name] ||= option.switch_name
-
end
-
end
-
end
-
-
1
def remaining
-
@extra
-
end
-
-
1
def peek
-
return super unless @parsing_options
-
-
result = super
-
if result == OPTS_END
-
shift
-
@parsing_options = false
-
super
-
else
-
result
-
end
-
end
-
-
1
def parse(args) # rubocop:disable MethodLength
-
@pile = args.dup
-
@parsing_options = true
-
-
while peek
-
if parsing_options?
-
match, is_switch = current_is_switch?
-
shifted = shift
-
-
if is_switch
-
case shifted
-
when SHORT_SQ_RE
-
unshift($1.split("").map { |f| "-#{f}" })
-
next
-
when EQ_RE, SHORT_NUM
-
unshift($2)
-
switch = $1
-
when LONG_RE, SHORT_RE
-
switch = $1
-
end
-
-
switch = normalize_switch(switch)
-
option = switch_option(switch)
-
@assigns[option.human_name] = parse_peek(switch, option)
-
elsif @stop_on_unknown
-
@parsing_options = false
-
@extra << shifted
-
@extra << shift while peek
-
break
-
elsif match
-
@extra << shifted
-
@extra << shift while peek && peek !~ /^-/
-
else
-
@extra << shifted
-
end
-
else
-
@extra << shift
-
end
-
end
-
-
check_requirement!
-
-
assigns = Thor::CoreExt::HashWithIndifferentAccess.new(@assigns)
-
assigns.freeze
-
assigns
-
end
-
-
1
def check_unknown!
-
# an unknown option starts with - or -- and has no more --'s afterward.
-
unknown = @extra.select { |str| str =~ /^--?(?:(?!--).)*$/ }
-
raise UnknownArgumentError, "Unknown switches '#{unknown.join(', ')}'" unless unknown.empty?
-
end
-
-
1
protected
-
-
# Check if the current value in peek is a registered switch.
-
#
-
# Two booleans are returned. The first is true if the current value
-
# starts with a hyphen; the second is true if it is a registered switch.
-
1
def current_is_switch?
-
case peek
-
when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM
-
[true, switch?($1)]
-
when SHORT_SQ_RE
-
[true, $1.split("").any? { |f| switch?("-#{f}") }]
-
else
-
[false, false]
-
end
-
end
-
-
1
def current_is_switch_formatted?
-
case peek
-
when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM, SHORT_SQ_RE
-
true
-
else
-
false
-
end
-
end
-
-
1
def current_is_value?
-
peek && (!parsing_options? || super)
-
end
-
-
1
def switch?(arg)
-
switch_option(normalize_switch(arg))
-
end
-
-
1
def switch_option(arg)
-
if match = no_or_skip?(arg) # rubocop:disable AssignmentInCondition
-
@switches[arg] || @switches["--#{match}"]
-
else
-
@switches[arg]
-
end
-
end
-
-
# Check if the given argument is actually a shortcut.
-
#
-
1
def normalize_switch(arg)
-
(@shorts[arg] || arg).tr("_", "-")
-
end
-
-
1
def parsing_options?
-
peek
-
@parsing_options
-
end
-
-
# Parse boolean values which can be given as --foo=true, --foo or --no-foo.
-
#
-
1
def parse_boolean(switch)
-
if current_is_value?
-
if ["true", "TRUE", "t", "T", true].include?(peek)
-
shift
-
true
-
elsif ["false", "FALSE", "f", "F", false].include?(peek)
-
shift
-
false
-
else
-
true
-
end
-
else
-
@switches.key?(switch) || !no_or_skip?(switch)
-
end
-
end
-
-
# Parse the value at the peek analyzing if it requires an input or not.
-
#
-
1
def parse_peek(switch, option)
-
if parsing_options? && (current_is_switch_formatted? || last?)
-
if option.boolean?
-
# No problem for boolean types
-
elsif no_or_skip?(switch)
-
return nil # User set value to nil
-
elsif option.string? && !option.required?
-
# Return the default if there is one, else the human name
-
return option.lazy_default || option.default || option.human_name
-
elsif option.lazy_default
-
return option.lazy_default
-
else
-
raise MalformattedArgumentError, "No value provided for option '#{switch}'"
-
end
-
end
-
-
@non_assigned_required.delete(option)
-
send(:"parse_#{option.type}", switch)
-
end
-
end
-
end
-
1
require "rbconfig"
-
-
1
class Thor
-
1
module Base
-
1
class << self
-
1
attr_writer :shell
-
-
# Returns the shell used in all Thor classes. If you are in a Unix platform
-
# it will use a colored log, otherwise it will use a basic one without color.
-
#
-
1
def shell
-
@shell ||= if ENV["THOR_SHELL"] && !ENV["THOR_SHELL"].empty?
-
Thor::Shell.const_get(ENV["THOR_SHELL"])
-
elsif RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ && !ENV["ANSICON"]
-
Thor::Shell::Basic
-
else
-
Thor::Shell::Color
-
end
-
end
-
end
-
end
-
-
1
module Shell
-
1
SHELL_DELEGATED_METHODS = [:ask, :error, :set_color, :yes?, :no?, :say, :say_status, :print_in_columns, :print_table, :print_wrapped, :file_collision, :terminal_width]
-
1
attr_writer :shell
-
-
1
autoload :Basic, "thor/shell/basic"
-
1
autoload :Color, "thor/shell/color"
-
1
autoload :HTML, "thor/shell/html"
-
-
# Add shell to initialize config values.
-
#
-
# ==== Configuration
-
# shell<Object>:: An instance of the shell to be used.
-
#
-
# ==== Examples
-
#
-
# class MyScript < Thor
-
# argument :first, :type => :numeric
-
# end
-
#
-
# MyScript.new [1.0], { :foo => :bar }, :shell => Thor::Shell::Basic.new
-
#
-
1
def initialize(args = [], options = {}, config = {})
-
super
-
self.shell = config[:shell]
-
shell.base ||= self if shell.respond_to?(:base)
-
end
-
-
# Holds the shell for the given Thor instance. If no shell is given,
-
# it gets a default shell from Thor::Base.shell.
-
1
def shell
-
@shell ||= Thor::Base.shell.new
-
end
-
-
# Common methods that are delegated to the shell.
-
1
SHELL_DELEGATED_METHODS.each do |method|
-
12
module_eval <<-METHOD, __FILE__, __LINE__
-
def #{method}(*args,&block)
-
shell.#{method}(*args,&block)
-
end
-
METHOD
-
end
-
-
# Yields the given block with padding.
-
1
def with_padding
-
shell.padding += 1
-
yield
-
ensure
-
shell.padding -= 1
-
end
-
-
1
protected
-
-
# Allow shell to be shared between invocations.
-
#
-
1
def _shared_configuration #:nodoc:
-
super.merge!(:shell => shell)
-
end
-
end
-
end
-
1
require "tempfile"
-
1
require "io/console" if RUBY_VERSION > "1.9.2"
-
-
1
class Thor
-
1
module Shell
-
1
class Basic
-
1
attr_accessor :base
-
1
attr_reader :padding
-
-
# Initialize base, mute and padding to nil.
-
#
-
1
def initialize #:nodoc:
-
@base = nil
-
@mute = false
-
@padding = 0
-
@always_force = false
-
end
-
-
# Mute everything that's inside given block
-
#
-
1
def mute
-
@mute = true
-
yield
-
ensure
-
@mute = false
-
end
-
-
# Check if base is muted
-
#
-
1
def mute?
-
@mute
-
end
-
-
# Sets the output padding, not allowing less than zero values.
-
#
-
1
def padding=(value)
-
@padding = [0, value].max
-
end
-
-
# Sets the output padding while executing a block and resets it.
-
#
-
1
def indent(count = 1)
-
orig_padding = padding
-
self.padding = padding + count
-
yield
-
self.padding = orig_padding
-
end
-
-
# Asks something to the user and receives a response.
-
#
-
# If asked to limit the correct responses, you can pass in an
-
# array of acceptable answers. If one of those is not supplied,
-
# they will be shown a message stating that one of those answers
-
# must be given and re-asked the question.
-
#
-
# If asking for sensitive information, the :echo option can be set
-
# to false to mask user input from $stdin.
-
#
-
# If the required input is a path, then set the path option to
-
# true. This will enable tab completion for file paths relative
-
# to the current working directory on systems that support
-
# Readline.
-
#
-
# ==== Example
-
# ask("What is your name?")
-
#
-
# ask("What is your favorite Neopolitan flavor?", :limited_to => ["strawberry", "chocolate", "vanilla"])
-
#
-
# ask("What is your password?", :echo => false)
-
#
-
# ask("Where should the file be saved?", :path => true)
-
#
-
1
def ask(statement, *args)
-
options = args.last.is_a?(Hash) ? args.pop : {}
-
color = args.first
-
-
if options[:limited_to]
-
ask_filtered(statement, color, options)
-
else
-
ask_simply(statement, color, options)
-
end
-
end
-
-
# Say (print) something to the user. If the sentence ends with a whitespace
-
# or tab character, a new line is not appended (print + flush). Otherwise
-
# are passed straight to puts (behavior got from Highline).
-
#
-
# ==== Example
-
# say("I know you knew that.")
-
#
-
1
def say(message = "", color = nil, force_new_line = (message.to_s !~ /( |\t)\Z/))
-
buffer = prepare_message(message, *color)
-
buffer << "\n" if force_new_line && !message.to_s.end_with?("\n")
-
-
stdout.print(buffer)
-
stdout.flush
-
end
-
-
# Say a status with the given color and appends the message. Since this
-
# method is used frequently by actions, it allows nil or false to be given
-
# in log_status, avoiding the message from being shown. If a Symbol is
-
# given in log_status, it's used as the color.
-
#
-
1
def say_status(status, message, log_status = true)
-
return if quiet? || log_status == false
-
spaces = " " * (padding + 1)
-
color = log_status.is_a?(Symbol) ? log_status : :green
-
-
status = status.to_s.rjust(12)
-
status = set_color status, color, true if color
-
-
buffer = "#{status}#{spaces}#{message}"
-
buffer << "\n" unless buffer.end_with?("\n")
-
-
stdout.print(buffer)
-
stdout.flush
-
end
-
-
# Make a question the to user and returns true if the user replies "y" or
-
# "yes".
-
#
-
1
def yes?(statement, color = nil)
-
!!(ask(statement, color, :add_to_history => false) =~ is?(:yes))
-
end
-
-
# Make a question the to user and returns true if the user replies "n" or
-
# "no".
-
#
-
1
def no?(statement, color = nil)
-
!!(ask(statement, color, :add_to_history => false) =~ is?(:no))
-
end
-
-
# Prints values in columns
-
#
-
# ==== Parameters
-
# Array[String, String, ...]
-
#
-
1
def print_in_columns(array)
-
return if array.empty?
-
colwidth = (array.map { |el| el.to_s.size }.max || 0) + 2
-
array.each_with_index do |value, index|
-
# Don't output trailing spaces when printing the last column
-
if ((((index + 1) % (terminal_width / colwidth))).zero? && !index.zero?) || index + 1 == array.length
-
stdout.puts value
-
else
-
stdout.printf("%-#{colwidth}s", value)
-
end
-
end
-
end
-
-
# Prints a table.
-
#
-
# ==== Parameters
-
# Array[Array[String, String, ...]]
-
#
-
# ==== Options
-
# indent<Integer>:: Indent the first column by indent value.
-
# colwidth<Integer>:: Force the first column to colwidth spaces wide.
-
#
-
1
def print_table(array, options = {}) # rubocop:disable MethodLength
-
return if array.empty?
-
-
formats = []
-
indent = options[:indent].to_i
-
colwidth = options[:colwidth]
-
options[:truncate] = terminal_width if options[:truncate] == true
-
-
formats << "%-#{colwidth + 2}s" if colwidth
-
start = colwidth ? 1 : 0
-
-
colcount = array.max { |a, b| a.size <=> b.size }.size
-
-
maximas = []
-
-
start.upto(colcount - 1) do |index|
-
maxima = array.map { |row| row[index] ? row[index].to_s.size : 0 }.max
-
maximas << maxima
-
formats << if index == colcount - 1
-
# Don't output 2 trailing spaces when printing the last column
-
"%-s"
-
else
-
"%-#{maxima + 2}s"
-
end
-
end
-
-
formats[0] = formats[0].insert(0, " " * indent)
-
formats << "%s"
-
-
array.each do |row|
-
sentence = ""
-
-
row.each_with_index do |column, index|
-
maxima = maximas[index]
-
-
f = if column.is_a?(Numeric)
-
if index == row.size - 1
-
# Don't output 2 trailing spaces when printing the last column
-
"%#{maxima}s"
-
else
-
"%#{maxima}s "
-
end
-
else
-
formats[index]
-
end
-
sentence << f % column.to_s
-
end
-
-
sentence = truncate(sentence, options[:truncate]) if options[:truncate]
-
stdout.puts sentence
-
end
-
end
-
-
# Prints a long string, word-wrapping the text to the current width of the
-
# terminal display. Ideal for printing heredocs.
-
#
-
# ==== Parameters
-
# String
-
#
-
# ==== Options
-
# indent<Integer>:: Indent each line of the printed paragraph by indent value.
-
#
-
1
def print_wrapped(message, options = {})
-
indent = options[:indent] || 0
-
width = terminal_width - indent
-
paras = message.split("\n\n")
-
-
paras.map! do |unwrapped|
-
unwrapped.strip.tr("\n", " ").squeeze(" ").gsub(/.{1,#{width}}(?:\s|\Z)/) { ($& + 5.chr).gsub(/\n\005/, "\n").gsub(/\005/, "\n") }
-
end
-
-
paras.each do |para|
-
para.split("\n").each do |line|
-
stdout.puts line.insert(0, " " * indent)
-
end
-
stdout.puts unless para == paras.last
-
end
-
end
-
-
# Deals with file collision and returns true if the file should be
-
# overwritten and false otherwise. If a block is given, it uses the block
-
# response as the content for the diff.
-
#
-
# ==== Parameters
-
# destination<String>:: the destination file to solve conflicts
-
# block<Proc>:: an optional block that returns the value to be used in diff
-
#
-
1
def file_collision(destination)
-
return true if @always_force
-
options = block_given? ? "[Ynaqdh]" : "[Ynaqh]"
-
-
loop do
-
answer = ask(
-
%[Overwrite #{destination}? (enter "h" for help) #{options}],
-
:add_to_history => false
-
)
-
-
case answer
-
when is?(:yes), is?(:force), ""
-
return true
-
when is?(:no), is?(:skip)
-
return false
-
when is?(:always)
-
return @always_force = true
-
when is?(:quit)
-
say "Aborting..."
-
raise SystemExit
-
when is?(:diff)
-
show_diff(destination, yield) if block_given?
-
say "Retrying..."
-
else
-
say file_collision_help
-
end
-
end
-
end
-
-
# This code was copied from Rake, available under MIT-LICENSE
-
# Copyright (c) 2003, 2004 Jim Weirich
-
1
def terminal_width
-
result = if ENV["THOR_COLUMNS"]
-
ENV["THOR_COLUMNS"].to_i
-
else
-
unix? ? dynamic_width : 80
-
end
-
result < 10 ? 80 : result
-
rescue
-
80
-
end
-
-
# Called if something goes wrong during the execution. This is used by Thor
-
# internally and should not be used inside your scripts. If something went
-
# wrong, you can always raise an exception. If you raise a Thor::Error, it
-
# will be rescued and wrapped in the method below.
-
#
-
1
def error(statement)
-
stderr.puts statement
-
end
-
-
# Apply color to the given string with optional bold. Disabled in the
-
# Thor::Shell::Basic class.
-
#
-
1
def set_color(string, *) #:nodoc:
-
string
-
end
-
-
1
protected
-
-
1
def prepare_message(message, *color)
-
spaces = " " * padding
-
spaces + set_color(message.to_s, *color)
-
end
-
-
1
def can_display_colors?
-
false
-
end
-
-
1
def lookup_color(color)
-
return color unless color.is_a?(Symbol)
-
self.class.const_get(color.to_s.upcase)
-
end
-
-
1
def stdout
-
$stdout
-
end
-
-
1
def stderr
-
$stderr
-
end
-
-
1
def is?(value) #:nodoc:
-
value = value.to_s
-
-
if value.size == 1
-
/\A#{value}\z/i
-
else
-
/\A(#{value}|#{value[0, 1]})\z/i
-
end
-
end
-
-
1
def file_collision_help #:nodoc:
-
<<-HELP
-
Y - yes, overwrite
-
n - no, do not overwrite
-
a - all, overwrite this and all others
-
q - quit, abort
-
d - diff, show the differences between the old and the new
-
h - help, show this help
-
HELP
-
end
-
-
1
def show_diff(destination, content) #:nodoc:
-
diff_cmd = ENV["THOR_DIFF"] || ENV["RAILS_DIFF"] || "diff -u"
-
-
Tempfile.open(File.basename(destination), File.dirname(destination)) do |temp|
-
temp.write content
-
temp.rewind
-
system %(#{diff_cmd} "#{destination}" "#{temp.path}")
-
end
-
end
-
-
1
def quiet? #:nodoc:
-
mute? || (base && base.options[:quiet])
-
end
-
-
# Calculate the dynamic width of the terminal
-
1
def dynamic_width
-
@dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput)
-
end
-
-
1
def dynamic_width_stty
-
`stty size 2>/dev/null`.split[1].to_i
-
end
-
-
1
def dynamic_width_tput
-
`tput cols 2>/dev/null`.to_i
-
end
-
-
1
def unix?
-
RUBY_PLATFORM =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i
-
end
-
-
1
def truncate(string, width)
-
as_unicode do
-
chars = string.chars.to_a
-
if chars.length <= width
-
chars.join
-
else
-
chars[0, width - 3].join + "..."
-
end
-
end
-
end
-
-
1
if "".respond_to?(:encode)
-
1
def as_unicode
-
yield
-
end
-
else
-
def as_unicode
-
old = $KCODE
-
$KCODE = "U"
-
yield
-
ensure
-
$KCODE = old
-
end
-
end
-
-
1
def ask_simply(statement, color, options)
-
default = options[:default]
-
message = [statement, ("(#{default})" if default), nil].uniq.join(" ")
-
message = prepare_message(message, *color)
-
result = Thor::LineEditor.readline(message, options)
-
-
return unless result
-
-
result.strip!
-
-
if default && result == ""
-
default
-
else
-
result
-
end
-
end
-
-
1
def ask_filtered(statement, color, options)
-
answer_set = options[:limited_to]
-
correct_answer = nil
-
until correct_answer
-
answers = answer_set.join(", ")
-
answer = ask_simply("#{statement} [#{answers}]", color, options)
-
correct_answer = answer_set.include?(answer) ? answer : nil
-
say("Your response must be one of: [#{answers}]. Please try again.") unless correct_answer
-
end
-
correct_answer
-
end
-
end
-
end
-
end
-
1
require "rbconfig"
-
-
1
class Thor
-
1
module Sandbox #:nodoc:
-
end
-
-
# This module holds several utilities:
-
#
-
# 1) Methods to convert thor namespaces to constants and vice-versa.
-
#
-
# Thor::Util.namespace_from_thor_class(Foo::Bar::Baz) #=> "foo:bar:baz"
-
#
-
# 2) Loading thor files and sandboxing:
-
#
-
# Thor::Util.load_thorfile("~/.thor/foo")
-
#
-
1
module Util
-
1
class << self
-
# Receives a namespace and search for it in the Thor::Base subclasses.
-
#
-
# ==== Parameters
-
# namespace<String>:: The namespace to search for.
-
#
-
1
def find_by_namespace(namespace)
-
namespace = "default#{namespace}" if namespace.empty? || namespace =~ /^:/
-
Thor::Base.subclasses.detect { |klass| klass.namespace == namespace }
-
end
-
-
# Receives a constant and converts it to a Thor namespace. Since Thor
-
# commands can be added to a sandbox, this method is also responsable for
-
# removing the sandbox namespace.
-
#
-
# This method should not be used in general because it's used to deal with
-
# older versions of Thor. On current versions, if you need to get the
-
# namespace from a class, just call namespace on it.
-
#
-
# ==== Parameters
-
# constant<Object>:: The constant to be converted to the thor path.
-
#
-
# ==== Returns
-
# String:: If we receive Foo::Bar::Baz it returns "foo:bar:baz"
-
#
-
1
def namespace_from_thor_class(constant)
-
constant = constant.to_s.gsub(/^Thor::Sandbox::/, "")
-
constant = snake_case(constant).squeeze(":")
-
constant
-
end
-
-
# Given the contents, evaluate it inside the sandbox and returns the
-
# namespaces defined in the sandbox.
-
#
-
# ==== Parameters
-
# contents<String>
-
#
-
# ==== Returns
-
# Array[Object]
-
#
-
1
def namespaces_in_content(contents, file = __FILE__)
-
old_constants = Thor::Base.subclasses.dup
-
Thor::Base.subclasses.clear
-
-
load_thorfile(file, contents)
-
-
new_constants = Thor::Base.subclasses.dup
-
Thor::Base.subclasses.replace(old_constants)
-
-
new_constants.map!(&:namespace)
-
new_constants.compact!
-
new_constants
-
end
-
-
# Returns the thor classes declared inside the given class.
-
#
-
1
def thor_classes_in(klass)
-
stringfied_constants = klass.constants.map(&:to_s)
-
Thor::Base.subclasses.select do |subclass|
-
next unless subclass.name
-
stringfied_constants.include?(subclass.name.gsub("#{klass.name}::", ""))
-
end
-
end
-
-
# Receives a string and convert it to snake case. SnakeCase returns snake_case.
-
#
-
# ==== Parameters
-
# String
-
#
-
# ==== Returns
-
# String
-
#
-
1
def snake_case(str)
-
return str.downcase if str =~ /^[A-Z_]+$/
-
str.gsub(/\B[A-Z]/, '_\&').squeeze("_") =~ /_*(.*)/
-
$+.downcase
-
end
-
-
# Receives a string and convert it to camel case. camel_case returns CamelCase.
-
#
-
# ==== Parameters
-
# String
-
#
-
# ==== Returns
-
# String
-
#
-
1
def camel_case(str)
-
return str if str !~ /_/ && str =~ /[A-Z]+.*/
-
str.split("_").map(&:capitalize).join
-
end
-
-
# Receives a namespace and tries to retrieve a Thor or Thor::Group class
-
# from it. It first searches for a class using the all the given namespace,
-
# if it's not found, removes the highest entry and searches for the class
-
# again. If found, returns the highest entry as the class name.
-
#
-
# ==== Examples
-
#
-
# class Foo::Bar < Thor
-
# def baz
-
# end
-
# end
-
#
-
# class Baz::Foo < Thor::Group
-
# end
-
#
-
# Thor::Util.namespace_to_thor_class("foo:bar") #=> Foo::Bar, nil # will invoke default command
-
# Thor::Util.namespace_to_thor_class("baz:foo") #=> Baz::Foo, nil
-
# Thor::Util.namespace_to_thor_class("foo:bar:baz") #=> Foo::Bar, "baz"
-
#
-
# ==== Parameters
-
# namespace<String>
-
#
-
1
def find_class_and_command_by_namespace(namespace, fallback = true)
-
if namespace.include?(":") # look for a namespaced command
-
pieces = namespace.split(":")
-
command = pieces.pop
-
klass = Thor::Util.find_by_namespace(pieces.join(":"))
-
end
-
unless klass # look for a Thor::Group with the right name
-
klass = Thor::Util.find_by_namespace(namespace)
-
command = nil
-
end
-
if !klass && fallback # try a command in the default namespace
-
command = namespace
-
klass = Thor::Util.find_by_namespace("")
-
end
-
[klass, command]
-
end
-
1
alias_method :find_class_and_task_by_namespace, :find_class_and_command_by_namespace
-
-
# Receives a path and load the thor file in the path. The file is evaluated
-
# inside the sandbox to avoid namespacing conflicts.
-
#
-
1
def load_thorfile(path, content = nil, debug = false)
-
content ||= File.binread(path)
-
-
begin
-
Thor::Sandbox.class_eval(content, path)
-
rescue StandardError => e
-
$stderr.puts("WARNING: unable to load thorfile #{path.inspect}: #{e.message}")
-
if debug
-
$stderr.puts(*e.backtrace)
-
else
-
$stderr.puts(e.backtrace.first)
-
end
-
end
-
end
-
-
1
def user_home
-
@@user_home ||= if ENV["HOME"]
-
ENV["HOME"]
-
elsif ENV["USERPROFILE"]
-
ENV["USERPROFILE"]
-
elsif ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
-
File.join(ENV["HOMEDRIVE"], ENV["HOMEPATH"])
-
elsif ENV["APPDATA"]
-
ENV["APPDATA"]
-
else
-
begin
-
File.expand_path("~")
-
rescue
-
if File::ALT_SEPARATOR
-
"C:/"
-
else
-
"/"
-
end
-
end
-
end
-
end
-
-
# Returns the root where thor files are located, depending on the OS.
-
#
-
1
def thor_root
-
File.join(user_home, ".thor").tr('\\', "/")
-
end
-
-
# Returns the files in the thor root. On Windows thor_root will be something
-
# like this:
-
#
-
# C:\Documents and Settings\james\.thor
-
#
-
# If we don't #gsub the \ character, Dir.glob will fail.
-
#
-
1
def thor_root_glob
-
files = Dir["#{escape_globs(thor_root)}/*"]
-
-
files.map! do |file|
-
File.directory?(file) ? File.join(file, "main.thor") : file
-
end
-
end
-
-
# Where to look for Thor files.
-
#
-
1
def globs_for(path)
-
path = escape_globs(path)
-
["#{path}/Thorfile", "#{path}/*.thor", "#{path}/tasks/*.thor", "#{path}/lib/tasks/*.thor"]
-
end
-
-
# Return the path to the ruby interpreter taking into account multiple
-
# installations and windows extensions.
-
#
-
1
def ruby_command
-
@ruby_command ||= begin
-
ruby_name = RbConfig::CONFIG["ruby_install_name"]
-
ruby = File.join(RbConfig::CONFIG["bindir"], ruby_name)
-
ruby << RbConfig::CONFIG["EXEEXT"]
-
-
# avoid using different name than ruby (on platforms supporting links)
-
if ruby_name != "ruby" && File.respond_to?(:readlink)
-
begin
-
alternate_ruby = File.join(RbConfig::CONFIG["bindir"], "ruby")
-
alternate_ruby << RbConfig::CONFIG["EXEEXT"]
-
-
# ruby is a symlink
-
if File.symlink? alternate_ruby
-
linked_ruby = File.readlink alternate_ruby
-
-
# symlink points to 'ruby_install_name'
-
ruby = alternate_ruby if linked_ruby == ruby_name || linked_ruby == ruby
-
end
-
rescue NotImplementedError # rubocop:disable HandleExceptions
-
# just ignore on windows
-
end
-
end
-
-
# escape string in case path to ruby executable contain spaces.
-
ruby.sub!(/.*\s.*/m, '"\&"')
-
ruby
-
end
-
end
-
-
# Returns a string that has had any glob characters escaped.
-
# The glob characters are `* ? { } [ ]`.
-
#
-
# ==== Examples
-
#
-
# Thor::Util.escape_globs('[apps]') # => '\[apps\]'
-
#
-
# ==== Parameters
-
# String
-
#
-
# ==== Returns
-
# String
-
#
-
1
def escape_globs(path)
-
path.to_s.gsub(/[*?{}\[\]]/, '\\\\\\&')
-
end
-
end
-
end
-
end
-
1
require 'thread_safe/version'
-
1
require 'thread_safe/synchronized_delegator'
-
-
1
module ThreadSafe
-
1
autoload :Cache, 'thread_safe/cache'
-
1
autoload :Util, 'thread_safe/util'
-
-
# Various classes within allows for +nil+ values to be stored, so a special +NULL+ token is required to indicate the "nil-ness".
-
1
NULL = Object.new
-
-
1
if defined?(JRUBY_VERSION)
-
require 'jruby/synchronized'
-
-
# A thread-safe subclass of Array. This version locks
-
# against the object itself for every method call,
-
# ensuring only one thread can be reading or writing
-
# at a time. This includes iteration methods like
-
# #each.
-
class Array < ::Array
-
include JRuby::Synchronized
-
end
-
-
# A thread-safe subclass of Hash. This version locks
-
# against the object itself for every method call,
-
# ensuring only one thread can be reading or writing
-
# at a time. This includes iteration methods like
-
# #each.
-
class Hash < ::Hash
-
include JRuby::Synchronized
-
end
-
elsif !defined?(RUBY_ENGINE) || RUBY_ENGINE == 'ruby'
-
# Because MRI never runs code in parallel, the existing
-
# non-thread-safe structures should usually work fine.
-
1
Array = ::Array
-
1
Hash = ::Hash
-
elsif defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx'
-
require 'monitor'
-
-
class Hash < ::Hash; end
-
class Array < ::Array; end
-
-
[Hash, Array].each do |klass|
-
klass.class_eval do
-
private
-
def _mon_initialize
-
@_monitor = Monitor.new unless @_monitor # avoid double initialisation
-
end
-
-
def self.allocate
-
obj = super
-
obj.send(:_mon_initialize)
-
obj
-
end
-
end
-
-
klass.superclass.instance_methods(false).each do |method|
-
klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{method}(*args)
-
@_monitor.synchronize { super }
-
end
-
RUBY_EVAL
-
end
-
end
-
end
-
end
-
1
require 'thread'
-
-
1
module ThreadSafe
-
1
autoload :JRubyCacheBackend, 'thread_safe/jruby_cache_backend'
-
1
autoload :MriCacheBackend, 'thread_safe/mri_cache_backend'
-
1
autoload :NonConcurrentCacheBackend, 'thread_safe/non_concurrent_cache_backend'
-
1
autoload :AtomicReferenceCacheBackend, 'thread_safe/atomic_reference_cache_backend'
-
1
autoload :SynchronizedCacheBackend, 'thread_safe/synchronized_cache_backend'
-
-
1
ConcurrentCacheBackend = if defined?(RUBY_ENGINE)
-
1
case RUBY_ENGINE
-
when 'jruby'; JRubyCacheBackend
-
1
when 'ruby'; MriCacheBackend
-
when 'rbx'; AtomicReferenceCacheBackend
-
else
-
warn 'ThreadSafe: unsupported Ruby engine, using a fully synchronized ThreadSafe::Cache implementation' if $VERBOSE
-
SynchronizedCacheBackend
-
end
-
else
-
MriCacheBackend
-
end
-
-
1
class Cache < ConcurrentCacheBackend
-
1
def initialize(options = nil, &block)
-
132
if options.kind_of?(::Hash)
-
79
validate_options_hash!(options)
-
else
-
53
options = nil
-
end
-
-
132
super(options)
-
132
@default_proc = block
-
end
-
-
1
def [](key)
-
5657
if value = super # non-falsy value is an existing mapping, return it right away
-
5480
value
-
# re-check is done with get_or_default(key, NULL) instead of a simple !key?(key) in order to avoid a race condition, whereby by the time the current thread gets to the key?(key) call
-
# a key => value mapping might have already been created by a different thread (key?(key) would then return true, this elsif branch wouldn't be taken and an incorrent +nil+ value
-
# would be returned)
-
# note: nil == value check is not technically necessary
-
177
elsif @default_proc && nil == value && NULL == (value = get_or_default(key, NULL))
-
73
@default_proc.call(self, key)
-
else
-
104
value
-
end
-
end
-
-
1
alias_method :get, :[]
-
1
alias_method :put, :[]=
-
-
1
def fetch(key, default_value = NULL)
-
44
if NULL != (value = get_or_default(key, NULL))
-
29
value
-
15
elsif block_given?
-
15
yield key
-
elsif NULL != default_value
-
default_value
-
else
-
raise_fetch_no_key
-
end
-
end
-
-
1
def fetch_or_store(key, default_value = NULL)
-
33
fetch(key) do
-
10
put(key, block_given? ? yield(key) : (NULL == default_value ? raise_fetch_no_key : default_value))
-
end
-
end
-
-
def put_if_absent(key, value)
-
computed = false
-
result = compute_if_absent(key) do
-
computed = true
-
value
-
end
-
computed ? nil : result
-
1
end unless method_defined?(:put_if_absent)
-
-
def value?(value)
-
each_value do |v|
-
return true if value.equal?(v)
-
end
-
false
-
1
end unless method_defined?(:value?)
-
-
def keys
-
arr = []
-
each_pair {|k, v| arr << k}
-
arr
-
1
end unless method_defined?(:keys)
-
-
def values
-
5
arr = []
-
10
each_pair {|k, v| arr << v}
-
5
arr
-
1
end unless method_defined?(:values)
-
-
def each_key
-
each_pair {|k, v| yield k}
-
1
end unless method_defined?(:each_key)
-
-
def each_value
-
each_pair {|k, v| yield v}
-
1
end unless method_defined?(:each_value)
-
-
def key(value)
-
each_pair {|k, v| return k if v == value}
-
nil
-
1
end unless method_defined?(:key)
-
1
alias_method :index, :key if RUBY_VERSION < '1.9'
-
-
def empty?
-
each_pair {|k, v| return false}
-
true
-
1
end unless method_defined?(:empty?)
-
-
def size
-
count = 0
-
each_pair {|k, v| count += 1}
-
count
-
1
end unless method_defined?(:size)
-
-
1
def marshal_dump
-
raise TypeError, "can't dump hash with default proc" if @default_proc
-
h = {}
-
each_pair {|k, v| h[k] = v}
-
h
-
end
-
-
1
def marshal_load(hash)
-
initialize
-
populate_from(hash)
-
end
-
-
1
undef :freeze
-
-
1
private
-
1
def raise_fetch_no_key
-
raise KeyError, 'key not found'
-
end
-
-
1
def initialize_copy(other)
-
super
-
populate_from(other)
-
end
-
-
1
def populate_from(hash)
-
hash.each_pair {|k, v| self[k] = v}
-
self
-
end
-
-
1
def validate_options_hash!(options)
-
79
if (initial_capacity = options[:initial_capacity]) && (!initial_capacity.kind_of?(0.class) || initial_capacity < 0)
-
raise ArgumentError, ":initial_capacity must be a positive #{0.class}"
-
end
-
79
if (load_factor = options[:load_factor]) && (!load_factor.kind_of?(Numeric) || load_factor <= 0 || load_factor > 1)
-
raise ArgumentError, ":load_factor must be a number between 0 and 1"
-
end
-
end
-
end
-
end
-
1
module ThreadSafe
-
1
class MriCacheBackend < NonConcurrentCacheBackend
-
# We can get away with a single global write lock (instead of a per-instance
-
# one) because of the GVL/green threads.
-
#
-
# NOTE: a neat idea of writing a c-ext to manually perform atomic
-
# put_if_absent, while relying on Ruby not releasing a GVL while calling a
-
# c-ext will not work because of the potentially Ruby implemented `#hash`
-
# and `#eql?` key methods.
-
1
WRITE_LOCK = Mutex.new
-
-
1
def []=(key, value)
-
358
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def compute_if_absent(key)
-
63
if stored_value = _get(key) # fast non-blocking path for the most likely case
-
24
stored_value
-
else
-
78
WRITE_LOCK.synchronize { super }
-
end
-
end
-
-
1
def compute_if_present(key)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def compute(key)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def merge_pair(key, value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def replace_pair(key, old_value, new_value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def replace_if_exists(key, new_value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def get_and_set(key, value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def delete(key)
-
2
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def delete_pair(key, value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def clear
-
148
WRITE_LOCK.synchronize { super }
-
end
-
end
-
end
-
1
module ThreadSafe
-
1
class NonConcurrentCacheBackend
-
# WARNING: all public methods of the class must operate on the @backend
-
# directly without calling each other. This is important because of the
-
# SynchronizedCacheBackend which uses a non-reentrant mutex for perfomance
-
# reasons.
-
1
def initialize(options = nil)
-
132
@backend = {}
-
end
-
-
1
def [](key)
-
5720
@backend[key]
-
end
-
-
1
def []=(key, value)
-
179
@backend[key] = value
-
end
-
-
1
def compute_if_absent(key)
-
39
if NULL != (stored_value = @backend.fetch(key, NULL))
-
stored_value
-
else
-
39
@backend[key] = yield
-
end
-
end
-
-
1
def replace_pair(key, old_value, new_value)
-
if pair?(key, old_value)
-
@backend[key] = new_value
-
true
-
else
-
false
-
end
-
end
-
-
1
def replace_if_exists(key, new_value)
-
if NULL != (stored_value = @backend.fetch(key, NULL))
-
@backend[key] = new_value
-
stored_value
-
end
-
end
-
-
1
def compute_if_present(key)
-
if NULL != (stored_value = @backend.fetch(key, NULL))
-
store_computed_value(key, yield(stored_value))
-
end
-
end
-
-
1
def compute(key)
-
store_computed_value(key, yield(@backend[key]))
-
end
-
-
1
def merge_pair(key, value)
-
if NULL == (stored_value = @backend.fetch(key, NULL))
-
@backend[key] = value
-
else
-
store_computed_value(key, yield(stored_value))
-
end
-
end
-
-
1
def get_and_set(key, value)
-
stored_value = @backend[key]
-
@backend[key] = value
-
stored_value
-
end
-
-
1
def key?(key)
-
@backend.key?(key)
-
end
-
-
1
def value?(value)
-
@backend.value?(value)
-
end
-
-
1
def delete(key)
-
1
@backend.delete(key)
-
end
-
-
1
def delete_pair(key, value)
-
if pair?(key, value)
-
@backend.delete(key)
-
true
-
else
-
false
-
end
-
end
-
-
1
def clear
-
74
@backend.clear
-
74
self
-
end
-
-
1
def each_pair
-
5
dupped_backend.each_pair do |k, v|
-
5
yield k, v
-
end
-
5
self
-
end
-
-
1
def size
-
@backend.size
-
end
-
-
1
def get_or_default(key, default_value)
-
117
@backend.fetch(key, default_value)
-
end
-
-
1
alias_method :_get, :[]
-
1
alias_method :_set, :[]=
-
1
private :_get, :_set
-
1
private
-
1
def initialize_copy(other)
-
super
-
@backend = {}
-
self
-
end
-
-
1
def dupped_backend
-
5
@backend.dup
-
end
-
-
1
def pair?(key, expected_value)
-
NULL != (stored_value = @backend.fetch(key, NULL)) && expected_value.equal?(stored_value)
-
end
-
-
1
def store_computed_value(key, new_value)
-
if new_value.nil?
-
@backend.delete(key)
-
nil
-
else
-
@backend[key] = new_value
-
end
-
end
-
end
-
end
-
1
require 'delegate'
-
1
require 'monitor'
-
-
# This class provides a trivial way to synchronize all calls to a given object
-
# by wrapping it with a `Delegator` that performs `Monitor#enter/exit` calls
-
# around the delegated `#send`. Example:
-
#
-
# array = [] # not thread-safe on many impls
-
# array = SynchronizedDelegator.new([]) # thread-safe
-
#
-
# A simple `Monitor` provides a very coarse-grained way to synchronize a given
-
# object, in that it will cause synchronization for methods that have no need
-
# for it, but this is a trivial way to get thread-safety where none may exist
-
# currently on some implementations.
-
#
-
# This class is currently being considered for inclusion into stdlib, via
-
# https://bugs.ruby-lang.org/issues/8556
-
class SynchronizedDelegator < SimpleDelegator
-
1
def setup
-
@old_abort = Thread.abort_on_exception
-
Thread.abort_on_exception = true
-
end
-
-
1
def teardown
-
Thread.abort_on_exception = @old_abort
-
end
-
-
1
def initialize(obj)
-
__setobj__(obj)
-
@monitor = Monitor.new
-
end
-
-
1
def method_missing(method, *args, &block)
-
monitor = @monitor
-
begin
-
monitor.enter
-
super
-
ensure
-
monitor.exit
-
end
-
end
-
-
1
end unless defined?(SynchronizedDelegator)
-
1
module ThreadSafe
-
1
VERSION = "0.3.6"
-
end
-
-
# NOTE: <= 0.2.0 used Threadsafe::VERSION
-
# @private
-
1
module Threadsafe
-
-
# @private
-
1
def self.const_missing(name)
-
name = name.to_sym
-
if ThreadSafe.const_defined?(name)
-
warn "[DEPRECATION] `Threadsafe::#{name}' is deprecated, use `ThreadSafe::#{name}' instead."
-
ThreadSafe.const_get(name)
-
else
-
warn "[DEPRECATION] the `Threadsafe' module is deprecated, please use `ThreadSafe` instead."
-
super
-
end
-
end
-
-
end
-
1
require 'tilt/mapping'
-
1
require 'tilt/template'
-
-
# Namespace for Tilt. This module is not intended to be included anywhere.
-
1
module Tilt
-
# Current version.
-
1
VERSION = '2.0.7'
-
-
1
@default_mapping = Mapping.new
-
-
# @return [Tilt::Mapping] the main mapping object
-
1
def self.default_mapping
-
42
@default_mapping
-
end
-
-
# @private
-
1
def self.lazy_map
-
default_mapping.lazy_map
-
end
-
-
# @see Tilt::Mapping#register
-
1
def self.register(template_class, *extensions)
-
default_mapping.register(template_class, *extensions)
-
end
-
-
# @see Tilt::Mapping#register_lazy
-
1
def self.register_lazy(class_name, file, *extensions)
-
42
default_mapping.register_lazy(class_name, file, *extensions)
-
end
-
-
# @deprecated Use {register} instead.
-
1
def self.prefer(template_class, *extensions)
-
register(template_class, *extensions)
-
end
-
-
# @see Tilt::Mapping#registered?
-
1
def self.registered?(ext)
-
default_mapping.registered?(ext)
-
end
-
-
# @see Tilt::Mapping#new
-
1
def self.new(file, line=nil, options={}, &block)
-
default_mapping.new(file, line, options, &block)
-
end
-
-
# @see Tilt::Mapping#[]
-
1
def self.[](file)
-
default_mapping[file]
-
end
-
-
# @see Tilt::Mapping#template_for
-
1
def self.template_for(file)
-
default_mapping.template_for(file)
-
end
-
-
# @see Tilt::Mapping#templates_for
-
1
def self.templates_for(file)
-
default_mapping.templates_for(file)
-
end
-
-
# @return the template object that is currently rendering.
-
#
-
# @example
-
# tmpl = Tilt['index.erb'].new { '<%= Tilt.current_template %>' }
-
# tmpl.render == tmpl.to_s
-
#
-
# @note This is currently an experimental feature and might return nil
-
# in the future.
-
1
def self.current_template
-
Thread.current[:tilt_current_template]
-
end
-
-
# Extremely simple template cache implementation. Calling applications
-
# create a Tilt::Cache instance and use #fetch with any set of hashable
-
# arguments (such as those to Tilt.new):
-
#
-
# cache = Tilt::Cache.new
-
# cache.fetch(path, line, options) { Tilt.new(path, line, options) }
-
#
-
# Subsequent invocations return the already loaded template object.
-
#
-
# @note
-
# Tilt::Cache is a thin wrapper around Hash. It has the following
-
# limitations:
-
# * Not thread-safe.
-
# * Size is unbounded.
-
# * Keys are not copied defensively, and should not be modified after
-
# being passed to #fetch. More specifically, the values returned by
-
# key#hash and key#eql? should not change.
-
# If this is too limiting for you, use a different cache implementation.
-
1
class Cache
-
1
def initialize
-
@cache = {}
-
end
-
-
# Caches a value for key, or returns the previously cached value.
-
# If a value has been previously cached for key then it is
-
# returned. Otherwise, block is yielded to and its return value
-
# which may be nil, is cached under key and returned.
-
# @yield
-
# @yieldreturn the value to cache for key
-
1
def fetch(*key)
-
@cache.fetch(key) do
-
@cache[key] = yield
-
end
-
end
-
-
# Clears the cache.
-
1
def clear
-
@cache = {}
-
end
-
end
-
-
-
# Template Implementations ================================================
-
-
# ERB
-
1
register_lazy :ERBTemplate, 'tilt/erb', 'erb', 'rhtml'
-
1
register_lazy :ErubisTemplate, 'tilt/erubis', 'erb', 'rhtml', 'erubis'
-
1
register_lazy :ErubiTemplate, 'tilt/erubi', 'erb', 'rhtml', 'erubi'
-
-
# Markdown
-
1
register_lazy :BlueClothTemplate, 'tilt/bluecloth', 'markdown', 'mkd', 'md'
-
1
register_lazy :MarukuTemplate, 'tilt/maruku', 'markdown', 'mkd', 'md'
-
1
register_lazy :KramdownTemplate, 'tilt/kramdown', 'markdown', 'mkd', 'md'
-
1
register_lazy :RDiscountTemplate, 'tilt/rdiscount', 'markdown', 'mkd', 'md'
-
1
register_lazy :RedcarpetTemplate, 'tilt/redcarpet', 'markdown', 'mkd', 'md'
-
1
register_lazy :CommonMarkerTemplate, 'tilt/commonmarker', 'markdown', 'mkd', 'md'
-
1
register_lazy :PandocTemplate, 'tilt/pandoc', 'markdown', 'mkd', 'md'
-
-
# Rest (sorted by name)
-
1
register_lazy :AsciidoctorTemplate, 'tilt/asciidoc', 'ad', 'adoc', 'asciidoc'
-
1
register_lazy :BabelTemplate, 'tilt/babel', 'es6', 'babel', 'jsx'
-
1
register_lazy :BuilderTemplate, 'tilt/builder', 'builder'
-
1
register_lazy :CSVTemplate, 'tilt/csv', 'rcsv'
-
1
register_lazy :CoffeeScriptTemplate, 'tilt/coffee', 'coffee'
-
1
register_lazy :CoffeeScriptLiterateTemplate, 'tilt/coffee', 'litcoffee'
-
1
register_lazy :CreoleTemplate, 'tilt/creole', 'wiki', 'creole'
-
1
register_lazy :EtanniTemplate, 'tilt/etanni', 'etn', 'etanni'
-
1
register_lazy :HamlTemplate, 'tilt/haml', 'haml'
-
1
register_lazy :LessTemplate, 'tilt/less', 'less'
-
1
register_lazy :LiquidTemplate, 'tilt/liquid', 'liquid'
-
1
register_lazy :LiveScriptTemplate, 'tilt/livescript','ls'
-
1
register_lazy :MarkabyTemplate, 'tilt/markaby', 'mab'
-
1
register_lazy :NokogiriTemplate, 'tilt/nokogiri', 'nokogiri'
-
1
register_lazy :PlainTemplate, 'tilt/plain', 'html'
-
1
register_lazy :PrawnTemplate, 'tilt/prawn', 'prawn'
-
1
register_lazy :RDocTemplate, 'tilt/rdoc', 'rdoc'
-
1
register_lazy :RadiusTemplate, 'tilt/radius', 'radius'
-
1
register_lazy :RedClothTemplate, 'tilt/redcloth', 'textile'
-
1
register_lazy :RstPandocTemplate, 'tilt/rst-pandoc', 'rst'
-
1
register_lazy :SassTemplate, 'tilt/sass', 'sass'
-
1
register_lazy :ScssTemplate, 'tilt/sass', 'scss'
-
1
register_lazy :SigilTemplate, 'tilt/sigil', 'sigil'
-
1
register_lazy :StringTemplate, 'tilt/string', 'str'
-
1
register_lazy :TypeScriptTemplate, 'tilt/typescript', 'ts'
-
1
register_lazy :WikiClothTemplate, 'tilt/wikicloth', 'wiki', 'mediawiki', 'mw'
-
1
register_lazy :YajlTemplate, 'tilt/yajl', 'yajl'
-
-
# External template engines
-
1
register_lazy 'Slim::Template', 'slim', 'slim'
-
1
register_lazy 'Tilt::HandlebarsTemplate', 'tilt/handlebars', 'handlebars', 'hbs'
-
1
register_lazy 'Tilt::OrgTemplate', 'org-ruby', 'org'
-
1
register_lazy 'Opal::Processor', 'opal', 'opal', 'rb'
-
1
register_lazy 'Tilt::JbuilderTemplate', 'tilt/jbuilder', 'jbuilder'
-
end
-
# Used for detecting autoloading bug in JRuby
-
1
class Tilt::Dummy; end
-
-
1
require 'tilt/template'
-
1
require 'erb'
-
-
1
module Tilt
-
# ERB template implementation. See:
-
# http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html
-
1
class ERBTemplate < Template
-
1
@@default_output_variable = '_erbout'
-
-
1
def self.default_output_variable
-
@@default_output_variable
-
end
-
-
1
def self.default_output_variable=(name)
-
warn "#{self}.default_output_variable= has been replaced with the :outvar-option"
-
@@default_output_variable = name
-
end
-
-
1
def prepare
-
@outvar = options[:outvar] || self.class.default_output_variable
-
options[:trim] = '<>' if !(options[:trim] == false) && (options[:trim].nil? || options[:trim] == true)
-
@engine = ::ERB.new(data, options[:safe], options[:trim], @outvar)
-
end
-
-
1
def precompiled_template(locals)
-
source = @engine.src
-
source
-
end
-
-
1
def precompiled_preamble(locals)
-
<<-RUBY
-
begin
-
__original_outvar = #{@outvar} if defined?(#{@outvar})
-
#{super}
-
RUBY
-
end
-
-
1
def precompiled_postamble(locals)
-
<<-RUBY
-
#{super}
-
ensure
-
#{@outvar} = __original_outvar
-
end
-
RUBY
-
end
-
-
# ERB generates a line to specify the character coding of the generated
-
# source in 1.9. Account for this in the line offset.
-
1
if RUBY_VERSION >= '1.9.0'
-
1
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
end
-
end
-
end
-
-
1
require 'tilt/erb'
-
1
require 'erubis'
-
-
1
module Tilt
-
# Erubis template implementation. See:
-
# http://www.kuwata-lab.com/erubis/
-
#
-
# ErubisTemplate supports the following additional options, which are not
-
# passed down to the Erubis engine:
-
#
-
# :engine_class allows you to specify a custom engine class to use
-
# instead of the default (which is ::Erubis::Eruby).
-
#
-
# :escape_html when true, ::Erubis::EscapedEruby will be used as
-
# the engine class instead of the default. All content
-
# within <%= %> blocks will be automatically html escaped.
-
1
class ErubisTemplate < ERBTemplate
-
1
def prepare
-
@outvar = options.delete(:outvar) || self.class.default_output_variable
-
@options.merge!(:preamble => false, :postamble => false, :bufvar => @outvar)
-
engine_class = options.delete(:engine_class)
-
engine_class = ::Erubis::EscapedEruby if options.delete(:escape_html)
-
@engine = (engine_class || ::Erubis::Eruby).new(data, options)
-
end
-
-
1
def precompiled_preamble(locals)
-
[super, "#{@outvar} = _buf = String.new"].join("\n")
-
end
-
-
1
def precompiled_postamble(locals)
-
[@outvar, super].join("\n")
-
end
-
-
# Erubis doesn't have ERB's line-off-by-one under 1.9 problem.
-
# Override and adjust back.
-
1
if RUBY_VERSION >= '1.9.0'
-
1
def precompiled(locals)
-
source, offset = super
-
[source, offset - 1]
-
end
-
end
-
end
-
end
-
1
require 'monitor'
-
-
1
module Tilt
-
# Tilt::Mapping associates file extensions with template implementations.
-
#
-
# mapping = Tilt::Mapping.new
-
# mapping.register(Tilt::RDocTemplate, 'rdoc')
-
# mapping['index.rdoc'] # => Tilt::RDocTemplate
-
# mapping.new('index.rdoc').render
-
#
-
# You can use {#register} to register a template class by file
-
# extension, {#registered?} to see if a file extension is mapped,
-
# {#[]} to lookup template classes, and {#new} to instantiate template
-
# objects.
-
#
-
# Mapping also supports *lazy* template implementations. Note that regularly
-
# registered template implementations *always* have preference over lazily
-
# registered template implementations. You should use {#register} if you
-
# depend on a specific template implementation and {#register_lazy} if there
-
# are multiple alternatives.
-
#
-
# mapping = Tilt::Mapping.new
-
# mapping.register_lazy('RDiscount::Template', 'rdiscount/template', 'md')
-
# mapping['index.md']
-
# # => RDiscount::Template
-
#
-
# {#register_lazy} takes a class name, a filename, and a list of file
-
# extensions. When you try to lookup a template name that matches the
-
# file extension, Tilt will automatically try to require the filename and
-
# constantize the class name.
-
#
-
# Unlike {#register}, there can be multiple template implementations
-
# registered lazily to the same file extension. Tilt will attempt to load the
-
# template implementations in order (registered *last* would be tried first),
-
# returning the first which doesn't raise LoadError.
-
#
-
# If all of the registered template implementations fails, Tilt will raise
-
# the exception of the first, since that was the most preferred one.
-
#
-
# mapping = Tilt::Mapping.new
-
# mapping.register_lazy('Bluecloth::Template', 'bluecloth/template', 'md')
-
# mapping.register_lazy('RDiscount::Template', 'rdiscount/template', 'md')
-
# mapping['index.md']
-
# # => RDiscount::Template
-
#
-
# In the previous example we say that RDiscount has a *higher priority* than
-
# BlueCloth. Tilt will first try to `require "rdiscount/template"`, falling
-
# back to `require "bluecloth/template"`. If none of these are successful,
-
# the first error will be raised.
-
1
class Mapping
-
# @private
-
1
attr_reader :lazy_map, :template_map
-
-
1
def initialize
-
1
@template_map = Hash.new
-
49
@lazy_map = Hash.new { |h, k| h[k] = [] }
-
end
-
-
# @private
-
1
def initialize_copy(other)
-
@template_map = other.template_map.dup
-
@lazy_map = other.lazy_map.dup
-
end
-
-
# Registers a lazy template implementation by file extension. You
-
# can have multiple lazy template implementations defined on the
-
# same file extension, in which case the template implementation
-
# defined *last* will be attempted loaded *first*.
-
#
-
# @param class_name [String] Class name of a template class.
-
# @param file [String] Filename where the template class is defined.
-
# @param extensions [Array<String>] List of extensions.
-
# @return [void]
-
#
-
# @example
-
# mapping.register_lazy 'MyEngine::Template', 'my_engine/template', 'mt'
-
#
-
# defined?(MyEngine::Template) # => false
-
# mapping['index.mt'] # => MyEngine::Template
-
# defined?(MyEngine::Template) # => true
-
1
def register_lazy(class_name, file, *extensions)
-
# Internal API
-
42
if class_name.is_a?(Symbol)
-
37
Tilt.autoload class_name, file
-
37
class_name = "Tilt::#{class_name}"
-
end
-
-
42
extensions.each do |ext|
-
71
@lazy_map[ext].unshift([class_name, file])
-
end
-
end
-
-
# Registers a template implementation by file extension. There can only be
-
# one template implementation per file extension, and this method will
-
# override any existing mapping.
-
#
-
# @param template_class
-
# @param extensions [Array<String>] List of extensions.
-
# @return [void]
-
#
-
# @example
-
# mapping.register MyEngine::Template, 'mt'
-
# mapping['index.mt'] # => MyEngine::Template
-
1
def register(template_class, *extensions)
-
if template_class.respond_to?(:to_str)
-
# Support register(ext, template_class) too
-
extensions, template_class = [template_class], extensions[0]
-
end
-
-
extensions.each do |ext|
-
@template_map[ext.to_s] = template_class
-
end
-
end
-
-
# Checks if a file extension is registered (either eagerly or
-
# lazily) in this mapping.
-
#
-
# @param ext [String] File extension.
-
#
-
# @example
-
# mapping.registered?('erb') # => true
-
# mapping.registered?('nope') # => false
-
1
def registered?(ext)
-
@template_map.has_key?(ext.downcase) or lazy?(ext)
-
end
-
-
# Instantiates a new template class based on the file.
-
#
-
# @raise [RuntimeError] if there is no template class registered for the
-
# file name.
-
#
-
# @example
-
# mapping.new('index.mt') # => instance of MyEngine::Template
-
#
-
# @see Tilt::Template.new
-
1
def new(file, line=nil, options={}, &block)
-
if template_class = self[file]
-
template_class.new(file, line, options, &block)
-
else
-
fail "No template engine registered for #{File.basename(file)}"
-
end
-
end
-
-
# Looks up a template class based on file name and/or extension.
-
#
-
# @example
-
# mapping['views/hello.erb'] # => Tilt::ERBTemplate
-
# mapping['hello.erb'] # => Tilt::ERBTemplate
-
# mapping['erb'] # => Tilt::ERBTemplate
-
#
-
# @return [template class]
-
1
def [](file)
-
_, ext = split(file)
-
ext && lookup(ext)
-
end
-
-
1
alias template_for []
-
-
# Looks up a list of template classes based on file name. If the file name
-
# has multiple extensions, it will return all template classes matching the
-
# extensions from the end.
-
#
-
# @example
-
# mapping.templates_for('views/index.haml.erb')
-
# # => [Tilt::ERBTemplate, Tilt::HamlTemplate]
-
#
-
# @return [Array<template class>]
-
1
def templates_for(file)
-
templates = []
-
-
while true
-
prefix, ext = split(file)
-
break unless ext
-
templates << lookup(ext)
-
file = prefix
-
end
-
-
templates
-
end
-
-
# Finds the extensions the template class has been registered under.
-
# @param [template class] template_class
-
1
def extensions_for(template_class)
-
res = []
-
template_map.each do |ext, klass|
-
res << ext if template_class == klass
-
end
-
lazy_map.each do |ext, choices|
-
res << ext if choices.any? { |klass, file| template_class.to_s == klass }
-
end
-
res
-
end
-
-
1
private
-
-
1
def lazy?(ext)
-
ext = ext.downcase
-
@lazy_map.has_key?(ext) && !@lazy_map[ext].empty?
-
end
-
-
1
def split(file)
-
pattern = file.to_s.downcase
-
full_pattern = pattern.dup
-
-
until registered?(pattern)
-
return if pattern.empty?
-
pattern = File.basename(pattern)
-
pattern.sub!(/^[^.]*\.?/, '')
-
end
-
-
prefix_size = full_pattern.size - pattern.size
-
[full_pattern[0,prefix_size-1], pattern]
-
end
-
-
1
def lookup(ext)
-
@template_map[ext] || lazy_load(ext)
-
end
-
-
1
LOCK = Monitor.new
-
-
1
def lazy_load(pattern)
-
return unless @lazy_map.has_key?(pattern)
-
-
LOCK.enter
-
entered = true
-
-
choices = @lazy_map[pattern]
-
-
# Check if a template class is already present
-
choices.each do |class_name, file|
-
template_class = constant_defined?(class_name)
-
if template_class
-
register(template_class, pattern)
-
return template_class
-
end
-
end
-
-
first_failure = nil
-
-
# Load in order
-
choices.each do |class_name, file|
-
begin
-
require file
-
# It's safe to eval() here because constant_defined? will
-
# raise NameError on invalid constant names
-
template_class = eval(class_name)
-
rescue LoadError => ex
-
first_failure ||= ex
-
else
-
register(template_class, pattern)
-
return template_class
-
end
-
end
-
-
raise first_failure if first_failure
-
ensure
-
LOCK.exit if entered
-
end
-
-
# This is due to a bug in JRuby (see GH issue jruby/jruby#3585)
-
1
Tilt.autoload :Dummy, "tilt/dummy"
-
1
require "tilt/dummy"
-
1
AUTOLOAD_IS_BROKEN = Tilt.autoload?(:Dummy)
-
-
# The proper behavior (in MRI) for autoload? is to
-
# return `false` when the constant/file has been
-
# explicitly required.
-
#
-
# However, in JRuby it returns `true` even after it's
-
# been required. In that case it turns out that `defined?`
-
# returns `"constant"` if it exists and `nil` when it doesn't.
-
# This is actually a second bug: `defined?` should resolve
-
# autoload (aka. actually try to require the file).
-
#
-
# We use the second bug in order to resolve the first bug.
-
-
1
def constant_defined?(name)
-
name.split('::').inject(Object) do |scope, n|
-
if scope.autoload?(n)
-
if !AUTOLOAD_IS_BROKEN
-
return false
-
end
-
-
if eval("!defined?(scope::#{n})")
-
return false
-
end
-
end
-
return false if !scope.const_defined?(n)
-
scope.const_get(n)
-
end
-
end
-
end
-
end
-
1
require 'thread'
-
-
1
module Tilt
-
# @private
-
1
TOPOBJECT = if RUBY_VERSION >= '2.0'
-
# @private
-
1
module CompiledTemplates
-
1
self
-
end
-
elsif RUBY_VERSION >= '1.9'
-
BasicObject
-
else
-
Object
-
end
-
# @private
-
1
LOCK = Mutex.new
-
-
# Base class for template implementations. Subclasses must implement
-
# the #prepare method and one of the #evaluate or #precompiled_template
-
# methods.
-
1
class Template
-
# Template source; loaded from a file or given directly.
-
1
attr_reader :data
-
-
# The name of the file where the template data was loaded from.
-
1
attr_reader :file
-
-
# The line number in #file where template data was loaded from.
-
1
attr_reader :line
-
-
# A Hash of template engine specific options. This is passed directly
-
# to the underlying engine and is not used by the generic template
-
# interface.
-
1
attr_reader :options
-
-
1
class << self
-
# An empty Hash that the template engine can populate with various
-
# metadata.
-
1
def metadata
-
@metadata ||= {}
-
end
-
-
# @deprecated Use `.metadata[:mime_type]` instead.
-
1
def default_mime_type
-
metadata[:mime_type]
-
end
-
-
# @deprecated Use `.metadata[:mime_type] = val` instead.
-
1
def default_mime_type=(value)
-
metadata[:mime_type] = value
-
end
-
end
-
-
# Create a new template with the file, line, and options specified. By
-
# default, template data is read from the file. When a block is given,
-
# it should read template data and return as a String. When file is nil,
-
# a block is required.
-
#
-
# All arguments are optional.
-
1
def initialize(file=nil, line=1, options={}, &block)
-
@file, @line, @options = nil, 1, {}
-
-
[options, line, file].compact.each do |arg|
-
case
-
when arg.respond_to?(:to_str) ; @file = arg.to_str
-
when arg.respond_to?(:to_int) ; @line = arg.to_int
-
when arg.respond_to?(:to_hash) ; @options = arg.to_hash.dup
-
when arg.respond_to?(:path) ; @file = arg.path
-
when arg.respond_to?(:to_path) ; @file = arg.to_path
-
else raise TypeError, "Can't load the template file. Pass a string with a path " +
-
"or an object that responds to 'to_str', 'path' or 'to_path'"
-
end
-
end
-
-
raise ArgumentError, "file or block required" if (@file || block).nil?
-
-
# used to hold compiled template methods
-
@compiled_method = {}
-
-
# used on 1.9 to set the encoding if it is not set elsewhere (like a magic comment)
-
# currently only used if template compiles to ruby
-
@default_encoding = @options.delete :default_encoding
-
-
# load template data and prepare (uses binread to avoid encoding issues)
-
@reader = block || lambda { |t| read_template_file }
-
@data = @reader.call(self)
-
-
if @data.respond_to?(:force_encoding)
-
if default_encoding
-
@data = @data.dup if @data.frozen?
-
@data.force_encoding(default_encoding)
-
end
-
-
if !@data.valid_encoding?
-
raise Encoding::InvalidByteSequenceError, "#{eval_file} is not valid #{@data.encoding}"
-
end
-
end
-
-
prepare
-
end
-
-
# Render the template in the given scope with the locals specified. If a
-
# block is given, it is typically available within the template via
-
# +yield+.
-
1
def render(scope=nil, locals={}, &block)
-
scope ||= Object.new
-
current_template = Thread.current[:tilt_current_template]
-
Thread.current[:tilt_current_template] = self
-
evaluate(scope, locals || {}, &block)
-
ensure
-
Thread.current[:tilt_current_template] = current_template
-
end
-
-
# The basename of the template file.
-
1
def basename(suffix='')
-
File.basename(file, suffix) if file
-
end
-
-
# The template file's basename with all extensions chomped off.
-
1
def name
-
basename.split('.', 2).first if basename
-
end
-
-
# The filename used in backtraces to describe the template.
-
1
def eval_file
-
file || '(__TEMPLATE__)'
-
end
-
-
# An empty Hash that the template engine can populate with various
-
# metadata.
-
1
def metadata
-
if respond_to?(:allows_script?)
-
self.class.metadata.merge(:allows_script => allows_script?)
-
else
-
self.class.metadata
-
end
-
end
-
-
1
protected
-
-
# @!group For template implementations
-
-
# The encoding of the source data. Defaults to the
-
# default_encoding-option if present. You may override this method
-
# in your template class if you have a better hint of the data's
-
# encoding.
-
1
def default_encoding
-
@default_encoding
-
end
-
-
# Do whatever preparation is necessary to setup the underlying template
-
# engine. Called immediately after template data is loaded. Instance
-
# variables set in this method are available when #evaluate is called.
-
#
-
# Subclasses must provide an implementation of this method.
-
1
def prepare
-
raise NotImplementedError
-
end
-
-
# Execute the compiled template and return the result string. Template
-
# evaluation is guaranteed to be performed in the scope object with the
-
# locals specified and with support for yielding to the block.
-
#
-
# This method is only used by source generating templates. Subclasses that
-
# override render() may not support all features.
-
1
def evaluate(scope, locals, &block)
-
locals_keys = locals.keys
-
locals_keys.sort!{|x, y| x.to_s <=> y.to_s}
-
method = compiled_method(locals_keys)
-
method.bind(scope).call(locals, &block)
-
end
-
-
# Generates all template source by combining the preamble, template, and
-
# postamble and returns a two-tuple of the form: [source, offset], where
-
# source is the string containing (Ruby) source code for the template and
-
# offset is the integer line offset where line reporting should begin.
-
#
-
# Template subclasses may override this method when they need complete
-
# control over source generation or want to adjust the default line
-
# offset. In most cases, overriding the #precompiled_template method is
-
# easier and more appropriate.
-
1
def precompiled(local_keys)
-
preamble = precompiled_preamble(local_keys)
-
template = precompiled_template(local_keys)
-
postamble = precompiled_postamble(local_keys)
-
source = String.new
-
-
# Ensure that our generated source code has the same encoding as the
-
# the source code generated by the template engine.
-
if source.respond_to?(:force_encoding)
-
template_encoding = extract_encoding(template)
-
-
source.force_encoding(template_encoding)
-
template.force_encoding(template_encoding)
-
end
-
-
source << preamble << "\n" << template << "\n" << postamble
-
-
[source, preamble.count("\n")+1]
-
end
-
-
# A string containing the (Ruby) source code for the template. The
-
# default Template#evaluate implementation requires either this
-
# method or the #precompiled method be overridden. When defined,
-
# the base Template guarantees correct file/line handling, locals
-
# support, custom scopes, proper encoding, and support for template
-
# compilation.
-
1
def precompiled_template(local_keys)
-
raise NotImplementedError
-
end
-
-
1
def precompiled_preamble(local_keys)
-
''
-
end
-
-
1
def precompiled_postamble(local_keys)
-
''
-
end
-
-
# !@endgroup
-
-
1
private
-
-
1
def read_template_file
-
data = File.open(file, 'rb') { |io| io.read }
-
if data.respond_to?(:force_encoding)
-
# Set it to the default external (without verifying)
-
data.force_encoding(Encoding.default_external) if Encoding.default_external
-
end
-
data
-
end
-
-
# The compiled method for the locals keys provided.
-
1
def compiled_method(locals_keys)
-
LOCK.synchronize do
-
@compiled_method[locals_keys] ||= compile_template_method(locals_keys)
-
end
-
end
-
-
1
def local_extraction(local_keys)
-
local_keys.map do |k|
-
if k.to_s =~ /\A[a-z_][a-zA-Z_0-9]*\z/
-
"#{k} = locals[#{k.inspect}]"
-
else
-
raise "invalid locals key: #{k.inspect} (keys must be variable names)"
-
end
-
end.join("\n")
-
end
-
-
1
def compile_template_method(local_keys)
-
source, offset = precompiled(local_keys)
-
local_code = local_extraction(local_keys)
-
-
method_name = "__tilt_#{Thread.current.object_id.abs}"
-
method_source = String.new
-
-
if method_source.respond_to?(:force_encoding)
-
method_source.force_encoding(source.encoding)
-
end
-
-
method_source << <<-RUBY
-
TOPOBJECT.class_eval do
-
def #{method_name}(locals)
-
Thread.current[:tilt_vars] = [self, locals]
-
class << self
-
this, locals = Thread.current[:tilt_vars]
-
this.instance_eval do
-
#{local_code}
-
RUBY
-
offset += method_source.count("\n")
-
method_source << source
-
method_source << "\nend;end;end;end"
-
Object.class_eval(method_source, eval_file, line - offset)
-
unbind_compiled_method(method_name)
-
end
-
-
1
def unbind_compiled_method(method_name)
-
method = TOPOBJECT.instance_method(method_name)
-
TOPOBJECT.class_eval { remove_method(method_name) }
-
method
-
end
-
-
1
def extract_encoding(script)
-
extract_magic_comment(script) || script.encoding
-
end
-
-
1
def extract_magic_comment(script)
-
binary(script) do
-
script[/\A[ \t]*\#.*coding\s*[=:]\s*([[:alnum:]\-_]+).*$/n, 1]
-
end
-
end
-
-
1
def binary(string)
-
original_encoding = string.encoding
-
string.force_encoding(Encoding::BINARY)
-
yield
-
ensure
-
string.force_encoding(original_encoding)
-
end
-
end
-
end
-
1
require 'turbolinks/version'
-
1
require 'turbolinks/redirection'
-
1
require 'turbolinks/source'
-
-
1
module Turbolinks
-
1
module Controller
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
include Redirection
-
end
-
end
-
-
1
class Engine < ::Rails::Engine
-
1
config.turbolinks = ActiveSupport::OrderedOptions.new
-
1
config.turbolinks.auto_include = true
-
1
config.assets.paths += [Turbolinks::Source.asset_path]
-
-
1
initializer :turbolinks do |app|
-
1
ActiveSupport.on_load(:action_controller) do
-
1
if app.config.turbolinks.auto_include
-
1
include Controller
-
end
-
end
-
end
-
end
-
end
-
1
module Turbolinks
-
1
module Redirection
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
before_action :set_turbolinks_location_header_from_session if respond_to?(:before_action)
-
end
-
-
1
def redirect_to(url = {}, options = {})
-
11
turbolinks = options.delete(:turbolinks)
-
-
11
super.tap do
-
11
if turbolinks != false && request.xhr? && !request.get?
-
visit_location_with_turbolinks(location, turbolinks)
-
else
-
11
if request.headers["Turbolinks-Referrer"]
-
store_turbolinks_location_in_session(location)
-
end
-
end
-
end
-
end
-
-
1
private
-
1
def visit_location_with_turbolinks(location, action)
-
visit_options = {
-
action: action.to_s == "advance" ? action : "replace"
-
}
-
-
script = []
-
script << "Turbolinks.clearCache()"
-
script << "Turbolinks.visit(#{location.to_json}, #{visit_options.to_json})"
-
-
self.status = 200
-
self.response_body = script.join("\n")
-
response.content_type = "text/javascript"
-
end
-
-
1
def store_turbolinks_location_in_session(location)
-
session[:_turbolinks_location] = location if session
-
end
-
-
1
def set_turbolinks_location_header_from_session
-
66
if session && session[:_turbolinks_location]
-
response.headers["Turbolinks-Location"] = session.delete(:_turbolinks_location)
-
end
-
end
-
end
-
end
-
1
module Turbolinks
-
1
VERSION = '5.0.1'
-
end
-
1
require 'turbolinks/source/version'
-
-
1
module Turbolinks
-
1
module Source
-
1
def self.asset_path
-
1
File.expand_path("../../assets/javascripts", __FILE__)
-
end
-
end
-
end
-
1
module Turbolinks
-
1
module Source
-
1
VERSION = "5.0.3"
-
end
-
end
-
# Top level module for TZInfo.
-
1
module TZInfo
-
end
-
-
1
require 'tzinfo/ruby_core_support'
-
1
require 'tzinfo/offset_rationals'
-
1
require 'tzinfo/time_or_datetime'
-
-
1
require 'tzinfo/timezone_definition'
-
-
1
require 'tzinfo/timezone_offset'
-
1
require 'tzinfo/timezone_transition'
-
1
require 'tzinfo/timezone_transition_definition'
-
-
1
require 'tzinfo/timezone_index_definition'
-
-
1
require 'tzinfo/timezone_info'
-
1
require 'tzinfo/data_timezone_info'
-
1
require 'tzinfo/linked_timezone_info'
-
1
require 'tzinfo/transition_data_timezone_info'
-
1
require 'tzinfo/zoneinfo_timezone_info'
-
-
1
require 'tzinfo/data_source'
-
1
require 'tzinfo/ruby_data_source'
-
1
require 'tzinfo/zoneinfo_data_source'
-
-
1
require 'tzinfo/timezone_period'
-
1
require 'tzinfo/timezone'
-
1
require 'tzinfo/info_timezone'
-
1
require 'tzinfo/data_timezone'
-
1
require 'tzinfo/linked_timezone'
-
1
require 'tzinfo/timezone_proxy'
-
-
1
require 'tzinfo/country_index_definition'
-
1
require 'tzinfo/country_info'
-
1
require 'tzinfo/ruby_country_info'
-
1
require 'tzinfo/zoneinfo_country_info'
-
-
1
require 'tzinfo/country'
-
1
require 'tzinfo/country_timezone'
-
1
require 'thread_safe'
-
-
1
module TZInfo
-
# Raised by Country#get if the code given is not valid.
-
1
class InvalidCountryCode < StandardError
-
end
-
-
# The Country class represents an ISO 3166-1 country. It can be used to
-
# obtain a list of Timezones for a country. For example:
-
#
-
# us = Country.get('US')
-
# us.zone_identifiers
-
# us.zones
-
# us.zone_info
-
#
-
# The Country class is thread-safe. It is safe to use class and instance
-
# methods of Country in concurrently executing threads. Instances of Country
-
# can be shared across thread boundaries.
-
#
-
# Country information available through TZInfo is intended as an aid for
-
# users, to help them select time zone data appropriate for their practical
-
# needs. It is not intended to take or endorse any position on legal or
-
# territorial claims.
-
1
class Country
-
1
include Comparable
-
-
# Defined countries.
-
#
-
# @!visibility private
-
1
@@countries = nil
-
-
# Whether the countries index has been loaded yet.
-
#
-
# @!visibility private
-
1
@@index_loaded = false
-
-
# Gets a Country by its ISO 3166-1 alpha-2 code. Raises an
-
# InvalidCountryCode exception if it couldn't be found.
-
1
def self.get(identifier)
-
instance = @@countries[identifier]
-
-
unless instance
-
# Thread-safety: It is possible that multiple equivalent Country
-
# instances could be created here in concurrently executing threads.
-
# The consequences of this are that the data may be loaded more than
-
# once (depending on the data source) and memoized calculations could
-
# be discarded. The performance benefit of ensuring that only a single
-
# instance is created is unlikely to be worth the overhead of only
-
# allowing one Country to be loaded at a time.
-
info = data_source.load_country_info(identifier)
-
instance = Country.new(info)
-
@@countries[identifier] = instance
-
end
-
-
instance
-
end
-
-
# If identifier is a CountryInfo object, initializes the Country instance,
-
# otherwise calls get(identifier).
-
1
def self.new(identifier)
-
if identifier.kind_of?(CountryInfo)
-
instance = super()
-
instance.send :setup, identifier
-
instance
-
else
-
get(identifier)
-
end
-
end
-
-
# Returns an Array of all the valid country codes.
-
1
def self.all_codes
-
data_source.country_codes
-
end
-
-
# Returns an Array of all the defined Countries.
-
1
def self.all
-
data_source.country_codes.collect {|code| get(code)}
-
end
-
-
# The ISO 3166-1 alpha-2 country code.
-
1
def code
-
@info.code
-
end
-
-
# The name of the country.
-
1
def name
-
@info.name
-
end
-
-
# Alias for name.
-
1
def to_s
-
name
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{@info.code}>"
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country. These
-
# are in an order that
-
#
-
# 1. makes some geographical sense, and
-
# 2. puts the most populous zones first, where that does not contradict 1.
-
#
-
# Returned zone identifiers may refer to cities and regions outside of the
-
# country. This will occur if the zone covers multiple countries. Any zones
-
# referring to a city or region in a different country will be listed after
-
# those relating to this country.
-
1
def zone_identifiers
-
@info.zone_identifiers
-
end
-
1
alias zone_names zone_identifiers
-
-
# An array of all the Timezones for this country. Returns TimezoneProxy
-
# objects to avoid the overhead of loading Timezone definitions until
-
# a conversion is actually required. The Timezones are returned in an order
-
# that
-
#
-
# 1. makes some geographical sense, and
-
# 2. puts the most populous zones first, where that does not contradict 1.
-
#
-
# Identifiers of the zones returned may refer to cities and regions outside
-
# of the country. This will occur if the zone covers multiple countries. Any
-
# zones referring to a city or region in a different country will be listed
-
# after those relating to this country.
-
1
def zones
-
zone_identifiers.collect {|id|
-
Timezone.get_proxy(id)
-
}
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances (containing extra information about each zone).
-
# These are in an order that
-
#
-
# 1. makes some geographical sense, and
-
# 2. puts the most populous zones first, where that does not contradict 1.
-
#
-
# Identifiers and descriptions of the zones returned may refer to cities and
-
# regions outside of the country. This will occur if the zone covers
-
# multiple countries. Any zones referring to a city or region in a different
-
# country will be listed after those relating to this country.
-
1
def zone_info
-
@info.zones
-
end
-
-
# Compare two Countries based on their code. Returns -1 if c is less
-
# than self, 0 if c is equal to self and +1 if c is greater than self.
-
#
-
# Returns nil if c is not comparable with Country instances.
-
1
def <=>(c)
-
return nil unless c.is_a?(Country)
-
code <=> c.code
-
end
-
-
# Returns true if and only if the code of c is equal to the code of this
-
# Country.
-
1
def eql?(c)
-
self == c
-
end
-
-
# Returns a hash value for this Country.
-
1
def hash
-
code.hash
-
end
-
-
# Dumps this Country for marshalling.
-
1
def _dump(limit)
-
code
-
end
-
-
# Loads a marshalled Country.
-
1
def self._load(data)
-
Country.get(data)
-
end
-
-
1
private
-
# Called by Country.new to initialize a new Country instance. The info
-
# parameter is a CountryInfo that defines the country.
-
1
def setup(info)
-
@info = info
-
end
-
-
# Initializes @@countries.
-
1
def self.init_countries
-
1
@@countries = ThreadSafe::Cache.new
-
end
-
1
init_countries
-
-
# Returns the current DataSource
-
1
def self.data_source
-
DataSource.get
-
end
-
end
-
end
-
1
module TZInfo
-
# The country index file includes CountryIndexDefinition which provides
-
# a country method used to define each country in the index.
-
#
-
# @private
-
1
module CountryIndexDefinition #:nodoc:
-
1
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
base.instance_eval { @countries = {} }
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
1
module ClassMethods #:nodoc:
-
# Defines a country with an ISO 3166 country code, name and block. The
-
# block will be evaluated to obtain all the timezones for the country.
-
# Calls Country.country_defined with the definition of each country.
-
1
def country(code, name, &block)
-
@countries[code] = RubyCountryInfo.new(code, name, &block)
-
end
-
-
# Returns a frozen hash of all the countries that have been defined in
-
# the index.
-
1
def countries
-
@countries.freeze
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents a country and references to its timezones as returned by a
-
# DataSource.
-
1
class CountryInfo
-
# The ISO 3166 country code.
-
1
attr_reader :code
-
-
# The name of the country.
-
1
attr_reader :name
-
-
# Constructs a new CountryInfo with an ISO 3166 country code and name
-
1
def initialize(code, name)
-
249
@code = code
-
249
@name = name
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@code>"
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country.
-
# The identifiers are ordered by importance according to the DataSource.
-
1
def zone_identifiers
-
raise_not_implemented('zone_identifiers')
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances.
-
#
-
# The timezones are ordered by importance according to the DataSource.
-
1
def zones
-
raise_not_implemented('zones')
-
end
-
-
1
private
-
-
1
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
1
module TZInfo
-
# A Timezone within a Country. This contains extra information about the
-
# Timezone that is specific to the Country (a Timezone could be used by
-
# multiple countries).
-
1
class CountryTimezone
-
# The zone identifier.
-
1
attr_reader :identifier
-
-
# A description of this timezone in relation to the country, e.g.
-
# "Eastern Time". This is usually nil for countries having only a single
-
# Timezone.
-
1
attr_reader :description
-
-
1
class << self
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude are specified as
-
# rationals - a numerator and denominator. For performance reasons, the
-
# numerators and denominators must be specified in their lowest form.
-
#
-
# For use internally within TZInfo.
-
#
-
# @!visibility private
-
1
alias :new! :new
-
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude must be specified
-
# as instances of Rational.
-
#
-
# CountryTimezone instances should normally only be constructed when
-
# creating new DataSource implementations.
-
1
def new(identifier, latitude, longitude, description = nil)
-
424
super(identifier, latitude, nil, longitude, nil, description)
-
end
-
end
-
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude are specified as
-
# rationals - a numerator and denominator. For performance reasons, the
-
# numerators and denominators must be specified in their lowest form.
-
#
-
# @!visibility private
-
1
def initialize(identifier, latitude_numerator, latitude_denominator,
-
longitude_numerator, longitude_denominator, description = nil) #:nodoc:
-
424
@identifier = identifier
-
-
424
if latitude_numerator.kind_of?(Rational)
-
424
@latitude = latitude_numerator
-
else
-
@latitude = nil
-
@latitude_numerator = latitude_numerator
-
@latitude_denominator = latitude_denominator
-
end
-
-
424
if longitude_numerator.kind_of?(Rational)
-
424
@longitude = longitude_numerator
-
else
-
@longitude = nil
-
@longitude_numerator = longitude_numerator
-
@longitude_denominator = longitude_denominator
-
end
-
-
424
@description = description
-
end
-
-
# The Timezone (actually a TimezoneProxy for performance reasons).
-
1
def timezone
-
Timezone.get_proxy(@identifier)
-
end
-
-
# if description is not nil, this method returns description; otherwise it
-
# returns timezone.friendly_identifier(true).
-
1
def description_or_friendly_identifier
-
description || timezone.friendly_identifier(true)
-
end
-
-
# The latitude of this timezone in degrees as a Rational.
-
1
def latitude
-
# Thread-safety: It is possible that the value of @latitude may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @latitude is only
-
# calculated once.
-
@latitude ||= RubyCoreSupport.rational_new!(@latitude_numerator, @latitude_denominator)
-
end
-
-
# The longitude of this timezone in degrees as a Rational.
-
1
def longitude
-
# Thread-safety: It is possible that the value of @longitude may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @longitude is only
-
# calculated once.
-
@longitude ||= RubyCoreSupport.rational_new!(@longitude_numerator, @longitude_denominator)
-
end
-
-
# Returns true if and only if the given CountryTimezone is equal to the
-
# current CountryTimezone (has the same identifer, latitude, longitude
-
# and description).
-
1
def ==(ct)
-
ct.kind_of?(CountryTimezone) &&
-
identifier == ct.identifier && latitude == ct.latitude &&
-
longitude == ct.longitude && description == ct.description
-
end
-
-
# Returns true if and only if the given CountryTimezone is equal to the
-
# current CountryTimezone (has the same identifer, latitude, longitude
-
# and description).
-
1
def eql?(ct)
-
self == ct
-
end
-
-
# Returns a hash of this CountryTimezone.
-
1
def hash
-
@identifier.hash ^
-
(@latitude ? @latitude.numerator.hash ^ @latitude.denominator.hash : @latitude_numerator.hash ^ @latitude_denominator.hash) ^
-
(@longitude ? @longitude.numerator.hash ^ @longitude.denominator.hash : @longitude_numerator.hash ^ @longitude_denominator.hash) ^
-
@description.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@identifier>"
-
end
-
end
-
end
-
1
require 'thread'
-
-
1
module TZInfo
-
# InvalidDataSource is raised if the DataSource is used doesn't implement one
-
# of the required methods.
-
1
class InvalidDataSource < StandardError
-
end
-
-
# DataSourceNotFound is raised if no data source could be found (i.e.
-
# if 'tzinfo/data' cannot be found on the load path and no valid zoneinfo
-
# directory can be found on the system).
-
1
class DataSourceNotFound < StandardError
-
end
-
-
# The base class for data sources of timezone and country data.
-
#
-
# Use DataSource.set to change the data source being used.
-
1
class DataSource
-
# The currently selected data source.
-
1
@@instance = nil
-
-
# Mutex used to ensure the default data source is only created once.
-
1
@@default_mutex = Mutex.new
-
-
# Returns the currently selected DataSource instance.
-
1
def self.get
-
# If a DataSource hasn't been manually set when the first request is
-
# made to obtain a DataSource, then a Default data source is created.
-
-
# This is done at the first request rather than when TZInfo is loaded to
-
# avoid unnecessary (or in some cases potentially harmful) attempts to
-
# find a suitable DataSource.
-
-
# A Mutex is used to ensure that only a single default instance is
-
# created (having two different DataSources in use simultaneously could
-
# cause unexpected results).
-
-
1
unless @@instance
-
1
@@default_mutex.synchronize do
-
1
set(create_default_data_source) unless @@instance
-
end
-
end
-
-
1
@@instance
-
end
-
-
# Sets the currently selected data source for Timezone and Country data.
-
#
-
# This should usually be set to one of the two standard data source types:
-
#
-
# * +:ruby+ - read data from the Ruby modules included in the TZInfo::Data
-
# library (tzinfo-data gem).
-
# * +:zoneinfo+ - read data from the zoneinfo files included with most
-
# Unix-like operating sytems (e.g. in /usr/share/zoneinfo).
-
#
-
# To set TZInfo to use one of the standard data source types, call
-
# \TZInfo::DataSource.set in one of the following ways:
-
#
-
# TZInfo::DataSource.set(:ruby)
-
# TZInfo::DataSource.set(:zoneinfo)
-
# TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir)
-
# TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file)
-
#
-
# \DataSource.set(:zoneinfo) will automatically search for the zoneinfo
-
# directory by checking the paths specified in
-
# ZoneinfoDataSource.search_paths. ZoneinfoDirectoryNotFound will be raised
-
# if no valid zoneinfo directory could be found.
-
#
-
# \DataSource.set(:zoneinfo, zoneinfo_dir) uses the specified zoneinfo
-
# directory as the data source. If the directory is not a valid zoneinfo
-
# directory, an InvalidZoneinfoDirectory exception will be raised.
-
#
-
# \DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file) uses the
-
# specified zoneinfo directory as the data source, but loads the iso3166.tab
-
# file from an alternate path. If the directory is not a valid zoneinfo
-
# directory, an InvalidZoneinfoDirectory exception will be raised.
-
#
-
# Custom data sources can be created by subclassing TZInfo::DataSource and
-
# implementing the following methods:
-
#
-
# * \load_timezone_info
-
# * \timezone_identifiers
-
# * \data_timezone_identifiers
-
# * \linked_timezone_identifiers
-
# * \load_country_info
-
# * \country_codes
-
#
-
# To have TZInfo use the custom data source, call \DataSource.set
-
# as follows:
-
#
-
# TZInfo::DataSource.set(CustomDataSource.new)
-
#
-
# To avoid inconsistent data, \DataSource.set should be called before
-
# accessing any Timezone or Country data.
-
#
-
# If \DataSource.set is not called, TZInfo will by default use TZInfo::Data
-
# as the data source. If TZInfo::Data is not available (i.e. if require
-
# 'tzinfo/data' fails), then TZInfo will search for a zoneinfo directory
-
# instead (using the search path specified by
-
# TZInfo::ZoneinfoDataSource::DEFAULT_SEARCH_PATH).
-
1
def self.set(data_source_or_type, *args)
-
1
if data_source_or_type.kind_of?(DataSource)
-
1
@@instance = data_source_or_type
-
elsif data_source_or_type == :ruby
-
@@instance = RubyDataSource.new
-
elsif data_source_or_type == :zoneinfo
-
@@instance = ZoneinfoDataSource.new(*args)
-
else
-
raise ArgumentError, 'data_source_or_type must be a DataSource instance or a data source type (:ruby)'
-
end
-
end
-
-
# Returns a TimezoneInfo instance for a given identifier. The TimezoneInfo
-
# instance should derive from either DataTimzoneInfo for timezones that
-
# define their own data or LinkedTimezoneInfo for links or aliases to
-
# other timezones.
-
#
-
# Raises InvalidTimezoneIdentifier if the timezone is not found or the
-
# identifier is invalid.
-
1
def load_timezone_info(identifier)
-
raise_invalid_data_source('load_timezone_info')
-
end
-
-
# Returns an array of all the available timezone identifiers.
-
1
def timezone_identifiers
-
raise_invalid_data_source('timezone_identifiers')
-
end
-
-
# Returns an array of all the available timezone identifiers for
-
# data timezones (i.e. those that actually contain definitions).
-
1
def data_timezone_identifiers
-
raise_invalid_data_source('data_timezone_identifiers')
-
end
-
-
# Returns an array of all the available timezone identifiers that
-
# are links to other timezones.
-
1
def linked_timezone_identifiers
-
raise_invalid_data_source('linked_timezone_identifiers')
-
end
-
-
# Returns a CountryInfo instance for the given ISO 3166-1 alpha-2
-
# country code. Raises InvalidCountryCode if the country could not be found
-
# or the code is invalid.
-
1
def load_country_info(code)
-
raise_invalid_data_source('load_country_info')
-
end
-
-
# Returns an array of all the available ISO 3166-1 alpha-2
-
# country codes.
-
1
def country_codes
-
raise_invalid_data_source('country_codes')
-
end
-
-
# Returns the name of this DataSource.
-
1
def to_s
-
"Default DataSource"
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}>"
-
end
-
-
1
private
-
-
# Creates a DataSource instance for use as the default. Used if
-
# no preference has been specified manually.
-
1
def self.create_default_data_source
-
1
has_tzinfo_data = false
-
-
1
begin
-
1
require 'tzinfo/data'
-
has_tzinfo_data = true
-
rescue LoadError
-
end
-
-
1
return RubyDataSource.new if has_tzinfo_data
-
-
1
begin
-
1
return ZoneinfoDataSource.new
-
rescue ZoneinfoDirectoryNotFound
-
raise DataSourceNotFound, "No source of timezone data could be found.\nPlease refer to http://tzinfo.github.io/datasourcenotfound for help resolving this error."
-
end
-
end
-
-
1
def raise_invalid_data_source(method_name)
-
raise InvalidDataSource, "#{method_name} not defined"
-
end
-
end
-
end
-
1
module TZInfo
-
-
# A Timezone based on a DataTimezoneInfo.
-
#
-
# @private
-
1
class DataTimezone < InfoTimezone #:nodoc:
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
#
-
# If no TimezonePeriod could be found, PeriodNotFound is raised.
-
1
def period_for_utc(utc)
-
56
info.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Raises PeriodNotFound if no periods are found for the given time.
-
1
def periods_for_local(local)
-
info.periods_for_local(local)
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
1
def transitions_up_to(utc_to, utc_from = nil)
-
info.transitions_up_to(utc_to, utc_from)
-
end
-
-
# Returns the canonical zone for this Timezone.
-
#
-
# For a DataTimezone, this is always self.
-
1
def canonical_zone
-
self
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents a defined timezone containing transition data.
-
1
class DataTimezoneInfo < TimezoneInfo
-
-
# Returns the TimezonePeriod for the given UTC time.
-
1
def period_for_utc(utc)
-
raise_not_implemented('period_for_utc')
-
end
-
-
# Returns the set of TimezonePeriods for the given local time as an array.
-
# Results returned are ordered by increasing UTC start date.
-
# Returns an empty array if no periods are found for the given time.
-
1
def periods_for_local(local)
-
raise_not_implemented('periods_for_local')
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
1
def transitions_up_to(utc_to, utc_from = nil)
-
raise_not_implemented('transitions_up_to')
-
end
-
-
# Constructs a Timezone instance for the timezone represented by this
-
# DataTimezoneInfo.
-
1
def create_timezone
-
1
DataTimezone.new(self)
-
end
-
-
1
private
-
-
1
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
1
module TZInfo
-
-
# A Timezone based on a TimezoneInfo.
-
#
-
# @private
-
1
class InfoTimezone < Timezone #:nodoc:
-
-
# Constructs a new InfoTimezone with a TimezoneInfo instance.
-
1
def self.new(info)
-
1
tz = super()
-
1
tz.send(:setup, info)
-
1
tz
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
1
def identifier
-
1
@info.identifier
-
end
-
-
1
protected
-
# The TimezoneInfo for this Timezone.
-
1
def info
-
56
@info
-
end
-
-
1
def setup(info)
-
1
@info = info
-
end
-
end
-
end
-
1
module TZInfo
-
-
# A Timezone based on a LinkedTimezoneInfo.
-
#
-
# @private
-
1
class LinkedTimezone < InfoTimezone #:nodoc:
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
#
-
# If no TimezonePeriod could be found, PeriodNotFound is raised.
-
1
def period_for_utc(utc)
-
@linked_timezone.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Raises PeriodNotFound if no periods are found for the given time.
-
1
def periods_for_local(local)
-
@linked_timezone.periods_for_local(local)
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
1
def transitions_up_to(utc_to, utc_from = nil)
-
@linked_timezone.transitions_up_to(utc_to, utc_from)
-
end
-
-
# Returns the canonical zone for this Timezone.
-
#
-
# For a LinkedTimezone, this is the canonical zone of the link target.
-
1
def canonical_zone
-
@linked_timezone.canonical_zone
-
end
-
-
1
protected
-
1
def setup(info)
-
super(info)
-
@linked_timezone = Timezone.get(info.link_to_identifier)
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents a timezone that is defined as a link or alias to another zone.
-
1
class LinkedTimezoneInfo < TimezoneInfo
-
-
# The zone that provides the data (that this zone is an alias for).
-
1
attr_reader :link_to_identifier
-
-
# Constructs a new LinkedTimezoneInfo with an identifier and the identifier
-
# of the zone linked to.
-
1
def initialize(identifier, link_to_identifier)
-
super(identifier)
-
@link_to_identifier = link_to_identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@identifier,#@link_to_identifier>"
-
end
-
-
# Constructs a Timezone instance for the timezone represented by this
-
# DataTimezoneInfo.
-
1
def create_timezone
-
LinkedTimezone.new(self)
-
end
-
end
-
end
-
1
require 'rational' unless defined?(Rational)
-
-
1
module TZInfo
-
-
# Provides a method for getting Rationals for a timezone offset in seconds.
-
# Pre-reduced rationals are returned for all the half-hour intervals between
-
# -14 and +14 hours to avoid having to call gcd at runtime.
-
#
-
# @private
-
1
module OffsetRationals #:nodoc:
-
1
@@rational_cache = {
-
-50400 => RubyCoreSupport.rational_new!(-7,12),
-
-48600 => RubyCoreSupport.rational_new!(-9,16),
-
-46800 => RubyCoreSupport.rational_new!(-13,24),
-
-45000 => RubyCoreSupport.rational_new!(-25,48),
-
-43200 => RubyCoreSupport.rational_new!(-1,2),
-
-41400 => RubyCoreSupport.rational_new!(-23,48),
-
-39600 => RubyCoreSupport.rational_new!(-11,24),
-
-37800 => RubyCoreSupport.rational_new!(-7,16),
-
-36000 => RubyCoreSupport.rational_new!(-5,12),
-
-34200 => RubyCoreSupport.rational_new!(-19,48),
-
-32400 => RubyCoreSupport.rational_new!(-3,8),
-
-30600 => RubyCoreSupport.rational_new!(-17,48),
-
-28800 => RubyCoreSupport.rational_new!(-1,3),
-
-27000 => RubyCoreSupport.rational_new!(-5,16),
-
-25200 => RubyCoreSupport.rational_new!(-7,24),
-
-23400 => RubyCoreSupport.rational_new!(-13,48),
-
-21600 => RubyCoreSupport.rational_new!(-1,4),
-
-19800 => RubyCoreSupport.rational_new!(-11,48),
-
-18000 => RubyCoreSupport.rational_new!(-5,24),
-
-16200 => RubyCoreSupport.rational_new!(-3,16),
-
-14400 => RubyCoreSupport.rational_new!(-1,6),
-
-12600 => RubyCoreSupport.rational_new!(-7,48),
-
-10800 => RubyCoreSupport.rational_new!(-1,8),
-
-9000 => RubyCoreSupport.rational_new!(-5,48),
-
-7200 => RubyCoreSupport.rational_new!(-1,12),
-
-5400 => RubyCoreSupport.rational_new!(-1,16),
-
-3600 => RubyCoreSupport.rational_new!(-1,24),
-
-1800 => RubyCoreSupport.rational_new!(-1,48),
-
0 => RubyCoreSupport.rational_new!(0,1),
-
1800 => RubyCoreSupport.rational_new!(1,48),
-
3600 => RubyCoreSupport.rational_new!(1,24),
-
5400 => RubyCoreSupport.rational_new!(1,16),
-
7200 => RubyCoreSupport.rational_new!(1,12),
-
9000 => RubyCoreSupport.rational_new!(5,48),
-
10800 => RubyCoreSupport.rational_new!(1,8),
-
12600 => RubyCoreSupport.rational_new!(7,48),
-
14400 => RubyCoreSupport.rational_new!(1,6),
-
16200 => RubyCoreSupport.rational_new!(3,16),
-
18000 => RubyCoreSupport.rational_new!(5,24),
-
19800 => RubyCoreSupport.rational_new!(11,48),
-
21600 => RubyCoreSupport.rational_new!(1,4),
-
23400 => RubyCoreSupport.rational_new!(13,48),
-
25200 => RubyCoreSupport.rational_new!(7,24),
-
27000 => RubyCoreSupport.rational_new!(5,16),
-
28800 => RubyCoreSupport.rational_new!(1,3),
-
30600 => RubyCoreSupport.rational_new!(17,48),
-
32400 => RubyCoreSupport.rational_new!(3,8),
-
34200 => RubyCoreSupport.rational_new!(19,48),
-
36000 => RubyCoreSupport.rational_new!(5,12),
-
37800 => RubyCoreSupport.rational_new!(7,16),
-
39600 => RubyCoreSupport.rational_new!(11,24),
-
41400 => RubyCoreSupport.rational_new!(23,48),
-
43200 => RubyCoreSupport.rational_new!(1,2),
-
45000 => RubyCoreSupport.rational_new!(25,48),
-
46800 => RubyCoreSupport.rational_new!(13,24),
-
48600 => RubyCoreSupport.rational_new!(9,16),
-
50400 => RubyCoreSupport.rational_new!(7,12)}.freeze
-
-
# Returns a Rational expressing the fraction of a day that offset in
-
# seconds represents (i.e. equivalent to Rational(offset, 86400)).
-
1
def rational_for_offset(offset)
-
@@rational_cache[offset] || Rational(offset, 86400)
-
end
-
1
module_function :rational_for_offset
-
end
-
end
-
1
require 'date'
-
1
require 'rational' unless defined?(Rational)
-
-
1
module TZInfo
-
-
# Methods to support different versions of Ruby.
-
#
-
# @private
-
1
module RubyCoreSupport #:nodoc:
-
-
# Use Rational.new! for performance reasons in Ruby 1.8.
-
# This has been removed from 1.9, but Rational performs better.
-
1
if Rational.respond_to? :new!
-
def self.rational_new!(numerator, denominator = 1)
-
Rational.new!(numerator, denominator)
-
end
-
else
-
1
def self.rational_new!(numerator, denominator = 1)
-
58
Rational(numerator, denominator)
-
end
-
end
-
-
# Ruby 1.8.6 introduced new! and deprecated new0.
-
# Ruby 1.9.0 removed new0.
-
# Ruby trunk revision 31668 removed the new! method.
-
# Still support new0 for better performance on older versions of Ruby (new0 indicates
-
# that the rational has already been reduced to its lowest terms).
-
# Fallback to jd with conversion from ajd if new! and new0 are unavailable.
-
1
if DateTime.respond_to? :new!
-
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
DateTime.new!(ajd, of, sg)
-
end
-
elsif DateTime.respond_to? :new0
-
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
DateTime.new0(ajd, of, sg)
-
end
-
else
-
1
HALF_DAYS_IN_DAY = rational_new!(1, 2)
-
-
1
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
# Convert from an Astronomical Julian Day number to a civil Julian Day number.
-
jd = ajd + of + HALF_DAYS_IN_DAY
-
-
# Ruby trunk revision 31862 changed the behaviour of DateTime.jd so that it will no
-
# longer accept a fractional civil Julian Day number if further arguments are specified.
-
# Calculate the hours, minutes and seconds to pass to jd.
-
-
jd_i = jd.to_i
-
jd_i -= 1 if jd < 0
-
hours = (jd - jd_i) * 24
-
hours_i = hours.to_i
-
minutes = (hours - hours_i) * 60
-
minutes_i = minutes.to_i
-
seconds = (minutes - minutes_i) * 60
-
-
DateTime.jd(jd_i, hours_i, minutes_i, seconds, of, sg)
-
end
-
end
-
-
# DateTime in Ruby 1.8.6 doesn't consider times within the 60th second to be
-
# valid. When attempting to specify such a DateTime, subtract the fractional
-
# part and then add it back later
-
1
if Date.respond_to?(:valid_time?) && !Date.valid_time?(0, 0, rational_new!(59001, 1000)) # 0:0:59.001
-
def self.datetime_new(y=-4712, m=1, d=1, h=0, min=0, s=0, of=0, sg=Date::ITALY)
-
if !s.kind_of?(Integer) && s > 59
-
dt = DateTime.new(y, m, d, h, min, 59, of, sg)
-
dt + (s - 59) / 86400
-
else
-
DateTime.new(y, m, d, h, min, s, of, sg)
-
end
-
end
-
else
-
1
def self.datetime_new(y=-4712, m=1, d=1, h=0, min=0, s=0, of=0, sg=Date::ITALY)
-
DateTime.new(y, m, d, h, min, s, of, sg)
-
end
-
end
-
-
# Returns true if Time on the runtime platform supports Times defined
-
# by negative 32-bit timestamps, otherwise false.
-
1
begin
-
1
Time.at(-1)
-
1
Time.at(-2147483648)
-
-
1
def self.time_supports_negative
-
true
-
end
-
rescue ArgumentError
-
def self.time_supports_negative
-
false
-
end
-
end
-
-
# Returns true if Time on the runtime platform supports Times defined by
-
# 64-bit timestamps, otherwise false.
-
1
begin
-
1
Time.at(-2147483649)
-
1
Time.at(2147483648)
-
-
1
def self.time_supports_64bit
-
1
true
-
end
-
rescue RangeError
-
def self.time_supports_64bit
-
false
-
end
-
end
-
-
# Return the result of Time#nsec if it exists, otherwise return the
-
# result of Time#usec * 1000.
-
1
if Time.method_defined?(:nsec)
-
1
def self.time_nsec(time)
-
55
time.nsec
-
end
-
else
-
def self.time_nsec(time)
-
time.usec * 1000
-
end
-
end
-
-
# Call String#force_encoding if this version of Ruby has encoding support
-
# otherwise treat as a no-op.
-
1
if String.method_defined?(:force_encoding)
-
1
def self.force_encoding(str, encoding)
-
1
str.force_encoding(encoding)
-
end
-
else
-
def self.force_encoding(str, encoding)
-
str
-
end
-
end
-
-
-
# Wrapper for File.open that supports passing hash options for specifying
-
# encodings on Ruby 1.9+. The options are ignored on earlier versions of
-
# Ruby.
-
1
if RUBY_VERSION =~ /\A1\.[0-8]\./
-
def self.open_file(file_name, mode, opts, &block)
-
File.open(file_name, mode, &block)
-
end
-
else
-
1
def self.open_file(file_name, mode, opts, &block)
-
2
File.open(file_name, mode, opts, &block)
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents information about a country returned by RubyDataSource.
-
#
-
# @private
-
1
class RubyCountryInfo < CountryInfo #:nodoc:
-
# Constructs a new CountryInfo with an ISO 3166 country code, name and
-
# block. The block will be evaluated to obtain the timezones for the
-
# country when the zones are first needed.
-
1
def initialize(code, name, &block)
-
super(code, name)
-
@block = block
-
@zones = nil
-
@zone_identifiers = nil
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country. These
-
# are in the order they were added using the timezone method.
-
1
def zone_identifiers
-
# Thread-safety: It is possible that the value of @zone_identifiers may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @zone_identifiers is only
-
# calculated once.
-
-
unless @zone_identifiers
-
@zone_identifiers = zones.collect {|zone| zone.identifier}.freeze
-
end
-
-
@zone_identifiers
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances. These are in the order they were added using
-
# the timezone method.
-
1
def zones
-
# Thread-safety: It is possible that the value of @zones may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @zones is only
-
# calculated once.
-
-
unless @zones
-
zones = Zones.new
-
@block.call(zones) if @block
-
@block = nil
-
@zones = zones.list.freeze
-
end
-
-
@zones
-
end
-
-
# An instance of the Zones class is passed to the block used to define
-
# timezones.
-
#
-
# @private
-
1
class Zones #:nodoc:
-
1
attr_reader :list
-
-
1
def initialize
-
@list = []
-
end
-
-
# Called by the index data to define a timezone for the country.
-
1
def timezone(identifier, latitude_numerator, latitude_denominator,
-
longitude_numerator, longitude_denominator, description = nil)
-
@list << CountryTimezone.new!(identifier, latitude_numerator,
-
latitude_denominator, longitude_numerator, longitude_denominator,
-
description)
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# A DataSource that loads data from the set of Ruby modules included in the
-
# TZInfo::Data library (tzinfo-data gem).
-
#
-
# To have TZInfo use this DataSource, call TZInfo::DataSource.set as follows:
-
#
-
# TZInfo::DataSource.set(:ruby)
-
1
class RubyDataSource < DataSource
-
# Base path for require.
-
1
REQUIRE_PATH = File.join('tzinfo', 'data', 'definitions')
-
-
# Whether the timezone index has been loaded yet.
-
1
@@timezone_index_loaded = false
-
-
# Whether the country index has been loaded yet.
-
1
@@country_index_loaded = false
-
-
# Returns a TimezoneInfo instance for a given identifier.
-
# Raises InvalidTimezoneIdentifier if the timezone is not found or the
-
# identifier is invalid.
-
1
def load_timezone_info(identifier)
-
raise InvalidTimezoneIdentifier, 'Invalid identifier' if identifier !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/
-
-
identifier = identifier.gsub(/-/, '__m__').gsub(/\+/, '__p__')
-
-
# Untaint identifier after it has been reassigned to a new string. We
-
# don't want to modify the original identifier. identifier may also be
-
# frozen and therefore cannot be untainted.
-
identifier.untaint
-
-
identifier = identifier.split('/')
-
begin
-
require_definition(identifier)
-
-
m = Data::Definitions
-
identifier.each {|part|
-
m = m.const_get(part)
-
}
-
-
m.get
-
rescue LoadError, NameError => e
-
raise InvalidTimezoneIdentifier, e.message
-
end
-
end
-
-
# Returns an array of all the available timezone identifiers.
-
1
def timezone_identifiers
-
load_timezone_index
-
Data::Indexes::Timezones.timezones
-
end
-
-
# Returns an array of all the available timezone identifiers for
-
# data timezones (i.e. those that actually contain definitions).
-
1
def data_timezone_identifiers
-
load_timezone_index
-
Data::Indexes::Timezones.data_timezones
-
end
-
-
# Returns an array of all the available timezone identifiers that
-
# are links to other timezones.
-
1
def linked_timezone_identifiers
-
load_timezone_index
-
Data::Indexes::Timezones.linked_timezones
-
end
-
-
# Returns a CountryInfo instance for the given ISO 3166-1 alpha-2
-
# country code. Raises InvalidCountryCode if the country could not be found
-
# or the code is invalid.
-
1
def load_country_info(code)
-
load_country_index
-
info = Data::Indexes::Countries.countries[code]
-
raise InvalidCountryCode, 'Invalid country code' unless info
-
info
-
end
-
-
# Returns an array of all the available ISO 3166-1 alpha-2
-
# country codes.
-
1
def country_codes
-
load_country_index
-
Data::Indexes::Countries.countries.keys.freeze
-
end
-
-
# Returns the name of this DataSource.
-
1
def to_s
-
"Ruby DataSource"
-
end
-
-
1
private
-
-
# Requires a zone definition by its identifier (split on /).
-
1
def require_definition(identifier)
-
require_data(*(['definitions'] + identifier))
-
end
-
-
# Requires an index by its name.
-
1
def self.require_index(name)
-
require_data(*['indexes', name])
-
end
-
-
# Requires a file from tzinfo/data.
-
1
def require_data(*file)
-
self.class.require_data(*file)
-
end
-
-
# Requires a file from tzinfo/data.
-
1
def self.require_data(*file)
-
require File.join('tzinfo', 'data', *file)
-
end
-
-
# Loads in the index of timezones if it hasn't already been loaded.
-
1
def load_timezone_index
-
self.class.load_timezone_index
-
end
-
-
# Loads in the index of timezones if it hasn't already been loaded.
-
1
def self.load_timezone_index
-
unless @@timezone_index_loaded
-
require_index('timezones')
-
@@timezone_index_loaded = true
-
end
-
end
-
-
# Loads in the index of countries if it hasn't already been loaded.
-
1
def load_country_index
-
self.class.load_country_index
-
end
-
-
# Loads in the index of countries if it hasn't already been loaded.
-
1
def self.load_country_index
-
unless @@country_index_loaded
-
require_index('countries')
-
@@country_index_loaded = true
-
end
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'rational' unless defined?(Rational)
-
1
require 'time'
-
-
1
module TZInfo
-
# Used by TZInfo internally to represent either a Time, DateTime or
-
# an Integer timestamp (seconds since 1970-01-01 00:00:00).
-
1
class TimeOrDateTime
-
1
include Comparable
-
-
# Constructs a new TimeOrDateTime. timeOrDateTime can be a Time, DateTime
-
# or Integer. If using a Time or DateTime, any time zone information
-
# is ignored.
-
#
-
# Integer timestamps must be within the range supported by Time on the
-
# platform being used.
-
1
def initialize(timeOrDateTime)
-
55
@time = nil
-
55
@datetime = nil
-
55
@timestamp = nil
-
-
55
if timeOrDateTime.is_a?(Time)
-
55
@time = timeOrDateTime
-
-
# Avoid using the slower Rational class unless necessary.
-
55
nsec = RubyCoreSupport.time_nsec(@time)
-
55
usec = nsec % 1000 == 0 ? nsec / 1000 : Rational(nsec, 1000)
-
-
55
@time = Time.utc(@time.year, @time.mon, @time.mday, @time.hour, @time.min, @time.sec, usec) unless @time.utc?
-
55
@orig = @time
-
elsif timeOrDateTime.is_a?(DateTime)
-
@datetime = timeOrDateTime
-
@datetime = @datetime.new_offset(0) unless @datetime.offset == 0
-
@orig = @datetime
-
else
-
@timestamp = timeOrDateTime.to_i
-
-
if !RubyCoreSupport.time_supports_64bit && (@timestamp > 2147483647 || @timestamp < -2147483648 || (@timestamp < 0 && !RubyCoreSupport.time_supports_negative))
-
raise RangeError, 'Timestamp is outside the supported range of Time on this platform'
-
end
-
-
@orig = @timestamp
-
end
-
end
-
-
# Returns the time as a Time.
-
#
-
# When converting from a DateTime, the result is truncated to microsecond
-
# precision.
-
1
def to_time
-
# Thread-safety: It is possible that the value of @time may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @time is only
-
# calculated once.
-
-
55
unless @time
-
if @timestamp
-
@time = Time.at(@timestamp).utc
-
else
-
@time = Time.utc(year, mon, mday, hour, min, sec, usec)
-
end
-
end
-
-
55
@time
-
end
-
-
# Returns the time as a DateTime.
-
#
-
# When converting from a Time, the result is truncated to microsecond
-
# precision.
-
1
def to_datetime
-
# Thread-safety: It is possible that the value of @datetime may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @datetime is only
-
# calculated once.
-
-
unless @datetime
-
# Avoid using Rational unless necessary.
-
u = usec
-
s = u == 0 ? sec : Rational(sec * 1000000 + u, 1000000)
-
@datetime = RubyCoreSupport.datetime_new(year, mon, mday, hour, min, s)
-
end
-
-
@datetime
-
end
-
-
# Returns the time as an integer timestamp.
-
1
def to_i
-
# Thread-safety: It is possible that the value of @timestamp may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @timestamp is only
-
# calculated once.
-
-
unless @timestamp
-
@timestamp = to_time.to_i
-
end
-
-
@timestamp
-
end
-
-
# Returns the time as the original time passed to new.
-
1
def to_orig
-
@orig
-
end
-
-
# Returns a string representation of the TimeOrDateTime.
-
1
def to_s
-
if @orig.is_a?(Time)
-
"Time: #{@orig.to_s}"
-
elsif @orig.is_a?(DateTime)
-
"DateTime: #{@orig.to_s}"
-
else
-
"Timestamp: #{@orig.to_s}"
-
end
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{@orig.inspect}>"
-
end
-
-
# Returns the year.
-
1
def year
-
if @time
-
@time.year
-
elsif @datetime
-
@datetime.year
-
else
-
to_time.year
-
end
-
end
-
-
# Returns the month of the year (1..12).
-
1
def mon
-
if @time
-
@time.mon
-
elsif @datetime
-
@datetime.mon
-
else
-
to_time.mon
-
end
-
end
-
1
alias :month :mon
-
-
# Returns the day of the month (1..n).
-
1
def mday
-
if @time
-
@time.mday
-
elsif @datetime
-
@datetime.mday
-
else
-
to_time.mday
-
end
-
end
-
1
alias :day :mday
-
-
# Returns the hour of the day (0..23).
-
1
def hour
-
if @time
-
@time.hour
-
elsif @datetime
-
@datetime.hour
-
else
-
to_time.hour
-
end
-
end
-
-
# Returns the minute of the hour (0..59).
-
1
def min
-
if @time
-
@time.min
-
elsif @datetime
-
@datetime.min
-
else
-
to_time.min
-
end
-
end
-
-
# Returns the second of the minute (0..60). (60 for a leap second).
-
1
def sec
-
if @time
-
@time.sec
-
elsif @datetime
-
@datetime.sec
-
else
-
to_time.sec
-
end
-
end
-
-
# Returns the number of microseconds for the time.
-
1
def usec
-
if @time
-
@time.usec
-
elsif @datetime
-
# Ruby 1.8 has sec_fraction (of which the documentation says
-
# 'I do NOT recommend you to use this method'). sec_fraction no longer
-
# exists in Ruby 1.9.
-
-
# Calculate the sec_fraction from the day_fraction.
-
((@datetime.day_fraction - OffsetRationals.rational_for_offset(@datetime.hour * 3600 + @datetime.min * 60 + @datetime.sec)) * 86400000000).to_i
-
else
-
0
-
end
-
end
-
-
# Compares this TimeOrDateTime with another Time, DateTime, timestamp
-
# (Integer) or TimeOrDateTime. Returns -1, 0 or +1 depending
-
# whether the receiver is less than, equal to, or greater than
-
# timeOrDateTime.
-
#
-
# Returns nil if the passed in timeOrDateTime is not comparable with
-
# TimeOrDateTime instances.
-
#
-
# Comparisons involving a DateTime will be performed using DateTime#<=>.
-
# Comparisons that don't involve a DateTime, but include a Time will be
-
# performed with Time#<=>. Otherwise comparisons will be performed with
-
# Integer#<=>.
-
1
def <=>(timeOrDateTime)
-
return nil unless timeOrDateTime.is_a?(TimeOrDateTime) ||
-
timeOrDateTime.is_a?(Time) ||
-
timeOrDateTime.is_a?(DateTime) ||
-
timeOrDateTime.respond_to?(:to_i)
-
-
unless timeOrDateTime.is_a?(TimeOrDateTime)
-
timeOrDateTime = TimeOrDateTime.wrap(timeOrDateTime)
-
end
-
-
orig = timeOrDateTime.to_orig
-
-
if @orig.is_a?(DateTime) || orig.is_a?(DateTime)
-
# If either is a DateTime, assume it is there for a reason
-
# (i.e. for its larger range of acceptable values on 32-bit systems).
-
to_datetime <=> timeOrDateTime.to_datetime
-
elsif @orig.is_a?(Time) || orig.is_a?(Time)
-
to_time <=> timeOrDateTime.to_time
-
else
-
to_i <=> timeOrDateTime.to_i
-
end
-
end
-
-
# Adds a number of seconds to the TimeOrDateTime. Returns a new
-
# TimeOrDateTime, preserving what the original constructed type was.
-
# If the original type is a Time and the resulting calculation goes out of
-
# range for Times, then an exception will be raised by the Time class.
-
1
def +(seconds)
-
55
if seconds == 0
-
55
self
-
else
-
if @orig.is_a?(DateTime)
-
TimeOrDateTime.new(@orig + OffsetRationals.rational_for_offset(seconds))
-
else
-
# + defined for Time and Integer
-
TimeOrDateTime.new(@orig + seconds)
-
end
-
end
-
end
-
-
# Subtracts a number of seconds from the TimeOrDateTime. Returns a new
-
# TimeOrDateTime, preserving what the original constructed type was.
-
# If the original type is a Time and the resulting calculation goes out of
-
# range for Times, then an exception will be raised by the Time class.
-
1
def -(seconds)
-
self + (-seconds)
-
end
-
-
# Similar to the + operator, but converts to a DateTime based TimeOrDateTime
-
# where the Time or Integer timestamp to go out of the allowed range for a
-
# Time, converts to a DateTime based TimeOrDateTime.
-
#
-
# Note that the range of Time varies based on the platform.
-
1
def add_with_convert(seconds)
-
if seconds == 0
-
self
-
else
-
if @orig.is_a?(DateTime)
-
TimeOrDateTime.new(@orig + OffsetRationals.rational_for_offset(seconds))
-
else
-
# A Time or timestamp.
-
result = to_i + seconds
-
-
if ((result > 2147483647 || result < -2147483648) && !RubyCoreSupport.time_supports_64bit) || (result < 0 && !RubyCoreSupport.time_supports_negative)
-
result = TimeOrDateTime.new(to_datetime + OffsetRationals.rational_for_offset(seconds))
-
else
-
result = TimeOrDateTime.new(@orig + seconds)
-
end
-
end
-
end
-
end
-
-
# Returns true if todt represents the same time and was originally
-
# constructed with the same type (DateTime, Time or timestamp) as this
-
# TimeOrDateTime.
-
1
def eql?(todt)
-
todt.kind_of?(TimeOrDateTime) && to_orig.eql?(todt.to_orig)
-
end
-
-
# Returns a hash of this TimeOrDateTime.
-
1
def hash
-
@orig.hash
-
end
-
-
# If no block is given, returns a TimeOrDateTime wrapping the given
-
# timeOrDateTime. If a block is specified, a TimeOrDateTime is constructed
-
# and passed to the block. The result of the block must be a TimeOrDateTime.
-
#
-
# The result of the block will be converted to the type of the originally
-
# passed in timeOrDateTime and then returned as the result of wrap.
-
#
-
# timeOrDateTime can be a Time, DateTime, timestamp (Integer) or
-
# TimeOrDateTime. If a TimeOrDateTime is passed in, no new TimeOrDateTime
-
# will be constructed and the value passed to wrap will be used when
-
# calling the block.
-
1
def self.wrap(timeOrDateTime)
-
55
t = timeOrDateTime.is_a?(TimeOrDateTime) ? timeOrDateTime : TimeOrDateTime.new(timeOrDateTime)
-
-
55
if block_given?
-
55
t = yield t
-
-
55
if timeOrDateTime.is_a?(TimeOrDateTime)
-
t
-
55
elsif timeOrDateTime.is_a?(Time)
-
55
t.to_time
-
elsif timeOrDateTime.is_a?(DateTime)
-
t.to_datetime
-
else
-
t.to_i
-
end
-
else
-
t
-
end
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'set'
-
1
require 'thread_safe'
-
-
1
module TZInfo
-
# AmbiguousTime is raised to indicates that a specified time in a local
-
# timezone has more than one possible equivalent UTC time. This happens when
-
# transitioning from daylight savings time to standard time where the clocks
-
# are rolled back.
-
#
-
# AmbiguousTime is raised by period_for_local and local_to_utc when using an
-
# ambiguous time and not specifying any means to resolve the ambiguity.
-
1
class AmbiguousTime < StandardError
-
end
-
-
# PeriodNotFound is raised to indicate that no TimezonePeriod matching a given
-
# time could be found.
-
1
class PeriodNotFound < StandardError
-
end
-
-
# Raised by Timezone#get if the identifier given is not valid.
-
1
class InvalidTimezoneIdentifier < StandardError
-
end
-
-
# Raised if an attempt is made to use a timezone created with
-
# Timezone.new(nil).
-
1
class UnknownTimezone < StandardError
-
end
-
-
# Timezone is the base class of all timezones. It provides a factory method,
-
# 'get', to access timezones by identifier. Once a specific Timezone has been
-
# retrieved, DateTimes, Times and timestamps can be converted between the UTC
-
# and the local time for the zone. For example:
-
#
-
# tz = TZInfo::Timezone.get('America/New_York')
-
# puts tz.utc_to_local(DateTime.new(2005,8,29,15,35,0)).to_s
-
# puts tz.local_to_utc(Time.utc(2005,8,29,11,35,0)).to_s
-
# puts tz.utc_to_local(1125315300).to_s
-
#
-
# Each time conversion method returns an object of the same type it was
-
# passed.
-
#
-
# The Timezone class is thread-safe. It is safe to use class and instance
-
# methods of Timezone in concurrently executing threads. Instances of Timezone
-
# can be shared across thread boundaries.
-
1
class Timezone
-
1
include Comparable
-
-
# Cache of loaded zones by identifier to avoid using require if a zone
-
# has already been loaded.
-
#
-
# @!visibility private
-
1
@@loaded_zones = nil
-
-
# Default value of the dst parameter of the local_to_utc and
-
# period_for_local methods.
-
#
-
# @!visibility private
-
1
@@default_dst = nil
-
-
# Sets the default value of the optional dst parameter of the
-
# local_to_utc and period_for_local methods. Can be set to nil, true or
-
# false.
-
#
-
# The value of default_dst defaults to nil if unset.
-
1
def self.default_dst=(value)
-
@@default_dst = value.nil? ? nil : !!value
-
end
-
-
# Gets the default value of the optional dst parameter of the
-
# local_to_utc and period_for_local methods. Can be set to nil, true or
-
# false.
-
1
def self.default_dst
-
@@default_dst
-
end
-
-
# Returns a timezone by its identifier (e.g. "Europe/London",
-
# "America/Chicago" or "UTC").
-
#
-
# Raises InvalidTimezoneIdentifier if the timezone couldn't be found.
-
1
def self.get(identifier)
-
1
instance = @@loaded_zones[identifier]
-
-
1
unless instance
-
# Thread-safety: It is possible that multiple equivalent Timezone
-
# instances could be created here in concurrently executing threads.
-
# The consequences of this are that the data may be loaded more than
-
# once (depending on the data source) and memoized calculations could
-
# be discarded. The performance benefit of ensuring that only a single
-
# instance is created is unlikely to be worth the overhead of only
-
# allowing one Timezone to be loaded at a time.
-
1
info = data_source.load_timezone_info(identifier)
-
1
instance = info.create_timezone
-
1
@@loaded_zones[instance.identifier] = instance
-
end
-
-
1
instance
-
end
-
-
# Returns a proxy for the Timezone with the given identifier. The proxy
-
# will cause the real timezone to be loaded when an attempt is made to
-
# find a period or convert a time. get_proxy will not validate the
-
# identifier. If an invalid identifier is specified, no exception will be
-
# raised until the proxy is used.
-
1
def self.get_proxy(identifier)
-
TimezoneProxy.new(identifier)
-
end
-
-
# If identifier is nil calls super(), otherwise calls get. An identfier
-
# should always be passed in when called externally.
-
1
def self.new(identifier = nil)
-
2
if identifier
-
get(identifier)
-
else
-
2
super()
-
end
-
end
-
-
# Returns an array containing all the available Timezones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all
-
get_proxies(all_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones.
-
1
def self.all_identifiers
-
data_source.timezone_identifiers
-
end
-
-
# Returns an array containing all the available Timezones that are based
-
# on data (are not links to other Timezones).
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all_data_zones
-
get_proxies(all_data_zone_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones that are based on data (are not links to other Timezones)..
-
1
def self.all_data_zone_identifiers
-
data_source.data_timezone_identifiers
-
end
-
-
# Returns an array containing all the available Timezones that are links
-
# to other Timezones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all_linked_zones
-
get_proxies(all_linked_zone_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones that are links to other Timezones.
-
1
def self.all_linked_zone_identifiers
-
data_source.linked_timezone_identifiers
-
end
-
-
# Returns all the Timezones defined for all Countries. This is not the
-
# complete set of Timezones as some are not country specific (e.g.
-
# 'Etc/GMT').
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all_country_zones
-
Country.all_codes.inject([]) do |zones,country|
-
zones += Country.get(country).zones
-
end.uniq
-
end
-
-
# Returns all the zone identifiers defined for all Countries. This is not the
-
# complete set of zone identifiers as some are not country specific (e.g.
-
# 'Etc/GMT'). You can obtain a Timezone instance for a given identifier
-
# with the get method.
-
1
def self.all_country_zone_identifiers
-
Country.all_codes.inject([]) do |zones,country|
-
zones += Country.get(country).zone_identifiers
-
end.uniq
-
end
-
-
# Returns all US Timezone instances. A shortcut for
-
# TZInfo::Country.get('US').zones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.us_zones
-
Country.get('US').zones
-
end
-
-
# Returns all US zone identifiers. A shortcut for
-
# TZInfo::Country.get('US').zone_identifiers.
-
1
def self.us_zone_identifiers
-
Country.get('US').zone_identifiers
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
1
def identifier
-
raise_unknown_timezone
-
end
-
-
# An alias for identifier.
-
1
def name
-
# Don't use alias, as identifier gets overridden.
-
identifier
-
end
-
-
# Returns a friendlier version of the identifier.
-
1
def to_s
-
friendly_identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{identifier}>"
-
end
-
-
# Returns a friendlier version of the identifier. Set skip_first_part to
-
# omit the first part of the identifier (typically a region name) where
-
# there is more than one part.
-
#
-
# For example:
-
#
-
# Timezone.get('Europe/Paris').friendly_identifier(false) #=> "Europe - Paris"
-
# Timezone.get('Europe/Paris').friendly_identifier(true) #=> "Paris"
-
# Timezone.get('America/Indiana/Knox').friendly_identifier(false) #=> "America - Knox, Indiana"
-
# Timezone.get('America/Indiana/Knox').friendly_identifier(true) #=> "Knox, Indiana"
-
1
def friendly_identifier(skip_first_part = false)
-
parts = identifier.split('/')
-
if parts.empty?
-
# shouldn't happen
-
identifier
-
elsif parts.length == 1
-
parts[0]
-
else
-
prefix = skip_first_part ? nil : "#{parts[0]} - "
-
-
parts = parts.drop(1).map do |part|
-
part.gsub!(/_/, ' ')
-
-
if part.index(/[a-z]/)
-
# Missing a space if a lower case followed by an upper case and the
-
# name isn't McXxxx.
-
part.gsub!(/([^M][a-z])([A-Z])/, '\1 \2')
-
part.gsub!(/([M][a-bd-z])([A-Z])/, '\1 \2')
-
-
# Missing an apostrophe if two consecutive upper case characters.
-
part.gsub!(/([A-Z])([A-Z])/, '\1\'\2')
-
end
-
-
part
-
end
-
-
"#{prefix}#{parts.reverse.join(', ')}"
-
end
-
end
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
1
def period_for_utc(utc)
-
raise_unknown_timezone
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how ambiguities should be resolved.
-
# Returns an empty array if no periods are found for the given time.
-
1
def periods_for_local(local)
-
raise_unknown_timezone
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
1
def transitions_up_to(utc_to, utc_from = nil)
-
raise_unknown_timezone
-
end
-
-
# Returns the canonical Timezone instance for this Timezone.
-
#
-
# The IANA Time Zone database contains two types of definition: Zones and
-
# Links. Zones are defined by rules that set out when transitions occur.
-
# Links are just references to fully defined Zone, creating an alias for
-
# that Zone.
-
#
-
# Links are commonly used where a time zone has been renamed in a
-
# release of the Time Zone database. For example, the Zone US/Eastern was
-
# renamed as America/New_York. A US/Eastern Link was added in its place,
-
# linking to (and creating an alias for) for America/New_York.
-
#
-
# Links are also used for time zones that are currently identical to a full
-
# Zone, but that are administered seperately. For example, Europe/Vatican is
-
# a Link to (and alias for) Europe/Rome.
-
#
-
# For a full Zone, canonical_zone returns self.
-
#
-
# For a Link, canonical_zone returns a Timezone instance representing the
-
# full Zone that the link targets.
-
#
-
# TZInfo can be used with different data sources (see the documentation for
-
# TZInfo::DataSource). Please note that some DataSource implementations may
-
# not support distinguishing between full Zones and Links and will treat all
-
# time zones as full Zones. In this case, the canonical_zone will always
-
# return self.
-
#
-
# There are two built-in DataSource implementations. RubyDataSource (which
-
# will be used if the tzinfo-data gem is available) supports Link zones.
-
# ZoneinfoDataSource returns Link zones as if they were full Zones. If the
-
# canonical_zone or canonical_identifier methods are required, the
-
# tzinfo-data gem should be installed.
-
#
-
# The TZInfo::DataSource.get method can be used to check which DataSource
-
# implementation is being used.
-
1
def canonical_zone
-
raise_unknown_timezone
-
end
-
-
# Returns the TimezonePeriod for the given local time. local can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in local is ignored (it is treated as a time in the current
-
# timezone).
-
#
-
# Warning: There are local times that have no equivalent UTC times (e.g.
-
# in the transition from standard time to daylight savings time). There are
-
# also local times that have more than one UTC equivalent (e.g. in the
-
# transition from daylight savings time to standard time).
-
#
-
# In the first case (no equivalent UTC time), a PeriodNotFound exception
-
# will be raised.
-
#
-
# In the second case (more than one equivalent UTC time), an AmbiguousTime
-
# exception will be raised unless the optional dst parameter or block
-
# handles the ambiguity.
-
#
-
# If the ambiguity is due to a transition from daylight savings time to
-
# standard time, the dst parameter can be used to select whether the
-
# daylight savings time or local time is used. For example,
-
#
-
# Timezone.get('America/New_York').period_for_local(DateTime.new(2004,10,31,1,30,0))
-
#
-
# would raise an AmbiguousTime exception.
-
#
-
# Specifying dst=true would the daylight savings period from April to
-
# October 2004. Specifying dst=false would return the standard period
-
# from October 2004 to April 2005.
-
#
-
# If the dst parameter does not resolve the ambiguity, and a block is
-
# specified, it is called. The block must take a single parameter - an
-
# array of the periods that need to be resolved. The block can select and
-
# return a single period or return nil or an empty array
-
# to cause an AmbiguousTime exception to be raised.
-
#
-
# The default value of the dst parameter can be specified by setting
-
# Timezone.default_dst. If default_dst is not set, or is set to nil, then
-
# an AmbiguousTime exception will be raised in ambiguous situations unless
-
# a block is given to resolve the ambiguity.
-
1
def period_for_local(local, dst = Timezone.default_dst)
-
results = periods_for_local(local)
-
-
if results.empty?
-
raise PeriodNotFound
-
elsif results.size < 2
-
results.first
-
else
-
# ambiguous result try to resolve
-
-
if !dst.nil?
-
matches = results.find_all {|period| period.dst? == dst}
-
results = matches if !matches.empty?
-
end
-
-
if results.size < 2
-
results.first
-
else
-
# still ambiguous, try the block
-
-
if block_given?
-
results = yield results
-
end
-
-
if results.is_a?(TimezonePeriod)
-
results
-
elsif results && results.size == 1
-
results.first
-
else
-
raise AmbiguousTime, "#{local} is an ambiguous local time."
-
end
-
end
-
end
-
end
-
-
# Converts a time in UTC to the local timezone. utc can either be
-
# a DateTime, Time or timestamp (Time.to_i). The returned time has the same
-
# type as utc. Any timezone information in utc is ignored (it is treated as
-
# a UTC time).
-
1
def utc_to_local(utc)
-
TimeOrDateTime.wrap(utc) {|wrapped|
-
period_for_utc(wrapped).to_local(wrapped)
-
}
-
end
-
-
# Converts a time in the local timezone to UTC. local can either be
-
# a DateTime, Time or timestamp (Time.to_i). The returned time has the same
-
# type as local. Any timezone information in local is ignored (it is treated
-
# as a local time).
-
#
-
# Warning: There are local times that have no equivalent UTC times (e.g.
-
# in the transition from standard time to daylight savings time). There are
-
# also local times that have more than one UTC equivalent (e.g. in the
-
# transition from daylight savings time to standard time).
-
#
-
# In the first case (no equivalent UTC time), a PeriodNotFound exception
-
# will be raised.
-
#
-
# In the second case (more than one equivalent UTC time), an AmbiguousTime
-
# exception will be raised unless the optional dst parameter or block
-
# handles the ambiguity.
-
#
-
# If the ambiguity is due to a transition from daylight savings time to
-
# standard time, the dst parameter can be used to select whether the
-
# daylight savings time or local time is used. For example,
-
#
-
# Timezone.get('America/New_York').local_to_utc(DateTime.new(2004,10,31,1,30,0))
-
#
-
# would raise an AmbiguousTime exception.
-
#
-
# Specifying dst=true would return 2004-10-31 5:30:00. Specifying dst=false
-
# would return 2004-10-31 6:30:00.
-
#
-
# If the dst parameter does not resolve the ambiguity, and a block is
-
# specified, it is called. The block must take a single parameter - an
-
# array of the periods that need to be resolved. The block can return a
-
# single period to use to convert the time or return nil or an empty array
-
# to cause an AmbiguousTime exception to be raised.
-
#
-
# The default value of the dst parameter can be specified by setting
-
# Timezone.default_dst. If default_dst is not set, or is set to nil, then
-
# an AmbiguousTime exception will be raised in ambiguous situations unless
-
# a block is given to resolve the ambiguity.
-
1
def local_to_utc(local, dst = Timezone.default_dst)
-
TimeOrDateTime.wrap(local) {|wrapped|
-
if block_given?
-
period = period_for_local(wrapped, dst) {|periods| yield periods }
-
else
-
period = period_for_local(wrapped, dst)
-
end
-
-
period.to_utc(wrapped)
-
}
-
end
-
-
# Returns information about offsets used by the Timezone up to a given
-
# date and time, specified using UTC (utc_to). The information is returned
-
# as an Array of TimezoneOffset instances.
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only offsets used from
-
# that date and time forward will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive.
-
#
-
# Offsets may be returned in any order.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# offsets_up_to raises an ArgumentError exception.
-
1
def offsets_up_to(utc_to, utc_from = nil)
-
utc_to = TimeOrDateTime.wrap(utc_to)
-
transitions = transitions_up_to(utc_to, utc_from)
-
-
if transitions.empty?
-
# No transitions in the range, find the period that covers it.
-
-
if utc_from
-
# Use the from date as it is inclusive.
-
period = period_for_utc(utc_from)
-
else
-
# utc_to is exclusive, so this can't be used with period_for_utc.
-
# However, any time earlier than utc_to can be used.
-
-
# Subtract 1 hour (since this is one of the cached OffsetRationals).
-
# Use add_with_convert so that conversion to DateTime is performed if
-
# required.
-
period = period_for_utc(utc_to.add_with_convert(-3600))
-
end
-
-
[period.offset]
-
else
-
result = Set.new
-
-
first = transitions.first
-
result << first.previous_offset unless utc_from && first.at == utc_from
-
-
transitions.each do |t|
-
result << t.offset
-
end
-
-
result.to_a
-
end
-
end
-
-
# Returns the canonical identifier for this Timezone.
-
#
-
# This is a shortcut for calling canonical_zone.identifier. Please refer
-
# to the canonical_zone documentation for further information.
-
1
def canonical_identifier
-
canonical_zone.identifier
-
end
-
-
# Returns the current time in the timezone as a Time.
-
1
def now
-
utc_to_local(Time.now.utc)
-
end
-
-
# Returns the TimezonePeriod for the current time.
-
1
def current_period
-
1
period_for_utc(Time.now.utc)
-
end
-
-
# Returns the current Time and TimezonePeriod as an array. The first element
-
# is the time, the second element is the period.
-
1
def current_period_and_time
-
utc = Time.now.utc
-
period = period_for_utc(utc)
-
[period.to_local(utc), period]
-
end
-
-
1
alias :current_time_and_period :current_period_and_time
-
-
# Converts a time in UTC to local time and returns it as a string according
-
# to the given format.
-
#
-
# The formatting is identical to Time.strftime and DateTime.strftime, except
-
# %Z and %z are replaced with the timezone abbreviation (for example, EST or
-
# EDT) and offset for the specified Timezone and time.
-
#
-
# The offset can be formatted as follows:
-
#
-
# - %z - hour and minute (e.g. +0500)
-
# - %:z - hour and minute separated with a colon (e.g. +05:00)
-
# - %::z - hour minute and second separated with colons (e.g. +05:00:00)
-
# - %:::z - hour only (e.g. +05)
-
#
-
# Timezone#strftime currently handles the replacement of %z. From TZInfo
-
# version 2.0.0, %z will be passed to Time#strftime and DateTime#strftime
-
# instead. Some of the formatting options may cease to be available
-
# depending on the version of Ruby in use (for example, %:::z is only
-
# supported by Time#strftime from MRI version 2.0.0 onwards.)
-
1
def strftime(format, utc = Time.now.utc)
-
period = period_for_utc(utc)
-
local = period.to_local(utc)
-
local = Time.at(local).utc unless local.kind_of?(Time) || local.kind_of?(DateTime)
-
abbreviation = period.abbreviation.to_s.gsub(/%/, '%%')
-
-
format = format.gsub(/%(%*)(Z|:*z)/) do
-
if $1.length.odd?
-
# Escaped literal percent or series of percents. Pass on to strftime.
-
"#$1%#$2"
-
elsif $2 == "Z"
-
"#$1#{abbreviation}"
-
else
-
m, s = period.utc_total_offset.divmod(60)
-
h, m = m.divmod(60)
-
case $2.length
-
when 1
-
"#$1#{'%+03d%02d' % [h,m]}"
-
when 2
-
"#$1#{'%+03d:%02d' % [h,m]}"
-
when 3
-
"#$1#{'%+03d:%02d:%02d' % [h,m,s]}"
-
when 4
-
"#$1#{'%+03d' % [h]}"
-
else # more than 3 colons - not a valid option
-
# Passing the invalid format string through to Time#strftime or
-
# DateTime#strtime would normally result in it being returned in the
-
# result. However, with Ruby 1.8.7 on Windows (as tested with Ruby
-
# 1.8.7-p374 from http://rubyinstaller.org/downloads/archives), this
-
# causes Time#strftime to always return an empty string (e.g.
-
# Time.now.strftime('a %::::z b') returns '').
-
#
-
# Escape the percent to force it to be evaluated as a literal.
-
"#$1%%#$2"
-
end
-
end
-
end
-
-
local.strftime(format)
-
end
-
-
# Compares two Timezones based on their identifier. Returns -1 if tz is less
-
# than self, 0 if tz is equal to self and +1 if tz is greater than self.
-
#
-
# Returns nil if tz is not comparable with Timezone instances.
-
1
def <=>(tz)
-
return nil unless tz.is_a?(Timezone)
-
identifier <=> tz.identifier
-
end
-
-
# Returns true if and only if the identifier of tz is equal to the
-
# identifier of this Timezone.
-
1
def eql?(tz)
-
self == tz
-
end
-
-
# Returns a hash of this Timezone.
-
1
def hash
-
identifier.hash
-
end
-
-
# Dumps this Timezone for marshalling.
-
1
def _dump(limit)
-
identifier
-
end
-
-
# Loads a marshalled Timezone.
-
1
def self._load(data)
-
Timezone.get(data)
-
end
-
-
1
private
-
# Initializes @@loaded_zones.
-
1
def self.init_loaded_zones
-
1
@@loaded_zones = ThreadSafe::Cache.new
-
end
-
1
init_loaded_zones
-
-
# Returns an array of proxies corresponding to the given array of
-
# identifiers.
-
1
def self.get_proxies(identifiers)
-
identifiers.collect {|identifier| get_proxy(identifier)}
-
end
-
-
# Returns the current DataSource.
-
1
def self.data_source
-
1
DataSource.get
-
end
-
-
# Raises an UnknownTimezone exception.
-
1
def raise_unknown_timezone
-
raise UnknownTimezone, 'TZInfo::Timezone constructed directly'
-
end
-
end
-
end
-
1
module TZInfo
-
-
# TimezoneDefinition is included into Timezone definition modules.
-
# TimezoneDefinition provides the methods for defining timezones.
-
#
-
# @private
-
1
module TimezoneDefinition #:nodoc:
-
# Add class methods to the includee.
-
1
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
1
module ClassMethods #:nodoc:
-
# Returns and yields a TransitionDataTimezoneInfo object to define a
-
# timezone.
-
1
def timezone(identifier)
-
yield @timezone = TransitionDataTimezoneInfo.new(identifier)
-
end
-
-
# Defines a linked timezone.
-
1
def linked_timezone(identifier, link_to_identifier)
-
@timezone = LinkedTimezoneInfo.new(identifier, link_to_identifier)
-
end
-
-
# Returns the last TimezoneInfo to be defined with timezone or
-
# linked_timezone.
-
1
def get
-
@timezone
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# The timezone index file includes TimezoneIndexDefinition which provides
-
# methods used to define timezones in the index.
-
#
-
# @private
-
1
module TimezoneIndexDefinition #:nodoc:
-
# Add class methods to the includee and initialize class instance variables.
-
1
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
base.instance_eval do
-
@timezones = []
-
@data_timezones = []
-
@linked_timezones = []
-
end
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
1
module ClassMethods #:nodoc:
-
# Defines a timezone based on data.
-
1
def timezone(identifier)
-
@timezones << identifier
-
@data_timezones << identifier
-
end
-
-
# Defines a timezone which is a link to another timezone.
-
1
def linked_timezone(identifier)
-
@timezones << identifier
-
@linked_timezones << identifier
-
end
-
-
# Returns a frozen array containing the identifiers of all the timezones.
-
# Identifiers appear in the order they were defined in the index.
-
1
def timezones
-
@timezones.freeze
-
end
-
-
# Returns a frozen array containing the identifiers of all data timezones.
-
# Identifiers appear in the order they were defined in the index.
-
1
def data_timezones
-
@data_timezones.freeze
-
end
-
-
# Returns a frozen array containing the identifiers of all linked
-
# timezones. Identifiers appear in the order they were defined in
-
# the index.
-
1
def linked_timezones
-
@linked_timezones.freeze
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents a timezone defined by a data source.
-
1
class TimezoneInfo
-
-
# The timezone identifier.
-
1
attr_reader :identifier
-
-
# Constructs a new TimezoneInfo with an identifier.
-
1
def initialize(identifier)
-
1
@identifier = identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@identifier>"
-
end
-
-
# Constructs a Timezone instance for the timezone represented by this
-
# TimezoneInfo.
-
1
def create_timezone
-
raise_not_implemented('create_timezone')
-
end
-
-
1
private
-
-
1
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents an offset defined in a Timezone data file.
-
1
class TimezoneOffset
-
# The base offset of the timezone from UTC in seconds.
-
1
attr_reader :utc_offset
-
-
# The offset from standard time for the zone in seconds (i.e. non-zero if
-
# daylight savings is being observed).
-
1
attr_reader :std_offset
-
-
# The total offset of this observance from UTC in seconds
-
# (utc_offset + std_offset).
-
1
attr_reader :utc_total_offset
-
-
# The abbreviation that identifies this observance, e.g. "GMT"
-
# (Greenwich Mean Time) or "BST" (British Summer Time) for "Europe/London". The returned identifier is a
-
# symbol.
-
1
attr_reader :abbreviation
-
-
# Constructs a new TimezoneOffset. utc_offset and std_offset are specified
-
# in seconds.
-
1
def initialize(utc_offset, std_offset, abbreviation)
-
1
@utc_offset = utc_offset
-
1
@std_offset = std_offset
-
1
@abbreviation = abbreviation
-
-
1
@utc_total_offset = @utc_offset + @std_offset
-
end
-
-
# True if std_offset is non-zero.
-
1
def dst?
-
@std_offset != 0
-
end
-
-
# Converts a UTC Time, DateTime or integer timestamp to local time, based on
-
# the offset of this period.
-
#
-
# Deprecation warning: this method will be removed in TZInfo version 2.0.0.
-
1
def to_local(utc)
-
55
TimeOrDateTime.wrap(utc) {|wrapped|
-
55
wrapped + @utc_total_offset
-
}
-
end
-
-
# Converts a local Time, DateTime or integer timestamp to UTC, based on the
-
# offset of this period.
-
#
-
# Deprecation warning: this method will be removed in TZInfo version 2.0.0.
-
1
def to_utc(local)
-
TimeOrDateTime.wrap(local) {|wrapped|
-
wrapped - @utc_total_offset
-
}
-
end
-
-
# Returns true if and only if toi has the same utc_offset, std_offset
-
# and abbreviation as this TimezoneOffset.
-
1
def ==(toi)
-
toi.kind_of?(TimezoneOffset) &&
-
utc_offset == toi.utc_offset && std_offset == toi.std_offset && abbreviation == toi.abbreviation
-
end
-
-
# Returns true if and only if toi has the same utc_offset, std_offset
-
# and abbreviation as this TimezoneOffset.
-
1
def eql?(toi)
-
self == toi
-
end
-
-
# Returns a hash of this TimezoneOffset.
-
1
def hash
-
utc_offset.hash ^ std_offset.hash ^ abbreviation.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@utc_offset,#@std_offset,#@abbreviation>"
-
end
-
end
-
end
-
1
module TZInfo
-
# A period of time in a timezone where the same offset from UTC applies.
-
#
-
# All the methods that take times accept instances of Time or DateTime as well
-
# as Integer timestamps.
-
1
class TimezonePeriod
-
# The TimezoneTransition that defines the start of this TimezonePeriod
-
# (may be nil if unbounded).
-
1
attr_reader :start_transition
-
-
# The TimezoneTransition that defines the end of this TimezonePeriod
-
# (may be nil if unbounded).
-
1
attr_reader :end_transition
-
-
# The TimezoneOffset for this period.
-
1
attr_reader :offset
-
-
# Initializes a new TimezonePeriod.
-
#
-
# TimezonePeriod instances should not normally be constructed manually.
-
1
def initialize(start_transition, end_transition, offset = nil)
-
56
@start_transition = start_transition
-
56
@end_transition = end_transition
-
-
56
if offset
-
56
raise ArgumentError, 'Offset specified with transitions' if @start_transition || @end_transition
-
56
@offset = offset
-
else
-
if @start_transition
-
@offset = @start_transition.offset
-
elsif @end_transition
-
@offset = @end_transition.previous_offset
-
else
-
raise ArgumentError, 'No offset specified and no transitions to determine it from'
-
end
-
end
-
-
56
@utc_total_offset_rational = nil
-
end
-
-
# Base offset of the timezone from UTC (seconds).
-
1
def utc_offset
-
1
@offset.utc_offset
-
end
-
-
# Offset from the local time where daylight savings is in effect (seconds).
-
# E.g.: utc_offset could be -5 hours. Normally, std_offset would be 0.
-
# During daylight savings, std_offset would typically become +1 hours.
-
1
def std_offset
-
@offset.std_offset
-
end
-
-
# The identifier of this period, e.g. "GMT" (Greenwich Mean Time) or "BST"
-
# (British Summer Time) for "Europe/London". The returned identifier is a
-
# symbol.
-
1
def abbreviation
-
@offset.abbreviation
-
end
-
1
alias :zone_identifier :abbreviation
-
-
# Total offset from UTC (seconds). Equal to utc_offset + std_offset.
-
1
def utc_total_offset
-
@offset.utc_total_offset
-
end
-
-
# Total offset from UTC (days). Result is a Rational.
-
1
def utc_total_offset_rational
-
# Thread-safety: It is possible that the value of
-
# @utc_total_offset_rational may be calculated multiple times in
-
# concurrently executing threads. It is not worth the overhead of locking
-
# to ensure that @zone_identifiers is only calculated once.
-
-
unless @utc_total_offset_rational
-
@utc_total_offset_rational = OffsetRationals.rational_for_offset(utc_total_offset)
-
end
-
@utc_total_offset_rational
-
end
-
-
# The start time of the period in UTC as a DateTime. May be nil if unbounded.
-
1
def utc_start
-
@start_transition ? @start_transition.at.to_datetime : nil
-
end
-
-
# The start time of the period in UTC as a Time. May be nil if unbounded.
-
1
def utc_start_time
-
@start_transition ? @start_transition.at.to_time : nil
-
end
-
-
# The end time of the period in UTC as a DateTime. May be nil if unbounded.
-
1
def utc_end
-
@end_transition ? @end_transition.at.to_datetime : nil
-
end
-
-
# The end time of the period in UTC as a Time. May be nil if unbounded.
-
1
def utc_end_time
-
@end_transition ? @end_transition.at.to_time : nil
-
end
-
-
# The start time of the period in local time as a DateTime. May be nil if
-
# unbounded.
-
1
def local_start
-
@start_transition ? @start_transition.local_start_at.to_datetime : nil
-
end
-
-
# The start time of the period in local time as a Time. May be nil if
-
# unbounded.
-
1
def local_start_time
-
@start_transition ? @start_transition.local_start_at.to_time : nil
-
end
-
-
# The end time of the period in local time as a DateTime. May be nil if
-
# unbounded.
-
1
def local_end
-
@end_transition ? @end_transition.local_end_at.to_datetime : nil
-
end
-
-
# The end time of the period in local time as a Time. May be nil if
-
# unbounded.
-
1
def local_end_time
-
@end_transition ? @end_transition.local_end_at.to_time : nil
-
end
-
-
# true if daylight savings is in effect for this period; otherwise false.
-
1
def dst?
-
@offset.dst?
-
end
-
-
# true if this period is valid for the given UTC DateTime; otherwise false.
-
#
-
# Deprecation warning: this method will be removed in TZInfo version 2.0.0.
-
1
def valid_for_utc?(utc)
-
utc_after_start?(utc) && utc_before_end?(utc)
-
end
-
-
# true if the given UTC DateTime is after the start of the period
-
# (inclusive); otherwise false.
-
#
-
# Deprecation warning: this method will be removed in TZInfo version 2.0.0.
-
1
def utc_after_start?(utc)
-
!@start_transition || @start_transition.at <= utc
-
end
-
-
# true if the given UTC DateTime is before the end of the period
-
# (exclusive); otherwise false.
-
#
-
# Deprecation warning: this method will be removed in TZInfo version 2.0.0.
-
1
def utc_before_end?(utc)
-
!@end_transition || @end_transition.at > utc
-
end
-
-
# true if this period is valid for the given local DateTime; otherwise
-
# false.
-
#
-
# Deprecation warning: this method will be removed in TZInfo version 2.0.0.
-
1
def valid_for_local?(local)
-
local_after_start?(local) && local_before_end?(local)
-
end
-
-
# true if the given local DateTime is after the start of the period
-
# (inclusive); otherwise false.
-
#
-
# Deprecation warning: this method will be removed in TZInfo version 2.0.0.
-
1
def local_after_start?(local)
-
!@start_transition || @start_transition.local_start_at <= local
-
end
-
-
# true if the given local DateTime is before the end of the period
-
# (exclusive); otherwise false.
-
#
-
# Deprecation warning: this method will be removed in TZInfo version 2.0.0.
-
1
def local_before_end?(local)
-
!@end_transition || @end_transition.local_end_at > local
-
end
-
-
# Converts a UTC DateTime to local time based on the offset of this period.
-
#
-
# Deprecation warning: this method will be removed in TZInfo version 2.0.0.
-
1
def to_local(utc)
-
55
@offset.to_local(utc)
-
end
-
-
# Converts a local DateTime to UTC based on the offset of this period.
-
#
-
# Deprecation warning: this method will be removed in TZInfo version 2.0.0.
-
1
def to_utc(local)
-
@offset.to_utc(local)
-
end
-
-
# Returns true if this TimezonePeriod is equal to p. This compares the
-
# start_transition, end_transition and offset using ==.
-
1
def ==(p)
-
p.kind_of?(TimezonePeriod) &&
-
start_transition == p.start_transition &&
-
end_transition == p.end_transition &&
-
offset == p.offset
-
end
-
-
# Returns true if this TimezonePeriods is equal to p. This compares the
-
# start_transition, end_transition and offset using eql?
-
1
def eql?(p)
-
p.kind_of?(TimezonePeriod) &&
-
start_transition.eql?(p.start_transition) &&
-
end_transition.eql?(p.end_transition) &&
-
offset.eql?(p.offset)
-
end
-
-
# Returns a hash of this TimezonePeriod.
-
1
def hash
-
result = @start_transition.hash ^ @end_transition.hash
-
result ^= @offset.hash unless @start_transition || @end_transition
-
result
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
result = "#<#{self.class}: #{@start_transition.inspect},#{@end_transition.inspect}"
-
result << ",#{@offset.inspect}>" unless @start_transition || @end_transition
-
result + '>'
-
end
-
end
-
end
-
1
module TZInfo
-
-
# A proxy class representing a timezone with a given identifier. TimezoneProxy
-
# inherits from Timezone and can be treated like any Timezone loaded with
-
# Timezone.get.
-
#
-
# The first time an attempt is made to access the data for the timezone, the
-
# real Timezone is loaded. If the proxy's identifier was not valid, then an
-
# exception will be raised at this point.
-
1
class TimezoneProxy < Timezone
-
# Construct a new TimezoneProxy for the given identifier. The identifier
-
# is not checked when constructing the proxy. It will be validated on the
-
# when the real Timezone is loaded.
-
1
def self.new(identifier)
-
# Need to override new to undo the behaviour introduced in Timezone#new.
-
1
tzp = super()
-
1
tzp.send(:setup, identifier)
-
1
tzp
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
1
def identifier
-
@real_timezone ? @real_timezone.identifier : @identifier
-
end
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
1
def period_for_utc(utc)
-
56
real_timezone.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Returns an empty array if no periods are found for the given time.
-
1
def periods_for_local(local)
-
real_timezone.periods_for_local(local)
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time (to).
-
#
-
# A from date and time may also be supplied using the from parameter. If
-
# from is not nil, only transitions from that date and time onwards will be
-
# returned.
-
#
-
# Comparisons with to are exclusive. Comparisons with from are inclusive.
-
# If a transition falls precisely on to, it will be excluded. If a
-
# transition falls on from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# to and from can be specified using either a Time, DateTime, Time or
-
# Timestamp.
-
#
-
# If from is specified and to is not greater than from, then an
-
# ArgumentError exception is raised.
-
#
-
# ArgumentError is raised if to is nil or of either to or from are
-
# Timestamps with unspecified offsets.
-
1
def transitions_up_to(to, from = nil)
-
real_timezone.transitions_up_to(to, from)
-
end
-
-
# Returns the canonical zone for this Timezone.
-
1
def canonical_zone
-
real_timezone.canonical_zone
-
end
-
-
# Dumps this TimezoneProxy for marshalling.
-
1
def _dump(limit)
-
identifier
-
end
-
-
# Loads a marshalled TimezoneProxy.
-
1
def self._load(data)
-
TimezoneProxy.new(data)
-
end
-
-
1
private
-
1
def setup(identifier)
-
1
@identifier = identifier
-
1
@real_timezone = nil
-
end
-
-
1
def real_timezone
-
# Thread-safety: It is possible that the value of @real_timezone may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @real_timezone is only
-
# calculated once.
-
56
@real_timezone ||= Timezone.get(@identifier)
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents a transition from one timezone offset to another at a particular
-
# date and time.
-
1
class TimezoneTransition
-
# The offset this transition changes to (a TimezoneOffset instance).
-
1
attr_reader :offset
-
-
# The offset this transition changes from (a TimezoneOffset instance).
-
1
attr_reader :previous_offset
-
-
# Initializes a new TimezoneTransition.
-
#
-
# TimezoneTransition instances should not normally be constructed manually.
-
1
def initialize(offset, previous_offset)
-
@offset = offset
-
@previous_offset = previous_offset
-
@local_end_at = nil
-
@local_start_at = nil
-
end
-
-
# A TimeOrDateTime instance representing the UTC time when this transition
-
# occurs.
-
1
def at
-
raise_not_implemented('at')
-
end
-
-
# The UTC time when this transition occurs, returned as a DateTime instance.
-
1
def datetime
-
at.to_datetime
-
end
-
-
# The UTC time when this transition occurs, returned as a Time instance.
-
1
def time
-
at.to_time
-
end
-
-
# A TimeOrDateTime instance representing the local time when this transition
-
# causes the previous observance to end (calculated from at using
-
# previous_offset).
-
1
def local_end_at
-
# Thread-safety: It is possible that the value of @local_end_at may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @local_end_at is only
-
# calculated once.
-
-
@local_end_at = at.add_with_convert(@previous_offset.utc_total_offset) unless @local_end_at
-
@local_end_at
-
end
-
-
# The local time when this transition causes the previous observance to end,
-
# returned as a DateTime instance.
-
1
def local_end
-
local_end_at.to_datetime
-
end
-
-
# The local time when this transition causes the previous observance to end,
-
# returned as a Time instance.
-
1
def local_end_time
-
local_end_at.to_time
-
end
-
-
# A TimeOrDateTime instance representing the local time when this transition
-
# causes the next observance to start (calculated from at using offset).
-
1
def local_start_at
-
# Thread-safety: It is possible that the value of @local_start_at may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @local_start_at is only
-
# calculated once.
-
-
@local_start_at = at.add_with_convert(@offset.utc_total_offset) unless @local_start_at
-
@local_start_at
-
end
-
-
# The local time when this transition causes the next observance to start,
-
# returned as a DateTime instance.
-
1
def local_start
-
local_start_at.to_datetime
-
end
-
-
# The local time when this transition causes the next observance to start,
-
# returned as a Time instance.
-
1
def local_start_time
-
local_start_at.to_time
-
end
-
-
# Returns true if this TimezoneTransition is equal to the given
-
# TimezoneTransition. Two TimezoneTransition instances are
-
# considered to be equal by == if offset, previous_offset and at are all
-
# equal.
-
1
def ==(tti)
-
tti.kind_of?(TimezoneTransition) &&
-
offset == tti.offset && previous_offset == tti.previous_offset && at == tti.at
-
end
-
-
# Returns true if this TimezoneTransition is equal to the given
-
# TimezoneTransition. Two TimezoneTransition instances are
-
# considered to be equal by eql? if offset, previous_offset and at are all
-
# equal and the type used to define at in both instances is the same.
-
1
def eql?(tti)
-
tti.kind_of?(TimezoneTransition) &&
-
offset == tti.offset && previous_offset == tti.previous_offset && at.eql?(tti.at)
-
end
-
-
# Returns a hash of this TimezoneTransition instance.
-
1
def hash
-
@offset.hash ^ @previous_offset.hash ^ at.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{at.inspect},#{@offset.inspect}>"
-
end
-
-
1
private
-
-
1
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
1
module TZInfo
-
# A TimezoneTransition defined by as integer timestamp, as a rational to
-
# create a DateTime or as both.
-
#
-
# @private
-
1
class TimezoneTransitionDefinition < TimezoneTransition #:nodoc:
-
# The numerator of the DateTime if the transition time is defined as a
-
# DateTime, otherwise the transition time as a timestamp.
-
1
attr_reader :numerator_or_time
-
1
protected :numerator_or_time
-
-
# Either the denominator of the DateTime if the transition time is defined
-
# as a DateTime, otherwise nil.
-
1
attr_reader :denominator
-
1
protected :denominator
-
-
# Creates a new TimezoneTransitionDefinition with the given offset,
-
# previous_offset (both TimezoneOffset instances) and UTC time.
-
#
-
# The time can be specified as a timestamp, as a rational to create a
-
# DateTime, or as both.
-
#
-
# If both a timestamp and rational are given, then the rational will only
-
# be used if the timestamp falls outside of the range of Time on the
-
# platform being used at runtime.
-
#
-
# DateTimes are created from the rational as follows:
-
#
-
# RubyCoreSupport.datetime_new!(RubyCoreSupport.rational_new!(numerator, denominator), 0, Date::ITALY)
-
#
-
# For performance reasons, the numerator and denominator must be specified
-
# in their lowest form.
-
1
def initialize(offset, previous_offset, numerator_or_timestamp, denominator_or_numerator = nil, denominator = nil)
-
super(offset, previous_offset)
-
-
if denominator
-
numerator = denominator_or_numerator
-
timestamp = numerator_or_timestamp
-
elsif denominator_or_numerator
-
numerator = numerator_or_timestamp
-
denominator = denominator_or_numerator
-
timestamp = nil
-
else
-
numerator = nil
-
denominator = nil
-
timestamp = numerator_or_timestamp
-
end
-
-
# Determine whether to use the timestamp or the numerator and denominator.
-
if numerator && (
-
!timestamp ||
-
(timestamp < 0 && !RubyCoreSupport.time_supports_negative) ||
-
((timestamp < -2147483648 || timestamp > 2147483647) && !RubyCoreSupport.time_supports_64bit)
-
)
-
-
@numerator_or_time = numerator
-
@denominator = denominator
-
else
-
@numerator_or_time = timestamp
-
@denominator = nil
-
end
-
-
@at = nil
-
end
-
-
# A TimeOrDateTime instance representing the UTC time when this transition
-
# occurs.
-
1
def at
-
# Thread-safety: It is possible that the value of @at may be calculated
-
# multiple times in concurrently executing threads. It is not worth the
-
# overhead of locking to ensure that @at is only calculated once.
-
-
unless @at
-
unless @denominator
-
@at = TimeOrDateTime.new(@numerator_or_time)
-
else
-
r = RubyCoreSupport.rational_new!(@numerator_or_time, @denominator)
-
dt = RubyCoreSupport.datetime_new!(r, 0, Date::ITALY)
-
@at = TimeOrDateTime.new(dt)
-
end
-
end
-
-
@at
-
end
-
-
# Returns true if this TimezoneTransitionDefinition is equal to the given
-
# TimezoneTransitionDefinition. Two TimezoneTransitionDefinition instances
-
# are considered to be equal by eql? if offset, previous_offset,
-
# numerator_or_time and denominator are all equal.
-
1
def eql?(tti)
-
tti.kind_of?(TimezoneTransitionDefinition) &&
-
offset == tti.offset && previous_offset == tti.previous_offset &&
-
numerator_or_time == tti.numerator_or_time && denominator == tti.denominator
-
end
-
-
# Returns a hash of this TimezoneTransitionDefinition instance.
-
1
def hash
-
@offset.hash ^ @previous_offset.hash ^ @numerator_or_time.hash ^ @denominator.hash
-
end
-
end
-
end
-
1
module TZInfo
-
# Raised if no offsets have been defined when calling period_for_utc or
-
# periods_for_local. Indicates an error in the timezone data.
-
1
class NoOffsetsDefined < StandardError
-
end
-
-
# Represents a data timezone defined by a set of offsets and a set
-
# of transitions.
-
#
-
# @private
-
1
class TransitionDataTimezoneInfo < DataTimezoneInfo #:nodoc:
-
-
# Constructs a new TransitionDataTimezoneInfo with its identifier.
-
1
def initialize(identifier)
-
1
super(identifier)
-
1
@offsets = {}
-
1
@transitions = []
-
1
@previous_offset = nil
-
1
@transitions_index = nil
-
end
-
-
# Defines a offset. The id uniquely identifies this offset within the
-
# timezone. utc_offset and std_offset define the offset in seconds of
-
# standard time from UTC and daylight savings from standard time
-
# respectively. abbreviation describes the timezone offset (e.g. GMT, BST,
-
# EST or EDT).
-
#
-
# The first offset to be defined is treated as the offset that applies
-
# until the first transition. This will usually be in Local Mean Time (LMT).
-
#
-
# ArgumentError will be raised if the id is already defined.
-
1
def offset(id, utc_offset, std_offset, abbreviation)
-
1
raise ArgumentError, 'Offset already defined' if @offsets.has_key?(id)
-
-
1
offset = TimezoneOffset.new(utc_offset, std_offset, abbreviation)
-
1
@offsets[id] = offset
-
1
@previous_offset = offset unless @previous_offset
-
end
-
-
# Defines a transition. Transitions must be defined in chronological order.
-
# ArgumentError will be raised if a transition is added out of order.
-
# offset_id refers to an id defined with offset. ArgumentError will be
-
# raised if the offset_id cannot be found. numerator_or_time and
-
# denomiator specify the time the transition occurs as. See
-
# TimezoneTransition for more detail about specifying times.
-
1
def transition(year, month, offset_id, numerator_or_timestamp, denominator_or_numerator = nil, denominator = nil)
-
offset = @offsets[offset_id]
-
raise ArgumentError, 'Offset not found' unless offset
-
-
if @transitions_index
-
if year < @last_year || (year == @last_year && month < @last_month)
-
raise ArgumentError, 'Transitions must be increasing date order'
-
end
-
-
# Record the position of the first transition with this index.
-
index = transition_index(year, month)
-
@transitions_index[index] ||= @transitions.length
-
-
# Fill in any gaps
-
(index - 1).downto(0) do |i|
-
break if @transitions_index[i]
-
@transitions_index[i] = @transitions.length
-
end
-
else
-
@transitions_index = [@transitions.length]
-
@start_year = year
-
@start_month = month
-
end
-
-
@transitions << TimezoneTransitionDefinition.new(offset, @previous_offset,
-
numerator_or_timestamp, denominator_or_numerator, denominator)
-
@last_year = year
-
@last_month = month
-
@previous_offset = offset
-
end
-
-
# Returns the TimezonePeriod for the given UTC time.
-
# Raises NoOffsetsDefined if no offsets have been defined.
-
1
def period_for_utc(utc)
-
56
unless @transitions.empty?
-
utc = TimeOrDateTime.wrap(utc)
-
index = transition_index(utc.year, utc.mon)
-
-
start_transition = nil
-
start = transition_before_end(index)
-
if start
-
start.downto(0) do |i|
-
if @transitions[i].at <= utc
-
start_transition = @transitions[i]
-
break
-
end
-
end
-
end
-
-
end_transition = nil
-
start = transition_after_start(index)
-
if start
-
start.upto(@transitions.length - 1) do |i|
-
if @transitions[i].at > utc
-
end_transition = @transitions[i]
-
break
-
end
-
end
-
end
-
-
if start_transition || end_transition
-
TimezonePeriod.new(start_transition, end_transition)
-
else
-
# Won't happen since there are transitions. Must always find one
-
# transition that is either >= or < the specified time.
-
raise 'No transitions found in search'
-
end
-
else
-
56
raise NoOffsetsDefined, 'No offsets have been defined' unless @previous_offset
-
56
TimezonePeriod.new(nil, nil, @previous_offset)
-
end
-
end
-
-
# Returns the set of TimezonePeriods for the given local time as an array.
-
# Results returned are ordered by increasing UTC start date.
-
# Returns an empty array if no periods are found for the given time.
-
# Raises NoOffsetsDefined if no offsets have been defined.
-
1
def periods_for_local(local)
-
unless @transitions.empty?
-
local = TimeOrDateTime.wrap(local)
-
index = transition_index(local.year, local.mon)
-
-
result = []
-
-
start_index = transition_after_start(index - 1)
-
if start_index && @transitions[start_index].local_end_at > local
-
if start_index > 0
-
if @transitions[start_index - 1].local_start_at <= local
-
result << TimezonePeriod.new(@transitions[start_index - 1], @transitions[start_index])
-
end
-
else
-
result << TimezonePeriod.new(nil, @transitions[start_index])
-
end
-
end
-
-
end_index = transition_before_end(index + 1)
-
-
if end_index
-
start_index = end_index unless start_index
-
-
start_index.upto(transition_before_end(index + 1)) do |i|
-
if @transitions[i].local_start_at <= local
-
if i + 1 < @transitions.length
-
if @transitions[i + 1].local_end_at > local
-
result << TimezonePeriod.new(@transitions[i], @transitions[i + 1])
-
end
-
else
-
result << TimezonePeriod.new(@transitions[i], nil)
-
end
-
end
-
end
-
end
-
-
result
-
else
-
raise NoOffsetsDefined, 'No offsets have been defined' unless @previous_offset
-
[TimezonePeriod.new(nil, nil, @previous_offset)]
-
end
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
1
def transitions_up_to(utc_to, utc_from = nil)
-
utc_to = TimeOrDateTime.wrap(utc_to)
-
utc_from = utc_from ? TimeOrDateTime.wrap(utc_from) : nil
-
-
if utc_from && utc_to <= utc_from
-
raise ArgumentError, 'utc_to must be greater than utc_from'
-
end
-
-
unless @transitions.empty?
-
if utc_from
-
from = transition_after_start(transition_index(utc_from.year, utc_from.mon))
-
-
if from
-
while from < @transitions.length && @transitions[from].at < utc_from
-
from += 1
-
end
-
-
if from >= @transitions.length
-
return []
-
end
-
else
-
# utc_from is later than last transition.
-
return []
-
end
-
else
-
from = 0
-
end
-
-
to = transition_before_end(transition_index(utc_to.year, utc_to.mon))
-
-
if to
-
while to >= 0 && @transitions[to].at >= utc_to
-
to -= 1
-
end
-
-
if to < 0
-
return []
-
end
-
else
-
# utc_to is earlier than first transition.
-
return []
-
end
-
-
@transitions[from..to]
-
else
-
[]
-
end
-
end
-
-
1
private
-
# Returns the index into the @transitions_index array for a given year
-
# and month.
-
1
def transition_index(year, month)
-
index = (year - @start_year) * 2
-
index += 1 if month > 6
-
index -= 1 if @start_month > 6
-
index
-
end
-
-
# Returns the index into @transitions of the first transition that occurs
-
# on or after the start of the given index into @transitions_index.
-
# Returns nil if there are no such transitions.
-
1
def transition_after_start(index)
-
if index >= @transitions_index.length
-
nil
-
else
-
index = 0 if index < 0
-
@transitions_index[index]
-
end
-
end
-
-
# Returns the index into @transitions of the first transition that occurs
-
# before the end of the given index into @transitions_index.
-
# Returns nil if there are no such transitions.
-
1
def transition_before_end(index)
-
index = index + 1
-
-
if index <= 0
-
nil
-
elsif index >= @transitions_index.length
-
@transitions.length - 1
-
else
-
@transitions_index[index] - 1
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents information about a country returned by ZoneinfoDataSource.
-
#
-
# @private
-
1
class ZoneinfoCountryInfo < CountryInfo #:nodoc:
-
# Constructs a new CountryInfo with an ISO 3166 country code, name and
-
# an array of CountryTimezones.
-
1
def initialize(code, name, zones)
-
249
super(code, name)
-
249
@zones = zones.dup.freeze
-
249
@zone_identifiers = nil
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country ordered
-
# geographically, most populous first.
-
1
def zone_identifiers
-
# Thread-safety: It is possible that the value of @zone_identifiers may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @zone_identifiers is only
-
# calculated once.
-
-
unless @zone_identifiers
-
@zone_identifiers = zones.collect {|zone| zone.identifier}.freeze
-
end
-
-
@zone_identifiers
-
end
-
-
# Returns a frozen array of all the timezones for the for the country
-
# ordered geographically, most populous first.
-
1
def zones
-
@zones
-
end
-
end
-
end
-
1
module TZInfo
-
# An InvalidZoneinfoDirectory exception is raised if the DataSource is
-
# set to a specific zoneinfo path, which is not a valid zoneinfo directory
-
# (i.e. a directory containing index files named iso3166.tab and zone.tab
-
# as well as other timezone files).
-
1
class InvalidZoneinfoDirectory < StandardError
-
end
-
-
# A ZoneinfoDirectoryNotFound exception is raised if no valid zoneinfo
-
# directory could be found when checking the paths listed in
-
# ZoneinfoDataSource.search_path. A valid zoneinfo directory is one that
-
# contains timezone files, a country code index file named iso3166.tab and a
-
# timezone index file named zone1970.tab or zone.tab.
-
1
class ZoneinfoDirectoryNotFound < StandardError
-
end
-
-
# A DataSource that loads data from a 'zoneinfo' directory containing
-
# compiled "TZif" version 3 (or earlier) files in addition to iso3166.tab and
-
# zone1970.tab or zone.tab index files.
-
#
-
# To have TZInfo load the system zoneinfo files, call TZInfo::DataSource.set
-
# as follows:
-
#
-
# TZInfo::DataSource.set(:zoneinfo)
-
#
-
# To load zoneinfo files from a particular directory, pass the directory to
-
# TZInfo::DataSource.set:
-
#
-
# TZInfo::DataSource.set(:zoneinfo, directory)
-
#
-
# Note that the platform used at runtime may limit the range of available
-
# transition data that can be loaded from zoneinfo files. There are two
-
# factors to consider:
-
#
-
# First of all, the zoneinfo support in TZInfo makes use of Ruby's Time class.
-
# On 32-bit builds of Ruby 1.8, the Time class only supports 32-bit
-
# timestamps. This means that only Times between 1901-12-13 20:45:52 and
-
# 2038-01-19 03:14:07 can be represented. Furthermore, certain platforms only
-
# allow for positive 32-bit timestamps (notably Windows), making the earliest
-
# representable time 1970-01-01 00:00:00.
-
#
-
# 64-bit builds of Ruby 1.8 and all builds of Ruby 1.9 support 64-bit
-
# timestamps. This means that there is no practical restriction on the range
-
# of the Time class on these platforms.
-
#
-
# TZInfo will only load transitions that fall within the supported range of
-
# the Time class. Any queries performed on times outside of this range may
-
# give inaccurate results.
-
#
-
# The second factor concerns the zoneinfo files. Versions of the 'zic' tool
-
# (used to build zoneinfo files) that were released prior to February 2006
-
# created zoneinfo files that used 32-bit integers for transition timestamps.
-
# Later versions of zic produce zoneinfo files that use 64-bit integers. If
-
# you have 32-bit zoneinfo files on your system, then any queries falling
-
# outside of the range 1901-12-13 20:45:52 to 2038-01-19 03:14:07 may be
-
# inaccurate.
-
#
-
# Most modern platforms include 64-bit zoneinfo files. However, Mac OS X (up
-
# to at least 10.8.4) still uses 32-bit zoneinfo files.
-
#
-
# To check whether your zoneinfo files contain 32-bit or 64-bit transition
-
# data, you can run the following code (substituting the identifier of the
-
# zone you want to test for zone_identifier):
-
#
-
# TZInfo::DataSource.set(:zoneinfo)
-
# dir = TZInfo::DataSource.get.zoneinfo_dir
-
# File.open(File.join(dir, zone_identifier), 'r') {|f| f.read(5) }
-
#
-
# If the last line returns "TZif\\x00", then you have a 32-bit zoneinfo file.
-
# If it returns "TZif2" or "TZif3" then you have a 64-bit zoneinfo file.
-
#
-
# If you require support for 64-bit transitions, but are restricted to 32-bit
-
# zoneinfo support, then you may want to consider using TZInfo::RubyDataSource
-
# instead.
-
1
class ZoneinfoDataSource < DataSource
-
# The default value of ZoneinfoDataSource.search_path.
-
1
DEFAULT_SEARCH_PATH = ['/usr/share/zoneinfo', '/usr/share/lib/zoneinfo', '/etc/zoneinfo'].freeze
-
-
# The default value of ZoneinfoDataSource.alternate_iso3166_tab_search_path.
-
1
DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH = ['/usr/share/misc/iso3166.tab', '/usr/share/misc/iso3166'].freeze
-
-
# Paths to be checked to find the system zoneinfo directory.
-
1
@@search_path = DEFAULT_SEARCH_PATH.dup
-
-
# Paths to possible alternate iso3166.tab files (used to locate the
-
# system-wide iso3166.tab files on FreeBSD and OpenBSD).
-
1
@@alternate_iso3166_tab_search_path = DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH.dup
-
-
# An Array of directories that will be checked to find the system zoneinfo
-
# directory.
-
#
-
# Directories are checked in the order they appear in the Array.
-
#
-
# The default value is ['/usr/share/zoneinfo', '/usr/share/lib/zoneinfo', '/etc/zoneinfo'].
-
1
def self.search_path
-
1
@@search_path
-
end
-
-
# Sets the directories to be checked when locating the system zoneinfo
-
# directory.
-
#
-
# Can be set to an Array of directories or a String containing directories
-
# separated with File::PATH_SEPARATOR.
-
#
-
# Directories are checked in the order they appear in the Array or String.
-
#
-
# Set to nil to revert to the default paths.
-
1
def self.search_path=(search_path)
-
@@search_path = process_search_path(search_path, DEFAULT_SEARCH_PATH)
-
end
-
-
# An Array of paths that will be checked to find an alternate iso3166.tab
-
# file if one was not included in the zoneinfo directory (for example, on
-
# FreeBSD and OpenBSD systems).
-
#
-
# Paths are checked in the order they appear in the array.
-
#
-
# The default value is ['/usr/share/misc/iso3166.tab', '/usr/share/misc/iso3166'].
-
1
def self.alternate_iso3166_tab_search_path
-
1
@@alternate_iso3166_tab_search_path
-
end
-
-
# Sets the paths to check to locate an alternate iso3166.tab file if one was
-
# not included in the zoneinfo directory.
-
#
-
# Can be set to an Array of directories or a String containing directories
-
# separated with File::PATH_SEPARATOR.
-
#
-
# Paths are checked in the order they appear in the array.
-
#
-
# Set to nil to revert to the default paths.
-
1
def self.alternate_iso3166_tab_search_path=(alternate_iso3166_tab_search_path)
-
@@alternate_iso3166_tab_search_path = process_search_path(alternate_iso3166_tab_search_path, DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH)
-
end
-
-
# The zoneinfo directory being used.
-
1
attr_reader :zoneinfo_dir
-
-
# Creates a new ZoneinfoDataSource.
-
#
-
# If zoneinfo_dir is specified, it will be checked and used as the source
-
# of zoneinfo files.
-
#
-
# The directory must contain a file named iso3166.tab and a file named
-
# either zone1970.tab or zone.tab. These may either be included in the root
-
# of the directory or in a 'tab' sub-directory and named 'country.tab' and
-
# 'zone_sun.tab' respectively (as is the case on Solaris.
-
#
-
# Additionally, the path to iso3166.tab can be overridden using the
-
# alternate_iso3166_tab_path parameter.
-
#
-
# InvalidZoneinfoDirectory will be raised if the iso3166.tab and
-
# zone1970.tab or zone.tab files cannot be found using the zoneinfo_dir and
-
# alternate_iso3166_tab_path parameters.
-
#
-
# If zoneinfo_dir is not specified or nil, the paths referenced in
-
# search_path are searched in order to find a valid zoneinfo directory
-
# (one that contains zone1970.tab or zone.tab and iso3166.tab files as
-
# above).
-
#
-
# The paths referenced in alternate_iso3166_tab_search_path are also
-
# searched to find an iso3166.tab file if one of the searched zoneinfo
-
# directories doesn't contain an iso3166.tab file.
-
#
-
# If no valid directory can be found by searching, ZoneinfoDirectoryNotFound
-
# will be raised.
-
1
def initialize(zoneinfo_dir = nil, alternate_iso3166_tab_path = nil)
-
1
if zoneinfo_dir
-
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(zoneinfo_dir, alternate_iso3166_tab_path)
-
-
unless iso3166_tab_path && zone_tab_path
-
raise InvalidZoneinfoDirectory, "#{zoneinfo_dir} is not a directory or doesn't contain a iso3166.tab file and a zone1970.tab or zone.tab file."
-
end
-
-
@zoneinfo_dir = zoneinfo_dir
-
else
-
1
@zoneinfo_dir, iso3166_tab_path, zone_tab_path = find_zoneinfo_dir
-
-
1
unless @zoneinfo_dir && iso3166_tab_path && zone_tab_path
-
raise ZoneinfoDirectoryNotFound, "None of the paths included in TZInfo::ZoneinfoDataSource.search_path are valid zoneinfo directories."
-
end
-
end
-
-
1
@zoneinfo_dir = File.expand_path(@zoneinfo_dir).freeze
-
1
@timezone_index = load_timezone_index.freeze
-
1
@country_index = load_country_index(iso3166_tab_path, zone_tab_path).freeze
-
end
-
-
# Returns a TimezoneInfo instance for a given identifier.
-
# Raises InvalidTimezoneIdentifier if the timezone is not found or the
-
# identifier is invalid.
-
1
def load_timezone_info(identifier)
-
1
begin
-
1
if @timezone_index.include?(identifier)
-
1
path = File.join(@zoneinfo_dir, identifier)
-
-
# Untaint path rather than identifier. We don't want to modify
-
# identifier. identifier may also be frozen and therefore cannot be
-
# untainted.
-
1
path.untaint
-
-
1
begin
-
1
ZoneinfoTimezoneInfo.new(identifier, path)
-
rescue InvalidZoneinfoFile => e
-
raise InvalidTimezoneIdentifier, e.message
-
end
-
else
-
raise InvalidTimezoneIdentifier, 'Invalid identifier'
-
end
-
rescue Errno::ENOENT, Errno::ENAMETOOLONG, Errno::ENOTDIR
-
raise InvalidTimezoneIdentifier, 'Invalid identifier'
-
rescue Errno::EACCES => e
-
raise InvalidTimezoneIdentifier, e.message
-
end
-
end
-
-
# Returns an array of all the available timezone identifiers.
-
1
def timezone_identifiers
-
@timezone_index
-
end
-
-
# Returns an array of all the available timezone identifiers for
-
# data timezones (i.e. those that actually contain definitions).
-
#
-
# For ZoneinfoDataSource, this will always be identical to
-
# timezone_identifers.
-
1
def data_timezone_identifiers
-
@timezone_index
-
end
-
-
# Returns an array of all the available timezone identifiers that
-
# are links to other timezones.
-
#
-
# For ZoneinfoDataSource, this will always be an empty array.
-
1
def linked_timezone_identifiers
-
[].freeze
-
end
-
-
# Returns a CountryInfo instance for the given ISO 3166-1 alpha-2
-
# country code. Raises InvalidCountryCode if the country could not be found
-
# or the code is invalid.
-
1
def load_country_info(code)
-
info = @country_index[code]
-
raise InvalidCountryCode, 'Invalid country code' unless info
-
info
-
end
-
-
# Returns an array of all the available ISO 3166-1 alpha-2
-
# country codes.
-
1
def country_codes
-
@country_index.keys.freeze
-
end
-
-
# Returns the name and information about this DataSource.
-
1
def to_s
-
"Zoneinfo DataSource: #{@zoneinfo_dir}"
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{@zoneinfo_dir}>"
-
end
-
-
1
private
-
-
# Processes a path for use as the search_path or
-
# alternate_iso3166_tab_search_path.
-
1
def self.process_search_path(path, default)
-
if path
-
if path.kind_of?(String)
-
path.split(File::PATH_SEPARATOR)
-
else
-
path.collect {|p| p.to_s}
-
end
-
else
-
default.dup
-
end
-
end
-
-
# Validates a zoneinfo directory and returns the paths to the iso3166.tab
-
# and zone1970.tab or zone.tab files if valid. If the directory is not
-
# valid, returns nil.
-
#
-
# The path to the iso3166.tab file may be overriden by passing in a path.
-
# This is treated as either absolute or relative to the current working
-
# directory.
-
1
def validate_zoneinfo_dir(path, iso3166_tab_path = nil)
-
1
if File.directory?(path)
-
1
if iso3166_tab_path
-
return nil unless File.file?(iso3166_tab_path)
-
else
-
1
iso3166_tab_path = resolve_tab_path(path, ['iso3166.tab'], 'country.tab')
-
1
return nil unless iso3166_tab_path
-
end
-
-
1
zone_tab_path = resolve_tab_path(path, ['zone1970.tab', 'zone.tab'], 'zone_sun.tab')
-
1
return nil unless zone_tab_path
-
-
1
[iso3166_tab_path, zone_tab_path]
-
else
-
nil
-
end
-
end
-
-
# Attempts to resolve the path to a tab file given its standard names and
-
# tab sub-directory name (as used on Solaris).
-
1
def resolve_tab_path(zoneinfo_path, standard_names, tab_name)
-
2
standard_names.each do |standard_name|
-
3
path = File.join(zoneinfo_path, standard_name)
-
3
return path if File.file?(path)
-
end
-
-
path = File.join(zoneinfo_path, 'tab', tab_name)
-
return path if File.file?(path)
-
-
nil
-
end
-
-
# Finds a zoneinfo directory using search_path and
-
# alternate_iso3166_tab_search_path. Returns the paths to the directory,
-
# the iso3166.tab file and the zone.tab file or nil if not found.
-
1
def find_zoneinfo_dir
-
1
alternate_iso3166_tab_path = self.class.alternate_iso3166_tab_search_path.detect do |path|
-
2
File.file?(path)
-
end
-
-
1
self.class.search_path.each do |path|
-
# Try without the alternate_iso3166_tab_path first.
-
1
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(path)
-
1
return path, iso3166_tab_path, zone_tab_path if iso3166_tab_path && zone_tab_path
-
-
if alternate_iso3166_tab_path
-
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(path, alternate_iso3166_tab_path)
-
return path, iso3166_tab_path, zone_tab_path if iso3166_tab_path && zone_tab_path
-
end
-
end
-
-
# Not found.
-
nil
-
end
-
-
# Scans @zoneinfo_dir and returns an Array of available timezone
-
# identifiers.
-
1
def load_timezone_index
-
1
index = []
-
-
# Ignoring particular files:
-
# +VERSION is included on Mac OS X.
-
# localtime current local timezone (may be a link).
-
# posix, posixrules and right are directories containing other versions of the zoneinfo files.
-
# src is a directory containing the tzdata source included on Solaris.
-
# timeconfig is a symlink included on Slackware.
-
-
1
enum_timezones(nil, ['+VERSION', 'localtime', 'posix', 'posixrules', 'right', 'src', 'timeconfig']) do |identifier|
-
606
index << identifier
-
end
-
-
1
index.sort
-
end
-
-
# Recursively scans a directory of timezones, calling the passed in block
-
# for each identifier found.
-
1
def enum_timezones(dir, exclude = [], &block)
-
22
Dir.foreach(dir ? File.join(@zoneinfo_dir, dir) : @zoneinfo_dir) do |entry|
-
678
unless entry =~ /\./ || exclude.include?(entry)
-
627
entry.untaint
-
627
path = dir ? File.join(dir, entry) : entry
-
627
full_path = File.join(@zoneinfo_dir, path)
-
-
627
if File.directory?(full_path)
-
21
enum_timezones(path, [], &block)
-
elsif File.file?(full_path)
-
606
yield path
-
end
-
end
-
end
-
end
-
-
# Uses the iso3166.tab and zone1970.tab or zone.tab files to build an index
-
# of the available countries and their timezones.
-
1
def load_country_index(iso3166_tab_path, zone_tab_path)
-
-
# Handle standard 3 to 4 column zone.tab files as well as the 4 to 5
-
# column format used by Solaris.
-
#
-
# On Solaris, an extra column before the comment gives an optional
-
# linked/alternate timezone identifier (or '-' if not set).
-
#
-
# Additionally, there is a section at the end of the file for timezones
-
# covering regions. These are given lower-case "country" codes. The timezone
-
# identifier column refers to a continent instead of an identifier. These
-
# lines will be ignored by TZInfo.
-
#
-
# Since the last column is optional in both formats, testing for the
-
# Solaris format is done in two passes. The first pass identifies if there
-
# are any lines using 5 columns.
-
-
-
# The first column is allowed to be a comma separated list of country
-
# codes, as used in zone1970.tab (introduced in tzdata 2014f).
-
#
-
# The first country code in the comma-separated list is the country that
-
# contains the city the zone identifer is based on. The first country
-
# code on each line is considered to be primary with the others
-
# secondary.
-
#
-
# The zones for each country are ordered primary first, then secondary.
-
# Within the primary and secondary groups, the zones are ordered by their
-
# order in the file.
-
-
1
file_is_5_column = false
-
1
zone_tab = []
-
-
1
RubyCoreSupport.open_file(zone_tab_path, 'r', :external_encoding => 'UTF-8', :internal_encoding => 'UTF-8') do |file|
-
1
file.each_line do |line|
-
448
line.chomp!
-
-
448
if line =~ /\A([A-Z]{2}(?:,[A-Z]{2})*)\t(?:([+\-])(\d{2})(\d{2})([+\-])(\d{3})(\d{2})|([+\-])(\d{2})(\d{2})(\d{2})([+\-])(\d{3})(\d{2})(\d{2}))\t([^\t]+)(?:\t([^\t]+))?(?:\t([^\t]+))?\z/
-
424
codes = $1
-
-
424
if $2
-
375
latitude = dms_to_rational($2, $3, $4)
-
375
longitude = dms_to_rational($5, $6, $7)
-
else
-
49
latitude = dms_to_rational($8, $9, $10, $11)
-
49
longitude = dms_to_rational($12, $13, $14, $15)
-
end
-
-
424
zone_identifier = $16
-
424
column4 = $17
-
424
column5 = $18
-
-
424
file_is_5_column = true if column5
-
-
424
zone_tab << [codes.split(','.freeze), zone_identifier, latitude, longitude, column4, column5]
-
end
-
end
-
end
-
-
1
primary_zones = {}
-
1
secondary_zones = {}
-
-
1
zone_tab.each do |codes, zone_identifier, latitude, longitude, column4, column5|
-
424
description = file_is_5_column ? column5 : column4
-
424
country_timezone = CountryTimezone.new(zone_identifier, latitude, longitude, description)
-
-
# codes will always have at least one element
-
-
424
(primary_zones[codes.first] ||= []) << country_timezone
-
-
424
codes[1..-1].each do |code|
-
(secondary_zones[code] ||= []) << country_timezone
-
end
-
end
-
-
1
countries = {}
-
-
1
RubyCoreSupport.open_file(iso3166_tab_path, 'r', :external_encoding => 'UTF-8', :internal_encoding => 'UTF-8') do |file|
-
1
file.each_line do |line|
-
274
line.chomp!
-
-
# Handle both the two column alpha-2 and name format used in the tz
-
# database as well as the 4 column alpha-2, alpha-3, numeric-3 and
-
# name format used by FreeBSD and OpenBSD.
-
-
274
if line =~ /\A([A-Z]{2})(?:\t[A-Z]{3}\t[0-9]{3})?\t(.+)\z/
-
249
code = $1
-
249
name = $2
-
249
zones = (primary_zones[code] || []) + (secondary_zones[code] || [])
-
-
249
countries[code] = ZoneinfoCountryInfo.new(code, name, zones)
-
end
-
end
-
end
-
-
1
countries
-
end
-
-
# Converts degrees, minutes and seconds to a Rational.
-
1
def dms_to_rational(sign, degrees, minutes, seconds = nil)
-
848
result = degrees.to_i + Rational(minutes.to_i, 60)
-
848
result += Rational(seconds.to_i, 3600) if seconds
-
848
result = -result if sign == '-'.freeze
-
848
result
-
end
-
end
-
end
-
1
module TZInfo
-
# An InvalidZoneinfoFile exception is raised if an attempt is made to load an
-
# invalid zoneinfo file.
-
1
class InvalidZoneinfoFile < StandardError
-
end
-
-
# Represents a timezone defined by a compiled zoneinfo TZif (\0, 2 or 3) file.
-
#
-
# @private
-
1
class ZoneinfoTimezoneInfo < TransitionDataTimezoneInfo #:nodoc:
-
-
# Minimum supported timestamp (inclusive).
-
#
-
# Time.utc(1700, 1, 1).to_i
-
1
MIN_TIMESTAMP = -8520336000
-
-
# Maximum supported timestamp (exclusive).
-
#
-
# Time.utc(2500, 1, 1).to_i
-
1
MAX_TIMESTAMP = 16725225600
-
-
# Constructs the new ZoneinfoTimezoneInfo with an identifier and path
-
# to the file.
-
1
def initialize(identifier, file_path)
-
1
super(identifier)
-
-
1
File.open(file_path, 'rb') do |file|
-
1
parse(file)
-
end
-
end
-
-
1
private
-
# Unpack will return unsigned 32-bit integers. Translate to
-
# signed 32-bit.
-
1
def make_signed_int32(long)
-
1
long >= 0x80000000 ? long - 0x100000000 : long
-
end
-
-
# Unpack will return a 64-bit integer as two unsigned 32-bit integers
-
# (most significant first). Translate to signed 64-bit
-
1
def make_signed_int64(high, low)
-
unsigned = (high << 32) | low
-
unsigned >= 0x8000000000000000 ? unsigned - 0x10000000000000000 : unsigned
-
end
-
-
# Read bytes from file and check that the correct number of bytes could
-
# be read. Raises InvalidZoneinfoFile if the number of bytes didn't match
-
# the number requested.
-
1
def check_read(file, bytes)
-
4
result = file.read(bytes)
-
-
4
unless result && result.length == bytes
-
raise InvalidZoneinfoFile, "Expected #{bytes} bytes reading '#{file.path}', but got #{result ? result.length : 0} bytes"
-
end
-
-
4
result
-
end
-
-
# Zoneinfo files don't include the offset from standard time (std_offset)
-
# for DST periods. Derive the base offset (utc_offset) where DST is
-
# observed from either the previous or next non-DST period.
-
#
-
# Returns the index of the offset to be used prior to the first
-
# transition.
-
1
def derive_offsets(transitions, offsets)
-
# The first non-DST offset (if there is one) is the offset observed
-
# before the first transition. Fallback to the first DST offset if there
-
# are no non-DST offsets.
-
2
first_non_dst_offset_index = offsets.index {|o| !o[:is_dst] }
-
1
first_offset_index = first_non_dst_offset_index || 0
-
1
return first_offset_index if transitions.empty?
-
-
# Determine the utc_offset of the next non-dst offset at each transition.
-
utc_offset_from_next = nil
-
-
transitions.reverse_each do |transition|
-
offset = offsets[transition[:offset]]
-
if offset[:is_dst]
-
transition[:utc_offset_from_next] = utc_offset_from_next if utc_offset_from_next
-
else
-
utc_offset_from_next = offset[:utc_total_offset]
-
end
-
end
-
-
utc_offset_from_previous = first_non_dst_offset_index ? offsets[first_non_dst_offset_index][:utc_total_offset] : nil
-
defined_offsets = {}
-
-
transitions.each do |transition|
-
offset_index = transition[:offset]
-
offset = offsets[offset_index]
-
utc_total_offset = offset[:utc_total_offset]
-
-
if offset[:is_dst]
-
utc_offset_from_next = transition[:utc_offset_from_next]
-
-
difference_to_previous = utc_total_offset - (utc_offset_from_previous || utc_total_offset)
-
difference_to_next = utc_total_offset - (utc_offset_from_next || utc_total_offset)
-
-
utc_offset = if difference_to_previous > 0 && difference_to_next > 0
-
difference_to_previous < difference_to_next ? utc_offset_from_previous : utc_offset_from_next
-
elsif difference_to_previous > 0
-
utc_offset_from_previous
-
elsif difference_to_next > 0
-
utc_offset_from_next
-
else # difference_to_previous <= 0 && difference_to_next <= 0
-
# DST, but the either the offset has stayed the same or decreased
-
# relative to both the previous and next used base utc offset, or
-
# there are no non-DST offsets. Assume a 1 hour offset from base.
-
utc_total_offset - 3600
-
end
-
-
if !offset[:utc_offset]
-
offset[:utc_offset] = utc_offset
-
defined_offsets[offset] = offset_index
-
elsif offset[:utc_offset] != utc_offset
-
# An earlier transition has already derived a different
-
# utc_offset. Define a new offset or reuse an existing identically
-
# defined offset.
-
new_offset = offset.dup
-
new_offset[:utc_offset] = utc_offset
-
-
offset_index = defined_offsets[new_offset]
-
-
unless offset_index
-
offsets << new_offset
-
offset_index = offsets.length - 1
-
defined_offsets[new_offset] = offset_index
-
end
-
-
transition[:offset] = offset_index
-
end
-
else
-
utc_offset_from_previous = utc_total_offset
-
end
-
end
-
-
first_offset_index
-
end
-
-
# Defines an offset for the timezone based on the given index and offset
-
# Hash.
-
1
def define_offset(index, offset)
-
1
utc_total_offset = offset[:utc_total_offset]
-
1
utc_offset = offset[:utc_offset]
-
-
1
if utc_offset
-
# DST offset with base utc_offset derived by derive_offsets.
-
1
std_offset = utc_total_offset - utc_offset
-
elsif offset[:is_dst]
-
# DST offset unreferenced by a transition (offset in use before the
-
# first transition). No derived base UTC offset, so assume 1 hour
-
# DST.
-
utc_offset = utc_total_offset - 3600
-
std_offset = 3600
-
else
-
# Non-DST offset.
-
utc_offset = utc_total_offset
-
std_offset = 0
-
end
-
-
1
offset index, utc_offset, std_offset, offset[:abbr].untaint.to_sym
-
end
-
-
# Parses a zoneinfo file and intializes the DataTimezoneInfo structures.
-
1
def parse(file)
-
1
magic, version, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt =
-
check_read(file, 44).unpack('a4 a x15 NNNNNN')
-
-
1
if magic != 'TZif'
-
raise InvalidZoneinfoFile, "The file '#{file.path}' does not start with the expected header."
-
end
-
-
1
if (version == '2' || version == '3') && RubyCoreSupport.time_supports_64bit
-
# Skip the first 32-bit section and read the header of the second 64-bit section
-
1
file.seek(timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisgmtcnt + ttisstdcnt, IO::SEEK_CUR)
-
-
1
prev_version = version
-
-
1
magic, version, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt =
-
check_read(file, 44).unpack('a4 a x15 NNNNNN')
-
-
1
unless magic == 'TZif' && (version == prev_version)
-
raise InvalidZoneinfoFile, "The file '#{file.path}' contains an invalid 64-bit section header."
-
end
-
-
1
using_64bit = true
-
elsif version != '3' && version != '2' && version != "\0"
-
raise InvalidZoneinfoFile, "The file '#{file.path}' contains a version of the zoneinfo format that is not currently supported."
-
else
-
using_64bit = false
-
end
-
-
1
unless leapcnt == 0
-
raise InvalidZoneinfoFile, "The zoneinfo file '#{file.path}' contains leap second data. TZInfo requires zoneinfo files that omit leap seconds."
-
end
-
-
1
transitions = []
-
-
1
if using_64bit
-
1
timecnt.times do |i|
-
high, low = check_read(file, 8).unpack('NN'.freeze)
-
transition_time = make_signed_int64(high, low)
-
transitions << {:at => transition_time}
-
end
-
else
-
timecnt.times do |i|
-
transition_time = make_signed_int32(check_read(file, 4).unpack('N'.freeze)[0])
-
transitions << {:at => transition_time}
-
end
-
end
-
-
1
timecnt.times do |i|
-
localtime_type = check_read(file, 1).unpack('C'.freeze)[0]
-
transitions[i][:offset] = localtime_type
-
end
-
-
1
offsets = []
-
-
1
typecnt.times do |i|
-
1
gmtoff, isdst, abbrind = check_read(file, 6).unpack('NCC'.freeze)
-
1
gmtoff = make_signed_int32(gmtoff)
-
1
isdst = isdst == 1
-
1
offset = {:utc_total_offset => gmtoff, :is_dst => isdst, :abbr_index => abbrind}
-
-
1
unless isdst
-
1
offset[:utc_offset] = gmtoff
-
1
offset[:std_offset] = 0
-
end
-
-
1
offsets << offset
-
end
-
-
1
abbrev = check_read(file, charcnt)
-
-
1
offsets.each do |o|
-
1
abbrev_start = o[:abbr_index]
-
1
raise InvalidZoneinfoFile, "Abbreviation index is out of range in file '#{file.path}'" unless abbrev_start < abbrev.length
-
-
1
abbrev_end = abbrev.index("\0", abbrev_start)
-
1
raise InvalidZoneinfoFile, "Missing abbreviation null terminator in file '#{file.path}'" unless abbrev_end
-
-
1
o[:abbr] = RubyCoreSupport.force_encoding(abbrev[abbrev_start...abbrev_end], 'UTF-8')
-
end
-
-
1
transitions.each do |t|
-
if t[:offset] < 0 || t[:offset] >= offsets.length
-
raise InvalidZoneinfoFile, "Invalid offset referenced by transition in file '#{file.path}'."
-
end
-
end
-
-
# Derive the offsets from standard time (std_offset).
-
1
first_offset_index = derive_offsets(transitions, offsets)
-
-
1
define_offset(first_offset_index, offsets[first_offset_index])
-
-
1
offsets.each_with_index do |o, i|
-
1
define_offset(i, o) unless i == first_offset_index
-
end
-
-
1
if !using_64bit && !RubyCoreSupport.time_supports_negative
-
# Filter out transitions that are not supported by Time on this
-
# platform.
-
-
# Move the last transition before the epoch up to the epoch. This
-
# allows for accurate conversions for all supported timestamps on the
-
# platform.
-
-
before_epoch, after_epoch = transitions.partition {|t| t[:at] < 0}
-
-
if before_epoch.length > 0 && after_epoch.length > 0 && after_epoch.first[:at] != 0
-
last_before = before_epoch.last
-
last_before[:at] = 0
-
transitions = [last_before] + after_epoch
-
else
-
transitions = after_epoch
-
end
-
end
-
-
# Ignore transitions that occur outside of a defined window. The
-
# transition index cannot handle a large range of transition times.
-
#
-
# This is primarily intended to ignore the far in the past transition
-
# added in zic 2014c (at timestamp -2**63 in zic 2014c and at the
-
# approximate time of the big bang from zic 2014d).
-
1
transitions.each do |t|
-
at = t[:at]
-
if at >= MIN_TIMESTAMP && at < MAX_TIMESTAMP
-
time = Time.at(at).utc
-
transition time.year, time.mon, t[:offset], at
-
end
-
end
-
end
-
end
-
end
-
# encoding: UTF-8
-
-
1
require "json"
-
1
require "base64"
-
1
require "execjs"
-
1
require "uglifier/version"
-
-
# A wrapper around the UglifyJS interface
-
1
class Uglifier
-
# Error class for compilation errors.
-
1
Error = ExecJS::Error
-
-
# UglifyJS source path
-
1
SourcePath = File.expand_path("../uglify.js", __FILE__)
-
# UglifyJS with Harmony source path
-
1
HarmonySourcePath = File.expand_path("../uglify-harmony.js", __FILE__)
-
# Source Map path
-
1
SourceMapPath = File.expand_path("../source-map.js", __FILE__)
-
# ES5 shims source path
-
1
ES5FallbackPath = File.expand_path("../es5.js", __FILE__)
-
# String.split shim source path
-
1
SplitFallbackPath = File.expand_path("../split.js", __FILE__)
-
# UglifyJS wrapper path
-
1
UglifyJSWrapperPath = File.expand_path("../uglifier.js", __FILE__)
-
-
# Default options for compilation
-
1
DEFAULTS = {
-
# rubocop:disable LineLength
-
:output => {
-
:ascii_only => true, # Escape non-ASCII characterss
-
:comments => :copyright, # Preserve comments (:all, :jsdoc, :copyright, :none)
-
:inline_script => false, # Escape occurrences of </script in strings
-
:quote_keys => false, # Quote keys in object literals
-
:max_line_len => 32 * 1024, # Maximum line length in minified code
-
:bracketize => false, # Bracketize if, for, do, while or with statements, even if their body is a single statement
-
:semicolons => true, # Separate statements with semicolons
-
:preserve_line => false, # Preserve line numbers in outputs
-
:beautify => false, # Beautify output
-
:indent_level => 4, # Indent level in spaces
-
:indent_start => 0, # Starting indent level
-
:space_colon => false, # Insert space before colons (only with beautifier)
-
:width => 80, # Specify line width when beautifier is used (only with beautifier)
-
:preamble => nil, # Preamble for the generated JS file. Can be used to insert any code or comment.
-
:wrap_iife => false # Wrap IIFEs in parenthesis. Note: this disables the negate_iife compression option.
-
},
-
:mangle => {
-
:eval => false, # Mangle names when eval of when is used in scope
-
:except => ["$super"], # Argument names to be excluded from mangling
-
:sort => false, # Assign shorter names to most frequently used variables. Often results in bigger output after gzip.
-
:toplevel => false, # Mangle names declared in the toplevel scope
-
:properties => false, # Mangle property names
-
:keep_fnames => false # Do not modify function names
-
}, # Mangle variable and function names, set to false to skip mangling
-
:mangle_properties => false, # Mangle property names
-
:compress => {
-
:sequences => true, # Allow statements to be joined by commas
-
:properties => true, # Rewrite property access using the dot notation
-
:dead_code => true, # Remove unreachable code
-
:drop_debugger => true, # Remove debugger; statements
-
:unsafe => false, # Apply "unsafe" transformations
-
:unsafe_comps => false, # Reverse < and <= to > and >= to allow improved compression. This might be unsafe when an at least one of two operands is an object with computed values due the use of methods like get, or valueOf. This could cause change in execution order after operands in the comparison are switching. Compression only works if both comparisons and unsafe_comps are both set to true.
-
:unsafe_proto => false, # Optimize expressions like Array.prototype.slice.call(a) into [].slice.call(a)
-
:conditionals => true, # Optimize for if-s and conditional expressions
-
:comparisons => true, # Apply binary node optimizations for comparisons
-
:evaluate => true, # Attempt to evaluate constant expressions
-
:booleans => true, # Various optimizations to boolean contexts
-
:loops => true, # Optimize loops when condition can be statically determined
-
:unused => true, # Drop unreferenced functions and variables (simple direct variable assignments do not count as references unless set to `"keep_assign"`)
-
:toplevel => false, # Drop unreferenced top-level functions and variables
-
:top_retain => [], # prevent specific toplevel functions and variables from `unused` removal
-
:hoist_funs => true, # Hoist function declarations
-
:hoist_vars => false, # Hoist var declarations
-
:if_return => true, # Optimizations for if/return and if/continue
-
:join_vars => true, # Join consecutive var statements
-
:cascade => true, # Cascade sequences
-
:collapse_vars => true, # Collapse single-use var and const definitions when possible.
-
:reduce_vars => false, # Collapse variables assigned with and used as constant values.
-
:negate_iife => true, # Negate immediately invoked function expressions to avoid extra parens
-
:pure_getters => false, # Assume that object property access does not have any side-effects
-
:pure_funcs => nil, # List of functions without side-effects. Can safely discard function calls when the result value is not used
-
:drop_console => false, # Drop calls to console.* functions
-
:angular => false, # Process @ngInject annotations
-
:keep_fargs => false, # Preserve unused function arguments
-
:keep_fnames => false, # Do not drop names in function definitions
-
:passes => 1 # Number of times to run compress. Raising the number of passes will increase compress time, but can produce slightly smaller code.
-
}, # Apply transformations to code, set to false to skip
-
:define => {}, # Define values for symbol replacement
-
:enclose => false, # Enclose in output function wrapper, define replacements as key-value pairs
-
:keep_fnames => false, # Generate code safe for the poor souls relying on Function.prototype.name at run-time. Sets both compress and mangle keep_fanems to true.
-
:screw_ie8 => false, # Don't bother to generate safe code for IE8
-
:source_map => false, # Generate source map
-
:harmony => false # Enable ES6/Harmony mode (experimental). Disabling mangling and compressing is recommended with Harmony mode.
-
}
-
-
1
LEGACY_OPTIONS = [:comments, :squeeze, :copyright, :mangle]
-
-
1
MANGLE_PROPERTIES_DEFAULTS = {
-
:regex => nil, # A regular expression to filter property names to be mangled
-
:ignore_quoted => false, # Only mangle unquoted property names
-
:debug => false # Mangle names with the original name still present
-
}
-
-
1
SOURCE_MAP_DEFAULTS = {
-
:map_url => false, # Url for source mapping to be appended in minified source
-
:url => false, # Url for original source to be appended in minified source
-
:sources_content => false, # Include original source content in map
-
:filename => nil, # The filename of the input file
-
:root => nil, # The URL of the directory which contains :filename
-
:output_filename => nil, # The filename or URL where the minified output can be found
-
:input_source_map => nil # The contents of the source map describing the input
-
}
-
-
# rubocop:enable LineLength
-
-
# Minifies JavaScript code using implicit context.
-
#
-
# @param source [IO, String] valid JS source code.
-
# @param options [Hash] optional overrides to +Uglifier::DEFAULTS+
-
# @return [String] minified code.
-
1
def self.compile(source, options = {})
-
new(options).compile(source)
-
end
-
-
# Minifies JavaScript code and generates a source map using implicit context.
-
#
-
# @param source [IO, String] valid JS source code.
-
# @param options [Hash] optional overrides to +Uglifier::DEFAULTS+
-
# @return [Array(String, String)] minified code and source map.
-
1
def self.compile_with_map(source, options = {})
-
new(options).compile_with_map(source)
-
end
-
-
# Initialize new context for Uglifier with given options
-
#
-
# @param options [Hash] optional overrides to +Uglifier::DEFAULTS+
-
1
def initialize(options = {})
-
(options.keys - DEFAULTS.keys - LEGACY_OPTIONS)[0..1].each do |missing|
-
raise ArgumentError, "Invalid option: #{missing}"
-
end
-
@options = options
-
-
source = @options[:harmony] ? source_with(HarmonySourcePath) : source_with(SourcePath)
-
@context = ExecJS.compile(source)
-
end
-
-
# Minifies JavaScript code
-
#
-
# @param source [IO, String] valid JS source code.
-
# @return [String] minified code.
-
1
def compile(source)
-
if @options[:source_map]
-
compiled, source_map = run_uglifyjs(source, true)
-
source_map_uri = Base64.strict_encode64(source_map)
-
source_map_mime = "application/json;charset=utf-8;base64"
-
compiled + "\n//# sourceMappingURL=data:#{source_map_mime},#{source_map_uri}"
-
else
-
run_uglifyjs(source, false)
-
end
-
end
-
1
alias_method :compress, :compile
-
-
# Minifies JavaScript code and generates a source map
-
#
-
# @param source [IO, String] valid JS source code.
-
# @return [Array(String, String)] minified code and source map.
-
1
def compile_with_map(source)
-
run_uglifyjs(source, true)
-
end
-
-
1
private
-
-
1
def source_with(path)
-
[ES5FallbackPath, SplitFallbackPath, SourceMapPath, path,
-
UglifyJSWrapperPath].map do |file|
-
File.open(file, "r:UTF-8", &:read)
-
end.join("\n")
-
end
-
-
# Run UglifyJS for given source code
-
1
def run_uglifyjs(input, generate_map)
-
source = read_source(input)
-
input_map = input_source_map(source, generate_map)
-
options = {
-
:source => source,
-
:output => output_options,
-
:compress => compressor_options,
-
:mangle => mangle_options,
-
:mangle_properties => mangle_properties_options,
-
:parse_options => parse_options,
-
:source_map_options => source_map_options(input_map),
-
:generate_map => generate_map,
-
:enclose => enclose_options
-
}
-
-
@context.call("uglifier", options)
-
end
-
-
1
def read_source(source)
-
if source.respond_to?(:read)
-
source.read
-
else
-
source.to_s
-
end
-
end
-
-
1
def mangle_options
-
defaults = conditional_option(
-
DEFAULTS[:mangle],
-
:keep_fnames => keep_fnames?(:mangle)
-
)
-
-
conditional_option(
-
@options.fetch(:mangle, DEFAULTS[:mangle]),
-
defaults,
-
:keep_fnames => keep_fnames?(:mangle)
-
)
-
end
-
-
1
def mangle_properties_options
-
mangle_options = @options.fetch(:mangle_properties, DEFAULTS[:mangle_properties])
-
options = conditional_option(mangle_options, MANGLE_PROPERTIES_DEFAULTS)
-
if options && options[:regex]
-
options.merge(:regex => encode_regexp(options[:regex]))
-
else
-
options
-
end
-
end
-
-
1
def compressor_options
-
defaults = conditional_option(
-
DEFAULTS[:compress],
-
:global_defs => @options[:define] || {},
-
:screw_ie8 => screw_ie8?
-
)
-
-
conditional_option(
-
@options[:compress] || @options[:squeeze],
-
defaults,
-
{ :keep_fnames => keep_fnames?(:compress) }.merge(negate_iife_block)
-
)
-
end
-
-
# Prevent negate_iife when wrap_iife is true
-
1
def negate_iife_block
-
if output_options[:wrap_iife]
-
{ :negate_iife => false }
-
else
-
{}
-
end
-
end
-
-
1
def comment_options
-
case comment_setting
-
when :all, true
-
true
-
when :jsdoc
-
"jsdoc"
-
when :copyright
-
encode_regexp(/(^!)|Copyright/i)
-
when Regexp
-
encode_regexp(comment_setting)
-
else
-
false
-
end
-
end
-
-
1
def comment_setting
-
if @options.has_key?(:output) && @options[:output].has_key?(:comments)
-
@options[:output][:comments]
-
elsif @options.has_key?(:comments)
-
@options[:comments]
-
elsif @options[:copyright] == false
-
:none
-
else
-
DEFAULTS[:output][:comments]
-
end
-
end
-
-
1
def output_options
-
DEFAULTS[:output].merge(@options[:output] || {}).merge(
-
:comments => comment_options,
-
:screw_ie8 => screw_ie8?
-
).reject { |key, _| key == :ie_proof }
-
end
-
-
1
def screw_ie8?
-
if (@options[:output] || {}).has_key?(:ie_proof)
-
!@options[:output][:ie_proof]
-
else
-
@options.fetch(:screw_ie8, DEFAULTS[:screw_ie8])
-
end
-
end
-
-
1
def keep_fnames?(type)
-
if @options[:keep_fnames] || DEFAULTS[:keep_fnames]
-
true
-
else
-
@options[type].respond_to?(:[]) && @options[type][:keep_fnames] ||
-
DEFAULTS[type].respond_to?(:[]) && DEFAULTS[type][:keep_fnames]
-
end
-
end
-
-
1
def source_map_options(input_map)
-
options = conditional_option(@options[:source_map], SOURCE_MAP_DEFAULTS) || SOURCE_MAP_DEFAULTS
-
-
{
-
:file => options[:output_filename],
-
:root => options.fetch(:root) { input_map ? input_map["sourceRoot"] : nil },
-
:orig => input_map,
-
:map_url => options[:map_url],
-
:url => options[:url],
-
:sources_content => options[:sources_content]
-
}
-
end
-
-
1
def parse_options
-
if @options[:source_map].respond_to?(:[])
-
{ :filename => @options[:source_map][:filename] }
-
else
-
{}
-
end
-
end
-
-
1
def enclose_options
-
if @options[:enclose]
-
@options[:enclose].map do |pair|
-
pair.first + ':' + pair.last
-
end
-
else
-
false
-
end
-
end
-
-
1
def encode_regexp(regexp)
-
modifiers = if regexp.casefold?
-
"i"
-
else
-
""
-
end
-
-
[regexp.source, modifiers]
-
end
-
-
1
def conditional_option(value, defaults, overrides = {})
-
if value == true || value.nil?
-
defaults.merge(overrides)
-
elsif value
-
defaults.merge(value).merge(overrides)
-
else
-
false
-
end
-
end
-
-
1
def sanitize_map_root(map)
-
if map.nil?
-
nil
-
elsif map.is_a? String
-
sanitize_map_root(JSON.parse(map))
-
elsif map["sourceRoot"] == ""
-
map.merge("sourceRoot" => nil)
-
else
-
map
-
end
-
end
-
-
1
def extract_source_mapping_url(source)
-
comment_start = %r{(?://|/\*\s*)}
-
comment_end = %r{\s*(?:\r?\n?\*/|$)?}
-
source_mapping_regex = /#{comment_start}[@#]\ssourceMappingURL=\s*(\S*?)#{comment_end}/
-
rest = /\s#{comment_start}[@#]\s[a-zA-Z]+=\s*(?:\S*?)#{comment_end}/
-
regex = /#{source_mapping_regex}(?:#{rest})*\Z/m
-
match = regex.match(source)
-
match && match[1]
-
end
-
-
1
def input_source_map(source, generate_map)
-
return nil unless generate_map
-
source_map_options = @options[:source_map].is_a?(Hash) ? @options[:source_map] : {}
-
sanitize_map_root(source_map_options.fetch(:input_source_map) do
-
url = extract_source_mapping_url(source)
-
if url && url.start_with?("data:")
-
Base64.strict_decode64(url.split(",", 2)[-1])
-
end
-
end)
-
rescue ArgumentError, JSON::ParserError
-
nil
-
end
-
end
-
1
class Uglifier
-
# Current version of Uglifier.
-
1
VERSION = "3.2.0"
-
end
-
1
require 'nokogiri'
-
-
1
require 'xpath/dsl'
-
1
require 'xpath/expression'
-
1
require 'xpath/literal'
-
1
require 'xpath/union'
-
1
require 'xpath/renderer'
-
1
require 'xpath/html'
-
-
1
module XPath
-
1
extend XPath::DSL
-
1
include XPath::DSL
-
-
1
def self.generate
-
11
yield(self)
-
end
-
end
-
1
module XPath
-
1
module DSL
-
1
def current
-
484
Expression.new(:this_node)
-
end
-
-
1
def descendant(*expressions)
-
139
Expression.new(:descendant, current, expressions)
-
end
-
-
1
def child(*expressions)
-
Expression.new(:child, current, expressions)
-
end
-
-
1
def axis(name, *element_names)
-
Expression.new(:axis, current, name, element_names)
-
end
-
-
1
def anywhere(*expressions)
-
23
Expression.new(:anywhere, expressions)
-
end
-
-
1
def attr(expression)
-
307
Expression.new(:attribute, current, expression)
-
end
-
-
1
def text
-
Expression.new(:text, current)
-
end
-
-
1
def css(selector)
-
Expression.new(:css, current, Literal.new(selector))
-
end
-
-
1
def function(name, *arguments)
-
Expression.new(:function, name, *arguments)
-
end
-
-
1
def method(name, *arguments)
-
172
Expression.new(:function, name, current, *arguments)
-
end
-
-
1
def where(expression)
-
225
Expression.new(:where, current, expression)
-
end
-
1
alias_method :[], :where
-
-
1
def is(expression)
-
166
Expression.new(:is, current, expression)
-
end
-
-
1
def binary_operator(name, rhs)
-
503
Expression.new(:binary_operator, name, current, rhs)
-
end
-
-
1
def union(*expressions)
-
47
Union.new(*[self, expressions].flatten)
-
end
-
1
alias_method :+, :union
-
-
1
def last
-
function(:last)
-
end
-
-
1
def position
-
function(:position)
-
end
-
-
1
METHODS = [
-
# node set
-
:count, :id, :local_name, :namespace_uri, :name,
-
# string
-
:string, :concat, :starts_with, :contains, :substring_before,
-
:substring_after, :substring, :string_length, :normalize_space,
-
:translate,
-
# boolean
-
:boolean, :not, :true, :false, :lang,
-
# number
-
:number, :sum, :floor, :ceiling, :round,
-
]
-
-
1
METHODS.each do |key|
-
25
name = key.to_s.gsub("_", "-").to_sym
-
25
define_method key do |*args|
-
172
method(name, *args)
-
end
-
end
-
-
1
alias_method :inverse, :not
-
1
alias_method :~, :not
-
1
alias_method :normalize, :normalize_space
-
1
alias_method :n, :normalize_space
-
-
1
OPERATORS = [
-
[:equals, :"=", :==],
-
[:or, :or, :|],
-
[:and, :and, :&],
-
[:lte, :<=, :<=],
-
[:lt, :<, :<],
-
[:gte, :>=, :>=],
-
[:gt, :>, :>],
-
[:plus, :+],
-
[:minus, :-],
-
[:multiply, :*, :*],
-
[:divide, :div, :/],
-
[:mod, :mod, :%],
-
]
-
-
1
OPERATORS.each do |(name, operator, alias_name)|
-
12
define_method name do |rhs|
-
503
binary_operator(operator, rhs)
-
end
-
12
alias_method alias_name, name if alias_name
-
end
-
-
1
AXES = [
-
:ancestor, :ancestor_or_self, :attribute, :descendant_or_self,
-
:following, :following_sibling, :namespace, :parent, :preceding,
-
:preceding_sibling, :self,
-
]
-
-
1
AXES.each do |key|
-
11
name = key.to_s.gsub("_", "-").to_sym
-
11
define_method key do |*element_names|
-
axis(name, *element_names)
-
end
-
end
-
-
1
alias_method :self_axis, :self
-
-
1
def one_of(*expressions)
-
expressions.map do |e|
-
116
current.equals(e)
-
22
end.reduce do |a, b|
-
94
a.or(b)
-
end
-
end
-
-
1
def next_sibling(*expressions)
-
axis(:"following-sibling")[1].axis(:self, *expressions)
-
end
-
-
1
def previous_sibling(*expressions)
-
axis(:"preceding-sibling")[1].axis(:self, *expressions)
-
end
-
end
-
end
-
1
module XPath
-
1
class Expression
-
1
attr_accessor :expression, :arguments
-
1
include XPath::DSL
-
-
1
def initialize(expression, *arguments)
-
2019
@expression = expression
-
2019
@arguments = arguments
-
end
-
-
1
def current
-
1144
self
-
end
-
-
1
def to_xpath(type=nil)
-
33
Renderer.render(self, type)
-
end
-
1
alias_method :to_s, :to_xpath
-
end
-
end
-
1
module XPath
-
1
module HTML
-
1
include XPath::DSL
-
1
extend self
-
-
# Match an `a` link element.
-
#
-
# @param [String] locator
-
# Text, id, title, or image alt attribute of the link
-
#
-
1
def link(locator)
-
29
locator = locator.to_s
-
29
link = descendant(:a)[attr(:href)]
-
29
link[attr(:id).equals(locator) | string.n.is(locator) | attr(:title).is(locator) | descendant(:img)[attr(:alt).is(locator)]]
-
end
-
-
# Match a `submit`, `image`, or `button` element.
-
#
-
# @param [String] locator
-
# Value, title, id, or image alt attribute of the button
-
#
-
1
def button(locator)
-
8
locator = locator.to_s
-
8
button = descendant(:input)[attr(:type).one_of('submit', 'reset', 'image', 'button')][attr(:id).equals(locator) | attr(:value).is(locator) | attr(:title).is(locator)]
-
8
button += descendant(:button)[attr(:id).equals(locator) | attr(:value).is(locator) | string.n.is(locator) | attr(:title).is(locator)]
-
8
button += descendant(:input)[attr(:type).equals('image')][attr(:alt).is(locator)]
-
end
-
-
-
# Match anything returned by either {#link} or {#button}.
-
#
-
# @param [String] locator
-
# Text, id, title, or image alt attribute of the link or button
-
#
-
1
def link_or_button(locator)
-
link(locator) + button(locator)
-
end
-
-
-
# Match any `fieldset` element.
-
#
-
# @param [String] locator
-
# Legend or id of the fieldset
-
#
-
1
def fieldset(locator)
-
locator = locator.to_s
-
descendant(:fieldset)[attr(:id).equals(locator) | child(:legend)[string.n.is(locator)]]
-
end
-
-
-
# Match any `input`, `textarea`, or `select` element that doesn't have a
-
# type of `submit`, `image`, or `hidden`.
-
#
-
# @param [String] locator
-
# Label, id, or name of field to match
-
#
-
1
def field(locator)
-
locator = locator.to_s
-
xpath = descendant(:input, :textarea, :select)[~attr(:type).one_of('submit', 'image', 'hidden')]
-
xpath = locate_field(xpath, locator)
-
xpath
-
end
-
-
-
# Match any `input` or `textarea` element that can be filled with text.
-
# This excludes any inputs with a type of `submit`, `image`, `radio`,
-
# `checkbox`, `hidden`, or `file`.
-
#
-
# @param [String] locator
-
# Label, id, or name of field to match
-
#
-
1
def fillable_field(locator)
-
14
locator = locator.to_s
-
14
xpath = descendant(:input, :textarea)[~attr(:type).one_of('submit', 'image', 'radio', 'checkbox', 'hidden', 'file')]
-
14
xpath = locate_field(xpath, locator)
-
14
xpath
-
end
-
-
-
# Match any `select` element.
-
#
-
# @param [String] locator
-
# Label, id, or name of the field to match
-
#
-
1
def select(locator)
-
1
locator = locator.to_s
-
1
locate_field(descendant(:select), locator)
-
end
-
-
-
# Match any `input` element of type `checkbox`.
-
#
-
# @param [String] locator
-
# Label, id, or name of the checkbox to match
-
#
-
1
def checkbox(locator)
-
locator = locator.to_s
-
locate_field(descendant(:input)[attr(:type).equals('checkbox')], locator)
-
end
-
-
-
# Match any `input` element of type `radio`.
-
#
-
# @param [String] locator
-
# Label, id, or name of the radio button to match
-
#
-
1
def radio_button(locator)
-
locator = locator.to_s
-
locate_field(descendant(:input)[attr(:type).equals('radio')], locator)
-
end
-
-
-
# Match any `input` element of type `file`.
-
#
-
# @param [String] locator
-
# Label, id, or name of the file field to match
-
#
-
1
def file_field(locator)
-
locator = locator.to_s
-
locate_field(descendant(:input)[attr(:type).equals('file')], locator)
-
end
-
-
-
# Match an `optgroup` element.
-
#
-
# @param [String] name
-
# Label for the option group
-
#
-
1
def optgroup(locator)
-
locator = locator.to_s
-
descendant(:optgroup)[attr(:label).is(locator)]
-
end
-
-
-
# Match an `option` element.
-
#
-
# @param [String] name
-
# Visible text of the option
-
#
-
1
def option(locator)
-
1
locator = locator.to_s
-
1
descendant(:option)[string.n.is(locator)]
-
end
-
-
-
# Match any `table` element.
-
#
-
# @param [String] locator
-
# Caption or id of the table to match
-
# @option options [Array] :rows
-
# Content of each cell in each row to match
-
#
-
1
def table(locator)
-
locator = locator.to_s
-
descendant(:table)[attr(:id).equals(locator) | descendant(:caption).is(locator)]
-
end
-
-
# Match any 'dd' element.
-
#
-
# @param [String] locator
-
# Id of the 'dd' element or text from preciding 'dt' element content
-
1
def definition_description(locator)
-
locator = locator.to_s
-
descendant(:dd)[attr(:id).equals(locator) | previous_sibling(:dt)[string.n.equals(locator)] ]
-
end
-
-
1
protected
-
-
1
def locate_field(xpath, locator)
-
15
locate_field = xpath[attr(:id).equals(locator) | attr(:name).equals(locator) | attr(:placeholder).equals(locator) | attr(:id).equals(anywhere(:label)[string.n.is(locator)].attr(:for))]
-
15
locate_field += descendant(:label)[string.n.is(locator)].descendant(xpath)
-
15
locate_field
-
end
-
end
-
end
-
1
module XPath
-
1
class Literal
-
1
attr_reader :value
-
1
def initialize(value)
-
@value = value
-
end
-
end
-
end
-
1
module XPath
-
1
class Renderer
-
1
def self.render(node, type)
-
66
new(type).render(node)
-
end
-
-
1
def initialize(type)
-
66
@type = type
-
end
-
-
1
def render(node)
-
7926
arguments = node.arguments.map { |argument| convert_argument(argument) }
-
2910
send(node.expression, *arguments)
-
end
-
-
1
def convert_argument(argument)
-
5281
case argument
-
2844
when Expression, Union then render(argument)
-
460
when Array then argument.map { |element| convert_argument(element) }
-
522
when String then string_literal(argument)
-
when Literal then argument.value
-
1720
else argument.to_s
-
end
-
end
-
-
1
def string_literal(string)
-
522
if string.include?("'")
-
string = string.split("'", -1).map do |substr|
-
"'#{substr}'"
-
end.join(%q{,"'",})
-
"concat(#{string})"
-
else
-
522
"'#{string}'"
-
end
-
end
-
-
1
def this_node
-
751
'.'
-
end
-
-
1
def descendant(current, element_names)
-
170
with_element_conditions("#{current}//", element_names)
-
end
-
-
1
def child(current, element_names)
-
with_element_conditions("#{current}/", element_names)
-
end
-
-
1
def axis(current, name, element_names)
-
with_element_conditions("#{current}/#{name}::", element_names)
-
end
-
-
1
def anywhere(element_names)
-
25
with_element_conditions("//", element_names)
-
end
-
-
1
def where(on, condition)
-
265
"#{on}[#{condition}]"
-
end
-
-
1
def attribute(current, name)
-
543
"#{current}/@#{name}"
-
end
-
-
1
def binary_operator(name, left, right)
-
897
"(#{left} #{name} #{right})"
-
end
-
-
1
def is(one, two)
-
178
if @type == :exact
-
174
binary_operator("=", one, two)
-
else
-
4
function(:contains, one, two)
-
end
-
end
-
-
1
def variable(name)
-
"%{#{name}}"
-
end
-
-
1
def text(current)
-
"#{current}/text()"
-
end
-
-
1
def literal(node)
-
node
-
end
-
-
1
def css(current, selector)
-
paths = Nokogiri::CSS.xpath_for(selector).map do |xpath_selector|
-
"#{current}#{xpath_selector}"
-
end
-
union(paths)
-
end
-
-
1
def union(*expressions)
-
49
expressions.join(' | ')
-
end
-
-
1
def function(name, *arguments)
-
210
"#{name}(#{arguments.join(", ")})"
-
end
-
-
1
private
-
-
1
def with_element_conditions(expression, element_names)
-
195
if element_names.length == 1
-
144
"#{expression}#{element_names.first}"
-
51
elsif element_names.length > 1
-
172
"#{expression}*[#{element_names.map { |e| "self::#{e}" }.join(" | ")}]"
-
else
-
"#{expression}*"
-
end
-
end
-
end
-
end
-
1
module XPath
-
1
class Union
-
1
include Enumerable
-
-
1
attr_reader :expressions
-
1
alias_method :arguments, :expressions
-
-
1
def initialize(*expressions)
-
63
@expressions = expressions
-
end
-
-
1
def expression
-
49
:union
-
end
-
-
1
def each(&block)
-
arguments.each(&block)
-
end
-
-
1
def method_missing(*args)
-
48
XPath::Union.new(*arguments.map { |e| e.send(*args) })
-
end
-
-
1
def to_xpath(type=nil)
-
33
Renderer.render(self, type)
-
end
-
1
alias_method :to_s, :to_xpath
-
end
-
end
-
1
class ApplicationController < ActionController::Base
-
# Prevent CSRF attacks by raising an exception.
-
# For APIs, you may want to use :null_session instead.
-
1
protect_from_forgery with: :exception
-
end
-
1
class DonorsController < ApplicationController
-
1
helper_method :sort_column, :sort_direction
-
-
# gets all Donors
-
1
def index
-
5
@donors = Donor.order(sort_column + " " + sort_direction)
-
end
-
-
# Gets a donor based on ID
-
1
def show
-
2
@donor = Donor.find(params[:id])
-
end
-
-
# Creates a new instance of Donor
-
1
def new
-
1
@donor = Donor.new
-
end
-
-
# Creates a new Donor with parameters to persist to the database
-
1
def create
-
1
@donor = Donor.create!(donor_params)
-
1
flash[:notice] = "Donor was successfully added!"
-
1
redirect_to donors_path
-
end
-
-
# Edits a Donor based on ID
-
1
def edit
-
1
@donor = Donor.find(params[:id])
-
end
-
-
# Updates a Donor based on ID
-
1
def update
-
1
@donor = Donor.find(params[:id])
-
1
@donor.update_attributes!(donor_params)
-
1
flash[:notice] = "Donor was successfully updated!"
-
1
redirect_to donors_path
-
end
-
-
# Deletes a donor based on ID
-
1
def destroy
-
@donor = Donor.find(params[:id])
-
@donor.destroy
-
redirect_to donors_path
-
end
-
-
1
private
-
1
def donor_params
-
2
params.require(:donor).permit(:donorName, :phoneNum)
-
end
-
-
1
def sort_column
-
25
Donor.column_names.include?(params[:sort]) ? params[:sort] : "donorName"
-
end
-
-
1
def sort_direction
-
15
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
-
end
-
end
-
1
class InventoriesController < ApplicationController
-
1
before_action :set_inventory, only: [:show, :edit, :update, :destroy]
-
-
-
# GET /inventories
-
# GET /inventories.json
-
1
def index
-
6
@inventories = Inventory.all
-
end
-
-
# GET /inventories/1
-
# GET /inventories/1.json
-
1
def show
-
end
-
-
# GET /inventories/new
-
1
def new
-
1
@inventory = Inventory.new
-
end
-
-
# GET /inventories/1/edit
-
1
def edit
-
end
-
-
# POST /inventories
-
# POST /inventories.json
-
1
def create
-
1
@inventory = Inventory.new(inventory_params)
-
-
1
respond_to do |format|
-
1
if @inventory.save
-
2
format.html { redirect_to @inventory, notice: 'Inventory was successfully created.' }
-
1
format.json { render :show, status: :created, location: @inventory }
-
else
-
format.html { render :new }
-
format.json { render json: @inventory.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# PATCH/PUT /inventories/1
-
# PATCH/PUT /inventories/1.json
-
1
def update
-
1
respond_to do |format|
-
1
if @inventory.update(inventory_params)
-
2
format.html { redirect_to @inventory, notice: 'Inventory was successfully updated.' }
-
1
format.json { render :show, status: :ok, location: @inventory }
-
else
-
format.html { render :edit }
-
format.json { render json: @inventory.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# DELETE /inventories/1
-
# DELETE /inventories/1.json
-
1
def destroy
-
1
@inventory.destroy
-
1
respond_to do |format|
-
2
format.html { redirect_to inventories_url, notice: 'Inventory was successfully destroyed.' }
-
1
format.json { head :no_content }
-
end
-
end
-
-
1
private
-
# Use callbacks to share common setup or constraints between actions.
-
1
def set_inventory
-
6
@inventory = Inventory.find(params[:id])
-
end
-
-
# Never trust parameters from the scary internet, only allow the white list through.
-
1
def inventory_params
-
2
params.require(:inventory).permit(:itemnum, :orgnum, :quantity, :expires, :category)
-
end
-
end
-
##
-
# This class provides methods to create, read, update, and
-
# delete Items
-
-
1
class ItemsController < ApplicationController
-
1
helper_method :sort_column, :sort_direction
-
-
# Gets all Items
-
1
def index
-
6
@items = Item.order(sort_column + " " + sort_direction)
-
end
-
-
# Gets an item based on ID
-
1
def show
-
3
@item = Item.find(params[:id])
-
end
-
-
# Creates a new instance of Item
-
1
def new
-
1
@item = Item.new
-
end
-
-
# Creates a new Item with parameters to persist to the database
-
1
def create
-
1
@item = Item.new(item_params)
-
-
1
if @item.save
-
1
redirect_to @item
-
else
-
render 'new'
-
end
-
end
-
-
# Edits an Item based on ID
-
1
def edit
-
1
@item = Item.find(params[:id])
-
end
-
-
# Edits an Item based on ID
-
1
def update
-
1
@item = Item.find(params[:id])
-
-
1
if @item.update(item_params)
-
1
redirect_to @item
-
else
-
render 'edit'
-
end
-
end
-
-
# Deletes an Item based on ID.
-
1
def destroy
-
1
@item = Item.find(params[:id])
-
1
@item.destroy
-
-
1
redirect_to items_path
-
end
-
-
1
private
-
1
def item_params
-
2
params.require(:item).permit(:itemName, :category)
-
end
-
-
1
def sort_column
-
18
Donor.column_names.include?(params[:sort]) ? params[:sort] : "itemName"
-
end
-
-
1
def sort_direction
-
18
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
-
end
-
end
-
##
-
# This class provides methods to create, read, update, and
-
# delete Organizations
-
-
1
class OrganizationsController < ApplicationController
-
1
helper_method :sort_column, :sort_direction
-
-
# Gets all Organizations
-
1
def index
-
6
@organizations = Organization.order(sort_column + " " + sort_direction)
-
end
-
-
# Gets an Organization based on ID
-
1
def show
-
3
@organization = Organization.find(params[:id])
-
end
-
-
# Creates a new instance of Organization
-
1
def new
-
1
@organization = Organization.new
-
end
-
-
# Creates a new Organization with parameters to persist to the database
-
1
def create
-
1
@organization = Organization.new(organization_params)
-
-
1
if @organization.save
-
1
redirect_to @organization
-
else
-
render 'new'
-
end
-
end
-
-
# Edits an Organization based on ID
-
1
def edit
-
1
@organization = Organization.find(params[:id])
-
end
-
-
# Edits an Organization based on ID
-
1
def update
-
1
@organization = Organization.find(params[:id])
-
-
1
if @organization.update(organization_params)
-
1
redirect_to @organization
-
else
-
render 'edit'
-
end
-
end
-
-
# Deletes an Organization based on ID
-
1
def destroy
-
1
@organization = Organization.find(params[:id])
-
1
@organization.destroy
-
-
1
redirect_to @organization
-
end
-
-
1
private
-
1
def organization_params
-
2
params.require(:organization).permit(:org_name, :address, :phone, :contact_id)
-
end
-
-
1
def sort_column
-
54
Organization.column_names.include?(params[:sort]) ? params[:sort] : "org_name"
-
end
-
-
1
def sort_direction
-
18
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
-
end
-
end
-
1
class WelcomeController < ApplicationController
-
1
def index
-
end
-
end
-
1
module ApplicationHelper
-
1
def sortable(column, title = nil)
-
40
title ||= column.titleize
-
40
css_class = column == sort_column ? "current #{sort_direction}" : nil
-
40
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
-
40
link_to title, {:sort => column, :direction => direction}, {:class => css_class}
-
end
-
end
-
1
module DonorsHelper
-
end
-
1
module InventoriesHelper
-
end
-
1
module InventoryHelper
-
end
-
1
module OrganizationsHelper
-
end
-
1
module WelcomeHelper
-
end
-
1
class Donor < ActiveRecord::Base
-
1
validates_presence_of :donorName, :phoneNum
-
end
-
1
class Inventory < ActiveRecord::Base
-
1
validates_presence_of :itemnum, :orgnum, :quantity, :expires, :category
-
1
has_many :items
-
1
belongs_to :items
-
-
1
delegate :get_itemName, :get_category, to: :items
-
1
delegate :get_organization, to: :organizations
-
-
-
end
-
1
class Item < ActiveRecord::Base
-
1
validates_presence_of :itemName, :category
-
1
belongs_to :inventory
-
-
1
public
-
1
def get_itemName(index)
-
return self[index].itemName
-
end
-
-
1
def get_category(index)
-
return self[index].category
-
end
-
end
-
1
class Organization < ActiveRecord::Base
-
1
validates_presence_of :org_name, :address, :phone, :contact_id
-
1
belongs_to :inventory
-
1
public
-
1
def get_organization(index)
-
return self[index].org_name
-
end
-
end
-
class StringCalculator
-
def self.add(input)
-
if input.empty?
-
0
-
else
-
numbers = input.split(",").map { |num| num.to_i }
-
numbers.inject(0) { |sum, number| sum + number }
-
end
-
end
-
end